FractalZoomWidget.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  1. #include "FractalZoomWidget.h"
  2. #include <QOpenGLContext>
  3. #include <QOpenGLFunctions>
  4. SliceGrid::SliceGrid(FractalZoomWidget& owner, int level) :
  5. owner{ owner },
  6. level{ level },
  7. dpp{ owner.getDpp(level) }
  8. {
  9. }
  10. std::pair<GridIndex, GridIndex> SliceGrid::getCellIndices(mnd::Real x, mnd::Real y)
  11. {
  12. return {
  13. GridIndex(mnd::floor(x / dpp / FractalZoomWidget::chunkSize)),
  14. GridIndex(mnd::floor(y / dpp / FractalZoomWidget::chunkSize))
  15. };
  16. }
  17. std::pair<mnd::Real, mnd::Real> SliceGrid::getPositions(GridIndex x, GridIndex y)
  18. {
  19. return {
  20. mnd::Real(x) * dpp * FractalZoomWidget::chunkSize,
  21. mnd::Real(y) * dpp * FractalZoomWidget::chunkSize
  22. };
  23. }
  24. GridElement* SliceGrid::getCell(GridIndex i, GridIndex j)
  25. {
  26. auto cIt = cells.find({i, j});
  27. if (cIt != cells.end()) {
  28. return cIt->second.get();
  29. }
  30. else {
  31. return nullptr;
  32. }
  33. }
  34. void SliceGrid::setCell(GridIndex i, GridIndex j, std::unique_ptr<GridElement> tex)
  35. {
  36. cells[{i, j}] = std::move(tex);
  37. }
  38. void SliceGrid::clearCells(void)
  39. {
  40. cells.clear();
  41. }
  42. void SliceGrid::clearUncleanCells(void)
  43. {
  44. for (auto it = cells.begin(); it != cells.end();) {
  45. if (it->second->img->getRecalcPriority() > 1)
  46. cells.erase(it++);
  47. else ++it;
  48. }
  49. }
  50. Calcer::Calcer(FractalZoomWidget& owner) :
  51. jobsMutex{ QMutex::Recursive },
  52. threadPool{ new QThreadPool(this) },
  53. owner{ owner }
  54. {
  55. threadPool->setMaxThreadCount(1);
  56. }
  57. void Calcer::clearAll(void)
  58. {
  59. this->threadPool->clear();
  60. }
  61. void Calcer::calc(SliceGrid& grid, int level, GridIndex i, GridIndex j, int priority)
  62. {
  63. jobsMutex.lock();
  64. if (jobs.find({ level, i, j }) == jobs.end()) {
  65. CalcJob* job = new CalcJob(owner, owner.getGenerator(), &grid, level, i, j, calcState);
  66. connect(job, &CalcJob::done, this, &Calcer::redirect);
  67. connect(job, &CalcJob::failed, this, &Calcer::jobFailed);
  68. connect(job, &QObject::destroyed, this, [this, level, i, j] () { this->notFinished(level, i, j); });
  69. jobs.emplace(std::tuple{ level, i, j }, job);
  70. threadPool->start(job, priority);
  71. }
  72. jobsMutex.unlock();
  73. }
  74. void Calcer::setCurrentLevel(int level)
  75. {
  76. if (this->currentLevel != level) {
  77. this->currentLevel = level;
  78. std::vector<QRunnable*> toCancel;
  79. jobsMutex.lock();
  80. for (auto&[tup, job] : jobs) {
  81. auto& [level, i, j] = tup;
  82. if(level != currentLevel) {
  83. toCancel.push_back(job);
  84. }
  85. }
  86. jobsMutex.unlock();
  87. for (auto* job : toCancel) {
  88. if (threadPool->tryTake(job)) {
  89. delete job;
  90. }
  91. }
  92. }
  93. }
  94. void Calcer::notFinished(int level, GridIndex i, GridIndex j)
  95. {
  96. jobsMutex.lock();
  97. jobs.erase({ level, i, j });
  98. jobsMutex.unlock();
  99. }
  100. void Calcer::jobFailed(int level, GridIndex i, GridIndex j)
  101. {
  102. jobsMutex.lock();
  103. jobs.erase({ level, i, j });
  104. jobsMutex.unlock();
  105. }
  106. void Calcer::redirect(int level, GridIndex i, GridIndex j, Bitmap<float>* bmp)
  107. {
  108. jobsMutex.lock();
  109. jobs.erase({ level, i, j });
  110. jobsMutex.unlock();
  111. if (this->calcState == calcState) { // TODO remove invalid results correctly
  112. emit done(level, i, j, bmp);
  113. }
  114. else {
  115. delete bmp;
  116. }
  117. }
  118. TextureUploader::TextureUploader(EscapeTimeVisualWidget& shareWith, QObject* parent) :
  119. QThread{ parent },
  120. owner{ shareWith }
  121. {
  122. this->context = new QOpenGLContext(this);
  123. this->context->setFormat(owner.context()->format());
  124. this->context->setScreen(owner.context()->screen());
  125. this->context->setShareContext(owner.context());
  126. bool created = this->context->create();
  127. }
  128. void TextureUploader::upload(int level, GridIndex i, GridIndex j, Bitmap<float>* bmp)
  129. {
  130. auto etvImg = std::make_shared<ETVImage>(owner, *bmp);
  131. delete bmp;
  132. bmp = nullptr;
  133. uploaded(level, i, j, std::move(etvImg));
  134. }
  135. const int FractalZoomWidget::chunkSize = 256;
  136. FractalZoomWidget::FractalZoomWidget(QWidget* parent) :
  137. EscapeTimeVisualWidget{ parent },
  138. calcer{ *this }
  139. {
  140. qMetaTypeId<GridIndex>();
  141. setMaxIterations(250);
  142. uploader = nullptr;
  143. uploadeThread = nullptr;
  144. }
  145. void FractalZoomWidget::setViewport(const mnd::MandelViewport& viewport)
  146. {
  147. mandelInfo.view = viewport;
  148. mandelInfo.view.adjustAspectRatio(getResolutionX(), getResolutionY());
  149. update();
  150. }
  151. const mnd::MandelViewport& FractalZoomWidget::getViewport(void) const
  152. {
  153. return mandelInfo.view;
  154. }
  155. int FractalZoomWidget::getLevel(const mnd::Real& dpp) const
  156. {
  157. int exponent = (dpp / chunkSize).backend().exponent();
  158. // replace log2 with cheaper operation
  159. //return int(mnd::log2(dpp / chunkSize));
  160. return exponent + 1;
  161. }
  162. mnd::Real FractalZoomWidget::getDpp(int level) const
  163. {
  164. mnd::Real a = 1;
  165. a.backend().exponent() += level;
  166. return a * chunkSize;
  167. // return mnd::pow(mnd::Real(2), mnd::Real(level)) * chunkSize;
  168. }
  169. SliceGrid& FractalZoomWidget::getGrid(int level)
  170. {
  171. auto it = levels.find(level);
  172. if (it != levels.end()) {
  173. return it->second;
  174. }
  175. else {
  176. levels.insert(std::pair<int, SliceGrid>{ level, SliceGrid{ *this, level } });
  177. return levels.at(level);
  178. }
  179. }
  180. void FractalZoomWidget::clearCells(void)
  181. {
  182. for(auto& [level, grid] : this->levels) {
  183. grid.clearCells();
  184. }
  185. calcer.changeState();
  186. calcer.clearAll();
  187. update();
  188. }
  189. void FractalZoomWidget::garbageCollect(int level, const GridIndex& /*i*/, const GridIndex& /*j*/)
  190. {
  191. for(auto& [l, grid] : levels) {
  192. int dist = ::abs(l - level);
  193. if (dist == 1) {
  194. grid.clearUncleanCells();
  195. }
  196. if (dist > 20) {
  197. grid.clearCells();
  198. }
  199. else if (dist > 10) {
  200. if (grid.countAllocatedCells() > 50)
  201. grid.clearCells();
  202. }
  203. else if (dist > 3) {
  204. if (grid.countAllocatedCells() > 150)
  205. grid.clearCells();
  206. }
  207. else if (dist > 0) {
  208. if (grid.countAllocatedCells() > 350)
  209. grid.clearCells();
  210. }
  211. else {
  212. if (grid.countAllocatedCells() > 2500)
  213. grid.clearCells();
  214. }
  215. }
  216. }
  217. GridElement* FractalZoomWidget::searchAbove(int level,
  218. const GridIndex &i, const GridIndex &j, int recursionLevel)
  219. {
  220. auto& grid = getGrid(level);
  221. auto& gridAbove = getGrid(level + 1);
  222. GridIndex ai = (i < 0 ? (i - 1) : i) / 2;
  223. GridIndex aj = (j < 0 ? (j - 1) : j) / 2;
  224. GridElement* above = gridAbove.getCell(ai, aj);
  225. if (above == nullptr && recursionLevel > 0) {
  226. auto abFound = searchAbove(level + 1, ai, aj, recursionLevel - 1);
  227. if (abFound)
  228. above = abFound;
  229. }
  230. if (above != nullptr) {
  231. auto newElement = std::make_unique<GridElement>(
  232. false, above->img->clip(short(i & 1), short(j & 1))
  233. );
  234. GridElement* ret = newElement.get();
  235. grid.setCell(i, j, std::move(newElement));
  236. return ret;
  237. }
  238. else {
  239. return nullptr;
  240. }
  241. }
  242. GridElement* FractalZoomWidget::searchUnder(int level,
  243. const GridIndex &i, const GridIndex &j, int recursionLevel)
  244. {
  245. if (recursionLevel == 0)
  246. return nullptr;
  247. auto& grid = getGrid(level);
  248. auto& gridUnder = getGrid(level - 1);
  249. GridIndex ai = i * 2;
  250. GridIndex aj = j * 2;
  251. GridElement* u00 = gridUnder.getCell(ai, aj);
  252. GridElement* u01 = gridUnder.getCell(ai, aj + 1);
  253. GridElement* u10 = gridUnder.getCell(ai + 1, aj);
  254. GridElement* u11 = gridUnder.getCell(ai + 1, aj + 1);
  255. /*if ( u00 == nullptr
  256. || u01 == nullptr
  257. || u10 == nullptr
  258. || u11 == nullptr) {
  259. auto abFound = searchUnder(level + 1, ai, aj, recursionLevel - 1);
  260. if (abFound)
  261. above = abFound;
  262. }*/
  263. if ( u00 != nullptr
  264. && u01 != nullptr
  265. && u10 != nullptr
  266. && u11 != nullptr) {
  267. auto newElement = std::make_unique<GridElement>(
  268. false, std::make_shared<QuadImage>(u00->img, u01->img, u10->img, u11->img)
  269. );
  270. GridElement* ret = newElement.get();
  271. grid.setCell(i, j, std::move(newElement));
  272. return ret;
  273. }
  274. else {
  275. return nullptr;
  276. }
  277. }
  278. const mnd::MandelInfo& FractalZoomWidget::getMandelInfo(void) const
  279. {
  280. return mandelInfo;
  281. }
  282. mnd::MandelInfo& FractalZoomWidget::getMandelInfo(void)
  283. {
  284. return mandelInfo;
  285. }
  286. void FractalZoomWidget::setGenerator(mnd::MandelGenerator* gen)
  287. {
  288. bool changed = true;
  289. if (this->generator == gen)
  290. changed = false;
  291. this->generator = gen;
  292. if (changed) {
  293. clearCells();
  294. update();
  295. }
  296. }
  297. mnd::MandelGenerator* FractalZoomWidget::getGenerator(void) const
  298. {
  299. return generator;
  300. }
  301. void FractalZoomWidget::zoom(float factor)
  302. {
  303. mandelInfo.view.zoomCenter(factor);
  304. update();
  305. }
  306. void FractalZoomWidget::setSmoothColoring(bool smooth)
  307. {
  308. if (mandelInfo.smooth != smooth) {
  309. mandelInfo.smooth = smooth;
  310. clearCells();
  311. update();
  312. }
  313. }
  314. void FractalZoomWidget::setMaxIterations(int maxIterations)
  315. {
  316. if (mandelInfo.maxIter != maxIterations) {
  317. mandelInfo.maxIter = maxIterations;
  318. EscapeTimeVisualWidget::setMaxIterationCutoff(float(maxIterations));
  319. clearCells();
  320. update();
  321. }
  322. }
  323. void FractalZoomWidget::initializeGL(void)
  324. {
  325. EscapeTimeVisualWidget::initializeGL();
  326. Bitmap<float> empty{ 1, 1 };
  327. empty.get(0, 0) = 0.0f;
  328. emptyImage = new ETVImage(*this, empty);
  329. if (useUploadThread) {
  330. uploader = new TextureUploader(*this, this);
  331. uploadeThread = new QThread(this);
  332. uploader->moveToThread(uploadeThread);
  333. uploadeThread->start();
  334. connect(&calcer, &Calcer::done, uploader, &TextureUploader::upload);
  335. connect(uploader, &TextureUploader::uploaded, this, &FractalZoomWidget::cellReadyTex);
  336. }
  337. else {
  338. connect(&calcer, &Calcer::done, this, &FractalZoomWidget::cellReady);
  339. }
  340. }
  341. void FractalZoomWidget::resizeGL(int w, int h)
  342. {
  343. EscapeTimeVisualWidget::resizeGL(w, h);
  344. mandelInfo.view.height = mandelInfo.view.width * h / w;
  345. }
  346. void FractalZoomWidget::paintGL(void)
  347. {
  348. EscapeTimeVisualWidget::paintGL();
  349. /*ETVImage etvi{ *this };
  350. auto& gl = *this->context()->functions();
  351. gl.glClearColor(0.0, 0.2, 0.0, 1.0);
  352. gl.glClear(GL_COLOR_BUFFER_BIT);
  353. etvi.draw(100, 100, 700, 700);*/
  354. ////////////////////
  355. int width = getResolutionX();
  356. int height = getResolutionY();
  357. auto& mvp = mandelInfo.view;
  358. mnd::Real dpp = mvp.width / width;
  359. int level = getLevel(dpp) - 1;
  360. auto& grid = getGrid(level);
  361. mnd::Real gw = getDpp(level) * chunkSize;
  362. auto [left, top] = grid.getCellIndices(mvp.x, mvp.y);
  363. auto [right, bottom] = grid.getCellIndices(mvp.right(), mvp.bottom());
  364. garbageCollect(level, (left + right) / 2, (top + bottom) / 2);
  365. emit calcer.setCurrentLevel(level);
  366. mnd::Real w = width * gw / mvp.width;
  367. auto [realXLeft, realYTop] = grid.getPositions(left, top);
  368. realXLeft = ((realXLeft - mvp.x) * mnd::Real(width)) / mvp.width;
  369. realYTop = ((realYTop - mvp.y) * mnd::Real(height)) / mvp.height;
  370. for(GridIndex i = left; i <= right; i++) {
  371. for(GridIndex j = top; j <= bottom; j++) {
  372. mnd::Real x = w * int(i - left) + realXLeft;
  373. mnd::Real y = w * int(j - top) + realYTop;
  374. GridElement* t = grid.getCell(i, j);
  375. if (t == nullptr) {
  376. auto under = searchUnder(level, i, j, 1);
  377. if (under) {
  378. t = under;
  379. }
  380. else {
  381. auto above = searchAbove(level, i, j, 3);
  382. if (above) {
  383. t = above;
  384. }
  385. }
  386. }
  387. if (t != nullptr) {
  388. if (!t->enoughResolution) {
  389. auto under = searchUnder(level, i, j, 1);
  390. if (under) {
  391. t = under;
  392. }
  393. calcer.calc(grid, level, i, j, t->img->getRecalcPriority());
  394. }
  395. t->img->drawRect(float(x), float(y), float(w), float(w));
  396. }
  397. else {
  398. calcer.calc(grid, level, i, j, 1000);
  399. if (emptyImage)
  400. emptyImage->draw(float(x), float(y), float(w), float(w));
  401. }
  402. }
  403. }
  404. }
  405. void FractalZoomWidget::cellReady(int level, GridIndex i, GridIndex j, Bitmap<float>* bmp)
  406. {
  407. this->getGrid(level).setCell(i, j,
  408. std::make_unique<GridElement>(true, std::make_shared<ImageClip>(std::make_shared<ETVImage>(*this, *bmp))));
  409. delete bmp;
  410. emit update();
  411. }
  412. void FractalZoomWidget::cellReadyTex(int level, GridIndex i, GridIndex j, std::shared_ptr<ETVImage> img)
  413. {
  414. this->getGrid(level).setCell(i, j,
  415. std::make_unique<GridElement>(true, std::make_shared<ImageClip>(std::move(img))));
  416. emit update();
  417. }