World.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  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 "Game.h"
  10. #include "Globals.h"
  11. using namespace Network;
  12. using namespace Framework;
  13. World* World::INSTANCE = 0;
  14. World::World(Screen3D* zScreen, FactoryClient* client)
  15. : Thread(),
  16. client(client)
  17. {
  18. renderedWorld = new World3D();
  19. renderedWorld->addDiffuseLight(DiffuseLight{
  20. Vec3<float>(0.5f, 0.5f, -1.f), Vec3<float>(1.f, 1.f, 1.f)});
  21. currentDimension = new Dimension();
  22. renderedWorld->addCollection(
  23. dynamic_cast<Model3DCollection*>(currentDimension->getThis()));
  24. zScreenPtr = zScreen;
  25. kam = new PlayerKam(zScreen);
  26. kam->setWorld(renderedWorld);
  27. zScreen->addKamera(kam);
  28. firstMessage = 1;
  29. ownEntityId = -1;
  30. currentTarget = 0;
  31. dayLightFactor = 1;
  32. time = 0;
  33. dayLength = 1000;
  34. transitionLength = 0;
  35. nightLength = 0;
  36. selectionModel = new FactoryCraftModel();
  37. selectionModel->setModelData(zScreen->zGraphicsApi()->getModel("cube"));
  38. selectionModel->setSize(1.005f);
  39. selectionModel->setVisible(0);
  40. unsigned char light[3] = {0xff, 0xff, 0xff};
  41. selectionModel->setAverageLight(light);
  42. selectionModel->setModelTextur(new Model3DTexture());
  43. for (int i = 0; i < 6; i++)
  44. {
  45. selectionModel->zTexture()->setPolygonTexture(i,
  46. zScreen->zGraphicsApi()->createOrGetTexture(
  47. "data/textures/blocks.ltdb/selectedblock.p"));
  48. }
  49. selectionModel->setAlpha(1);
  50. selectionModel->setUseEffectAlpha(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. 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(Point)> requestChunk =
  203. [this](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. Point pos = center;
  211. subLock.lockRead();
  212. bool found = 0;
  213. for (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. this->time += time;
  255. if (this->time >= dayLength + nightLength + transitionLength * 2)
  256. {
  257. this->time -= dayLength + nightLength + transitionLength * 2;
  258. }
  259. if (this->time > dayLength && this->time < dayLength + transitionLength)
  260. {
  261. dayLightFactor
  262. = 1.f
  263. - (float)((this->time - dayLength) / transitionLength) * 0.95f;
  264. }
  265. else if (this->time > dayLength + transitionLength
  266. && this->time < dayLength + transitionLength + nightLength)
  267. {
  268. // night
  269. dayLightFactor = 0.05f;
  270. if (renderedWorld->getDiffuseLightCount() > 0)
  271. {
  272. renderedWorld->removeDiffuseLight(0);
  273. }
  274. }
  275. else if (this->time > dayLength + transitionLength + nightLength)
  276. {
  277. dayLightFactor
  278. = (float)((this->time - dayLength - nightLength - transitionLength)
  279. / transitionLength)
  280. * 0.95f
  281. + 0.05f;
  282. }
  283. else
  284. {
  285. dayLightFactor = 1.f;
  286. }
  287. if (this->time < dayLength + transitionLength
  288. || this->time > dayLength + transitionLength + nightLength)
  289. {
  290. float currentDayTime
  291. = (float)(this->time < dayLength + transitionLength
  292. ? this->time + transitionLength
  293. : this->time - dayLength + transitionLength
  294. + nightLength);
  295. Vec3<float> sunPos = Vec3<float>(-200.f, 50.f, 0.f);
  296. sunPos.rotateY((
  297. float)((currentDayTime / (dayLength + transitionLength * 2)) * PI));
  298. sunPos.normalize();
  299. if (!renderedWorld->getDiffuseLightCount())
  300. {
  301. renderedWorld->addDiffuseLight(
  302. {-sunPos, Vec3<float>(1.0, 1.0, 1.0)});
  303. }
  304. else
  305. {
  306. renderedWorld->getDiffuseLight(0).direction = -sunPos;
  307. }
  308. }
  309. }
  310. void World::setChunk(Chunk* chunk)
  311. {
  312. currentDimension->setChunk(chunk, chunk->getCenter());
  313. }
  314. void World::thread()
  315. {
  316. new AsynchronCall("World Update", [this]() {
  317. Timer tm;
  318. tm.measureStart();
  319. double sum = 0;
  320. int updates = 0;
  321. int messages = 0;
  322. double wait = 0;
  323. while (client->isConnected())
  324. {
  325. if (World::INSTANCE != this)
  326. {
  327. return;
  328. }
  329. messages += update(0);
  330. updates++;
  331. tm.measureEnd();
  332. sum += tm.getSekunden();
  333. wait += 10 - tm.getSekunden();
  334. tm.measureStart();
  335. if ((int)wait > 0)
  336. {
  337. Sleep((int)wait);
  338. }
  339. if (sum > 1.0)
  340. {
  341. std::cout << "updates: " << updates
  342. << ", messages: " << (double)messages
  343. << ", seconds: " << sum << "\n";
  344. sum = 0;
  345. updates = 0;
  346. messages = 0;
  347. }
  348. }
  349. std::cout << "foreground connection lost\n";
  350. });
  351. while (client->isConnected())
  352. {
  353. if (World::INSTANCE != this)
  354. {
  355. return;
  356. }
  357. update(1);
  358. Sleep(100);
  359. }
  360. Sleep(1000);
  361. std::cout << "background connection lost\n";
  362. menuRegister->get("game")->hide();
  363. menuRegister->get("serverSelection")->show();
  364. zScreenPtr->postAction([this]() {
  365. if (World::INSTANCE == this)
  366. {
  367. World::INSTANCE = 0;
  368. release();
  369. }
  370. });
  371. }
  372. Block* World::zBlockAt(Framework::Vec3<int> location) const
  373. {
  374. return currentDimension->zBlock(location);
  375. }
  376. Block* World::getBlockAt(Framework::Vec3<int> location) const
  377. {
  378. return currentDimension->getBlock(location);
  379. }
  380. Dimension* World::zDimension() const
  381. {
  382. return currentDimension;
  383. }
  384. void World::setVisibility(Entity* zEntity, bool visible)
  385. {
  386. if (visible)
  387. renderedWorld->addDrawable(
  388. dynamic_cast<Framework::Model3D*>(zEntity->getThis()));
  389. else
  390. renderedWorld->removeDrawable(zEntity);
  391. }
  392. Framework::Point World::getChunkCenter(int x, int y) const
  393. {
  394. return Point(((x < 0 ? x + 1 : x) / CHUNK_SIZE) * CHUNK_SIZE
  395. + (x < 0 ? -CHUNK_SIZE : CHUNK_SIZE) / 2,
  396. ((y < 0 ? y + 1 : y) / CHUNK_SIZE) * CHUNK_SIZE
  397. + (y < 0 ? -CHUNK_SIZE : CHUNK_SIZE) / 2);
  398. }
  399. Entity* World::zEntity(int id) const
  400. {
  401. Entity* e = currentDimension->zEntity(id);
  402. if (e) return e;
  403. return 0;
  404. }
  405. Entity* World::getEntity(int id) const
  406. {
  407. Entity* e = currentDimension->getEntity(id);
  408. if (e) return e;
  409. return 0;
  410. }
  411. void World::removeEntity(int id)
  412. {
  413. currentDimension->removeEntity(id);
  414. }
  415. PlayerKam* World::zKamera() const
  416. {
  417. return kam;
  418. }
  419. int World::getCurrentPlayerId() const
  420. {
  421. return ownEntityId;
  422. }
  423. Entity* World::getCurrentPlayerEntity() const
  424. {
  425. return zEntity(ownEntityId);
  426. }
  427. void World::setTarget(Framework::Model3D* zTarget)
  428. {
  429. if (zTarget != currentTarget)
  430. {
  431. targetLock.lock();
  432. if (!zTarget)
  433. {
  434. selectionModel->setVisible(0);
  435. }
  436. else
  437. {
  438. selectionModel->setPosition(
  439. zTarget->getPos().x, zTarget->getPos().y, zTarget->getPos().z);
  440. Block* b = dynamic_cast<Block*>(zTarget);
  441. if (b && b->getPartOfModels())
  442. {
  443. selectionModel->setDestroyedState(b->getEffectPercentage());
  444. }
  445. else
  446. {
  447. selectionModel->setDestroyedState(0);
  448. }
  449. selectionModel->setVisible(1);
  450. }
  451. if (currentTarget)
  452. {
  453. currentTarget->setAmbientFactor(
  454. currentTarget->getAmbientFactor() - 0.2f);
  455. currentTarget->release();
  456. currentTarget = 0;
  457. }
  458. if (zTarget)
  459. {
  460. currentTarget
  461. = dynamic_cast<Framework::Model3D*>(zTarget->getThis());
  462. if (currentTarget)
  463. currentTarget->setAmbientFactor(
  464. currentTarget->getAmbientFactor() + 0.2f);
  465. }
  466. targetLock.unlock();
  467. }
  468. }
  469. void World::onChunkAdded(Point pos)
  470. {
  471. subLock.lockWrite();
  472. int index = 0;
  473. for (Point p : subscriptions)
  474. {
  475. if (p == pos)
  476. {
  477. subscriptions.remove(index);
  478. break;
  479. }
  480. index++;
  481. }
  482. subLock.unlockWrite();
  483. }
  484. Framework::Model3D* World::getCurrentTarget() const
  485. {
  486. while (targetLock.isLocked())
  487. Sleep(1);
  488. return currentTarget
  489. ? dynamic_cast<Framework::Model3D*>(currentTarget->getThis())
  490. : 0;
  491. }
  492. FactoryCraftModel* World::zSelectedEffectModel() const
  493. {
  494. return selectionModel;
  495. }
  496. Chunk* World::zChunk(Point center)
  497. {
  498. return currentDimension->zChunk(center);
  499. }
  500. Lock& World::getChunkReadLock()
  501. {
  502. return currentDimension->getReadLock();
  503. }
  504. FactoryClient* World::zClient() const
  505. {
  506. return client;
  507. }
  508. float World::getDayLightFactor() const
  509. {
  510. return dayLightFactor;
  511. }