imageAPI.cpp 30 KB

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