World.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  1. #include "World.h"
  2. #include <AsynchronCall.h>
  3. #include <DX12Buffer.h>
  4. #include <GraphicsApi.h>
  5. #include <iostream>
  6. #include <Network.h>
  7. #include <World3D.h>
  8. #include "Constants.h"
  9. #include "Dimension.h"
  10. #include "FactoryClient.h"
  11. #include "Game.h"
  12. #include "Globals.h"
  13. #include "PlayerKam.h"
  14. using namespace Network;
  15. using namespace Framework;
  16. World* World::INSTANCE = 0;
  17. World::World(Screen3D* zScreen, FactoryClient* client)
  18. : Thread(),
  19. client(client)
  20. {
  21. renderedWorld = new World3D();
  22. renderedWorld->addDiffuseLight(DiffuseLight{
  23. Vec3<float>(0.5f, 0.5f, -1.f), Vec3<float>(1.f, 1.f, 1.f)});
  24. currentDimension = new Dimension();
  25. renderedWorld->addCollection(
  26. dynamic_cast<Model3DCollection*>(currentDimension->getThis()));
  27. zScreenPtr = zScreen;
  28. kam = new PlayerKam(zScreen);
  29. kam->setWorld(renderedWorld);
  30. zScreen->addKamera(kam);
  31. firstMessage = 1;
  32. ownEntityId = -1;
  33. currentTarget = 0;
  34. dayLightFactor = Vec3<float>(1.f, 1.f, 1.f);
  35. dayLightDirection = Vec3<float>(0.f, 0.f, -1.f);
  36. time = 0;
  37. dayLength = 1000;
  38. transitionLength = 0;
  39. nightLength = 0;
  40. selectionModel = new FactoryCraftModel();
  41. selectionModel->setModelData(zScreen->zGraphicsApi()->getModel("cube"));
  42. selectionModel->setSize(1.005f);
  43. selectionModel->setVisible(0);
  44. unsigned char light[3] = {0xff, 0xff, 0xff};
  45. selectionModel->setAverageLight(light);
  46. selectionModel->setModelTextur(new Model3DTexture());
  47. for (int i = 0; i < 6; i++)
  48. {
  49. selectionModel->zTexture()->setPolygonTexture(i,
  50. zScreen->zGraphicsApi()->createOrGetTexture(
  51. "data/textures/blocks.ltdb/selectedblock.p"));
  52. }
  53. selectionModel->setAlpha(1);
  54. selectionModel->setUseEffectAlpha(1);
  55. renderedWorld->addDrawable(selectionModel);
  56. start();
  57. }
  58. World::~World()
  59. {
  60. zScreenPtr->removeKamera(kam);
  61. currentDimension->release();
  62. if (currentTarget) currentTarget->release();
  63. client->release();
  64. World::INSTANCE = 0;
  65. }
  66. int World::update(bool background)
  67. {
  68. if (background && currentDimension->getId() < 0) return 0;
  69. NetworkReader* serverMessageReader = 0;
  70. unsigned char type = 0;
  71. int messageCount = 0;
  72. while (background
  73. ? serverMessageReader = client->getNextBackgroundMessage()
  74. : serverMessageReader = client->getNextForegroundMessage())
  75. {
  76. messageCount++;
  77. serverMessageReader->read((char*)&type, 1);
  78. if (type == 3) // API MESSAGE
  79. {
  80. int length;
  81. serverMessageReader->read((char*)&length, 4);
  82. char* data = new char[length];
  83. serverMessageReader->read(data, length);
  84. switch (data[0])
  85. {
  86. case 1: // dimension message
  87. {
  88. int dimId = *(int*)(data + 1);
  89. if (dimId == currentDimension->getId())
  90. {
  91. currentDimension->api(data + 5);
  92. }
  93. break;
  94. }
  95. case 2: // gui message
  96. ((Game*)(Menu*)menuRegister->get("game"))->api(data + 1);
  97. break;
  98. case 3: // set target
  99. {
  100. switch (data[1])
  101. {
  102. case 0:
  103. setTarget(0);
  104. ((Game*)(Menu*)menuRegister->get("game"))
  105. ->setTargetUIML("");
  106. break;
  107. case 1:
  108. {
  109. setTarget(zEntity(*(int*)(data + 2)));
  110. short len = *(short*)(data + 6);
  111. char* uiml = new char[len + 8];
  112. memcpy(uiml, data + 8, len);
  113. uiml[len] = 0;
  114. ((Game*)(Menu*)menuRegister->get("game"))
  115. ->setTargetUIML(uiml);
  116. delete[] uiml;
  117. break;
  118. }
  119. case 2:
  120. {
  121. setTarget(zBlockAt(Vec3<int>(*(int*)(data + 2),
  122. *(int*)(data + 6),
  123. *(int*)(data + 10))));
  124. Direction side = *(Direction*)(data + 14);
  125. short len = *(short*)(data + 15);
  126. char* uiml = new char[len + 1];
  127. memcpy(uiml, data + 17, len);
  128. uiml[len] = 0;
  129. ((Game*)(Menu*)menuRegister->get("game"))
  130. ->setTargetUIML(uiml);
  131. delete[] uiml;
  132. break;
  133. }
  134. }
  135. break;
  136. }
  137. case 4: // chat message
  138. {
  139. ((Game*)(Menu*)menuRegister->get("game"))
  140. ->zChat()
  141. ->addMessage(data + 1);
  142. break;
  143. }
  144. case 5: // chat options
  145. {
  146. ((Game*)(Menu*)menuRegister->get("game"))
  147. ->zChat()
  148. ->initOptions(data + 1);
  149. break;
  150. }
  151. case 6: // map data
  152. {
  153. ByteArrayReader reader(data + 1, length - 1, 0);
  154. ChunkMap* map = new ChunkMap(&reader);
  155. ((Game*)(Menu*)menuRegister->get("game"))
  156. ->zMap()
  157. ->addChunk(map);
  158. break;
  159. }
  160. case 7: // map player data
  161. {
  162. ((Game*)(Menu*)menuRegister->get("game"))
  163. ->zMap()
  164. ->updatePlayerData(data + 1);
  165. break;
  166. }
  167. case 8: // time sync
  168. {
  169. nightLength = *(double*)(data + 9);
  170. transitionLength = *(double*)(data + 17);
  171. dayLength = *(double*)(data + 25);
  172. time = *(double*)(data + 1);
  173. break;
  174. }
  175. }
  176. delete[] data;
  177. }
  178. if (type == 4) // POSITION UPDATE
  179. {
  180. int old = ownEntityId;
  181. serverMessageReader->read((char*)&ownEntityId, 4);
  182. int dimensionId = 0;
  183. serverMessageReader->read((char*)&dimensionId, 4);
  184. currentDimension->setId(dimensionId);
  185. kam->setEntityId(ownEntityId);
  186. Entity* p = zEntity(ownEntityId);
  187. if (p) p->setPlayerControlled();
  188. if (old != ownEntityId) client->sendPlayerAction("\5", 1);
  189. }
  190. client->endMessageReading(background);
  191. }
  192. client->endMessageReading(background);
  193. if (!background)
  194. {
  195. Entity* player = getCurrentPlayerEntity();
  196. if (player)
  197. {
  198. currentDimension->removeDistantChunks(
  199. {(int)player->getPos().x, (int)player->getPos().y});
  200. Framework::Point currentChunk
  201. = getChunkCenter((int)player->getX(), (int)player->getY());
  202. for (int x = 0; x <= CHUNK_VISIBILITY_RANGE; x++)
  203. {
  204. for (int y = 0; y <= CHUNK_VISIBILITY_RANGE; y++)
  205. {
  206. std::function<void(Framework::Point)> requestChunk =
  207. [this](Framework::Point center) {
  208. Chunk* zC = currentDimension->zChunk(center);
  209. if (!zC)
  210. {
  211. char msg[1];
  212. msg[0]
  213. = 0; // add observer and request chaunk data
  214. Framework::Point pos = center;
  215. subLock.lockRead();
  216. bool found = 0;
  217. for (Framework::Point p : subscriptions)
  218. {
  219. if (p == pos)
  220. {
  221. found = 1;
  222. break;
  223. }
  224. }
  225. if (!found)
  226. {
  227. client->chunkAPIRequest(pos, msg, 1);
  228. subLock.lockWrite();
  229. subscriptions.add(pos);
  230. subLock.unlockWrite();
  231. }
  232. subLock.unlockRead();
  233. }
  234. };
  235. requestChunk(
  236. currentChunk + Point(x * CHUNK_SIZE, y * CHUNK_SIZE));
  237. if (y > 0)
  238. requestChunk(currentChunk
  239. + Point(x * CHUNK_SIZE, -y * CHUNK_SIZE));
  240. if (x > 0)
  241. {
  242. requestChunk(currentChunk
  243. + Point(-x * CHUNK_SIZE, y * CHUNK_SIZE));
  244. if (y > 0)
  245. requestChunk(
  246. currentChunk
  247. + Point(-x * CHUNK_SIZE, -y * CHUNK_SIZE));
  248. }
  249. }
  250. }
  251. }
  252. }
  253. return messageCount;
  254. }
  255. void World::onTick(double time)
  256. {
  257. // selectionModel->tick(0.1);
  258. Vec3<float> dayColor = Vec3<float>(1.f, 1.f, 1.f);
  259. Vec3<float> dawnColor = Vec3<float>(1.f, 0.8f, 0.f);
  260. Vec3<float> nightColor = Vec3<float>(0.05f, 0.05f, 0.05f);
  261. Vec3<float> beginDayLightDirection = Vec3<float>(-1.f, -0.2f, 0.2f);
  262. this->time += time;
  263. if (this->time >= dayLength + nightLength + transitionLength * 2)
  264. {
  265. this->time -= dayLength + nightLength + transitionLength * 2;
  266. }
  267. double startTime = dayLength + transitionLength + nightLength;
  268. float dayDirectionRotation = (float)(this->time - startTime);
  269. if (dayDirectionRotation < 0)
  270. {
  271. dayDirectionRotation
  272. += (float)(dayLength + nightLength + transitionLength * 2);
  273. }
  274. dayDirectionRotation = max(0.f,
  275. (float)(dayDirectionRotation
  276. / (dayLength + transitionLength + 2 * transitionLength
  277. + nightLength)));
  278. dayLightDirection
  279. = beginDayLightDirection.rotateY(dayDirectionRotation * (float)PI);
  280. if (this->time > dayLength && this->time < dayLength + transitionLength)
  281. { // transition from day to night;
  282. float transformation = (float)min(
  283. (this->time - dayLength) / (transitionLength / 2), 1.0);
  284. float transformation2
  285. = (float)min(max((this->time - dayLength - transitionLength / 2)
  286. / (transitionLength / 2),
  287. 0.0),
  288. 1.0);
  289. dayLightFactor
  290. = dawnColor * transformation + dayColor * (1.f - transformation);
  291. dayLightFactor = dayLightFactor * (1.f - transformation2)
  292. + nightColor * transformation2;
  293. }
  294. else if (this->time > dayLength + transitionLength
  295. && this->time < dayLength + transitionLength + nightLength)
  296. {
  297. // night
  298. dayLightFactor = nightColor;
  299. if (renderedWorld->getDiffuseLightCount() > 0)
  300. {
  301. renderedWorld->removeDiffuseLight(0);
  302. }
  303. }
  304. else if (this->time > dayLength + transitionLength + nightLength)
  305. { // transition from night to day
  306. float transformation = (float)min(
  307. (this->time - dayLength - transitionLength - nightLength)
  308. / (transitionLength / 2),
  309. 1.0);
  310. float transformation2
  311. = (float)min(max((this->time - dayLength - transitionLength
  312. - nightLength - transitionLength / 2)
  313. / (transitionLength / 2),
  314. 0.0),
  315. 1.0);
  316. dayLightFactor
  317. = nightColor * (1.f - transformation) + dawnColor * transformation;
  318. dayLightFactor = dayLightFactor * (1.f - transformation2)
  319. + dayColor * transformation2;
  320. }
  321. else
  322. {
  323. dayLightFactor = dayColor;
  324. }
  325. if (this->time < dayLength + transitionLength
  326. || this->time > dayLength + transitionLength + nightLength)
  327. {
  328. float currentDayTime
  329. = (float)(this->time < dayLength + transitionLength
  330. ? this->time + transitionLength
  331. : this->time - dayLength + transitionLength
  332. + nightLength);
  333. Vec3<float> sunPos = Vec3<float>(-200.f, 50.f, 0.f);
  334. sunPos.rotateY((
  335. float)((currentDayTime / (dayLength + transitionLength * 2)) * PI));
  336. sunPos.normalize();
  337. if (!renderedWorld->getDiffuseLightCount())
  338. {
  339. renderedWorld->addDiffuseLight(
  340. {-sunPos, Vec3<float>(1.0, 1.0, 1.0)});
  341. }
  342. else
  343. {
  344. renderedWorld->getDiffuseLight(0).direction = -sunPos;
  345. }
  346. }
  347. }
  348. void World::setChunk(Chunk* chunk)
  349. {
  350. currentDimension->setChunk(chunk, chunk->getCenter());
  351. }
  352. void World::thread()
  353. {
  354. new AsynchronCall("World Update", [this]() {
  355. Timer tm;
  356. tm.measureStart();
  357. double sum = 0;
  358. int updates = 0;
  359. int messages = 0;
  360. double wait = 0;
  361. while (client->isConnected())
  362. {
  363. if (World::INSTANCE != this)
  364. {
  365. return;
  366. }
  367. messages += update(0);
  368. updates++;
  369. tm.measureEnd();
  370. sum += tm.getSekunden();
  371. wait += 10 - tm.getSekunden();
  372. tm.measureStart();
  373. if ((int)wait > 0)
  374. {
  375. Sleep((int)wait);
  376. }
  377. if (sum > 1.0)
  378. {
  379. std::cout << "updates: " << updates
  380. << ", messages: " << (double)messages
  381. << ", seconds: " << sum << "\n";
  382. sum = 0;
  383. updates = 0;
  384. messages = 0;
  385. }
  386. }
  387. std::cout << "foreground connection lost\n";
  388. });
  389. while (client->isConnected())
  390. {
  391. if (World::INSTANCE != this)
  392. {
  393. return;
  394. }
  395. update(1);
  396. Sleep(100);
  397. }
  398. Sleep(1000);
  399. std::cout << "background connection lost\n";
  400. menuRegister->get("game")->hide();
  401. menuRegister->get("serverSelection")->show();
  402. zScreenPtr->postAction([this]() {
  403. if (World::INSTANCE == this)
  404. {
  405. World::INSTANCE = 0;
  406. release();
  407. }
  408. });
  409. }
  410. Block* World::zBlockAt(Framework::Vec3<int> location) const
  411. {
  412. return currentDimension->zBlock(location);
  413. }
  414. Block* World::getBlockAt(Framework::Vec3<int> location) const
  415. {
  416. return currentDimension->getBlock(location);
  417. }
  418. Dimension* World::zDimension() const
  419. {
  420. return currentDimension;
  421. }
  422. void World::setVisibility(Entity* zEntity, bool visible)
  423. {
  424. if (visible)
  425. renderedWorld->addDrawable(
  426. dynamic_cast<Framework::Model3D*>(zEntity->getThis()));
  427. else
  428. renderedWorld->removeDrawable(zEntity);
  429. }
  430. Framework::Point World::getChunkCenter(int x, int y) const
  431. {
  432. return Point(((x < 0 ? x + 1 : x) / CHUNK_SIZE) * CHUNK_SIZE
  433. + (x < 0 ? -CHUNK_SIZE : CHUNK_SIZE) / 2,
  434. ((y < 0 ? y + 1 : y) / CHUNK_SIZE) * CHUNK_SIZE
  435. + (y < 0 ? -CHUNK_SIZE : CHUNK_SIZE) / 2);
  436. }
  437. Entity* World::zEntity(int id) const
  438. {
  439. Entity* e = currentDimension->zEntity(id);
  440. if (e) return e;
  441. return 0;
  442. }
  443. Entity* World::getEntity(int id) const
  444. {
  445. Entity* e = currentDimension->getEntity(id);
  446. if (e) return e;
  447. return 0;
  448. }
  449. void World::removeEntity(int id)
  450. {
  451. currentDimension->removeEntity(id);
  452. }
  453. PlayerKam* World::zKamera() const
  454. {
  455. return kam;
  456. }
  457. int World::getCurrentPlayerId() const
  458. {
  459. return ownEntityId;
  460. }
  461. Entity* World::getCurrentPlayerEntity() const
  462. {
  463. return zEntity(ownEntityId);
  464. }
  465. void World::setTarget(Framework::Model3D* zTarget)
  466. {
  467. if (zTarget != currentTarget)
  468. {
  469. targetLock.lock();
  470. if (!zTarget)
  471. {
  472. selectionModel->setVisible(0);
  473. }
  474. else
  475. {
  476. selectionModel->setPosition(
  477. zTarget->getPos().x, zTarget->getPos().y, zTarget->getPos().z);
  478. Block* b = dynamic_cast<Block*>(zTarget);
  479. if (b)
  480. {
  481. selectionModel->setDestroyedState(b->getEffectPercentage());
  482. }
  483. else
  484. {
  485. selectionModel->setDestroyedState(0);
  486. }
  487. selectionModel->setVisible(1);
  488. }
  489. if (currentTarget)
  490. {
  491. currentTarget->setAmbientFactor(
  492. currentTarget->getAmbientFactor() - 0.2f);
  493. currentTarget->release();
  494. currentTarget = 0;
  495. }
  496. if (zTarget)
  497. {
  498. currentTarget
  499. = dynamic_cast<Framework::Model3D*>(zTarget->getThis());
  500. if (currentTarget)
  501. currentTarget->setAmbientFactor(
  502. currentTarget->getAmbientFactor() + 0.2f);
  503. }
  504. targetLock.unlock();
  505. }
  506. }
  507. void World::onChunkAdded(Framework::Point pos)
  508. {
  509. subLock.lockWrite();
  510. int index = 0;
  511. for (Framework::Point p : subscriptions)
  512. {
  513. if (p == pos)
  514. {
  515. subscriptions.remove(index);
  516. break;
  517. }
  518. index++;
  519. }
  520. subLock.unlockWrite();
  521. }
  522. Framework::Model3D* World::getCurrentTarget() const
  523. {
  524. while (targetLock.isLocked())
  525. Sleep(1);
  526. return currentTarget
  527. ? dynamic_cast<Framework::Model3D*>(currentTarget->getThis())
  528. : 0;
  529. }
  530. FactoryCraftModel* World::zSelectedEffectModel() const
  531. {
  532. return selectionModel;
  533. }
  534. Chunk* World::zChunk(Framework::Point center)
  535. {
  536. return currentDimension->zChunk(center);
  537. }
  538. Framework::Lock& World::getChunkReadLock()
  539. {
  540. return currentDimension->getReadLock();
  541. }
  542. FactoryClient* World::zClient() const
  543. {
  544. return client;
  545. }
  546. Vec3<float> World::getDayLightFactor() const
  547. {
  548. return dayLightFactor;
  549. }
  550. Vec3<float> World::getDayLightDirection() const
  551. {
  552. return dayLightDirection;
  553. }