MandelWidget.cpp 29 KB

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