MandelWidget.cpp 23 KB

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