MandelWidget.cpp 31 KB

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