MandelWidget.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  1. #include "MandelWidget.h"
  2. #include <cmath>
  3. using namespace mnd;
  4. #include <QOpenGLVertexArrayObject>
  5. Texture::Texture(const Bitmap<RGBColor>& bitmap) :
  6. context{ nullptr }
  7. {
  8. glGenTextures(1, &id);
  9. glBindTexture(GL_TEXTURE_2D, id);
  10. long lineLength = (bitmap.width * 3 + 3) & ~3;
  11. unsigned char* pixels = new unsigned char[lineLength * bitmap.height];
  12. for (int i = 0; i < bitmap.width; i++) {
  13. for (int j = 0; j < bitmap.height; j++) {
  14. int index = i * 3 + j * lineLength;
  15. RGBColor c = bitmap.get(i, j);
  16. pixels[index] = c.r;
  17. pixels[index + 1] = c.g;
  18. pixels[index + 2] = c.b;
  19. }
  20. }
  21. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, int(bitmap.width), int(bitmap.height), 0, GL_RGB, GL_UNSIGNED_BYTE, pixels);
  22. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  23. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  24. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  25. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  26. }
  27. Texture::Texture(const Bitmap<RGBColor>& bitmap, QOpenGLContext* context) :
  28. context{ context }
  29. {
  30. context->functions()->glGenTextures(1, &id);
  31. context->functions()->glBindTexture(GL_TEXTURE_2D, id);
  32. long lineLength = (bitmap.width * 3 + 3) & ~3;
  33. unsigned char* pixels = new unsigned char[lineLength * bitmap.height];
  34. for (int i = 0; i < bitmap.width; i++) {
  35. for (int j = 0; j < bitmap.height; j++) {
  36. int index = i * 3 + j * lineLength;
  37. RGBColor c = bitmap.get(i, j);
  38. pixels[index] = c.r;
  39. pixels[index + 1] = c.g;
  40. pixels[index + 2] = c.b;
  41. }
  42. }
  43. context->functions()->glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, int(bitmap.width), int(bitmap.height), 0, GL_RGB, GL_UNSIGNED_BYTE, pixels);
  44. context->functions()->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  45. context->functions()->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  46. context->functions()->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  47. context->functions()->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  48. }
  49. Texture::~Texture(void)
  50. {
  51. if (id != 0)
  52. glDeleteTextures(1, &id);
  53. }
  54. Texture::Texture(Texture&& other) :
  55. id{ other.id },
  56. context{ other.context }
  57. {
  58. other.id = 0;
  59. }
  60. Texture& Texture::operator=(Texture&& other)
  61. {
  62. this->id = other.id;
  63. this->context = other.context;
  64. other.id = 0;
  65. return *this;
  66. }
  67. void Texture::bind(void) const
  68. {
  69. glBindTexture(GL_TEXTURE_2D, id);
  70. }
  71. void Texture::drawRect(float x, float y, float width, float height)
  72. {
  73. glColor3ub(255, 255, 255);
  74. glEnable(GL_TEXTURE_2D);
  75. bind();
  76. glBegin(GL_TRIANGLE_STRIP);
  77. glTexCoord2f(0, 0);
  78. glVertex2f(x, y);
  79. glTexCoord2f(1, 0);
  80. glVertex2f(x + width, y);
  81. glTexCoord2f(0, 1);
  82. glVertex2f(x, y + height);
  83. glTexCoord2f(1, 1);
  84. glVertex2f(x + width, y + height);
  85. glEnd();
  86. glDisable(GL_TEXTURE_2D);
  87. }
  88. std::pair<int, int> TexGrid::getCellIndices(double x, double y)
  89. {
  90. return { ::floor(x / dpp / MandelV::chunkSize), ::floor(y / dpp / MandelV::chunkSize) };
  91. }
  92. std::pair<double, double> TexGrid::getPositions(int x, int y)
  93. {
  94. return { x * dpp * MandelV::chunkSize, y * dpp * MandelV::chunkSize };
  95. }
  96. Texture* TexGrid::getCell(int i, int j)
  97. {
  98. auto cIt = cells.find({i, j});
  99. if (cIt != cells.end()) {
  100. return cIt->second.get();
  101. }
  102. else {
  103. return nullptr;
  104. }
  105. }
  106. void TexGrid::setCell(int i, int j, std::unique_ptr<Texture> tex)
  107. {
  108. cells[{i, j}] = std::move(tex);
  109. }
  110. void TexGrid::clearCells(void)
  111. {
  112. cells.clear();
  113. }
  114. void Job::run(void)
  115. {
  116. auto [absX, absY] = grid->getPositions(i, j);
  117. double gw = grid->dpp * MandelV::chunkSize;
  118. Bitmap<float> f(MandelV::chunkSize, MandelV::chunkSize);
  119. mnd::MandelInfo mi;
  120. mi.view.x = absX;
  121. mi.view.y = absY;
  122. mi.view.width = mi.view.height = gw;
  123. mi.bWidth = mi.bHeight = MandelV::chunkSize;
  124. mi.maxIter = 500;
  125. mndContext.getDefaultGenerator().generate(mi, f.pixels.get());
  126. Bitmap<RGBColor>* rgb = new Bitmap<RGBColor>(f.map<RGBColor>([] (float f) {
  127. return RGBColor{ uint8_t(f / 2), uint8_t(f / 2), uint8_t(f / 2) };
  128. }));
  129. emit done(level, i, j, rgb);
  130. }
  131. void Calcer::calc(TexGrid& grid, int level, int i, int j)
  132. {
  133. if (jobs.find({ level, i, j }) == jobs.end()) {
  134. Job* job = new Job(mndContext, &grid, level, i, j);
  135. connect(job, &Job::done, this, &Calcer::redirect);
  136. jobs.insert({ level, i, j });
  137. //jobs.push_back(std::move(job));
  138. threadPool->start(job);
  139. }
  140. }
  141. void Calcer::redirect(int level, int i, int j, Bitmap<RGBColor>* bmp)
  142. {
  143. jobs.erase({ level, i, j });
  144. emit done(level, i, j, bmp);
  145. }
  146. MandelV::MandelV(mnd::MandelContext& mndContext) :
  147. mndContext{ mndContext },
  148. calcThread{ std::make_unique<Calcer>(mndContext) }
  149. {
  150. Bitmap<RGBColor> emp(8, 8);
  151. for(auto i = 0; i < emp.width; i++) {
  152. for(auto j = 0; j < emp.height; j++) {
  153. if((i + j) & 0x1) { // if i+j is odd
  154. emp.get(i, j) = RGBColor{ 255, 255, 255 };
  155. }
  156. else {
  157. emp.get(i, j) = RGBColor{ 120, 120, 120 };
  158. }
  159. }
  160. }
  161. empty = std::make_unique<Texture>(emp);
  162. connect(calcThread.get(), &Calcer::done, this, &MandelV::cellReady);
  163. }
  164. int MandelV::getLevel(double dpp) {
  165. return -int(::log2(dpp / chunkSize));
  166. }
  167. double MandelV::getDpp(int level)
  168. {
  169. return ::pow(2, -level) * chunkSize;
  170. }
  171. TexGrid& MandelV::getGrid(int level)
  172. {
  173. auto it = levels.find(level);
  174. if (it != levels.end())
  175. return it->second;
  176. else {
  177. levels.insert({ level, TexGrid(getDpp(level)) });
  178. return levels[level];
  179. }
  180. }
  181. void MandelV::paint(const mnd::MandelViewport& mvp)
  182. {
  183. double dpp = mvp.width / width;
  184. int level = getLevel(dpp);
  185. auto& grid = getGrid(level);
  186. double gw = getDpp(level) * chunkSize;
  187. auto [left, top] = grid.getCellIndices(mvp.x, mvp.y);
  188. auto [right, bottom] = grid.getCellIndices(mvp.right(), mvp.bottom());
  189. for(int i = left; i <= right; i++) {
  190. for(int j = top; j <= bottom; j++) {
  191. auto [absX, absY] = grid.getPositions(i, j);
  192. double x = (absX - mvp.x) * width / mvp.width;
  193. double y = (absY - mvp.y) * height / mvp.height;
  194. double w = width * gw / mvp.width;
  195. double h = height * gw / mvp.height;
  196. Texture* t = grid.getCell(i, j);
  197. if (t != nullptr) {
  198. t->drawRect(x, y, w, w);
  199. }
  200. else {
  201. calcThread->calc(grid, level, i, j);
  202. this->empty->drawRect(x, y, w, w);
  203. }
  204. }
  205. }
  206. }
  207. void MandelV::cellReady(int level, int i, int j, Bitmap<RGBColor>* bmp)
  208. {
  209. this->getGrid(level).setCell(i, j, std::make_unique<Texture>(*bmp));
  210. delete bmp;
  211. printf("cellReady: %d --> %d, %d\n", level, i, j);
  212. emit redrawRequested();
  213. }
  214. MandelView::MandelView(mnd::Generator& generator, Gradient &gradient, MandelWidget* mWidget) :
  215. generator{ &generator },
  216. gradient{ gradient },
  217. mWidget{ mWidget }
  218. //context{ new QOpenGLContext(this) }
  219. {
  220. //context->setShareContext(mWidget->context()->contextHandle());
  221. hasToCalc.store(false);
  222. finish.store(false);
  223. }
  224. MandelView::~MandelView(void)
  225. {
  226. finish.store(true);
  227. condVar.notify_one();
  228. //calcThread.wait(100);
  229. calcThread.wait(100);
  230. calcThread.terminate();
  231. }
  232. void MandelView::setGenerator(mnd::Generator& value)
  233. {
  234. generator = &value;
  235. }
  236. void MandelView::start(void)
  237. {
  238. this->moveToThread(&calcThread);
  239. connect(&calcThread, SIGNAL(started()), this, SLOT(loop()));
  240. calcThread.start();
  241. }
  242. void MandelView::loop(void)
  243. {
  244. printf("thread!\n"); fflush(stdout);
  245. //QGLWidget* hiddenWidget = new QGLWidget(nullptr, mWidget);
  246. //hiddenWidget->setVisible(false);
  247. //hiddenWidget->context()->contextHandle()->moveToThread(&calcThread);
  248. //QOpenGLContext* context = hiddenWidget->context()->contextHandle();
  249. //context->setShareContext(mWidget->context()->contextHandle());
  250. //context->create();
  251. //printf("sharing: %d\n", QOpenGLContext::areSharing(hiddenWidget->context()->contextHandle(), mWidget->context()->contextHandle()));
  252. //fflush(stdout);
  253. //std::this_thread::sleep_for(std::chrono::milliseconds(3000));
  254. std::unique_lock<std::mutex> lock(mut);
  255. while(true) {
  256. printf("calcing!\n"); fflush(stdout);
  257. if (finish.load()) {
  258. break;
  259. }
  260. if (hasToCalc.exchange(false)) {
  261. const MandelInfo& mi = toCalc.load();
  262. auto fmap = Bitmap<float>(mi.bWidth, mi.bHeight);
  263. generator->generate(mi, fmap.pixels.get());
  264. auto* bitmap = new Bitmap<RGBColor>(fmap.map<RGBColor>([&mi, this](float i) {
  265. return i >= mi.maxIter ? RGBColor{ 0, 0, 0 } : gradient.get(i);
  266. }));
  267. /*return i >= mi.maxIter ?
  268. RGBColor{ 0,0,0 } :
  269. RGBColor{ uint8_t(cos(i * 0.015f) * 127 + 127),
  270. uint8_t(sin(i * 0.01f) * 127 + 127),
  271. uint8_t(i) }; }));//uint8_t(::sin(i * 0.01f) * 100 + 100), uint8_t(i) }; });
  272. */
  273. //hiddenWidget->makeCurrent();
  274. //Texture* tex = new Texture(bitmap);
  275. //hiddenWidget->doneCurrent();
  276. //Texture* tex = 0;
  277. emit updated(bitmap);
  278. }
  279. printf("finished calcing!\n"); fflush(stdout);
  280. condVar.wait(lock);
  281. printf("waking!\n"); fflush(stdout);
  282. }
  283. }
  284. void MandelView::adaptViewport(const MandelInfo mi)
  285. {
  286. //bmp->get(0, 0) = RGBColor{ 10, uint8_t(sin(1 / vp.width) * 127 + 127), 10 };
  287. /*printf("adapted\n");
  288. if (calc.valid()) {
  289. auto status = calc.wait_for(std::chrono::milliseconds(0));
  290. if (status == std::future_status::deferred) {
  291. printf("deferred\n");
  292. } else if (status == std::future_status::timeout) {
  293. printf("timeout\n");
  294. } else if (status == std::future_status::ready) {
  295. printf("ready!\n");
  296. }
  297. }*/
  298. /*if (!calc.valid() || calc.wait_for(std::chrono::milliseconds(0)) == std::future_status::ready) {
  299. toCalc = mi;
  300. hasToCalc = true;
  301. calc = std::async([this, mi] () {
  302. QGLWidget* hiddenWidget = new QGLWidget(nullptr, (QGLWidget*) mWidget);
  303. QOpenGLContext* context = hiddenWidget->context()->contextHandle();
  304. hiddenWidget->makeCurrent();
  305. //context->setShareContext(mWidget->context()->contextHandle());
  306. //context->create();
  307. printf("sharing: %d\n", QOpenGLContext::areSharing(context, mWidget->context()->contextHandle()));
  308. fflush(stdout);
  309. //std::this_thread::sleep_for(std::chrono::milliseconds(1000));
  310. do {
  311. auto fmap = Bitmap<float>(mi.bWidth, mi.bHeight);
  312. generator->generate(mi, fmap.pixels.get());
  313. auto bitmap = fmap.map<RGBColor>([&mi](float i) { return i > mi.maxIter ?
  314. RGBColor{ 0,0,0 } :
  315. RGBColor{ uint8_t(cos(i * 0.015f) * 127 + 127),
  316. uint8_t(sin(i * 0.01f) * 127 + 127),
  317. uint8_t(i) }; });//uint8_t(::sin(i * 0.01f) * 100 + 100), uint8_t(i) }; });
  318. Texture* tex = new Texture(bitmap, context);
  319. //Texture* tex = 0;
  320. emit updated(tex);
  321. } while(hasToCalc.exchange(false));
  322. });
  323. }
  324. else {*/
  325. //std::unique_lock<std::mutex> lock(mut, std::try_to_lock);
  326. toCalc = mi;
  327. hasToCalc.exchange(true);
  328. condVar.notify_one();
  329. //}
  330. }
  331. MandelWidget::MandelWidget(mnd::MandelContext& ctxt, QWidget* parent) :
  332. QOpenGLWidget{ parent },
  333. mndContext{ ctxt },
  334. mv{ ctxt.getDefaultGenerator(), gradient, this }
  335. {
  336. this->setContentsMargins(0, 0, 0, 0);
  337. this->setSizePolicy(QSizePolicy::Expanding,
  338. QSizePolicy::Expanding);
  339. QObject::connect(&mv, &MandelView::updated, this, &MandelWidget::viewUpdated, Qt::AutoConnection);
  340. QObject::connect(this, &MandelWidget::needsUpdate, &mv, &MandelView::adaptViewport, Qt::DirectConnection);
  341. /*if (!ctxt.getDevices().empty()) {
  342. if (auto* gen = ctxt.getDevices()[0].getGeneratorDouble(); gen) {
  343. mv.setGenerator(*gen);
  344. }
  345. }*/
  346. }
  347. MandelWidget::~MandelWidget()
  348. {
  349. }
  350. void MandelWidget::initializeGL(void)
  351. {
  352. this->context()->functions()->glClearColor(0, 0, 0, 0);
  353. this->context()->makeCurrent(nullptr);
  354. glDisable(GL_DEPTH_TEST);
  355. // looks not even better
  356. //glDisable(GL_FRAMEBUFFER_SRGB);
  357. //glShadeModel(GL_SMOOTH);
  358. /*CpuGenerator<double> cpg;
  359. MandelInfo mi;
  360. mi.bWidth = this->width();//ql.geometry().width();
  361. mi.bHeight = this->height(); //ql.geometry().height();
  362. mi.maxIter = 250;
  363. mi.view = viewport;
  364. auto bitmap = cpg.generate(mi);*/
  365. Bitmap<RGBColor> bitmap(1, 1);
  366. bitmap.get(0, 0) = RGBColor{50, 50, 50};
  367. v = nullptr;
  368. tex = std::make_unique<Texture>(bitmap, context());
  369. mv.start();
  370. requestRecalc();
  371. }
  372. void MandelWidget::paintGL(void)
  373. {
  374. if (v == nullptr) {
  375. v = std::make_unique<MandelV>(mndContext);
  376. QObject::connect(v.get(), &MandelV::redrawRequested, this, static_cast<void(QOpenGLWidget::*)(void)>(&QOpenGLWidget::update));
  377. }
  378. /*if (!initialized) {
  379. emit needsUpdate(viewport);
  380. initialized = true;
  381. }*/
  382. int width = this->width();
  383. int height = this->height();
  384. v->width = width;
  385. v->height = height;
  386. //v = std::make_unique<MandelV>(context());
  387. /*CpuGenerator<double> cpg;
  388. ClGenerator clg;
  389. MandelGenerator& mg = cpg;
  390. MandelInfo mi;
  391. mi.bWidth = width;
  392. mi.bHeight = height;
  393. mi.maxIter = 5000;
  394. mi.view = viewport;*/
  395. //auto bitmap = mg.generate(mi);
  396. /*Bitmap<RGBColor> bitmap(1000, 1000);
  397. for (int i = 0; i < 1000 * 1000; i++)
  398. bitmap.pixels[i] = RGBColor{5, uint8_t((i % 1000) ^ (i / 1000)), 50};
  399. tex = std::make_unique<Texture>(bitmap);*/
  400. glViewport(0, 0, width, height);
  401. glMatrixMode(GL_PROJECTION);
  402. glLoadIdentity();
  403. #ifdef QT_OPENGL_ES_1
  404. glOrthof(0, width, height, 0, -1.0, 1.0);
  405. #else
  406. glOrtho(0, width, height, 0, -1.0, 1.0);
  407. #endif
  408. glMatrixMode(GL_MODELVIEW);
  409. glClear(GL_COLOR_BUFFER_BIT);
  410. glLoadIdentity();
  411. //tex->drawRect(0, 0, width, height);
  412. //v->empty = std::move(*tex)
  413. //v->empty.bind();
  414. v->paint(this->viewport);
  415. //*tex = std::move(v->empty);
  416. if (rubberbandDragging)
  417. drawRubberband();
  418. printf("painted GL\n");
  419. }
  420. void MandelWidget::drawRubberband(void)
  421. {
  422. glColor3ub(10, 200, 10);
  423. glBegin(GL_LINE_LOOP);
  424. glVertex2d(rubberband.x(), rubberband.y());
  425. glVertex2d(rubberband.right(), rubberband.y());
  426. glVertex2d(rubberband.right(), rubberband.bottom());
  427. glVertex2d(rubberband.x(), rubberband.bottom());
  428. glEnd();
  429. }
  430. void MandelWidget::zoom(float scale)
  431. {
  432. viewport.zoomCenter(scale);
  433. requestRecalc();
  434. }
  435. void MandelWidget::setMaxIterations(int maxIter)
  436. {
  437. this->maxIterations = maxIter;
  438. requestRecalc();
  439. }
  440. void MandelWidget::requestRecalc()
  441. {
  442. //emit needsUpdate(MandelInfo{ viewport, this->width(), this->height(), maxIterations });
  443. this->update();
  444. }
  445. void MandelWidget::resizeGL(int width, int height)
  446. {
  447. //glViewport(0, 0, (GLint) width, (GLint) height);
  448. }
  449. /*void MandelWidget::redraw(void)
  450. {
  451. /*CpuGenerator<double> cpg;
  452. MandelInfo mi;
  453. mi.bWidth = this->geometry().width();//ql.geometry().width();
  454. mi.bHeight = this->geometry().height(); //ql.geometry().height();
  455. mi.maxIter = 250;
  456. mi.view = viewport;*/
  457. //update();
  458. //emit needsUpdate(viewport);
  459. //auto bitmap = cpg.generate(mi).map<uint32_t>([](RGBColor rgb) { return 255 << 24 | rgb.b << 16 | rgb.g << 8 | rgb.r; });
  460. //}
  461. void MandelWidget::resizeEvent(QResizeEvent* re)
  462. {
  463. double aspect = double(geometry().width()) / geometry().height();
  464. //if (viewport.width > viewport.height * aspect)
  465. viewport.height = (viewport.width / aspect);
  466. //else
  467. // viewport.width = (viewport.height * aspect);
  468. requestRecalc();
  469. //redraw();
  470. }
  471. void MandelWidget::mousePressEvent(QMouseEvent* me)
  472. {
  473. rubberband.setCoords(me->x(), me->y(), 0, 0);
  474. rubberbandDragging = true;
  475. }
  476. void MandelWidget::mouseMoveEvent(QMouseEvent* me)
  477. {
  478. QRectF& rect = rubberband;
  479. float aspect = float(geometry().width()) / geometry().height();
  480. rect.setBottomRight(QPoint(me->x(), me->y()));
  481. if (rect.width() > rect.height() * aspect)
  482. rect.setHeight(rect.width() / aspect);
  483. else
  484. rect.setWidth(rect.height() * aspect);
  485. if (rubberbandDragging)
  486. emit repaint();
  487. }
  488. void MandelWidget::mouseReleaseEvent(QMouseEvent* me)
  489. {
  490. QRect rect = rubberband.toRect();
  491. QRect full = this->geometry();
  492. viewport.x += double(rect.left()) * viewport.width / full.width();
  493. viewport.y += double(rect.top()) * viewport.height / full.height();
  494. viewport.width *= double(rect.width()) / full.width();
  495. viewport.height *= double(rect.height()) / full.height();
  496. viewport.normalize();
  497. rubberbandDragging = false;
  498. requestRecalc();
  499. }
  500. void MandelWidget::viewUpdated(Bitmap<RGBColor>* bitmap)
  501. {
  502. if (bitmap != nullptr) {
  503. tex = std::make_unique<Texture>(*bitmap);
  504. delete bitmap;
  505. printf("viewUpdated\n");
  506. emit repaint();
  507. }
  508. }