MandelWidget.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983
  1. #include "MandelWidget.h"
  2. #include <cmath>
  3. #include <sstream>
  4. using namespace mnd;
  5. #include <QPainter>
  6. #include <cstdio>
  7. Texture::Texture(const Bitmap<RGBColor>& bitmap, GLint param)
  8. {
  9. glGenTextures(1, &id);
  10. glBindTexture(GL_TEXTURE_2D, id);
  11. //int lineLength = (bitmap.width * 3 + 3) & ~3;
  12. /*std::unique_ptr<unsigned char[]> pixels = std::make_unique<unsigned char[]>(lineLength * bitmap.height);
  13. for (int i = 0; i < bitmap.width; i++) {
  14. for (int j = 0; j < bitmap.height; j++) {
  15. int index = i * 3 + j * lineLength;
  16. RGBColor c = bitmap.get(i, j);
  17. pixels[index] = c.r;
  18. pixels[index + 1] = c.g;
  19. pixels[index + 2] = c.b;
  20. }
  21. }*/
  22. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, int(bitmap.width), int(bitmap.height), 0, GL_RGB, GL_UNSIGNED_BYTE, reinterpret_cast<char*> (bitmap.pixels.get()));
  23. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  24. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  25. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, param);
  26. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, param);
  27. }
  28. Texture::~Texture(void)
  29. {
  30. if (id != 0)
  31. glDeleteTextures(1, &id);
  32. }
  33. Texture::Texture(Texture&& other) :
  34. id{ other.id }
  35. {
  36. other.id = 0;
  37. }
  38. Texture& Texture::operator=(Texture&& other)
  39. {
  40. this->id = other.id;
  41. other.id = 0;
  42. return *this;
  43. }
  44. void Texture::bind(void) const
  45. {
  46. glBindTexture(GL_TEXTURE_2D, id);
  47. }
  48. void Texture::drawRect(float x, float y, float width, float height)
  49. {
  50. glColor3ub(255, 255, 255);
  51. glEnable(GL_TEXTURE_2D);
  52. bind();
  53. glBegin(GL_TRIANGLE_STRIP);
  54. glTexCoord2f(0, 0);
  55. glVertex2f(x, y);
  56. glTexCoord2f(1, 0);
  57. glVertex2f(x + width, y);
  58. glTexCoord2f(0, 1);
  59. glVertex2f(x, y + height);
  60. glTexCoord2f(1, 1);
  61. glVertex2f(x + width, y + height);
  62. glEnd();
  63. glDisable(GL_TEXTURE_2D);
  64. }
  65. CellImage::~CellImage(void)
  66. {
  67. }
  68. TextureClip::~TextureClip(void)
  69. {
  70. }
  71. void TextureClip::drawRect(float x, float y, float width, float height)
  72. {
  73. glColor3ub(255, 255, 255);
  74. glEnable(GL_TEXTURE_2D);
  75. glBindTexture(GL_TEXTURE_2D, texture->getId());
  76. glBegin(GL_TRIANGLE_STRIP);
  77. glTexCoord2f(tx, ty);
  78. glVertex2f(x, y);
  79. glTexCoord2f(tx + tw, ty);
  80. glVertex2f(x + width, y);
  81. glTexCoord2f(tx, ty + th);
  82. glVertex2f(x, y + height);
  83. glTexCoord2f(tx + tw, ty + th);
  84. glVertex2f(x + width, y + height);
  85. glEnd();
  86. glDisable(GL_TEXTURE_2D);
  87. }
  88. TextureClip TextureClip::clip(float x, float y, float w, float h)
  89. {
  90. float tx = this->tx + x * this->tw;
  91. float ty = this->ty + y * this->th;
  92. float tw = this->tw * w;
  93. float th = this->th * h;
  94. return TextureClip{ this->texture, tx, ty, tw, th };
  95. }
  96. std::shared_ptr<CellImage> TextureClip::clip(short i, short j)
  97. {
  98. return std::make_shared<TextureClip>(clip(i * 0.5f, j * 0.5f, 0.5f, 0.5f));
  99. }
  100. int TextureClip::getRecalcPriority() const
  101. {
  102. return int(1.0f / tw);
  103. }
  104. QuadImage::~QuadImage(void)
  105. {
  106. }
  107. void QuadImage::drawRect(float x, float y, float width, float height)
  108. {
  109. for (int i = 0; i < 2; i++) {
  110. for (int j = 0; j < 2; j++) {
  111. this->cells[i][j]->drawRect(x + i * 0.5f * width,
  112. y + j * 0.5f * height,
  113. width * 0.5f,
  114. height * 0.5f);
  115. }
  116. }
  117. }
  118. std::shared_ptr<CellImage> QuadImage::clip(short i, short j)
  119. {
  120. return cells[i][j];
  121. }
  122. int QuadImage::getRecalcPriority() const
  123. {
  124. return 1;
  125. }
  126. TexGrid::TexGrid(MandelView& owner, int level) :
  127. owner{ owner },
  128. level{ level },
  129. dpp{ owner.getDpp(level) }
  130. {
  131. }
  132. std::pair<GridIndex, GridIndex> TexGrid::getCellIndices(mnd::Real x, mnd::Real y)
  133. {
  134. return { GridIndex(mnd::floor(x / dpp / MandelView::chunkSize)), GridIndex(mnd::floor(y / dpp / MandelView::chunkSize)) };
  135. }
  136. std::pair<mnd::Real, mnd::Real> TexGrid::getPositions(GridIndex x, GridIndex y)
  137. {
  138. return { mnd::Real(x) * dpp * MandelView::chunkSize, mnd::Real(y) * dpp * MandelView::chunkSize };
  139. }
  140. GridElement* TexGrid::getCell(GridIndex i, GridIndex j)
  141. {
  142. auto cIt = cells.find({i, j});
  143. if (cIt != cells.end()) {
  144. return cIt->second.get();
  145. }
  146. else {
  147. return nullptr;
  148. }
  149. }
  150. void TexGrid::setCell(GridIndex i, GridIndex j, std::unique_ptr<GridElement> tex)
  151. {
  152. cells[{i, j}] = std::move(tex);
  153. }
  154. void TexGrid::clearCells(void)
  155. {
  156. cells.clear();
  157. }
  158. void TexGrid::clearUncleanCells(void)
  159. {
  160. for (auto it = cells.begin(); it != cells.end();) {
  161. if (it->second->img->getRecalcPriority() > 1)
  162. cells.erase(it++);
  163. else ++it;
  164. }
  165. }
  166. void Job::run(void)
  167. {
  168. auto [absX, absY] = grid->getPositions(i, j);
  169. mnd::Real gw = grid->dpp * MandelView::chunkSize;
  170. Bitmap<float> f(MandelView::chunkSize, MandelView::chunkSize);
  171. mnd::MandelInfo mi = owner.getMandelInfo();
  172. mi.view.x = absX;
  173. mi.view.y = absY;
  174. mi.view.width = mi.view.height = gw;
  175. mi.bWidth = mi.bHeight = MandelView::chunkSize;
  176. try {
  177. generator->generate(mi, f.pixels.get());
  178. auto* rgb = new Bitmap<RGBColor>(f.map<RGBColor>([&mi, this] (float i) {
  179. return i >= mi.maxIter ? RGBColor{ 0, 0, 0 } : gradient.get(i);
  180. }));
  181. emit done(level, i, j, calcState, rgb);
  182. }
  183. catch(std::exception& ex) {
  184. printf("wat: %s?!\n", ex.what()); fflush(stdout);
  185. exit(1);
  186. }
  187. catch(...) {
  188. printf("wat?!\n"); fflush(stdout);
  189. exit(1);
  190. }
  191. }
  192. Calcer::Calcer(mnd::MandelGenerator* generator, MandelWidget& owner) :
  193. jobsMutex{ QMutex::Recursive },
  194. generator{ generator },
  195. threadPool{ std::make_unique<QThreadPool>() },
  196. owner{ owner },
  197. gradient{ owner.getGradient() }
  198. {
  199. threadPool->setMaxThreadCount(1);
  200. }
  201. void Calcer::clearAll(void)
  202. {
  203. this->threadPool->clear();
  204. }
  205. void Calcer::calc(TexGrid& grid, int level, GridIndex i, GridIndex j, int priority)
  206. {
  207. jobsMutex.lock();
  208. if (jobs.find({ level, i, j }) == jobs.end()) {
  209. Job* job = new Job(generator, gradient, owner, &grid, level, i, j, calcState);
  210. connect(job, &Job::done, this, &Calcer::redirect);
  211. connect(job, &QObject::destroyed, this, [this, level, i, j] () { this->notFinished(level, i, j); });
  212. jobs.emplace(std::tuple{level, i, j}, job);
  213. threadPool->start(job, priority);
  214. }
  215. jobsMutex.unlock();
  216. }
  217. void Calcer::setCurrentLevel(int level)
  218. {
  219. if (this->currentLevel != level) {
  220. this->currentLevel = level;
  221. std::vector<QRunnable*> toCancel;
  222. jobsMutex.lock();
  223. for (auto&[tup, job] : jobs) {
  224. auto& [level, i, j] = tup;
  225. if(level != currentLevel) {
  226. toCancel.push_back(job);
  227. }
  228. }
  229. jobsMutex.unlock();
  230. for (auto* job : toCancel) {
  231. if (threadPool->tryTake(job)) {
  232. delete job;
  233. }
  234. }
  235. }
  236. }
  237. void Calcer::notFinished(int level, GridIndex i, GridIndex j)
  238. {
  239. jobsMutex.lock();
  240. jobs.erase({ level, i, j });
  241. jobsMutex.unlock();
  242. }
  243. void Calcer::redirect(int level, GridIndex i, GridIndex j, long calcState, Bitmap<RGBColor>* bmp)
  244. {
  245. jobsMutex.lock();
  246. jobs.erase({ level, i, j });
  247. jobsMutex.unlock();
  248. if (this->calcState == calcState) {
  249. emit done(level, i, j, bmp);
  250. }
  251. else {
  252. delete bmp;
  253. }
  254. }
  255. const int MandelView::chunkSize = 256;
  256. MandelView::MandelView(mnd::MandelGenerator* generator, MandelWidget& owner) :
  257. generator{ generator },
  258. calcer{ generator, owner },
  259. owner{ owner }
  260. {
  261. Bitmap<RGBColor> emp(8, 8);
  262. for(auto i = 0; i < emp.width; i++) {
  263. for(auto j = 0; j < emp.height; j++) {
  264. if((i + j) & 0x1) { // if i+j is odd
  265. emp.get(i, j) = RGBColor{ 255, 255, 255 };
  266. }
  267. else {
  268. emp.get(i, j) = RGBColor{ 120, 120, 120 };
  269. }
  270. }
  271. }
  272. empty = std::make_unique<Texture>(emp, GL_NEAREST);
  273. connect(&calcer, &Calcer::done, this, &MandelView::cellReady);
  274. }
  275. int MandelView::getLevel(mnd::Real dpp)
  276. {
  277. return int(mnd::log2(dpp / chunkSize));
  278. }
  279. mnd::Real MandelView::getDpp(int level)
  280. {
  281. return mnd::pow(mnd::Real(2), mnd::Real(level)) * chunkSize;
  282. }
  283. TexGrid& MandelView::getGrid(int level)
  284. {
  285. auto it = levels.find(level);
  286. if (it != levels.end()) {
  287. return it->second;
  288. }
  289. else {
  290. levels.insert(std::pair<int, TexGrid>{ level, TexGrid{ *this, level } });
  291. return levels.at(level);
  292. }
  293. }
  294. void MandelView::setGenerator(mnd::MandelGenerator* generator)
  295. {
  296. if (this->generator != generator) {
  297. this->generator = generator;
  298. calcer.setGenerator(generator);
  299. clearCells();
  300. emit redrawRequested();
  301. }
  302. }
  303. void MandelView::clearCells(void)
  304. {
  305. for(auto& [level, grid] : this->levels) {
  306. grid.clearCells();
  307. }
  308. }
  309. void MandelView::garbageCollect(int level, GridIndex /*i*/, GridIndex /*j*/)
  310. {
  311. for(auto& [l, grid] : levels) {
  312. int dist = ::abs(l - level);
  313. if (dist == 1) {
  314. grid.clearUncleanCells();
  315. }
  316. if (dist > 20) {
  317. grid.clearCells();
  318. }
  319. else if (dist > 10) {
  320. if (grid.countAllocatedCells() > 50)
  321. grid.clearCells();
  322. }
  323. else if (dist > 3) {
  324. if (grid.countAllocatedCells() > 150)
  325. grid.clearCells();
  326. }
  327. else if (dist > 0) {
  328. if (grid.countAllocatedCells() > 350)
  329. grid.clearCells();
  330. }
  331. else {
  332. if (grid.countAllocatedCells() > 2500)
  333. grid.clearCells();
  334. }
  335. }
  336. }
  337. GridElement* MandelView::searchAbove(int level, GridIndex i, GridIndex j, int recursionLevel)
  338. {
  339. auto& grid = getGrid(level);
  340. auto& gridAbove = getGrid(level + 1);
  341. GridIndex ai = (i < 0 ? (i - 1) : i) / 2;
  342. GridIndex aj = (j < 0 ? (j - 1) : j) / 2;
  343. GridElement* above = gridAbove.getCell(ai, aj);
  344. if (above == nullptr && recursionLevel > 0) {
  345. auto abFound = searchAbove(level + 1, ai, aj, recursionLevel - 1);
  346. if (abFound)
  347. above = abFound;
  348. }
  349. if (above != nullptr) {
  350. auto newElement = std::make_unique<GridElement>(
  351. false, above->img->clip(short(i & 1), short(j & 1))
  352. );
  353. GridElement* ret = newElement.get();
  354. grid.setCell(i, j, std::move(newElement));
  355. return ret;
  356. }
  357. else {
  358. return nullptr;
  359. }
  360. }
  361. GridElement* MandelView::searchUnder(int level, GridIndex i, GridIndex j, int recursionLevel)
  362. {
  363. if (recursionLevel == 0)
  364. return nullptr;
  365. auto& grid = getGrid(level);
  366. auto& gridUnder = getGrid(level - 1);
  367. GridIndex ai = i * 2;
  368. GridIndex aj = j * 2;
  369. GridElement* u00 = gridUnder.getCell(ai, aj);
  370. GridElement* u01 = gridUnder.getCell(ai, aj + 1);
  371. GridElement* u10 = gridUnder.getCell(ai + 1, aj);
  372. GridElement* u11 = gridUnder.getCell(ai + 1, aj + 1);
  373. /*if ( u00 == nullptr
  374. || u01 == nullptr
  375. || u10 == nullptr
  376. || u11 == nullptr) {
  377. auto abFound = searchUnder(level + 1, ai, aj, recursionLevel - 1);
  378. if (abFound)
  379. above = abFound;
  380. }*/
  381. if ( u00 != nullptr
  382. && u01 != nullptr
  383. && u10 != nullptr
  384. && u11 != nullptr) {
  385. auto newElement = std::make_unique<GridElement>(
  386. false, std::make_shared<QuadImage>(u00->img, u01->img, u10->img, u11->img)
  387. );
  388. GridElement* ret = newElement.get();
  389. grid.setCell(i, j, std::move(newElement));
  390. return ret;
  391. }
  392. else {
  393. return nullptr;
  394. }
  395. }
  396. void MandelView::paint(const mnd::MandelViewport& mvp)
  397. {
  398. mnd::Real dpp = mvp.width / width;
  399. int level = getLevel(dpp) - 1;
  400. auto& grid = getGrid(level);
  401. mnd::Real gw = getDpp(level) * chunkSize;
  402. auto [left, top] = grid.getCellIndices(mvp.x, mvp.y);
  403. auto [right, bottom] = grid.getCellIndices(mvp.right(), mvp.bottom());
  404. garbageCollect(level, (left + right) / 2, (top + bottom) / 2);
  405. emit calcer.setCurrentLevel(level);
  406. mnd::Real w = width * gw / mvp.width;
  407. auto [realXLeft, realYTop] = grid.getPositions(left, top);
  408. realXLeft = ((realXLeft - mvp.x) * mnd::Real(width)) / mvp.width;
  409. realYTop = ((realYTop - mvp.y) * mnd::Real(height)) / mvp.height;
  410. for(GridIndex i = left; i <= right; i++) {
  411. for(GridIndex j = top; j <= bottom; j++) {
  412. mnd::Real x = w * int(i - left) + realXLeft;
  413. mnd::Real y = w * int(j - top) + realYTop;
  414. GridElement* t = grid.getCell(i, j);
  415. if (t == nullptr) {
  416. auto under = searchUnder(level, i, j, 1);
  417. if (under) {
  418. t = under;
  419. }
  420. else {
  421. auto above = searchAbove(level, i, j, 3);
  422. if (above) {
  423. t = above;
  424. }
  425. }
  426. }
  427. if (t != nullptr) {
  428. t->img->drawRect(float(x), float(y), float(w), float(w));
  429. /*glBegin(GL_LINE_LOOP);
  430. glVertex2f(float(x), float(y));
  431. glVertex2f(float(x) + float(w), float(y));
  432. glVertex2f(float(x) + float(w), float(y) + float(w));
  433. glVertex2f(float(x), float(y) + float(w));
  434. glEnd();*/
  435. if (!t->enoughResolution) {
  436. calcer.calc(grid, level, i, j, t->img->getRecalcPriority());
  437. }
  438. }
  439. else {
  440. calcer.calc(grid, level, i, j, 1000);
  441. this->empty->drawRect(float(x), float(y), float(w), float(w));
  442. }
  443. }
  444. }
  445. }
  446. void MandelView::cellReady(int level, GridIndex i, GridIndex j, Bitmap<RGBColor>* bmp)
  447. {
  448. this->getGrid(level).setCell(i, j,
  449. std::make_unique<GridElement>(true, std::make_shared<TextureClip>(std::make_shared<Texture>(*bmp))));
  450. delete bmp;
  451. emit redrawRequested();
  452. }
  453. MandelWidget::MandelWidget(mnd::MandelContext& ctxt, mnd::MandelGenerator* generator, QWidget* parent) :
  454. QOpenGLWidget{ parent },
  455. mndContext{ ctxt },
  456. generator{ generator },
  457. gradient{ Gradient::defaultGradient() }
  458. {
  459. this->setContentsMargins(0, 0, 0, 0);
  460. this->setSizePolicy(QSizePolicy::Expanding,
  461. QSizePolicy::Expanding);
  462. qRegisterMetaType<GridIndex>("GridIndex");
  463. this->format().setSwapInterval(1);
  464. /*gradient = Gradient {
  465. {
  466. { RGBColor{ 0, 0, 0 }, 0 },
  467. { RGBColor{ 180, 20, 10 }, 30 },
  468. { RGBColor{ 210, 180, 15 }, 70 },
  469. { RGBColor{ 160, 220, 45 }, 170 },
  470. { RGBColor{ 50, 150, 170 }, 300 },
  471. }
  472. };*/
  473. }
  474. MandelWidget::~MandelWidget()
  475. {
  476. }
  477. void MandelWidget::setGradient(Gradient g)
  478. {
  479. this->gradient = std::move(g);
  480. if (mandelView) {
  481. mandelView->clearCells();
  482. mandelView->calcer.changeState();
  483. }
  484. emit update();
  485. }
  486. void MandelWidget::setSmoothColoring(bool sc)
  487. {
  488. if (sc != mandelInfo.smooth) {
  489. mandelInfo.smooth = sc;
  490. if (mandelView) {
  491. mandelView->clearCells();
  492. emit update();
  493. }
  494. }
  495. }
  496. void MandelWidget::setDisplayInfo(bool di)
  497. {
  498. if (di != this->displayInfo) {
  499. this->displayInfo = di;
  500. emit update();
  501. }
  502. }
  503. void MandelWidget::setMaxIterations(int maxIter)
  504. {
  505. if (mandelInfo.maxIter != maxIter) {
  506. mandelInfo.maxIter = maxIter;
  507. if (mandelView) {
  508. mandelView->clearCells();
  509. mandelView->calcer.clearAll();
  510. mandelView->calcer.changeState();
  511. }
  512. emit update();
  513. }
  514. }
  515. void MandelWidget::setJuliaPos(const mnd::Real& x, const mnd::Real& y)
  516. {
  517. mandelInfo.juliaX = x;
  518. mandelInfo.juliaY = y;
  519. if (mandelView)
  520. mandelView->calcer.changeState();
  521. emit update();
  522. }
  523. void MandelWidget::setGenerator(mnd::MandelGenerator* generator)
  524. {
  525. if (this->generator != generator) {
  526. this->generator = generator;
  527. if (mandelView)
  528. mandelView->setGenerator(generator);
  529. }
  530. }
  531. void MandelWidget::clearAll(void)
  532. {
  533. mandelView->clearCells();
  534. mandelView->calcer.clearAll();
  535. }
  536. void MandelWidget::initializeGL(void)
  537. {
  538. this->context()->functions()->glClearColor(0, 0, 0, 0);
  539. this->context()->makeCurrent(nullptr);
  540. glDisable(GL_DEPTH_TEST);
  541. // looks not even better
  542. glEnable(GL_FRAMEBUFFER_SRGB);
  543. //glShadeModel(GL_SMOOTH);
  544. mandelView = nullptr;
  545. requestRecalc();
  546. }
  547. void MandelWidget::paintGL(void)
  548. {
  549. if (mandelView == nullptr) {
  550. mandelView = std::make_unique<MandelView>(generator, *this);
  551. QObject::connect(mandelView.get(), &MandelView::redrawRequested, this, static_cast<void(QOpenGLWidget::*)(void)>(&QOpenGLWidget::update));
  552. }
  553. int width = this->width();
  554. int height = this->height();
  555. mandelView->width = width;
  556. mandelView->height = height;
  557. glViewport(0, 0, width, height);
  558. glMatrixMode(GL_PROJECTION);
  559. glLoadIdentity();
  560. #ifdef QT_OPENGL_ES_1
  561. glOrthof(0, width, height, 0, -1.0, 1.0);
  562. #else
  563. glOrtho(0, width, height, 0, -1.0, 1.0);
  564. #endif
  565. glMatrixMode(GL_MODELVIEW);
  566. glClear(GL_COLOR_BUFFER_BIT);
  567. glLoadIdentity();
  568. updateAnimations();
  569. mandelView->paint(this->currentViewport);
  570. if (rubberbanding)
  571. drawRubberband();
  572. if (displayInfo)
  573. drawInfo();
  574. if (selectingPoint)
  575. drawPoint();
  576. }
  577. void MandelWidget::updateAnimations(void)
  578. {
  579. if (mnd::abs(currentViewport.width / targetViewport.width - 1.0) < 0.1e-5
  580. && mnd::abs(currentViewport.height / targetViewport.height - 1.0) < 0.1e-5) {
  581. // animation finished
  582. currentViewport = targetViewport;
  583. }
  584. else {
  585. auto now = std::chrono::high_resolution_clock::now();
  586. auto millis = std::chrono::duration_cast<std::chrono::milliseconds>(now - lastAnimUpdate).count();
  587. const mnd::Real factor = mnd::Real(::pow(0.97, millis));
  588. const mnd::Real one(1.0);
  589. currentViewport.x = currentViewport.x * factor + targetViewport.x * (one - factor);
  590. currentViewport.y = currentViewport.y * factor + targetViewport.y * (one - factor);
  591. currentViewport.width = currentViewport.width * factor + targetViewport.width * (one - factor);
  592. currentViewport.height = currentViewport.height * factor + targetViewport.height * (one - factor);
  593. lastAnimUpdate = now;
  594. emit update();
  595. }
  596. }
  597. void MandelWidget::drawRubberband(void)
  598. {
  599. glColor3ub(10, 200, 10);
  600. glBegin(GL_LINE_LOOP);
  601. glVertex2d(rubberband.x(), rubberband.y());
  602. glVertex2d(rubberband.right(), rubberband.y());
  603. glVertex2d(rubberband.right(), rubberband.bottom());
  604. glVertex2d(rubberband.x(), rubberband.bottom());
  605. glEnd();
  606. glEnable(GL_BLEND);
  607. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  608. glColor4f(0.1f, 0.9f, 0.1f, 0.2f);
  609. glBegin(GL_TRIANGLE_FAN);
  610. glVertex2d(rubberband.x(), rubberband.y());
  611. glVertex2d(rubberband.right(), rubberband.y());
  612. glVertex2d(rubberband.right(), rubberband.bottom());
  613. glVertex2d(rubberband.x(), rubberband.bottom());
  614. glEnd();
  615. glDisable(GL_BLEND);
  616. }
  617. void MandelWidget::drawInfo(void)
  618. {
  619. const float DIST_FROM_BORDER = 15;
  620. float maxWidth = this->width() - 2 * DIST_FROM_BORDER;
  621. mnd::Real distPerPixel = currentViewport.width / this->width();
  622. float log10 = (mnd::convert<float>(mnd::log(distPerPixel)) + ::logf(maxWidth)) / ::logf(10);
  623. mnd::Real displayDist = mnd::pow(mnd::Real(10), ::floor(log10));
  624. float pixels = mnd::convert<float>(displayDist / distPerPixel);
  625. int factor = 1;
  626. for (int i = 9; i > 1; i--) {
  627. if (pixels * i < maxWidth) {
  628. factor *= i;
  629. pixels *= i;
  630. displayDist *= i;
  631. break;
  632. }
  633. }
  634. std::stringstream dis;
  635. if (::abs(log10) < 3) {
  636. dis << mnd::convert<float>(displayDist);
  637. }
  638. else {
  639. dis << factor << "e" << int(::floor(log10));
  640. }
  641. if (maxWidth > 400) {
  642. dis << "; per pixel: " << distPerPixel;
  643. }
  644. float lineY = this->height() - DIST_FROM_BORDER;
  645. float lineXEnd = DIST_FROM_BORDER + pixels;
  646. QPainter infoPainter{ this };
  647. infoPainter.setPen(Qt::white);
  648. infoPainter.setFont(QFont("Arial", 12));
  649. infoPainter.drawLine(QPointF{ DIST_FROM_BORDER, lineY }, QPointF{ lineXEnd, lineY });
  650. infoPainter.drawLine(QPointF{ DIST_FROM_BORDER, lineY }, QPointF{ DIST_FROM_BORDER, lineY - 5 });
  651. infoPainter.drawLine(QPointF{ lineXEnd, lineY }, QPointF{ lineXEnd, lineY - 5 });
  652. infoPainter.drawText(int(DIST_FROM_BORDER), int(lineY - 20), int(lineXEnd - DIST_FROM_BORDER), 20,
  653. Qt::AlignCenter, QString::fromStdString(dis.str()));
  654. infoPainter.end();
  655. }
  656. void MandelWidget::drawPoint(void)
  657. {
  658. glColor3ub(255, 255, 255);
  659. glBegin(GL_LINES);
  660. glVertex2f(0, pointY);
  661. glVertex2f(width(), pointY);
  662. glVertex2f(pointX, 0);
  663. glVertex2f(pointX, height());
  664. glEnd();
  665. }
  666. void MandelWidget::zoom(float scale, float x, float y)
  667. {
  668. targetViewport.zoom(scale, x, y);
  669. lastAnimUpdate = std::chrono::high_resolution_clock::now();
  670. //currentViewport.zoom(scale, x, y);
  671. requestRecalc();
  672. }
  673. void MandelWidget::setViewport(const mnd::MandelViewport& viewport)
  674. {
  675. targetViewport = viewport;
  676. targetViewport.adjustAspectRatio(this->width(), this->height());
  677. currentViewport = targetViewport;
  678. //lastAnimUpdate = std::chrono::high_resolution_clock::now();
  679. //currentViewport.zoom(scale, x, y);
  680. requestRecalc();
  681. }
  682. void MandelWidget::selectPoint(void)
  683. {
  684. this->selectingPoint = true;
  685. this->setMouseTracking(true);
  686. }
  687. void MandelWidget::stopSelectingPoint(void)
  688. {
  689. this->selectingPoint = false;
  690. this->setMouseTracking(false);
  691. }
  692. void MandelWidget::requestRecalc()
  693. {
  694. emit update();
  695. }
  696. void MandelWidget::resizeEvent(QResizeEvent* re)
  697. {
  698. QOpenGLWidget::resizeEvent(re);
  699. double aspect = double(geometry().width()) / geometry().height();
  700. currentViewport.height = currentViewport.width / aspect;
  701. targetViewport = currentViewport;
  702. if (mandelView.get() != nullptr) {
  703. mandelView->width = this->width();
  704. mandelView->height = this->height();
  705. }
  706. requestRecalc();
  707. }
  708. void MandelWidget::mousePressEvent(QMouseEvent* me)
  709. {
  710. QOpenGLWidget::mousePressEvent(me);
  711. if (me->button() == Qt::RightButton) {
  712. rubberbanding = true;
  713. rubberband.setCoords(me->x(), me->y(), me->x(), me->y());
  714. emit repaint();
  715. me->accept();
  716. }
  717. else if (me->button() == Qt::LeftButton) {
  718. dragging = true;
  719. dragX = me->x();
  720. dragY = me->y();
  721. me->accept();
  722. }
  723. }
  724. void MandelWidget::mouseMoveEvent(QMouseEvent* me)
  725. {
  726. QOpenGLWidget::mouseMoveEvent(me);
  727. if (rubberbanding) {
  728. QRectF& rect = rubberband;
  729. double aspect = double(geometry().width()) / geometry().height();
  730. rect.setBottomRight(QPoint(me->x(), me->y()));
  731. if (rect.width() > rect.height() * aspect)
  732. rect.setHeight(rect.width() / aspect);
  733. else
  734. rect.setWidth(rect.height() * aspect);
  735. emit repaint();
  736. }
  737. else if (selectingPoint) {
  738. pointX = me->x();
  739. pointY = me->y();
  740. emit repaint();
  741. }
  742. else if (dragging) {
  743. double deltaX = me->x() - dragX;
  744. double deltaY = me->y() - dragY;
  745. this->currentViewport.x -= deltaX * currentViewport.width / this->width();
  746. this->currentViewport.y -= deltaY * currentViewport.height / this->height();
  747. targetViewport = currentViewport;
  748. dragX = me->x(); dragY = me->y();
  749. emit repaint();
  750. }
  751. me->accept();
  752. }
  753. void MandelWidget::mouseReleaseEvent(QMouseEvent* me)
  754. {
  755. QOpenGLWidget::mouseReleaseEvent(me);
  756. if (rubberbanding) {
  757. QRect rect = rubberband.toRect();
  758. if(rect.width() != 0 && rect.height() != 0) {
  759. QRect full = this->geometry();
  760. targetViewport.x += mnd::Real(rect.left()) * targetViewport.width / full.width();
  761. targetViewport.y += mnd::Real(rect.top()) * targetViewport.height / full.height();
  762. targetViewport.width *= mnd::Real(rect.width()) / full.width();
  763. targetViewport.height *= mnd::Real(rect.height()) / full.height();
  764. targetViewport.normalize();
  765. currentViewport = targetViewport;
  766. }
  767. requestRecalc();
  768. rubberbanding = false;
  769. }
  770. else if (selectingPoint) {
  771. selectingPoint = false;
  772. this->setMouseTracking(false);
  773. mnd::Real x = currentViewport.x + currentViewport.width * mnd::convert<mnd::Real>(float(me->x()) / width());
  774. mnd::Real y = currentViewport.y + currentViewport.height * mnd::convert<mnd::Real>(float(me->y()) / height());
  775. emit pointSelected(x, y);
  776. emit repaint();
  777. }
  778. dragging = false;
  779. //requestRecalc();
  780. }
  781. void MandelWidget::wheelEvent(QWheelEvent* we)
  782. {
  783. QOpenGLWidget::wheelEvent(we);
  784. float x = float(we->x()) / this->width();
  785. float y = float(we->y()) / this->height();
  786. float scale = ::powf(0.9975f, we->angleDelta().y());
  787. zoom(scale, x, y);
  788. if (!we->pixelDelta().isNull())
  789. this->currentViewport = this->targetViewport;
  790. we->accept();
  791. }
  792. /*void MandelWidget::viewUpdated(Bitmap<RGBColor>* bitmap)
  793. {
  794. if (bitmap != nullptr) {
  795. delete bitmap;
  796. emit repaint();
  797. }
  798. }*/