FractalZoomWidget.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  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->surface = new QOffscreenSurface(owner.context()->screen(), this);
  124. surface->create();
  125. this->context->setFormat(owner.context()->format());
  126. this->context->setScreen(owner.context()->screen());
  127. this->context->setShareContext(owner.context());
  128. bool created = this->context->create();
  129. printf("is created: %d\n", created);
  130. }
  131. void TextureUploader::upload(int level, GridIndex i, GridIndex j, Bitmap<float>* bmp)
  132. {
  133. bool isCurrent = context->makeCurrent(surface);
  134. if (!isCurrent) {
  135. printf("texture redirected");
  136. return;
  137. }
  138. auto etvImg = std::make_shared<ETVImage>(owner, context, *bmp);
  139. delete bmp;
  140. bmp = nullptr;
  141. uploaded(level, i, j, std::move(etvImg));
  142. }
  143. const int FractalZoomWidget::chunkSize = 256;
  144. FractalZoomWidget::FractalZoomWidget(QWidget* parent) :
  145. EscapeTimeVisualWidget{ parent },
  146. calcer{ *this }
  147. {
  148. qMetaTypeId<GridIndex>();
  149. setMaxIterations(250);
  150. uploader = nullptr;
  151. uploadeThread = nullptr;
  152. }
  153. void FractalZoomWidget::setViewport(const mnd::MandelViewport& viewport)
  154. {
  155. mandelInfo.view = viewport;
  156. mandelInfo.view.adjustAspectRatio(getResolutionX(), getResolutionY());
  157. update();
  158. }
  159. const mnd::MandelViewport& FractalZoomWidget::getViewport(void) const
  160. {
  161. return mandelInfo.view;
  162. }
  163. int FractalZoomWidget::getLevel(const mnd::Real& dpp) const
  164. {
  165. int exponent = (dpp / chunkSize).backend().exponent();
  166. // replace log2 with cheaper operation
  167. //return int(mnd::log2(dpp / chunkSize));
  168. return exponent + 1;
  169. }
  170. mnd::Real FractalZoomWidget::getDpp(int level) const
  171. {
  172. mnd::Real a = 1;
  173. a.backend().exponent() += level;
  174. return a * chunkSize;
  175. // return mnd::pow(mnd::Real(2), mnd::Real(level)) * chunkSize;
  176. }
  177. SliceGrid& FractalZoomWidget::getGrid(int level)
  178. {
  179. auto it = levels.find(level);
  180. if (it != levels.end()) {
  181. return it->second;
  182. }
  183. else {
  184. levels.insert(std::pair<int, SliceGrid>{ level, SliceGrid{ *this, level } });
  185. return levels.at(level);
  186. }
  187. }
  188. void FractalZoomWidget::clearCells(void)
  189. {
  190. for(auto& [level, grid] : this->levels) {
  191. grid.clearCells();
  192. }
  193. calcer.changeState();
  194. calcer.clearAll();
  195. update();
  196. }
  197. void FractalZoomWidget::garbageCollect(int level, const GridIndex& /*i*/, const GridIndex& /*j*/)
  198. {
  199. for(auto& [l, grid] : levels) {
  200. int dist = ::abs(l - level);
  201. if (dist == 1) {
  202. grid.clearUncleanCells();
  203. }
  204. if (dist > 20) {
  205. grid.clearCells();
  206. }
  207. else if (dist > 10) {
  208. if (grid.countAllocatedCells() > 50)
  209. grid.clearCells();
  210. }
  211. else if (dist > 3) {
  212. if (grid.countAllocatedCells() > 150)
  213. grid.clearCells();
  214. }
  215. else if (dist > 0) {
  216. if (grid.countAllocatedCells() > 350)
  217. grid.clearCells();
  218. }
  219. else {
  220. if (grid.countAllocatedCells() > 2500)
  221. grid.clearCells();
  222. }
  223. }
  224. }
  225. GridElement* FractalZoomWidget::searchAbove(int level,
  226. const GridIndex &i, const GridIndex &j, int recursionLevel)
  227. {
  228. auto& grid = getGrid(level);
  229. auto& gridAbove = getGrid(level + 1);
  230. GridIndex ai = (i < 0 ? (i - 1) : i) / 2;
  231. GridIndex aj = (j < 0 ? (j - 1) : j) / 2;
  232. GridElement* above = gridAbove.getCell(ai, aj);
  233. if (above == nullptr && recursionLevel > 0) {
  234. auto abFound = searchAbove(level + 1, ai, aj, recursionLevel - 1);
  235. if (abFound)
  236. above = abFound;
  237. }
  238. if (above != nullptr) {
  239. auto newElement = std::make_unique<GridElement>(
  240. false, above->img->clip(short(i & 1), short(j & 1))
  241. );
  242. GridElement* ret = newElement.get();
  243. grid.setCell(i, j, std::move(newElement));
  244. return ret;
  245. }
  246. else {
  247. return nullptr;
  248. }
  249. }
  250. GridElement* FractalZoomWidget::searchUnder(int level,
  251. const GridIndex &i, const GridIndex &j, int recursionLevel)
  252. {
  253. if (recursionLevel == 0)
  254. return nullptr;
  255. auto& grid = getGrid(level);
  256. auto& gridUnder = getGrid(level - 1);
  257. GridIndex ai = i * 2;
  258. GridIndex aj = j * 2;
  259. GridElement* u00 = gridUnder.getCell(ai, aj);
  260. GridElement* u01 = gridUnder.getCell(ai, aj + 1);
  261. GridElement* u10 = gridUnder.getCell(ai + 1, aj);
  262. GridElement* u11 = gridUnder.getCell(ai + 1, aj + 1);
  263. /*if ( u00 == nullptr
  264. || u01 == nullptr
  265. || u10 == nullptr
  266. || u11 == nullptr) {
  267. auto abFound = searchUnder(level + 1, ai, aj, recursionLevel - 1);
  268. if (abFound)
  269. above = abFound;
  270. }*/
  271. if ( u00 != nullptr
  272. && u01 != nullptr
  273. && u10 != nullptr
  274. && u11 != nullptr) {
  275. auto newElement = std::make_unique<GridElement>(
  276. false, std::make_shared<QuadImage>(u00->img, u01->img, u10->img, u11->img)
  277. );
  278. GridElement* ret = newElement.get();
  279. grid.setCell(i, j, std::move(newElement));
  280. return ret;
  281. }
  282. else {
  283. return nullptr;
  284. }
  285. }
  286. const mnd::MandelInfo& FractalZoomWidget::getMandelInfo(void) const
  287. {
  288. return mandelInfo;
  289. }
  290. mnd::MandelInfo& FractalZoomWidget::getMandelInfo(void)
  291. {
  292. return mandelInfo;
  293. }
  294. void FractalZoomWidget::setGenerator(mnd::MandelGenerator* gen)
  295. {
  296. bool changed = true;
  297. if (this->generator == gen)
  298. changed = false;
  299. this->generator = gen;
  300. if (changed) {
  301. clearCells();
  302. update();
  303. }
  304. }
  305. mnd::MandelGenerator* FractalZoomWidget::getGenerator(void) const
  306. {
  307. return generator;
  308. }
  309. void FractalZoomWidget::zoom(float factor)
  310. {
  311. mandelInfo.view.zoomCenter(factor);
  312. update();
  313. }
  314. void FractalZoomWidget::setSmoothColoring(bool smooth)
  315. {
  316. if (mandelInfo.smooth != smooth) {
  317. mandelInfo.smooth = smooth;
  318. clearCells();
  319. update();
  320. }
  321. }
  322. void FractalZoomWidget::setMaxIterations(int maxIterations)
  323. {
  324. if (mandelInfo.maxIter != maxIterations) {
  325. mandelInfo.maxIter = maxIterations;
  326. EscapeTimeVisualWidget::setMaxIterationCutoff(float(maxIterations));
  327. clearCells();
  328. update();
  329. }
  330. }
  331. void FractalZoomWidget::initializeGL(void)
  332. {
  333. EscapeTimeVisualWidget::initializeGL();
  334. Bitmap<float> empty{ 1, 1 };
  335. empty.get(0, 0) = 0.0f;
  336. emptyImage = new ETVImage(*this, empty);
  337. if (useUploadThread) {
  338. uploader = new TextureUploader(*this);
  339. uploadeThread = new QThread(this);
  340. uploadeThread->start();
  341. uploader->moveToThread(uploadeThread);
  342. connect(&calcer, &Calcer::done, uploader, &TextureUploader::upload);
  343. connect(uploader, &TextureUploader::uploaded, this, &FractalZoomWidget::cellReadyTex);
  344. }
  345. else {
  346. connect(&calcer, &Calcer::done, this, &FractalZoomWidget::cellReady);
  347. }
  348. }
  349. void FractalZoomWidget::resizeGL(int w, int h)
  350. {
  351. EscapeTimeVisualWidget::resizeGL(w, h);
  352. mandelInfo.view.height = mandelInfo.view.width * h / w;
  353. }
  354. void FractalZoomWidget::paintGL(void)
  355. {
  356. EscapeTimeVisualWidget::paintGL();
  357. /*ETVImage etvi{ *this };
  358. auto& gl = *this->context()->functions();
  359. gl.glClearColor(0.0, 0.2, 0.0, 1.0);
  360. gl.glClear(GL_COLOR_BUFFER_BIT);
  361. etvi.draw(100, 100, 700, 700);*/
  362. ////////////////////
  363. int width = getResolutionX();
  364. int height = getResolutionY();
  365. auto& mvp = mandelInfo.view;
  366. mnd::Real dpp = mvp.width / width;
  367. int level = getLevel(dpp) - 1;
  368. auto& grid = getGrid(level);
  369. mnd::Real gw = getDpp(level) * chunkSize;
  370. auto [left, top] = grid.getCellIndices(mvp.x, mvp.y);
  371. auto [right, bottom] = grid.getCellIndices(mvp.right(), mvp.bottom());
  372. garbageCollect(level, (left + right) / 2, (top + bottom) / 2);
  373. emit calcer.setCurrentLevel(level);
  374. mnd::Real w = width * gw / mvp.width;
  375. auto [realXLeft, realYTop] = grid.getPositions(left, top);
  376. realXLeft = ((realXLeft - mvp.x) * mnd::Real(width)) / mvp.width;
  377. realYTop = ((realYTop - mvp.y) * mnd::Real(height)) / mvp.height;
  378. for(GridIndex i = left; i <= right; i++) {
  379. for(GridIndex j = top; j <= bottom; j++) {
  380. mnd::Real x = w * int(i - left) + realXLeft;
  381. mnd::Real y = w * int(j - top) + realYTop;
  382. GridElement* t = grid.getCell(i, j);
  383. if (t == nullptr) {
  384. auto under = searchUnder(level, i, j, 1);
  385. if (under) {
  386. t = under;
  387. }
  388. else {
  389. auto above = searchAbove(level, i, j, 3);
  390. if (above) {
  391. t = above;
  392. }
  393. }
  394. }
  395. if (t != nullptr) {
  396. if (!t->enoughResolution) {
  397. auto under = searchUnder(level, i, j, 1);
  398. if (under) {
  399. t = under;
  400. }
  401. calcer.calc(grid, level, i, j, t->img->getRecalcPriority());
  402. }
  403. t->img->drawRect(float(x), float(y), float(w), float(w));
  404. }
  405. else {
  406. calcer.calc(grid, level, i, j, 1000);
  407. if (emptyImage)
  408. emptyImage->draw(float(x), float(y), float(w), float(w));
  409. }
  410. }
  411. }
  412. }
  413. void FractalZoomWidget::cellReady(int level, GridIndex i, GridIndex j, Bitmap<float>* bmp)
  414. {
  415. this->getGrid(level).setCell(i, j,
  416. std::make_unique<GridElement>(true, std::make_shared<ImageClip>(std::make_shared<ETVImage>(*this, *bmp))));
  417. delete bmp;
  418. emit update();
  419. }
  420. void FractalZoomWidget::cellReadyTex(int level, GridIndex i, GridIndex j, std::shared_ptr<ETVImage> img)
  421. {
  422. this->getGrid(level).setCell(i, j,
  423. std::make_unique<GridElement>(true, std::make_shared<ImageClip>(std::move(img))));
  424. emit update();
  425. }