World.cpp 17 KB

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