MandelWidget.cpp 26 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010
  1. #include "MandelWidget.h"
  2. #include <cmath>
  3. #include <sstream>
  4. #include <QStyle>
  5. #include <QStyleOption>
  6. #include <QOpenGLShader>
  7. #include <QOpenGLShaderProgram>
  8. using namespace mnd;
  9. #include <cstdio>
  10. Texture::Texture(QOpenGLFunctions_2_0& gl, const Bitmap<RGBColor>& bitmap, GLint param) :
  11. gl{ gl }
  12. {
  13. gl.glGenTextures(1, &id);
  14. gl.glBindTexture(GL_TEXTURE_2D, id);
  15. //int lineLength = (bitmap.width * 3 + 3) & ~3;
  16. /*std::unique_ptr<unsigned char[]> pixels = std::make_unique<unsigned char[]>(lineLength * bitmap.height);
  17. for (int i = 0; i < bitmap.width; i++) {
  18. for (int j = 0; j < bitmap.height; j++) {
  19. int index = i * 3 + j * lineLength;
  20. RGBColor c = bitmap.get(i, j);
  21. pixels[index] = c.r;
  22. pixels[index + 1] = c.g;
  23. pixels[index + 2] = c.b;
  24. }
  25. }*/
  26. gl.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()));
  27. gl.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  28. gl.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  29. gl.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, param);
  30. gl.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, param);
  31. }
  32. Texture::~Texture(void)
  33. {
  34. if (id != 0)
  35. gl.glDeleteTextures(1, &id);
  36. }
  37. Texture::Texture(Texture&& other) :
  38. id{ other.id },
  39. gl{ other.gl }
  40. {
  41. other.id = 0;
  42. }
  43. void Texture::bind(void) const
  44. {
  45. gl.glBindTexture(GL_TEXTURE_2D, id);
  46. }
  47. void Texture::drawRect(float x, float y, float width, float height)
  48. {
  49. gl.glColor3ub(255, 255, 255);
  50. gl.glEnable(GL_TEXTURE_2D);
  51. bind();
  52. gl.glBegin(GL_TRIANGLE_STRIP);
  53. gl.glTexCoord2f(0, 0);
  54. gl.glVertex2f(x, y);
  55. gl.glTexCoord2f(1, 0);
  56. gl.glVertex2f(x + width, y);
  57. gl.glTexCoord2f(0, 1);
  58. gl.glVertex2f(x, y + height);
  59. gl.glTexCoord2f(1, 1);
  60. gl.glVertex2f(x + width, y + height);
  61. gl.glEnd();
  62. gl.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. auto& gl = texture->gl;
  73. gl.glColor3ub(255, 255, 255);
  74. gl.glEnable(GL_TEXTURE_2D);
  75. gl.glBindTexture(GL_TEXTURE_2D, texture->getId());
  76. gl.glBegin(GL_TRIANGLE_STRIP);
  77. gl.glTexCoord2f(tx, ty);
  78. gl.glVertex2f(x, y);
  79. gl.glTexCoord2f(tx + tw, ty);
  80. gl.glVertex2f(x + width, y);
  81. gl.glTexCoord2f(tx, ty + th);
  82. gl.glVertex2f(x, y + height);
  83. gl.glTexCoord2f(tx + tw, ty + th);
  84. gl.glVertex2f(x + width, y + height);
  85. gl.glEnd();
  86. gl.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. Bitmap<RGBColor> emp(1, 1);
  273. emp.get(0, 0) = RGBColor{ 0, 0, 0 };
  274. auto& gl = *QOpenGLContext::currentContext()->versionFunctions<QOpenGLFunctions_2_0>();
  275. empty = std::make_unique<Texture>(gl, emp, GL_NEAREST);
  276. connect(&calcer, &Calcer::done, this, &MandelView::cellReady);
  277. }
  278. int MandelView::getLevel(mnd::Real dpp)
  279. {
  280. return int(mnd::log2(dpp / chunkSize));
  281. }
  282. mnd::Real MandelView::getDpp(int level)
  283. {
  284. return mnd::pow(mnd::Real(2), mnd::Real(level)) * chunkSize;
  285. }
  286. TexGrid& MandelView::getGrid(int level)
  287. {
  288. auto it = levels.find(level);
  289. if (it != levels.end()) {
  290. return it->second;
  291. }
  292. else {
  293. levels.insert(std::pair<int, TexGrid>{ level, TexGrid{ *this, level } });
  294. return levels.at(level);
  295. }
  296. }
  297. void MandelView::setGenerator(mnd::MandelGenerator* generator)
  298. {
  299. if (this->generator != generator) {
  300. this->generator = generator;
  301. calcer.setGenerator(generator);
  302. clearCells();
  303. emit redrawRequested();
  304. }
  305. }
  306. void MandelView::clearCells(void)
  307. {
  308. for(auto& [level, grid] : this->levels) {
  309. grid.clearCells();
  310. }
  311. }
  312. void MandelView::garbageCollect(int level, GridIndex /*i*/, GridIndex /*j*/)
  313. {
  314. for(auto& [l, grid] : levels) {
  315. int dist = ::abs(l - level);
  316. if (dist == 1) {
  317. grid.clearUncleanCells();
  318. }
  319. if (dist > 20) {
  320. grid.clearCells();
  321. }
  322. else if (dist > 10) {
  323. if (grid.countAllocatedCells() > 50)
  324. grid.clearCells();
  325. }
  326. else if (dist > 3) {
  327. if (grid.countAllocatedCells() > 150)
  328. grid.clearCells();
  329. }
  330. else if (dist > 0) {
  331. if (grid.countAllocatedCells() > 350)
  332. grid.clearCells();
  333. }
  334. else {
  335. if (grid.countAllocatedCells() > 2500)
  336. grid.clearCells();
  337. }
  338. }
  339. }
  340. GridElement* MandelView::searchAbove(int level, GridIndex i, GridIndex j, int recursionLevel)
  341. {
  342. auto& grid = getGrid(level);
  343. auto& gridAbove = getGrid(level + 1);
  344. GridIndex ai = (i < 0 ? (i - 1) : i) / 2;
  345. GridIndex aj = (j < 0 ? (j - 1) : j) / 2;
  346. GridElement* above = gridAbove.getCell(ai, aj);
  347. if (above == nullptr && recursionLevel > 0) {
  348. auto abFound = searchAbove(level + 1, ai, aj, recursionLevel - 1);
  349. if (abFound)
  350. above = abFound;
  351. }
  352. if (above != nullptr) {
  353. auto newElement = std::make_unique<GridElement>(
  354. false, above->img->clip(short(i & 1), short(j & 1))
  355. );
  356. GridElement* ret = newElement.get();
  357. grid.setCell(i, j, std::move(newElement));
  358. return ret;
  359. }
  360. else {
  361. return nullptr;
  362. }
  363. }
  364. GridElement* MandelView::searchUnder(int level, GridIndex i, GridIndex j, int recursionLevel)
  365. {
  366. if (recursionLevel == 0)
  367. return nullptr;
  368. auto& grid = getGrid(level);
  369. auto& gridUnder = getGrid(level - 1);
  370. GridIndex ai = i * 2;
  371. GridIndex aj = j * 2;
  372. GridElement* u00 = gridUnder.getCell(ai, aj);
  373. GridElement* u01 = gridUnder.getCell(ai, aj + 1);
  374. GridElement* u10 = gridUnder.getCell(ai + 1, aj);
  375. GridElement* u11 = gridUnder.getCell(ai + 1, aj + 1);
  376. /*if ( u00 == nullptr
  377. || u01 == nullptr
  378. || u10 == nullptr
  379. || u11 == nullptr) {
  380. auto abFound = searchUnder(level + 1, ai, aj, recursionLevel - 1);
  381. if (abFound)
  382. above = abFound;
  383. }*/
  384. if ( u00 != nullptr
  385. && u01 != nullptr
  386. && u10 != nullptr
  387. && u11 != nullptr) {
  388. auto newElement = std::make_unique<GridElement>(
  389. false, std::make_shared<QuadImage>(u00->img, u01->img, u10->img, u11->img)
  390. );
  391. GridElement* ret = newElement.get();
  392. grid.setCell(i, j, std::move(newElement));
  393. return ret;
  394. }
  395. else {
  396. return nullptr;
  397. }
  398. }
  399. void MandelView::paint(const mnd::MandelViewport& mvp, QPainter& qp)
  400. { mnd::Real dpp = mvp.width / width;
  401. int level = getLevel(dpp) - 1;
  402. auto& grid = getGrid(level);
  403. mnd::Real gw = getDpp(level) * chunkSize;
  404. auto [left, top] = grid.getCellIndices(mvp.x, mvp.y);
  405. auto [right, bottom] = grid.getCellIndices(mvp.right(), mvp.bottom());
  406. garbageCollect(level, (left + right) / 2, (top + bottom) / 2);
  407. emit calcer.setCurrentLevel(level);
  408. mnd::Real w = width * gw / mvp.width;
  409. auto [realXLeft, realYTop] = grid.getPositions(left, top);
  410. realXLeft = ((realXLeft - mvp.x) * mnd::Real(width)) / mvp.width;
  411. realYTop = ((realYTop - mvp.y) * mnd::Real(height)) / mvp.height;
  412. for(GridIndex i = left; i <= right; i++) {
  413. for(GridIndex j = top; j <= bottom; j++) {
  414. mnd::Real x = w * int(i - left) + realXLeft;
  415. mnd::Real y = w * int(j - top) + realYTop;
  416. GridElement* t = grid.getCell(i, j);
  417. if (t == nullptr) {
  418. auto under = searchUnder(level, i, j, 1);
  419. if (under) {
  420. t = under;
  421. }
  422. else {
  423. auto above = searchAbove(level, i, j, 3);
  424. if (above) {
  425. t = above;
  426. }
  427. }
  428. }
  429. if (t != nullptr) {
  430. t->img->drawRect(float(x), float(y), float(w), float(w));
  431. /*glBegin(GL_LINE_LOOP);
  432. glVertex2f(float(x), float(y));
  433. glVertex2f(float(x) + float(w), float(y));
  434. glVertex2f(float(x) + float(w), float(y) + float(w));
  435. glVertex2f(float(x), float(y) + float(w));
  436. glEnd();*/
  437. if (!t->enoughResolution) {
  438. calcer.calc(grid, level, i, j, t->img->getRecalcPriority());
  439. }
  440. }
  441. else {
  442. calcer.calc(grid, level, i, j, 1000);
  443. this->empty->drawRect(float(x), float(y), float(w), float(w));
  444. }
  445. }
  446. }
  447. }
  448. void MandelView::cellReady(int level, GridIndex i, GridIndex j, Bitmap<RGBColor>* bmp)
  449. {
  450. auto& gl = *QOpenGLContext::currentContext()->versionFunctions<QOpenGLFunctions_2_0>();
  451. this->getGrid(level).setCell(i, j,
  452. std::make_unique<GridElement>(true, std::make_shared<TextureClip>(std::make_shared<Texture>(gl, *bmp))));
  453. delete bmp;
  454. emit redrawRequested();
  455. }
  456. MandelWidget::MandelWidget(mnd::MandelContext& ctxt, mnd::MandelGenerator* generator, QWidget* parent) :
  457. QOpenGLWidget{ parent },
  458. mndContext{ ctxt },
  459. generator{ generator },
  460. gradient{ Gradient::defaultGradient() }
  461. {
  462. this->setContentsMargins(0, 0, 0, 0);
  463. this->setSizePolicy(QSizePolicy::Expanding,
  464. QSizePolicy::Expanding);
  465. qRegisterMetaType<GridIndex>("GridIndex");
  466. this->format().setSwapInterval(1);
  467. }
  468. MandelWidget::~MandelWidget()
  469. {
  470. }
  471. void MandelWidget::setGradient(Gradient g)
  472. {
  473. this->gradient = std::move(g);
  474. if (mandelView) {
  475. mandelView->clearCells();
  476. mandelView->calcer.changeState();
  477. }
  478. emit update();
  479. }
  480. void MandelWidget::setSmoothColoring(bool sc)
  481. {
  482. if (sc != mandelInfo.smooth) {
  483. mandelInfo.smooth = sc;
  484. if (mandelView) {
  485. mandelView->clearCells();
  486. emit update();
  487. }
  488. }
  489. }
  490. void MandelWidget::setDisplayInfo(bool di)
  491. {
  492. if (di != this->displayInfo) {
  493. this->displayInfo = di;
  494. emit update();
  495. }
  496. }
  497. void MandelWidget::setMaxIterations(int maxIter)
  498. {
  499. if (mandelInfo.maxIter != maxIter) {
  500. mandelInfo.maxIter = maxIter;
  501. if (mandelView) {
  502. mandelView->clearCells();
  503. mandelView->calcer.clearAll();
  504. mandelView->calcer.changeState();
  505. }
  506. emit update();
  507. }
  508. }
  509. void MandelWidget::setJuliaPos(const mnd::Real& x, const mnd::Real& y)
  510. {
  511. mandelInfo.juliaX = x;
  512. mandelInfo.juliaY = y;
  513. if (mandelView)
  514. mandelView->calcer.changeState();
  515. emit update();
  516. }
  517. void MandelWidget::setGenerator(mnd::MandelGenerator* generator)
  518. {
  519. if (this->generator != generator) {
  520. this->generator = generator;
  521. if (mandelView)
  522. mandelView->setGenerator(generator);
  523. }
  524. }
  525. void MandelWidget::clearAll(void)
  526. {
  527. mandelView->clearCells();
  528. mandelView->calcer.clearAll();
  529. }
  530. void MandelWidget::initializeGL(void)
  531. {
  532. auto& gl = *this->context()->functions();
  533. gl.glClearColor(0, 0, 0, 0);
  534. this->context()->makeCurrent(nullptr);
  535. gl.glDisable(GL_DEPTH_TEST);
  536. // looks not even better
  537. gl.glEnable(GL_FRAMEBUFFER_SRGB);
  538. //glShadeModel(GL_SMOOTH);
  539. QOpenGLShaderProgram program(this->context());
  540. program.addShaderFromSourceCode(QOpenGLShader::Vertex,
  541. "attribute highp vec4 vertex;\n"
  542. "uniform highp mat4 matrix;\n"
  543. "void main(void)\n"
  544. "{\n"
  545. " gl_Position = matrix * vertex;\n"
  546. "}");
  547. program.addShaderFromSourceCode(QOpenGLShader::Fragment,
  548. "uniform mediump vec4 color;\n"
  549. "void main(void)\n"
  550. "{\n"
  551. " gl_FragColor = asd afd asfd vec4(1, 1, 1, 2) - color;\n"
  552. "}");
  553. program.link();
  554. program.bind();
  555. mandelView = nullptr;
  556. requestRecalc();
  557. }
  558. void MandelWidget::resizeGL(int w, int h)
  559. {
  560. auto& gl = *this->context()->functions();
  561. double aspect = double(w) / h;
  562. currentViewport.height = currentViewport.width / aspect;
  563. targetViewport = currentViewport;
  564. float pixelRatio = this->devicePixelRatioF();
  565. gl.glViewport(0, 0, w * pixelRatio, h * pixelRatio);
  566. if (mandelView.get() != nullptr) {
  567. mandelView->width = w;
  568. mandelView->height = h;
  569. //printf("resize: %d, %d\n", w, h);
  570. }
  571. }
  572. void MandelWidget::paintGL(void)
  573. {
  574. auto& gl = *QOpenGLContext::currentContext()->versionFunctions<QOpenGLFunctions_2_0>();
  575. if (mandelView == nullptr) {
  576. mandelView = std::make_unique<MandelView>(generator, *this);
  577. QObject::connect(mandelView.get(), &MandelView::redrawRequested, this, static_cast<void(QOpenGLWidget::*)(void)>(&QOpenGLWidget::update));
  578. }
  579. int width = this->width();
  580. int height = this->height();
  581. float pixelRatio = this->devicePixelRatioF();
  582. mandelView->width = width * pixelRatio;
  583. mandelView->height = height * pixelRatio;
  584. //glViewport(0, 0, width, height);
  585. gl.glMatrixMode(GL_PROJECTION);
  586. gl.glLoadIdentity();
  587. #ifdef QT_OPENGL_ES_1
  588. gl.glOrthof(0, width * pixelRatio, height * pixelRatio, 0, -1.0, 1.0);
  589. #else
  590. gl.glOrtho(0, width * pixelRatio, height * pixelRatio, 0, -1.0, 1.0);
  591. #endif
  592. gl.glMatrixMode(GL_MODELVIEW);
  593. gl.glLoadIdentity();
  594. gl.glClear(GL_COLOR_BUFFER_BIT);
  595. updateAnimations();
  596. QPainter painter{ this };
  597. mandelView->paint(this->currentViewport, painter);
  598. if (rubberbanding)
  599. drawRubberband();
  600. if (displayInfo)
  601. drawInfo();
  602. if (selectingPoint)
  603. drawPoint();
  604. }
  605. void MandelWidget::updateAnimations(void)
  606. {
  607. if (mnd::abs(currentViewport.width / targetViewport.width - 1.0) < 1e-3
  608. && mnd::abs(currentViewport.height / targetViewport.height - 1.0) < 1e-3) {
  609. // animation finished
  610. currentViewport = targetViewport;
  611. }
  612. else {
  613. auto now = std::chrono::high_resolution_clock::now();
  614. auto millis = std::chrono::duration_cast<std::chrono::milliseconds>(now - lastAnimUpdate).count();
  615. const mnd::Real factor = mnd::Real(::pow(0.97, millis));
  616. const mnd::Real one(1.0);
  617. currentViewport.x = currentViewport.x * factor + targetViewport.x * (one - factor);
  618. currentViewport.y = currentViewport.y * factor + targetViewport.y * (one - factor);
  619. currentViewport.width = currentViewport.width * factor + targetViewport.width * (one - factor);
  620. currentViewport.height = currentViewport.height * factor + targetViewport.height * (one - factor);
  621. lastAnimUpdate = now;
  622. emit update();
  623. }
  624. }
  625. void MandelWidget::drawRubberband(void)
  626. {
  627. QPainter rubberbandPainter{ this };
  628. rubberbandPainter.fillRect(rubberband, QColor{ 125, 140, 225, 120 });
  629. QPen pen{ QColor{ 100, 115, 200 } };
  630. pen.setWidth(2);
  631. rubberbandPainter.setPen(pen);
  632. rubberbandPainter.drawRect(rubberband);
  633. //QStyleOption so;
  634. //style()->drawControl(QStyle::CE_RubberBand, &so, &rubberbandPainter, this);
  635. }
  636. void MandelWidget::drawInfo(void)
  637. {
  638. const float DIST_FROM_BORDER = 15;
  639. float maxWidth = this->width() - 2 * DIST_FROM_BORDER;
  640. mnd::Real distPerPixel = currentViewport.width / this->width();
  641. float log10 = (mnd::convert<float>(mnd::log(distPerPixel)) + ::logf(maxWidth)) / ::logf(10);
  642. mnd::Real displayDist = mnd::pow(mnd::Real(10), ::floor(log10));
  643. float pixels = mnd::convert<float>(displayDist / distPerPixel);
  644. int factor = 1;
  645. for (int i = 9; i > 1; i--) {
  646. if (pixels * i < maxWidth) {
  647. factor *= i;
  648. pixels *= i;
  649. displayDist *= i;
  650. break;
  651. }
  652. }
  653. std::stringstream dis;
  654. if (::abs(log10) < 3) {
  655. dis << mnd::convert<float>(displayDist);
  656. }
  657. else {
  658. dis << factor << "e" << int(::floor(log10));
  659. }
  660. if (maxWidth > 400) {
  661. dis << "; per pixel: " << distPerPixel;
  662. }
  663. float lineY = this->height() - DIST_FROM_BORDER;
  664. float lineXEnd = DIST_FROM_BORDER + pixels;
  665. QPainter infoPainter{ this };
  666. infoPainter.setPen(Qt::white);
  667. infoPainter.setFont(QFont("Arial", 12));
  668. infoPainter.drawLine(QPointF{ DIST_FROM_BORDER, lineY }, QPointF{ lineXEnd, lineY });
  669. infoPainter.drawLine(QPointF{ DIST_FROM_BORDER, lineY }, QPointF{ DIST_FROM_BORDER, lineY - 5 });
  670. infoPainter.drawLine(QPointF{ lineXEnd, lineY }, QPointF{ lineXEnd, lineY - 5 });
  671. infoPainter.drawText(int(DIST_FROM_BORDER), int(lineY - 20), int(lineXEnd - DIST_FROM_BORDER), 20,
  672. Qt::AlignCenter, QString::fromStdString(dis.str()));
  673. infoPainter.end();
  674. }
  675. void MandelWidget::drawPoint(void)
  676. {
  677. QPainter pointPainter{ this };
  678. pointPainter.setPen(QColor{ 255, 255, 255 });
  679. pointPainter.drawLine(0, pointY, width(), pointY);
  680. pointPainter.drawLine(pointX, 0, pointX, height());
  681. /*glColor3ub(255, 255, 255);
  682. glBegin(GL_LINES);
  683. glVertex2f(0, pointY);
  684. glVertex2f(width(), pointY);
  685. glVertex2f(pointX, 0);
  686. glVertex2f(pointX, height());
  687. glEnd();*/
  688. }
  689. void MandelWidget::zoom(float scale, float x, float y)
  690. {
  691. targetViewport.zoom(scale, x, y);
  692. lastAnimUpdate = std::chrono::high_resolution_clock::now();
  693. //currentViewport.zoom(scale, x, y);
  694. requestRecalc();
  695. }
  696. void MandelWidget::setViewport(const mnd::MandelViewport& viewport)
  697. {
  698. targetViewport = viewport;
  699. targetViewport.adjustAspectRatio(this->width(), this->height());
  700. currentViewport = targetViewport;
  701. //lastAnimUpdate = std::chrono::high_resolution_clock::now();
  702. //currentViewport.zoom(scale, x, y);
  703. requestRecalc();
  704. }
  705. void MandelWidget::selectPoint(void)
  706. {
  707. this->selectingPoint = true;
  708. this->setMouseTracking(true);
  709. }
  710. void MandelWidget::stopSelectingPoint(void)
  711. {
  712. this->selectingPoint = false;
  713. this->setMouseTracking(false);
  714. }
  715. void MandelWidget::requestRecalc()
  716. {
  717. emit update();
  718. }
  719. void MandelWidget::resizeEvent(QResizeEvent* re)
  720. {
  721. QOpenGLWidget::resizeEvent(re);
  722. double aspect = double(geometry().width()) / geometry().height();
  723. currentViewport.height = currentViewport.width / aspect;
  724. targetViewport = currentViewport;
  725. if (mandelView.get() != nullptr) {
  726. mandelView->width = this->width();
  727. mandelView->height = this->height();
  728. }
  729. requestRecalc();
  730. }
  731. void MandelWidget::mousePressEvent(QMouseEvent* me)
  732. {
  733. QOpenGLWidget::mousePressEvent(me);
  734. if (me->button() == Qt::RightButton) {
  735. rubberbanding = true;
  736. rubberband.setCoords(me->x(), me->y(), me->x(), me->y());
  737. update();
  738. me->accept();
  739. }
  740. else if (me->button() == Qt::LeftButton) {
  741. dragging = true;
  742. dragX = me->x();
  743. dragY = me->y();
  744. me->accept();
  745. }
  746. }
  747. void MandelWidget::mouseMoveEvent(QMouseEvent* me)
  748. {
  749. QOpenGLWidget::mouseMoveEvent(me);
  750. if (rubberbanding) {
  751. QRectF& rect = rubberband;
  752. double aspect = double(geometry().width()) / geometry().height();
  753. rect.setBottomRight(QPoint(me->x(), me->y()));
  754. if (rect.width() > rect.height() * aspect)
  755. rect.setHeight(rect.width() / aspect);
  756. else
  757. rect.setWidth(rect.height() * aspect);
  758. update();
  759. }
  760. else if (selectingPoint) {
  761. pointX = me->x();
  762. pointY = me->y();
  763. update();
  764. }
  765. else if (dragging) {
  766. double deltaX = me->x() - dragX;
  767. double deltaY = me->y() - dragY;
  768. this->currentViewport.x -= deltaX * currentViewport.width / this->width();
  769. this->currentViewport.y -= deltaY * currentViewport.height / this->height();
  770. targetViewport = currentViewport;
  771. dragX = me->x(); dragY = me->y();
  772. update();
  773. }
  774. me->accept();
  775. }
  776. void MandelWidget::mouseReleaseEvent(QMouseEvent* me)
  777. {
  778. QOpenGLWidget::mouseReleaseEvent(me);
  779. if (rubberbanding) {
  780. QRect rect = rubberband.toRect();
  781. if(rect.width() != 0 && rect.height() != 0) {
  782. QRect full = this->geometry();
  783. targetViewport.x += mnd::Real(rect.left()) * targetViewport.width / full.width();
  784. targetViewport.y += mnd::Real(rect.top()) * targetViewport.height / full.height();
  785. targetViewport.width *= mnd::Real(rect.width()) / full.width();
  786. targetViewport.height *= mnd::Real(rect.height()) / full.height();
  787. targetViewport.normalize();
  788. currentViewport = targetViewport;
  789. }
  790. requestRecalc();
  791. rubberbanding = false;
  792. }
  793. else if (selectingPoint) {
  794. selectingPoint = false;
  795. this->setMouseTracking(false);
  796. mnd::Real x = currentViewport.x + currentViewport.width * mnd::convert<mnd::Real>(float(me->x()) / width());
  797. mnd::Real y = currentViewport.y + currentViewport.height * mnd::convert<mnd::Real>(float(me->y()) / height());
  798. emit pointSelected(x, y);
  799. update();
  800. }
  801. dragging = false;
  802. //requestRecalc();
  803. }
  804. void MandelWidget::wheelEvent(QWheelEvent* we)
  805. {
  806. QOpenGLWidget::wheelEvent(we);
  807. float x = float(we->x()) / this->width();
  808. float y = float(we->y()) / this->height();
  809. float scale = ::powf(0.9975f, we->angleDelta().y());
  810. zoom(scale, x, y);
  811. if (!we->pixelDelta().isNull())
  812. this->currentViewport = this->targetViewport;
  813. we->accept();
  814. }
  815. /*void MandelWidget::viewUpdated(Bitmap<RGBColor>* bitmap)
  816. {
  817. if (bitmap != nullptr) {
  818. delete bitmap;
  819. emit repaint();
  820. }
  821. }*/