imageAPI.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842
  1. 
  2. // zlib open source license
  3. //
  4. // Copyright (c) 2017 to 2022 David Forsgren Piuva
  5. //
  6. // This software is provided 'as-is', without any express or implied
  7. // warranty. In no event will the authors be held liable for any damages
  8. // arising from the use of this software.
  9. //
  10. // Permission is granted to anyone to use this software for any purpose,
  11. // including commercial applications, and to alter it and redistribute it
  12. // freely, subject to the following restrictions:
  13. //
  14. // 1. The origin of this software must not be misrepresented; you must not
  15. // claim that you wrote the original software. If you use this software
  16. // in a product, an acknowledgment in the product documentation would be
  17. // appreciated but is not required.
  18. //
  19. // 2. Altered source versions must be plainly marked as such, and must not be
  20. // misrepresented as being the original software.
  21. //
  22. // 3. This notice may not be removed or altered from any source
  23. // distribution.
  24. #define DFPSR_INTERNAL_ACCESS
  25. #include <limits>
  26. #include <cassert>
  27. #include "imageAPI.h"
  28. #include "drawAPI.h"
  29. #include "fileAPI.h"
  30. #include "../image/draw.h"
  31. #include "../image/internal/imageInternal.h"
  32. #include "../image/stbImage/stbImageWrapper.h"
  33. #include "../math/scalar.h"
  34. using namespace dsr;
  35. // Constructors
  36. AlignedImageU8 dsr::image_create_U8(int32_t width, int32_t height) {
  37. return AlignedImageU8(std::make_shared<ImageU8Impl>(width, height));
  38. }
  39. AlignedImageU16 dsr::image_create_U16(int32_t width, int32_t height) {
  40. return AlignedImageU16(std::make_shared<ImageU16Impl>(width, height));
  41. }
  42. AlignedImageF32 dsr::image_create_F32(int32_t width, int32_t height) {
  43. return AlignedImageF32(std::make_shared<ImageF32Impl>(width, height));
  44. }
  45. OrderedImageRgbaU8 dsr::image_create_RgbaU8(int32_t width, int32_t height) {
  46. return OrderedImageRgbaU8(std::make_shared<ImageRgbaU8Impl>(width, height));
  47. }
  48. AlignedImageRgbaU8 dsr::image_create_RgbaU8_native(int32_t width, int32_t height, PackOrderIndex packOrderIndex) {
  49. return AlignedImageRgbaU8(std::make_shared<ImageRgbaU8Impl>(width, height, packOrderIndex));
  50. }
  51. // Loading from data pointer
  52. OrderedImageRgbaU8 dsr::image_decode_RgbaU8(const SafePointer<uint8_t> data, int size) {
  53. if (data.isNotNull()) {
  54. return image_stb_decode_RgbaU8(data, size);
  55. } else {
  56. return OrderedImageRgbaU8();
  57. }
  58. }
  59. // Loading from buffer
  60. OrderedImageRgbaU8 dsr::image_decode_RgbaU8(const Buffer& fileContent) {
  61. return image_decode_RgbaU8(buffer_getSafeData<uint8_t>(fileContent, "image file buffer"), buffer_getSize(fileContent));
  62. }
  63. // Loading from file
  64. OrderedImageRgbaU8 dsr::image_load_RgbaU8(const String& filename, bool mustExist) {
  65. OrderedImageRgbaU8 result;
  66. Buffer fileContent = file_loadBuffer(filename, mustExist);
  67. if (buffer_exists(fileContent)) {
  68. result = image_decode_RgbaU8(fileContent);
  69. if (mustExist && !image_exists(result)) {
  70. throwError(U"buffer_save: Can't save a buffer that don't exist to a file.\n");
  71. }
  72. }
  73. return result;
  74. }
  75. // Pre-condition: image exists.
  76. // Post-condition: Returns true if the stride is larger than the image's width.
  77. static bool imageIsPadded(const ImageRgbaU8 &image) {
  78. return image_getWidth(image) * 4 < image_getStride(image);
  79. }
  80. Buffer dsr::image_encode(const ImageRgbaU8 &image, ImageFileFormat format, int quality) {
  81. if (buffer_exists) {
  82. ImageRgbaU8 orderedImage;
  83. if (image_getPackOrderIndex(image) != PackOrderIndex::RGBA) {
  84. // Repack into RGBA.
  85. orderedImage = image_clone(image);
  86. } else {
  87. // Take the image handle as is.
  88. orderedImage = image;
  89. }
  90. if (imageIsPadded(orderedImage) && format != ImageFileFormat::PNG) {
  91. // If orderedImage is padded and it's not requested as PNG, the padding has to be removed first.
  92. return image_stb_encode(image_removePadding(orderedImage), format, quality);
  93. } else {
  94. // Send orderedImage directly to encoding.
  95. return image_stb_encode(orderedImage, format, quality);
  96. }
  97. } else {
  98. return Buffer();
  99. }
  100. }
  101. static ImageFileFormat detectImageFileExtension(const String& filename) {
  102. ImageFileFormat result = ImageFileFormat::Unknown;
  103. int lastDotIndex = string_findLast(filename, U'.');
  104. if (lastDotIndex != -1) {
  105. ReadableString extension = string_upperCase(file_getExtension(filename));
  106. if (string_match(extension, U"JPG") || string_match(extension, U"JPEG")) {
  107. result = ImageFileFormat::JPG;
  108. } else if (string_match(extension, U"PNG")) {
  109. result = ImageFileFormat::PNG;
  110. } else if (string_match(extension, U"TARGA") || string_match(extension, U"TGA")) {
  111. result = ImageFileFormat::TGA;
  112. } else if (string_match(extension, U"BMP")) {
  113. result = ImageFileFormat::BMP;
  114. }
  115. }
  116. return result;
  117. }
  118. bool dsr::image_save(const ImageRgbaU8 &image, const String& filename, bool mustWork, int quality) {
  119. ImageFileFormat extension = detectImageFileExtension(filename);
  120. Buffer buffer;
  121. if (extension == ImageFileFormat::Unknown) {
  122. ReadableString extension = file_getExtension(filename);
  123. if (mustWork) { throwError(U"The extension *.", extension, " in ", filename, " is not a supported image format.\n"); }
  124. return false;
  125. } else {
  126. buffer = image_encode(image, extension, quality);
  127. }
  128. if (buffer_exists(buffer)) {
  129. return file_saveBuffer(filename, buffer, mustWork);
  130. } else {
  131. if (mustWork) { throwError(U"Failed to encode an image that was going to be saved as ", filename, "\n"); }
  132. return false;
  133. }
  134. }
  135. #define GET_OPTIONAL(SOURCE,DEFAULT) \
  136. if (image) { \
  137. return SOURCE; \
  138. } else { \
  139. return DEFAULT; \
  140. }
  141. // Properties
  142. int32_t dsr::image_getWidth(const ImageU8& image) { GET_OPTIONAL(image->width, 0); }
  143. int32_t dsr::image_getWidth(const ImageU16& image) { GET_OPTIONAL(image->width, 0); }
  144. int32_t dsr::image_getWidth(const ImageF32& image) { GET_OPTIONAL(image->width, 0); }
  145. int32_t dsr::image_getWidth(const ImageRgbaU8& image) { GET_OPTIONAL(image->width, 0); }
  146. int32_t dsr::image_getHeight(const ImageU8& image) { GET_OPTIONAL(image->height, 0); }
  147. int32_t dsr::image_getHeight(const ImageU16& image) { GET_OPTIONAL(image->height, 0); }
  148. int32_t dsr::image_getHeight(const ImageF32& image) { GET_OPTIONAL(image->height, 0); }
  149. int32_t dsr::image_getHeight(const ImageRgbaU8& image) { GET_OPTIONAL(image->height, 0); }
  150. int32_t dsr::image_getStride(const ImageU8& image) { GET_OPTIONAL(image->stride, 0); }
  151. int32_t dsr::image_getStride(const ImageU16& image) { GET_OPTIONAL(image->stride, 0); }
  152. int32_t dsr::image_getStride(const ImageF32& image) { GET_OPTIONAL(image->stride, 0); }
  153. int32_t dsr::image_getStride(const ImageRgbaU8& image) { GET_OPTIONAL(image->stride, 0); }
  154. IRect dsr::image_getBound(const ImageU8& image) { GET_OPTIONAL(IRect(0, 0, image->width, image->height), IRect()); }
  155. IRect dsr::image_getBound(const ImageU16& image) { GET_OPTIONAL(IRect(0, 0, image->width, image->height), IRect()); }
  156. IRect dsr::image_getBound(const ImageF32& image) { GET_OPTIONAL(IRect(0, 0, image->width, image->height), IRect()); }
  157. IRect dsr::image_getBound(const ImageRgbaU8& image) { GET_OPTIONAL(IRect(0, 0, image->width, image->height), IRect()); }
  158. bool dsr::image_exists(const ImageU8& image) { GET_OPTIONAL(true, false); }
  159. bool dsr::image_exists(const ImageU16& image) { GET_OPTIONAL(true, false); }
  160. bool dsr::image_exists(const ImageF32& image) { GET_OPTIONAL(true, false); }
  161. bool dsr::image_exists(const ImageRgbaU8& image) { GET_OPTIONAL(true, false); }
  162. int dsr::image_useCount(const ImageU8& image) { return image.use_count(); }
  163. int dsr::image_useCount(const ImageU16& image) { return image.use_count(); }
  164. int dsr::image_useCount(const ImageF32& image) { return image.use_count(); }
  165. int dsr::image_useCount(const ImageRgbaU8& image) { return image.use_count(); }
  166. PackOrderIndex dsr::image_getPackOrderIndex(const ImageRgbaU8& image) {
  167. GET_OPTIONAL(image->packOrder.packOrderIndex, PackOrderIndex::RGBA);
  168. }
  169. // Texture
  170. void dsr::image_generatePyramid(ImageRgbaU8& image) {
  171. if (image) {
  172. image->generatePyramid();
  173. }
  174. }
  175. void dsr::image_removePyramid(ImageRgbaU8& image) {
  176. if (image) {
  177. image->removePyramid();
  178. }
  179. }
  180. bool dsr::image_hasPyramid(const ImageRgbaU8& image) {
  181. GET_OPTIONAL(image->texture.hasMipBuffer(), false);
  182. }
  183. bool dsr::image_isTexture(const ImageRgbaU8& image) {
  184. GET_OPTIONAL(image->isTexture(), false);
  185. }
  186. // Pixel access
  187. #define INSIDE_XY (x >= 0 && x < image->width && y >= 0 && y < image->height)
  188. #define CLAMP_XY \
  189. if (x < 0) { x = 0; } \
  190. if (y < 0) { y = 0; } \
  191. if (x >= image->width) { x = image->width - 1; } \
  192. if (y >= image->height) { y = image->height - 1; }
  193. #define TILE_XY \
  194. x = signedModulo(x, image->width); \
  195. y = signedModulo(y, image->height);
  196. void dsr::image_writePixel(ImageU8& image, int32_t x, int32_t y, int32_t color) {
  197. if (image) {
  198. if (INSIDE_XY) {
  199. if (color < 0) { color = 0; }
  200. if (color > 255) { color = 255; }
  201. ImageU8Impl::writePixel_unsafe(*image, x, y, color);
  202. }
  203. }
  204. }
  205. void dsr::image_writePixel(ImageU16& image, int32_t x, int32_t y, int32_t color) {
  206. if (image) {
  207. if (INSIDE_XY) {
  208. if (color < 0) { color = 0; }
  209. if (color > 65535) { color = 65535; }
  210. ImageU16Impl::writePixel_unsafe(*image, x, y, color);
  211. }
  212. }
  213. }
  214. void dsr::image_writePixel(ImageF32& image, int32_t x, int32_t y, float color) {
  215. if (image) {
  216. if (INSIDE_XY) {
  217. ImageF32Impl::writePixel_unsafe(*image, x, y, color);
  218. }
  219. }
  220. }
  221. void dsr::image_writePixel(ImageRgbaU8& image, int32_t x, int32_t y, const ColorRgbaI32& color) {
  222. if (image) {
  223. if (INSIDE_XY) {
  224. ImageRgbaU8Impl::writePixel_unsafe(*image, x, y, image->packRgba(color.saturate()));
  225. }
  226. }
  227. }
  228. int32_t dsr::image_readPixel_border(const ImageU8& image, int32_t x, int32_t y, int32_t border) {
  229. if (image) {
  230. if (INSIDE_XY) {
  231. return ImageU8Impl::readPixel_unsafe(*image, x, y);
  232. } else {
  233. return border;
  234. }
  235. } else {
  236. return 0;
  237. }
  238. }
  239. int32_t dsr::image_readPixel_border(const ImageU16& image, int32_t x, int32_t y, int32_t border) {
  240. if (image) {
  241. if (INSIDE_XY) {
  242. return ImageU16Impl::readPixel_unsafe(*image, x, y);
  243. } else {
  244. return border;
  245. }
  246. } else {
  247. return 0;
  248. }
  249. }
  250. float dsr::image_readPixel_border(const ImageF32& image, int32_t x, int32_t y, float border) {
  251. if (image) {
  252. if (INSIDE_XY) {
  253. return ImageF32Impl::readPixel_unsafe(*image, x, y);
  254. } else {
  255. return border;
  256. }
  257. } else {
  258. return 0.0f;
  259. }
  260. }
  261. ColorRgbaI32 dsr::image_readPixel_border(const ImageRgbaU8& image, int32_t x, int32_t y, const ColorRgbaI32& border) {
  262. if (image) {
  263. if (INSIDE_XY) {
  264. return image->unpackRgba(ImageRgbaU8Impl::readPixel_unsafe(*image, x, y));
  265. } else {
  266. return border; // Can return unsaturated colors as error codes
  267. }
  268. } else {
  269. return ColorRgbaI32();
  270. }
  271. }
  272. uint8_t dsr::image_readPixel_clamp(const ImageU8& image, int32_t x, int32_t y) {
  273. if (image) {
  274. CLAMP_XY;
  275. return ImageU8Impl::readPixel_unsafe(*image, x, y);
  276. } else {
  277. return 0;
  278. }
  279. }
  280. uint16_t dsr::image_readPixel_clamp(const ImageU16& image, int32_t x, int32_t y) {
  281. if (image) {
  282. CLAMP_XY;
  283. return ImageU16Impl::readPixel_unsafe(*image, x, y);
  284. } else {
  285. return 0;
  286. }
  287. }
  288. float dsr::image_readPixel_clamp(const ImageF32& image, int32_t x, int32_t y) {
  289. if (image) {
  290. CLAMP_XY;
  291. return ImageF32Impl::readPixel_unsafe(*image, x, y);
  292. } else {
  293. return 0.0f;
  294. }
  295. }
  296. ColorRgbaI32 dsr::image_readPixel_clamp(const ImageRgbaU8& image, int32_t x, int32_t y) {
  297. if (image) {
  298. CLAMP_XY;
  299. return image->unpackRgba(ImageRgbaU8Impl::readPixel_unsafe(*image, x, y));
  300. } else {
  301. return ColorRgbaI32();
  302. }
  303. }
  304. uint8_t dsr::image_readPixel_tile(const ImageU8& image, int32_t x, int32_t y) {
  305. if (image) {
  306. TILE_XY;
  307. return ImageU8Impl::readPixel_unsafe(*image, x, y);
  308. } else {
  309. return 0;
  310. }
  311. }
  312. uint16_t dsr::image_readPixel_tile(const ImageU16& image, int32_t x, int32_t y) {
  313. if (image) {
  314. TILE_XY;
  315. return ImageU16Impl::readPixel_unsafe(*image, x, y);
  316. } else {
  317. return 0;
  318. }
  319. }
  320. float dsr::image_readPixel_tile(const ImageF32& image, int32_t x, int32_t y) {
  321. if (image) {
  322. TILE_XY;
  323. return ImageF32Impl::readPixel_unsafe(*image, x, y);
  324. } else {
  325. return 0.0f;
  326. }
  327. }
  328. ColorRgbaI32 dsr::image_readPixel_tile(const ImageRgbaU8& image, int32_t x, int32_t y) {
  329. if (image) {
  330. TILE_XY;
  331. return image->unpackRgba(ImageRgbaU8Impl::readPixel_unsafe(*image, x, y));
  332. } else {
  333. return ColorRgbaI32();
  334. }
  335. }
  336. void dsr::image_fill(ImageU8& image, int32_t color) {
  337. if (image) {
  338. imageImpl_draw_solidRectangle(*image, imageInternal::getBound(*image), color);
  339. }
  340. }
  341. void dsr::image_fill(ImageU16& image, int32_t color) {
  342. if (image) {
  343. imageImpl_draw_solidRectangle(*image, imageInternal::getBound(*image), color);
  344. }
  345. }
  346. void dsr::image_fill(ImageF32& image, float color) {
  347. if (image) {
  348. imageImpl_draw_solidRectangle(*image, imageInternal::getBound(*image), color);
  349. }
  350. }
  351. void dsr::image_fill(ImageRgbaU8& image, const ColorRgbaI32& color) {
  352. if (image) {
  353. imageImpl_draw_solidRectangle(*image, imageInternal::getBound(*image), color);
  354. }
  355. }
  356. AlignedImageU8 dsr::image_clone(const ImageU8& image) {
  357. if (image) {
  358. AlignedImageU8 result = image_create_U8(image->width, image->height);
  359. draw_copy(result, image);
  360. return result;
  361. } else {
  362. return AlignedImageU8(); // Null gives null
  363. }
  364. }
  365. AlignedImageU16 dsr::image_clone(const ImageU16& image) {
  366. if (image) {
  367. AlignedImageU16 result = image_create_U16(image->width, image->height);
  368. draw_copy(result, image);
  369. return result;
  370. } else {
  371. return AlignedImageU16(); // Null gives null
  372. }
  373. }
  374. AlignedImageF32 dsr::image_clone(const ImageF32& image) {
  375. if (image) {
  376. AlignedImageF32 result = image_create_F32(image->width, image->height);
  377. draw_copy(result, image);
  378. return result;
  379. } else {
  380. return AlignedImageF32(); // Null gives null
  381. }
  382. }
  383. OrderedImageRgbaU8 dsr::image_clone(const ImageRgbaU8& image) {
  384. if (image) {
  385. OrderedImageRgbaU8 result = image_create_RgbaU8(image->width, image->height);
  386. draw_copy(result, image);
  387. return result;
  388. } else {
  389. return OrderedImageRgbaU8(); // Null gives null
  390. }
  391. }
  392. ImageRgbaU8 dsr::image_removePadding(const ImageRgbaU8& image) {
  393. if (image) {
  394. // TODO: Copy the implementation of getWithoutPadding, to create ImageRgbaU8 directly
  395. return ImageRgbaU8(image->getWithoutPadding());
  396. } else {
  397. return ImageRgbaU8(); // Null gives null
  398. }
  399. }
  400. AlignedImageU8 dsr::image_get_red(const ImageRgbaU8& image) {
  401. if (image) {
  402. // TODO: Copy the implementation of getChannel, to create ImageU8 directly
  403. return AlignedImageU8(image->getChannel(image->packOrder.redIndex));
  404. } else {
  405. return AlignedImageU8(); // Null gives null
  406. }
  407. }
  408. AlignedImageU8 dsr::image_get_green(const ImageRgbaU8& image) {
  409. if (image) {
  410. // TODO: Copy the implementation of getChannel, to create ImageU8 directly
  411. return AlignedImageU8(image->getChannel(image->packOrder.greenIndex));
  412. } else {
  413. return AlignedImageU8(); // Null gives null
  414. }
  415. }
  416. AlignedImageU8 dsr::image_get_blue(const ImageRgbaU8& image) {
  417. if (image) {
  418. // TODO: Copy the implementation of getChannel, to create ImageU8 directly
  419. return AlignedImageU8(image->getChannel(image->packOrder.blueIndex));
  420. } else {
  421. return AlignedImageU8(); // Null gives null
  422. }
  423. }
  424. AlignedImageU8 dsr::image_get_alpha(const ImageRgbaU8& image) {
  425. if (image) {
  426. // TODO: Copy the implementation of getChannel, to create ImageU8 directly
  427. return AlignedImageU8(image->getChannel(image->packOrder.alphaIndex));
  428. } else {
  429. return AlignedImageU8(); // Null gives null
  430. }
  431. }
  432. static inline int32_t readColor(const ImageU8& channel, int x, int y) {
  433. return ImageU8Impl::readPixel_unsafe(*channel, x, y);
  434. }
  435. static inline int32_t readColor(int32_t color, int x, int y) {
  436. return color;
  437. }
  438. template <typename R, typename G, typename B, typename A>
  439. static OrderedImageRgbaU8 pack_template(int32_t width, int32_t height, R red, G green, B blue, A alpha) {
  440. OrderedImageRgbaU8 result = image_create_RgbaU8(width, height);
  441. for (int y = 0; y < height; y++) {
  442. for (int x = 0; x < width; x++) {
  443. ColorRgbaI32 color = ColorRgbaI32(readColor(red, x, y), readColor(green, x, y), readColor(blue, x, y), readColor(alpha, x, y));
  444. image_writePixel(result, x, y, color);
  445. }
  446. }
  447. return result;
  448. }
  449. #define PACK1(FIRST) \
  450. if (FIRST) { \
  451. return pack_template(FIRST->width, FIRST->height, red, green, blue, alpha); \
  452. } else { \
  453. return OrderedImageRgbaU8(); \
  454. }
  455. OrderedImageRgbaU8 dsr::image_pack(const ImageU8& red, int32_t green, int32_t blue, int32_t alpha) { PACK1(red); }
  456. OrderedImageRgbaU8 dsr::image_pack(int32_t red, const ImageU8& green, int32_t blue, int32_t alpha) { PACK1(green); }
  457. OrderedImageRgbaU8 dsr::image_pack(int32_t red, int32_t green, const ImageU8& blue, int32_t alpha) { PACK1(blue); }
  458. OrderedImageRgbaU8 dsr::image_pack(int32_t red, int32_t green, int32_t blue, const ImageU8& alpha) { PACK1(alpha); }
  459. #define PACK2(FIRST,SECOND) \
  460. if (FIRST && SECOND) { \
  461. if (FIRST->width != SECOND->width || FIRST->height != SECOND->height) { \
  462. throwError("Cannot pack two channels of different size!\n"); \
  463. } \
  464. return pack_template(FIRST->width, FIRST->height, red, green, blue, alpha); \
  465. } else { \
  466. return OrderedImageRgbaU8(); \
  467. }
  468. OrderedImageRgbaU8 dsr::image_pack(const ImageU8& red, const ImageU8& green, int32_t blue, int32_t alpha) { PACK2(red,green) }
  469. OrderedImageRgbaU8 dsr::image_pack(const ImageU8& red, int32_t green, const ImageU8& blue, int32_t alpha) { PACK2(red,blue) }
  470. OrderedImageRgbaU8 dsr::image_pack(const ImageU8& red, int32_t green, int32_t blue, const ImageU8& alpha) { PACK2(red,alpha) }
  471. OrderedImageRgbaU8 dsr::image_pack(int32_t red, const ImageU8& green, const ImageU8& blue, int32_t alpha) { PACK2(green,blue) }
  472. OrderedImageRgbaU8 dsr::image_pack(int32_t red, const ImageU8& green, int32_t blue, const ImageU8& alpha) { PACK2(green,alpha) }
  473. OrderedImageRgbaU8 dsr::image_pack(int32_t red, int32_t green, const ImageU8& blue, const ImageU8& alpha) { PACK2(blue,alpha) }
  474. #define PACK3(FIRST,SECOND,THIRD) \
  475. if (FIRST && SECOND && THIRD) { \
  476. if (FIRST->width != SECOND->width || FIRST->height != SECOND->height \
  477. || FIRST->width != THIRD->width || FIRST->height != THIRD->height) { \
  478. throwError("Cannot pack three channels of different size!\n"); \
  479. } \
  480. return pack_template(FIRST->width, FIRST->height, red, green, blue, alpha); \
  481. } else { \
  482. return OrderedImageRgbaU8(); \
  483. }
  484. OrderedImageRgbaU8 dsr::image_pack(int32_t red, const ImageU8& green, const ImageU8& blue, const ImageU8& alpha) { PACK3(green, blue, alpha) }
  485. OrderedImageRgbaU8 dsr::image_pack(const ImageU8& red, int32_t green, const ImageU8& blue, const ImageU8& alpha) { PACK3(red, blue, alpha) }
  486. OrderedImageRgbaU8 dsr::image_pack(const ImageU8& red, const ImageU8& green, int32_t blue, const ImageU8& alpha) { PACK3(red, green, alpha) }
  487. OrderedImageRgbaU8 dsr::image_pack(const ImageU8& red, const ImageU8& green, const ImageU8& blue, int32_t alpha) { PACK3(red, green, blue) }
  488. // TODO: Optimize using zip instructions
  489. #define PACK4(FIRST,SECOND,THIRD,FOURTH) \
  490. if (FIRST && SECOND && THIRD && FOURTH) { \
  491. if (FIRST->width != SECOND->width || FIRST->height != SECOND->height \
  492. || FIRST->width != THIRD->width || FIRST->height != THIRD->height \
  493. || FIRST->width != FOURTH->width || FIRST->height != FOURTH->height) { \
  494. throwError("Cannot pack four channels of different size!\n"); \
  495. } \
  496. return pack_template(FIRST->width, FIRST->height, red, green, blue, alpha); \
  497. } else { \
  498. return OrderedImageRgbaU8(); \
  499. }
  500. OrderedImageRgbaU8 dsr::image_pack(const ImageU8& red, const ImageU8& green, const ImageU8& blue, const ImageU8& alpha) { PACK4(red, green, blue, alpha) }
  501. // Convert a grayscale image into an ascii image using the given alphabet.
  502. // Since all 256 characters cannot be in the alphabet, the encoding is lossy.
  503. // Each line is stored within <> to prevent text editors from removing meaningful white space.
  504. // The first line contains the given alphabet as a gradient from black to white.
  505. // Preconditions:
  506. // alphabet may not have extended ascii, non printable, '\', '"', '>' or linebreak
  507. // width <= stride
  508. // size of monochromeImage = height * stride
  509. // Example alphabet: " .,-_':;!+~=^?*abcdefghijklmnopqrstuvwxyz()[]{}|&@#0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  510. String dsr::image_toAscii(const ImageU8& image, const String& alphabet) {
  511. if (!image_exists(image)) {
  512. return U"null";
  513. }
  514. String result;
  515. char alphabetMap[256];
  516. int alphabetSize = string_length(alphabet);
  517. int width = image_getWidth(image);
  518. int height = image_getHeight(image);
  519. string_reserve(result, ((width + 4) * height) + alphabetSize + 5);
  520. double scale = (double)(alphabetSize - 1) / 255.0;
  521. double output = 0.49;
  522. for (int rawValue = 0; rawValue < 256; rawValue++) {
  523. int charIndex = (int)output;
  524. if (charIndex < 0) charIndex = 0;
  525. if (charIndex > alphabetSize - 1) charIndex = alphabetSize - 1;
  526. alphabetMap[rawValue] = alphabet[charIndex];
  527. output += scale;
  528. }
  529. string_appendChar(result, U'<');
  530. for (int charIndex = 0; charIndex < alphabetSize; charIndex++) {
  531. string_appendChar(result, alphabet[charIndex]);
  532. }
  533. string_append(result, U">\n");
  534. for (int y = 0; y < height; y++) {
  535. string_appendChar(result, U'<');
  536. for (int x = 0; x < width; x++) {
  537. string_appendChar(result, alphabetMap[image_readPixel_clamp(image, x, y)]);
  538. }
  539. string_append(result, U">\n");
  540. }
  541. return result;
  542. }
  543. String dsr::image_toAscii(const ImageU8& image) {
  544. return image_toAscii(image, U" .,-_':;!+~=^?*abcdefghijklmnopqrstuvwxyz()[]{}|&@#0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ");
  545. }
  546. // Create a monochrome image from the ascii image in content.
  547. // String is used instead of ReadableString, so that the content can be decompressed from 8-bit strings in the binary.
  548. AlignedImageU8 dsr::image_fromAscii(const String& content) {
  549. char alphabet[128];
  550. uint8_t alphabetMap[128];
  551. char current;
  552. int x = 0;
  553. int y = -1;
  554. int width = 0;
  555. int height = 0;
  556. int alphabetSize = 0;
  557. int contentSize = string_length(content);
  558. bool quoted = false;
  559. int i = 0;
  560. while (i < contentSize && ((current = content[i]) != '\0')) {
  561. if (quoted) {
  562. if (y < 0) {
  563. if (current == '>') {
  564. quoted = false;
  565. y = 0;
  566. } else if (alphabetSize < 128) {
  567. alphabet[alphabetSize] = current;
  568. alphabetSize++;
  569. }
  570. } else {
  571. if (current == '>') {
  572. quoted = false;
  573. if (width < x) width = x;
  574. y++;
  575. x = 0;
  576. } else {
  577. x++;
  578. }
  579. }
  580. } else if (current == '<') {
  581. quoted = true;
  582. }
  583. i++;
  584. }
  585. if (alphabetSize < 2) {
  586. throwError(U"The alphabet needs at least two characters!");
  587. }
  588. height = y;
  589. if (x > 0) {
  590. throwError(U"All ascii images must end with a linebreak!");
  591. }
  592. for (i = 0; i < 128; i++) {
  593. alphabetMap[i] = 0;
  594. }
  595. for (i = 0; i < alphabetSize; i++) {
  596. int code = (int)(alphabet[i]);
  597. if (code < 32 || code > 126) {
  598. throwError(U"Ascii image contained non-printable standard ascii! Use codes 32 to 126.");
  599. }
  600. if (alphabetMap[code] > 0) {
  601. throwError(U"A character in the alphabet was used more than once!");
  602. }
  603. int value = (int)(((double)i) * (255.0f / ((double)(alphabetSize - 1))));
  604. if (value < 0) value = 0;
  605. if (value > 255) value = 255;
  606. alphabetMap[code] = value;
  607. }
  608. if (width <= 0 || height <= 0) {
  609. throwError(U"An ascii image had zero dimensions!");
  610. }
  611. AlignedImageU8 result = image_create_U8(width, height);
  612. x = 0; y = -1;
  613. quoted = false;
  614. i = 0;
  615. while (i < contentSize && ((current = content[i]) != '\0')) {
  616. if (quoted) {
  617. if (current == '>') {
  618. quoted = false;
  619. if (y >= 0 && x != width) {
  620. throwError(U"Lines in the ascii image do not have the same lengths.");
  621. }
  622. y++;
  623. x = 0;
  624. } else if (y >= 0) {
  625. int code = (int)current;
  626. if (code < 0) code = 0;
  627. if (code > 127) code = 127;
  628. image_writePixel(result, x, y, alphabetMap[code]);
  629. x++;
  630. }
  631. } else if (current == '<') {
  632. quoted = true;
  633. }
  634. i++;
  635. }
  636. return result;
  637. }
  638. // TODO: Try to recycle the memory to reduce overhead from heap allocating heads pointing to existing buffers
  639. template <typename IMAGE_TYPE, typename VALUE_TYPE>
  640. static inline IMAGE_TYPE subImage_template(const IMAGE_TYPE& image, const IRect& region) {
  641. if (image) {
  642. IRect cut = IRect::cut(imageInternal::getBound(*image), region);
  643. if (cut.hasArea()) {
  644. intptr_t newOffset = image->startOffset + (cut.left() * image->pixelSize) + (cut.top() * image->stride);
  645. return IMAGE_TYPE(std::make_shared<VALUE_TYPE>(cut.width(), cut.height(), image->stride, image->buffer, newOffset));
  646. }
  647. }
  648. return IMAGE_TYPE(); // Null if where are no overlapping pixels
  649. }
  650. template <typename IMAGE_TYPE, typename VALUE_TYPE>
  651. static inline IMAGE_TYPE subImage_template_withPackOrder(const IMAGE_TYPE& image, const IRect& region) {
  652. if (image) {
  653. IRect cut = IRect::cut(imageInternal::getBound(*image), region);
  654. if (cut.hasArea()) {
  655. intptr_t newOffset = image->startOffset + (cut.left() * image->pixelSize) + (cut.top() * image->stride);
  656. return IMAGE_TYPE(std::make_shared<VALUE_TYPE>(cut.width(), cut.height(), image->stride, image->buffer, newOffset, image->packOrder));
  657. }
  658. }
  659. return IMAGE_TYPE(); // Null if where are no overlapping pixels
  660. }
  661. ImageU8 dsr::image_getSubImage(const ImageU8& image, const IRect& region) {
  662. return subImage_template<ImageU8, ImageU8Impl>(image, region);
  663. }
  664. ImageU16 dsr::image_getSubImage(const ImageU16& image, const IRect& region) {
  665. return subImage_template<ImageU16, ImageU16Impl>(image, region);
  666. }
  667. ImageF32 dsr::image_getSubImage(const ImageF32& image, const IRect& region) {
  668. return subImage_template<ImageF32, ImageF32Impl>(image, region);
  669. }
  670. ImageRgbaU8 dsr::image_getSubImage(const ImageRgbaU8& image, const IRect& region) {
  671. return subImage_template_withPackOrder<ImageRgbaU8, ImageRgbaU8Impl>(image, region);
  672. }
  673. template <typename IMAGE_TYPE, int CHANNELS, typename ELEMENT_TYPE>
  674. ELEMENT_TYPE maxDifference_template(const IMAGE_TYPE& imageA, const IMAGE_TYPE& imageB) {
  675. if (imageA.width != imageB.width || imageA.height != imageB.height) {
  676. return std::numeric_limits<ELEMENT_TYPE>::max();
  677. } else {
  678. ELEMENT_TYPE maxDifference = 0;
  679. const SafePointer<ELEMENT_TYPE> rowDataA = imageInternal::getSafeData<ELEMENT_TYPE>(imageA);
  680. const SafePointer<ELEMENT_TYPE> rowDataB = imageInternal::getSafeData<ELEMENT_TYPE>(imageB);
  681. for (int y = 0; y < imageA.height; y++) {
  682. const SafePointer<ELEMENT_TYPE> pixelDataA = rowDataA;
  683. const SafePointer<ELEMENT_TYPE> pixelDataB = rowDataB;
  684. for (int x = 0; x < imageA.width; x++) {
  685. for (int c = 0; c < CHANNELS; c++) {
  686. ELEMENT_TYPE difference = absDiff(*pixelDataA, *pixelDataB);
  687. if (difference > maxDifference) {
  688. maxDifference = difference;
  689. }
  690. pixelDataA += 1;
  691. pixelDataB += 1;
  692. }
  693. }
  694. rowDataA.increaseBytes(imageA.stride);
  695. rowDataB.increaseBytes(imageB.stride);
  696. }
  697. return maxDifference;
  698. }
  699. }
  700. uint8_t dsr::image_maxDifference(const ImageU8& imageA, const ImageU8& imageB) {
  701. if (imageA && imageB) {
  702. return maxDifference_template<ImageU8Impl, 1, uint8_t>(*imageA, *imageB);
  703. } else {
  704. return std::numeric_limits<uint8_t>::infinity();
  705. }
  706. }
  707. uint16_t dsr::image_maxDifference(const ImageU16& imageA, const ImageU16& imageB) {
  708. if (imageA && imageB) {
  709. return maxDifference_template<ImageU16Impl, 1, uint16_t>(*imageA, *imageB);
  710. } else {
  711. return std::numeric_limits<uint16_t>::infinity();
  712. }
  713. }
  714. float dsr::image_maxDifference(const ImageF32& imageA, const ImageF32& imageB) {
  715. if (imageA && imageB) {
  716. return maxDifference_template<ImageF32Impl, 1, float>(*imageA, *imageB);
  717. } else {
  718. return std::numeric_limits<float>::infinity();
  719. }
  720. }
  721. uint8_t dsr::image_maxDifference(const ImageRgbaU8& imageA, const ImageRgbaU8& imageB) {
  722. if (imageA && imageB) {
  723. return maxDifference_template<ImageRgbaU8Impl, 4, uint8_t>(*imageA, *imageB);
  724. } else {
  725. return std::numeric_limits<uint8_t>::infinity();
  726. }
  727. }
  728. SafePointer<uint8_t> dsr::image_getSafePointer(const ImageU8& image, int rowIndex) {
  729. if (image) {
  730. return imageInternal::getSafeData<uint8_t>(image.get(), rowIndex);
  731. } else {
  732. return SafePointer<uint8_t>();
  733. }
  734. }
  735. SafePointer<uint16_t> dsr::image_getSafePointer(const ImageU16& image, int rowIndex) {
  736. if (image) {
  737. return imageInternal::getSafeData<uint16_t>(image.get(), rowIndex);
  738. } else {
  739. return SafePointer<uint16_t>();
  740. }
  741. }
  742. SafePointer<float> dsr::image_getSafePointer(const ImageF32& image, int rowIndex) {
  743. if (image) {
  744. return imageInternal::getSafeData<float>(image.get(), rowIndex);
  745. } else {
  746. return SafePointer<float>();
  747. }
  748. }
  749. SafePointer<uint32_t> dsr::image_getSafePointer(const ImageRgbaU8& image, int rowIndex) {
  750. if (image) {
  751. return imageInternal::getSafeData<uint32_t>(image.get(), rowIndex);
  752. } else {
  753. return SafePointer<uint32_t>();
  754. }
  755. }
  756. SafePointer<uint8_t> dsr::image_getSafePointer_channels(const ImageRgbaU8& image, int rowIndex) {
  757. if (image) {
  758. return imageInternal::getSafeData<uint8_t>(image.get(), rowIndex);
  759. } else {
  760. return SafePointer<uint8_t>();
  761. }
  762. }
  763. void dsr::image_dangerous_replaceDestructor(ImageU8& image, const std::function<void(uint8_t *)>& newDestructor) {
  764. if (image) { return buffer_replaceDestructor(image->buffer, newDestructor); }
  765. }
  766. void dsr::image_dangerous_replaceDestructor(ImageU16& image, const std::function<void(uint8_t *)>& newDestructor) {
  767. if (image) { return buffer_replaceDestructor(image->buffer, newDestructor); }
  768. }
  769. void dsr::image_dangerous_replaceDestructor(ImageF32& image, const std::function<void(uint8_t *)>& newDestructor) {
  770. if (image) { return buffer_replaceDestructor(image->buffer, newDestructor); }
  771. }
  772. void dsr::image_dangerous_replaceDestructor(ImageRgbaU8& image, const std::function<void(uint8_t *)>& newDestructor) {
  773. if (image) { return buffer_replaceDestructor(image->buffer, newDestructor); }
  774. }
  775. uint8_t* dsr::image_dangerous_getData(const ImageU8& image) {
  776. if (image) {
  777. return imageInternal::getSafeData<uint8_t>(*image).getUnsafe();
  778. } else {
  779. return nullptr;
  780. }
  781. }
  782. uint8_t* dsr::image_dangerous_getData(const ImageU16& image) {
  783. if (image) {
  784. return imageInternal::getSafeData<uint8_t>(*image).getUnsafe();
  785. } else {
  786. return nullptr;
  787. }
  788. }
  789. uint8_t* dsr::image_dangerous_getData(const ImageF32& image) {
  790. if (image) {
  791. return imageInternal::getSafeData<uint8_t>(*image).getUnsafe();
  792. } else {
  793. return nullptr;
  794. }
  795. }
  796. uint8_t* dsr::image_dangerous_getData(const ImageRgbaU8& image) {
  797. if (image) {
  798. return imageInternal::getSafeData<uint8_t>(*image).getUnsafe();
  799. } else {
  800. return nullptr;
  801. }
  802. }