bit_mask.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  1. /*************************************************************************/
  2. /* bit_mask.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #include "bit_mask.h"
  31. #include "core/io/image_loader.h"
  32. void BitMap::create(const Size2 &p_size) {
  33. ERR_FAIL_COND(p_size.width < 1);
  34. ERR_FAIL_COND(p_size.height < 1);
  35. width = p_size.width;
  36. height = p_size.height;
  37. bitmask.resize(((width * height) / 8) + 1);
  38. zeromem(bitmask.ptrw(), bitmask.size());
  39. }
  40. void BitMap::create_from_image_alpha(const Ref<Image> &p_image, float p_threshold) {
  41. ERR_FAIL_COND(p_image.is_null() || p_image->empty());
  42. Ref<Image> img = p_image->duplicate();
  43. img->convert(Image::FORMAT_LA8);
  44. ERR_FAIL_COND(img->get_format() != Image::FORMAT_LA8);
  45. create(Size2(img->get_width(), img->get_height()));
  46. PoolVector<uint8_t>::Read r = img->get_data().read();
  47. uint8_t *w = bitmask.ptrw();
  48. for (int i = 0; i < width * height; i++) {
  49. int bbyte = i / 8;
  50. int bbit = i % 8;
  51. if (r[i * 2 + 1] / 255.0 > p_threshold) {
  52. w[bbyte] |= (1 << bbit);
  53. }
  54. }
  55. }
  56. void BitMap::set_bit_rect(const Rect2 &p_rect, bool p_value) {
  57. Rect2i current = Rect2i(0, 0, width, height).clip(p_rect);
  58. uint8_t *data = bitmask.ptrw();
  59. for (int i = current.position.x; i < current.position.x + current.size.x; i++) {
  60. for (int j = current.position.y; j < current.position.y + current.size.y; j++) {
  61. int ofs = width * j + i;
  62. int bbyte = ofs / 8;
  63. int bbit = ofs % 8;
  64. uint8_t b = data[bbyte];
  65. if (p_value)
  66. b |= (1 << bbit);
  67. else
  68. b &= ~(1 << bbit);
  69. data[bbyte] = b;
  70. }
  71. }
  72. }
  73. int BitMap::get_true_bit_count() const {
  74. int ds = bitmask.size();
  75. const uint8_t *d = bitmask.ptr();
  76. int c = 0;
  77. //fast, almot branchless version
  78. for (int i = 0; i < ds; i++) {
  79. c += (d[i] & (1 << 7)) >> 7;
  80. c += (d[i] & (1 << 6)) >> 6;
  81. c += (d[i] & (1 << 5)) >> 5;
  82. c += (d[i] & (1 << 4)) >> 4;
  83. c += (d[i] & (1 << 3)) >> 3;
  84. c += (d[i] & (1 << 2)) >> 2;
  85. c += d[i] & 1;
  86. }
  87. return c;
  88. }
  89. void BitMap::set_bit(const Point2 &p_pos, bool p_value) {
  90. int x = p_pos.x;
  91. int y = p_pos.y;
  92. ERR_FAIL_INDEX(x, width);
  93. ERR_FAIL_INDEX(y, height);
  94. int ofs = width * y + x;
  95. int bbyte = ofs / 8;
  96. int bbit = ofs % 8;
  97. uint8_t b = bitmask[bbyte];
  98. if (p_value)
  99. b |= (1 << bbit);
  100. else
  101. b &= ~(1 << bbit);
  102. bitmask.write[bbyte] = b;
  103. }
  104. bool BitMap::get_bit(const Point2 &p_pos) const {
  105. int x = Math::fast_ftoi(p_pos.x);
  106. int y = Math::fast_ftoi(p_pos.y);
  107. ERR_FAIL_INDEX_V(x, width, false);
  108. ERR_FAIL_INDEX_V(y, height, false);
  109. int ofs = width * y + x;
  110. int bbyte = ofs / 8;
  111. int bbit = ofs % 8;
  112. return (bitmask[bbyte] & (1 << bbit)) != 0;
  113. }
  114. Size2 BitMap::get_size() const {
  115. return Size2(width, height);
  116. }
  117. void BitMap::_set_data(const Dictionary &p_d) {
  118. ERR_FAIL_COND(!p_d.has("size"));
  119. ERR_FAIL_COND(!p_d.has("data"));
  120. create(p_d["size"]);
  121. bitmask = p_d["data"];
  122. }
  123. Dictionary BitMap::_get_data() const {
  124. Dictionary d;
  125. d["size"] = get_size();
  126. d["data"] = bitmask;
  127. return d;
  128. }
  129. Vector<Vector2> BitMap::_march_square(const Rect2i &rect, const Point2i &start) const {
  130. int stepx = 0;
  131. int stepy = 0;
  132. int prevx = 0;
  133. int prevy = 0;
  134. int startx = start.x;
  135. int starty = start.y;
  136. int curx = startx;
  137. int cury = starty;
  138. unsigned int count = 0;
  139. Set<Point2i> case9s;
  140. Set<Point2i> case6s;
  141. Vector<Vector2> _points;
  142. do {
  143. int sv = 0;
  144. { //square value
  145. /*
  146. checking the 2x2 pixel grid, assigning these values to each pixel, if not transparent
  147. +---+---+
  148. | 1 | 2 |
  149. +---+---+
  150. | 4 | 8 | <- current pixel (curx,cury)
  151. +---+---+
  152. */
  153. //NOTE: due to the way we pick points from texture, rect needs to be smaller, otherwise it goes outside 1 pixel
  154. Rect2i fixed_rect = Rect2i(rect.position, rect.size - Size2i(2, 2));
  155. Point2i tl = Point2i(curx - 1, cury - 1);
  156. sv += (fixed_rect.has_point(tl) && get_bit(tl)) ? 1 : 0;
  157. Point2i tr = Point2i(curx, cury - 1);
  158. sv += (fixed_rect.has_point(tr) && get_bit(tr)) ? 2 : 0;
  159. Point2i bl = Point2i(curx - 1, cury);
  160. sv += (fixed_rect.has_point(bl) && get_bit(bl)) ? 4 : 0;
  161. Point2i br = Point2i(curx, cury);
  162. sv += (fixed_rect.has_point(br) && get_bit(br)) ? 8 : 0;
  163. ERR_FAIL_COND_V(sv == 0 || sv == 15, Vector<Vector2>());
  164. }
  165. switch (sv) {
  166. case 1:
  167. case 5:
  168. case 13:
  169. /* going UP with these cases:
  170. 1 5 13
  171. +---+---+ +---+---+ +---+---+
  172. | 1 | | | 1 | | | 1 | |
  173. +---+---+ +---+---+ +---+---+
  174. | | | | 4 | | | 4 | 8 |
  175. +---+---+ +---+---+ +---+---+
  176. */
  177. stepx = 0;
  178. stepy = -1;
  179. break;
  180. case 8:
  181. case 10:
  182. case 11:
  183. /* going DOWN with these cases:
  184. 8 10 11
  185. +---+---+ +---+---+ +---+---+
  186. | | | | | 2 | | 1 | 2 |
  187. +---+---+ +---+---+ +---+---+
  188. | | 8 | | | 8 | | | 8 |
  189. +---+---+ +---+---+ +---+---+
  190. */
  191. stepx = 0;
  192. stepy = 1;
  193. break;
  194. case 4:
  195. case 12:
  196. case 14:
  197. /* going LEFT with these cases:
  198. 4 12 14
  199. +---+---+ +---+---+ +---+---+
  200. | | | | | | | | 2 |
  201. +---+---+ +---+---+ +---+---+
  202. | 4 | | | 4 | 8 | | 4 | 8 |
  203. +---+---+ +---+---+ +---+---+
  204. */
  205. stepx = -1;
  206. stepy = 0;
  207. break;
  208. case 2:
  209. case 3:
  210. case 7:
  211. /* going RIGHT with these cases:
  212. 2 3 7
  213. +---+---+ +---+---+ +---+---+
  214. | | 2 | | 1 | 2 | | 1 | 2 |
  215. +---+---+ +---+---+ +---+---+
  216. | | | | | | | 4 | |
  217. +---+---+ +---+---+ +---+---+
  218. */
  219. stepx = 1;
  220. stepy = 0;
  221. break;
  222. case 9:
  223. /*
  224. +---+---+
  225. | 1 | |
  226. +---+---+
  227. | | 8 |
  228. +---+---+
  229. this should normally go UP, but if we already been here, we go down
  230. */
  231. if (case9s.has(Point2i(curx, cury))) {
  232. //found, so we go down, and delete from case9s;
  233. stepx = 0;
  234. stepy = 1;
  235. case9s.erase(Point2i(curx, cury));
  236. } else {
  237. //not found, we go up, and add to case9s;
  238. stepx = 0;
  239. stepy = -1;
  240. case9s.insert(Point2i(curx, cury));
  241. }
  242. break;
  243. case 6:
  244. /*
  245. 6
  246. +---+---+
  247. | | 2 |
  248. +---+---+
  249. | 4 | |
  250. +---+---+
  251. this normally go RIGHT, but if its coming from UP, it should go LEFT
  252. */
  253. if (case6s.has(Point2i(curx, cury))) {
  254. //found, so we go down, and delete from case6s;
  255. stepx = -1;
  256. stepy = 0;
  257. case6s.erase(Point2i(curx, cury));
  258. } else {
  259. //not found, we go up, and add to case6s;
  260. stepx = 1;
  261. stepy = 0;
  262. case6s.insert(Point2i(curx, cury));
  263. }
  264. break;
  265. default:
  266. ERR_PRINT("this shouldn't happen.");
  267. }
  268. //little optimization
  269. // if previous direction is same as current direction,
  270. // then we should modify the last vec to current
  271. curx += stepx;
  272. cury += stepy;
  273. if (stepx == prevx && stepy == prevy) {
  274. _points.write[_points.size() - 1].x = (float)(curx - rect.position.x);
  275. _points.write[_points.size() - 1].y = (float)(cury + rect.position.y);
  276. } else {
  277. _points.push_back(Vector2((float)(curx - rect.position.x), (float)(cury + rect.position.y)));
  278. }
  279. count++;
  280. prevx = stepx;
  281. prevy = stepy;
  282. ERR_FAIL_COND_V(count > width * height, _points);
  283. } while (curx != startx || cury != starty);
  284. return _points;
  285. }
  286. static float perpendicular_distance(const Vector2 &i, const Vector2 &start, const Vector2 &end) {
  287. float res;
  288. float slope;
  289. float intercept;
  290. if (start.x == end.x) {
  291. res = Math::absf(i.x - end.x);
  292. } else if (start.y == end.y) {
  293. res = Math::absf(i.y - end.y);
  294. } else {
  295. slope = (end.y - start.y) / (end.x - start.x);
  296. intercept = start.y - (slope * start.x);
  297. res = Math::absf(slope * i.x - i.y + intercept) / Math::sqrt(Math::pow(slope, 2.0f) + 1.0);
  298. }
  299. return res;
  300. }
  301. static Vector<Vector2> rdp(const Vector<Vector2> &v, float optimization) {
  302. if (v.size() < 3)
  303. return v;
  304. int index = -1;
  305. float dist = 0;
  306. //not looping first and last point
  307. for (size_t i = 1, size = v.size(); i < size - 1; ++i) {
  308. float cdist = perpendicular_distance(v[i], v[0], v[v.size() - 1]);
  309. if (cdist > dist) {
  310. dist = cdist;
  311. index = static_cast<int>(i);
  312. }
  313. }
  314. if (dist > optimization) {
  315. Vector<Vector2> left, right;
  316. left.resize(index);
  317. for (int i = 0; i < index; i++) {
  318. left.write[i] = v[i];
  319. }
  320. right.resize(v.size() - index);
  321. for (int i = 0; i < right.size(); i++) {
  322. right.write[i] = v[index + i];
  323. }
  324. Vector<Vector2> r1 = rdp(left, optimization);
  325. Vector<Vector2> r2 = rdp(right, optimization);
  326. int middle = r1.size();
  327. r1.resize(r1.size() + r2.size());
  328. for (int i = 0; i < r2.size(); i++) {
  329. r1.write[middle + i] = r2[i];
  330. }
  331. return r1;
  332. } else {
  333. Vector<Vector2> ret;
  334. ret.push_back(v[0]);
  335. ret.push_back(v[v.size() - 1]);
  336. return ret;
  337. }
  338. }
  339. static Vector<Vector2> reduce(const Vector<Vector2> &points, const Rect2i &rect, float epsilon) {
  340. int size = points.size();
  341. // if there are less than 3 points, then we have nothing
  342. ERR_FAIL_COND_V(size < 3, Vector<Vector2>());
  343. // if there are less than 9 points (but more than 3), then we don't need to reduce it
  344. if (size < 9) {
  345. return points;
  346. }
  347. float maxEp = MIN(rect.size.width, rect.size.height);
  348. float ep = CLAMP(epsilon, 0.0, maxEp / 2);
  349. Vector<Vector2> result = rdp(points, ep);
  350. Vector2 last = result[result.size() - 1];
  351. if (last.y > result[0].y && last.distance_to(result[0]) < ep * 0.5f) {
  352. result.write[0].y = last.y;
  353. result.resize(result.size() - 1);
  354. }
  355. return result;
  356. }
  357. struct FillBitsStackEntry {
  358. Point2i pos;
  359. int i;
  360. int j;
  361. };
  362. static void fill_bits(const BitMap *p_src, Ref<BitMap> &p_map, const Point2i &p_pos, const Rect2i &rect) {
  363. // Using a custom stack to work iteratively to avoid stack overflow on big bitmaps
  364. PoolVector<FillBitsStackEntry> stack;
  365. // Tracking size since we won't be shrinking the stack vector
  366. int stack_size = 0;
  367. Point2i pos = p_pos;
  368. int next_i = 0;
  369. int next_j = 0;
  370. bool reenter = true;
  371. bool popped = false;
  372. do {
  373. if (reenter) {
  374. next_i = pos.x - 1;
  375. next_j = pos.y - 1;
  376. reenter = false;
  377. }
  378. for (int i = next_i; i <= pos.x + 1; i++) {
  379. for (int j = next_j; j <= pos.y + 1; j++) {
  380. if (popped) {
  381. // The next loop over j must start normally
  382. next_j = pos.y;
  383. popped = false;
  384. // Skip because an iteration was already executed with current counter values
  385. continue;
  386. }
  387. if (i < rect.position.x || i >= rect.position.x + rect.size.x)
  388. continue;
  389. if (j < rect.position.y || j >= rect.position.y + rect.size.y)
  390. continue;
  391. if (p_map->get_bit(Vector2(i, j)))
  392. continue;
  393. else if (p_src->get_bit(Vector2(i, j))) {
  394. p_map->set_bit(Vector2(i, j), true);
  395. FillBitsStackEntry se = { pos, i, j };
  396. stack.resize(MAX(stack_size + 1, stack.size()));
  397. stack.set(stack_size, se);
  398. stack_size++;
  399. pos = Point2i(i, j);
  400. reenter = true;
  401. break;
  402. }
  403. }
  404. if (reenter) {
  405. break;
  406. }
  407. }
  408. if (!reenter) {
  409. if (stack_size) {
  410. FillBitsStackEntry se = stack.get(stack_size - 1);
  411. stack_size--;
  412. pos = se.pos;
  413. next_i = se.i;
  414. next_j = se.j;
  415. popped = true;
  416. }
  417. }
  418. } while (reenter || popped);
  419. print_verbose("BitMap: Max stack size: " + itos(stack.size()));
  420. }
  421. Vector<Vector<Vector2> > BitMap::clip_opaque_to_polygons(const Rect2 &p_rect, float p_epsilon) const {
  422. Rect2i r = Rect2i(0, 0, width, height).clip(p_rect);
  423. print_verbose("BitMap: Rect: " + r);
  424. Point2i from;
  425. Ref<BitMap> fill;
  426. fill.instance();
  427. fill->create(get_size());
  428. Vector<Vector<Vector2> > polygons;
  429. for (int i = r.position.y; i < r.position.y + r.size.height; i++) {
  430. for (int j = r.position.x; j < r.position.x + r.size.width; j++) {
  431. if (!fill->get_bit(Point2(j, i)) && get_bit(Point2(j, i))) {
  432. Vector<Vector2> polygon = _march_square(r, Point2i(j, i));
  433. print_verbose("BitMap: Pre reduce: " + itos(polygon.size()));
  434. polygon = reduce(polygon, r, p_epsilon);
  435. print_verbose("BitMap: Post reduce: " + itos(polygon.size()));
  436. polygons.push_back(polygon);
  437. fill_bits(this, fill, Point2i(j, i), r);
  438. }
  439. }
  440. }
  441. return polygons;
  442. }
  443. void BitMap::grow_mask(int p_pixels, const Rect2 &p_rect) {
  444. Rect2i r = Rect2i(0, 0, width, height).clip(p_rect);
  445. Ref<BitMap> copy;
  446. copy.instance();
  447. copy->create(get_size());
  448. copy->bitmask = bitmask;
  449. for (int i = r.position.y; i < r.position.y + r.size.height; i++) {
  450. for (int j = r.position.x; j < r.position.x + r.size.width; j++) {
  451. if (copy->get_bit(Point2(j, i)))
  452. continue;
  453. bool found = false;
  454. for (int y = i - p_pixels; y <= i + p_pixels; y++) {
  455. for (int x = j - p_pixels; x <= j + p_pixels; x++) {
  456. if (x < p_rect.position.x || x >= p_rect.position.x + p_rect.size.x)
  457. continue;
  458. if (y < p_rect.position.y || y >= p_rect.position.y + p_rect.size.y)
  459. continue;
  460. float d = Point2(j, i).distance_to(Point2(x, y)) - CMP_EPSILON;
  461. if (d > p_pixels)
  462. continue;
  463. if (copy->get_bit(Point2(x, y))) {
  464. found = true;
  465. break;
  466. }
  467. }
  468. if (found)
  469. break;
  470. }
  471. if (found) {
  472. set_bit(Point2(j, i), true);
  473. }
  474. }
  475. }
  476. }
  477. Array BitMap::_opaque_to_polygons_bind(const Rect2 &p_rect, float p_epsilon) const {
  478. Vector<Vector<Vector2> > result = clip_opaque_to_polygons(p_rect, p_epsilon);
  479. // Convert result to bindable types
  480. Array result_array;
  481. result_array.resize(result.size());
  482. for (int i = 0; i < result.size(); i++) {
  483. const Vector<Vector2> &polygon = result[i];
  484. PoolVector2Array polygon_array;
  485. polygon_array.resize(polygon.size());
  486. {
  487. PoolVector2Array::Write w = polygon_array.write();
  488. for (int j = 0; j < polygon.size(); j++) {
  489. w[j] = polygon[j];
  490. }
  491. }
  492. result_array[i] = polygon_array;
  493. }
  494. return result_array;
  495. }
  496. void BitMap::_bind_methods() {
  497. ClassDB::bind_method(D_METHOD("create", "size"), &BitMap::create);
  498. ClassDB::bind_method(D_METHOD("create_from_image_alpha", "image", "threshold"), &BitMap::create_from_image_alpha, DEFVAL(0.1));
  499. ClassDB::bind_method(D_METHOD("set_bit", "position", "bit"), &BitMap::set_bit);
  500. ClassDB::bind_method(D_METHOD("get_bit", "position"), &BitMap::get_bit);
  501. ClassDB::bind_method(D_METHOD("set_bit_rect", "rect", "bit"), &BitMap::set_bit_rect);
  502. ClassDB::bind_method(D_METHOD("get_true_bit_count"), &BitMap::get_true_bit_count);
  503. ClassDB::bind_method(D_METHOD("get_size"), &BitMap::get_size);
  504. ClassDB::bind_method(D_METHOD("_set_data"), &BitMap::_set_data);
  505. ClassDB::bind_method(D_METHOD("_get_data"), &BitMap::_get_data);
  506. ClassDB::bind_method(D_METHOD("grow_mask", "pixels", "rect"), &BitMap::grow_mask);
  507. ClassDB::bind_method(D_METHOD("opaque_to_polygons", "rect", "epsilon"), &BitMap::_opaque_to_polygons_bind, DEFVAL(2.0));
  508. ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY, "data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_INTERNAL), "_set_data", "_get_data");
  509. }
  510. BitMap::BitMap() {
  511. width = 0;
  512. height = 0;
  513. }
  514. //////////////////////////////////////