World.cpp 19 KB

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