ZoomImage.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #include <TestFramework.h>
  5. #include <Image/ZoomImage.h>
  6. #include <Image/Surface.h>
  7. #include <Image/BlitSurface.h>
  8. #include <Jolt/Core/Profiler.h>
  9. //////////////////////////////////////////////////////////////////////////////////////////
  10. // ImageFilter
  11. //
  12. // Abstract class and some implementations of a filter, essentially an 1D weighting function
  13. // which is not zero for t e [-GetSupport(), GetSupport()] and zero for all other t
  14. // The integrand is usually 1 although it is not required for this implementation,
  15. // since the filter is renormalized when it is sampled.
  16. //////////////////////////////////////////////////////////////////////////////////////////
  17. class ImageFilter
  18. {
  19. public:
  20. // Destructor
  21. virtual ~ImageFilter() = default;
  22. // Get support of this filter (+/- the range the filter function is not zero)
  23. virtual float GetSupport() const = 0;
  24. // Sample filter function at a certain point
  25. virtual float GetValue(float t) const = 0;
  26. };
  27. class ImageFilterBox : public ImageFilter
  28. {
  29. virtual float GetSupport() const override
  30. {
  31. return 0.5f;
  32. }
  33. virtual float GetValue(float t) const override
  34. {
  35. if (abs(t) <= 0.5f)
  36. return 1.0f;
  37. else
  38. return 0.0f;
  39. }
  40. };
  41. class ImageFilterTriangle : public ImageFilter
  42. {
  43. virtual float GetSupport() const override
  44. {
  45. return 1.0f;
  46. }
  47. virtual float GetValue(float t) const override
  48. {
  49. t = abs(t);
  50. if (t < 1.0f)
  51. return 1.0f - t;
  52. else
  53. return 0.0f;
  54. }
  55. };
  56. class ImageFilterBell : public ImageFilter
  57. {
  58. virtual float GetSupport() const override
  59. {
  60. return 1.5f;
  61. }
  62. virtual float GetValue(float t) const override
  63. {
  64. t = abs(t);
  65. if (t < 0.5f)
  66. return 0.75f - t * t;
  67. else if (t < 1.5f)
  68. {
  69. t = t - 1.5f;
  70. return 0.5f * t * t;
  71. }
  72. else
  73. return 0.0f;
  74. }
  75. };
  76. class ImageFilterBSpline : public ImageFilter
  77. {
  78. virtual float GetSupport() const override
  79. {
  80. return 2.0f;
  81. }
  82. virtual float GetValue(float t) const override
  83. {
  84. t = abs(t);
  85. if (t < 1.0f)
  86. {
  87. float tt = t * t;
  88. return (0.5f * tt * t) - tt + (2.0f / 3.0f);
  89. }
  90. else if (t < 2.0f)
  91. {
  92. t = 2.0f - t;
  93. return (1.0f / 6.0f) * (t * t * t);
  94. }
  95. else
  96. return 0.0f;
  97. }
  98. };
  99. class ImageFilterLanczos3 : public ImageFilter
  100. {
  101. virtual float GetSupport() const override
  102. {
  103. return 3.0f;
  104. }
  105. virtual float GetValue(float t) const override
  106. {
  107. t = abs(t);
  108. if (t < 3.0f)
  109. return Sinc(t) * Sinc(t / 3.0f);
  110. else
  111. return 0.0f;
  112. }
  113. private:
  114. static float Sinc(float x)
  115. {
  116. x *= JPH_PI;
  117. if (abs(x) < 1.0e-5f)
  118. return 1.0f;
  119. return Sin(x) / x;
  120. }
  121. };
  122. class ImageFilterMitchell : public ImageFilter
  123. {
  124. virtual float GetSupport() const override
  125. {
  126. return 2.0f;
  127. }
  128. virtual float GetValue(float t) const override
  129. {
  130. float tt = t * t;
  131. t = abs(t);
  132. if (t < 1.0f)
  133. return (7.0f * (t * tt) - 12.0f * tt + (16.0f / 3.0f)) / 6.0f;
  134. else if (t < 2.0f)
  135. return ((-7.0f / 3.0f) * (t * tt) + 12.0f * tt + -20.0f * t + (32.0f / 3.0f)) / 6.0f;
  136. else
  137. return 0.0f;
  138. }
  139. };
  140. static const ImageFilter &GetFilter(EFilter inFilter)
  141. {
  142. static ImageFilterBox box;
  143. static ImageFilterTriangle triangle;
  144. static ImageFilterBell bell;
  145. static ImageFilterBSpline bspline;
  146. static ImageFilterLanczos3 lanczos3;
  147. static ImageFilterMitchell mitchell;
  148. switch (inFilter)
  149. {
  150. case FilterBox: return box;
  151. case FilterTriangle: return triangle;
  152. case FilterBell: return bell;
  153. case FilterBSpline: return bspline;
  154. case FilterLanczos3: return lanczos3;
  155. case FilterMitchell: return mitchell;
  156. default: JPH_ASSERT(false); return mitchell;
  157. }
  158. }
  159. //////////////////////////////////////////////////////////////////////////////////////////
  160. // ZoomSettings
  161. //////////////////////////////////////////////////////////////////////////////////////////
  162. const ZoomSettings ZoomSettings::sDefault;
  163. ZoomSettings::ZoomSettings() :
  164. mFilter(FilterMitchell),
  165. mWrapFilter(true),
  166. mBlur(1.0f)
  167. {
  168. }
  169. bool ZoomSettings::operator == (const ZoomSettings &inRHS) const
  170. {
  171. return mFilter == inRHS.mFilter
  172. && mWrapFilter == inRHS.mWrapFilter
  173. && mBlur == inRHS.mBlur;
  174. }
  175. //////////////////////////////////////////////////////////////////////////////////////////
  176. // Resizing a surface
  177. //////////////////////////////////////////////////////////////////////////////////////////
  178. // Structure used for zooming
  179. struct Contrib
  180. {
  181. int mOffset; // Offset of this pixel (relative to start of scanline)
  182. int mWeight; // Weight of this pixel in 0.12 fixed point format
  183. };
  184. static void sPrecalculateFilter(const ZoomSettings &inZoomSettings, int inOldLength, int inNewLength, int inOffsetFactor, Array<Array<Contrib>> &outContrib)
  185. {
  186. JPH_PROFILE("PrecalculateFilter");
  187. // Get filter
  188. const ImageFilter &filter = GetFilter(inZoomSettings.mFilter);
  189. // Get scale
  190. float scale = float(inNewLength) / inOldLength;
  191. float fwidth, fscale;
  192. if (scale < 1.0f)
  193. {
  194. // Minify, broaden filter
  195. fwidth = filter.GetSupport() / scale;
  196. fscale = scale;
  197. }
  198. else
  199. {
  200. // Enlarge, filter is always used as is
  201. fwidth = filter.GetSupport();
  202. fscale = 1.0f;
  203. }
  204. // Adjust filter for blur
  205. fwidth *= inZoomSettings.mBlur;
  206. fscale /= inZoomSettings.mBlur;
  207. float min_fwidth = 1.0f;
  208. if (fwidth < min_fwidth)
  209. {
  210. fwidth = min_fwidth;
  211. fscale = filter.GetSupport() / min_fwidth;
  212. }
  213. // Make room for a whole scanline
  214. outContrib.resize(inNewLength);
  215. // Loop over the whole scanline
  216. for (int i = 0; i < inNewLength; ++i)
  217. {
  218. // Compute center and left- and rightmost pixels affected
  219. float center = float(i) / scale;
  220. int left = int(floor(center - fwidth));
  221. int right = int(ceil(center + fwidth));
  222. // Reserve required elements
  223. Array<Contrib> &a = outContrib[i];
  224. a.reserve(right - left + 1);
  225. // Total sum of all weights, for renormalization of the filter
  226. int filter_sum = 0;
  227. // Compute the contributions for each
  228. for (int source = left; source <= right; ++source)
  229. {
  230. Contrib c;
  231. // Initialize the offset
  232. c.mOffset = source;
  233. // Compute weight at this position in 0.12 fixed point
  234. c.mWeight = int(4096.0f * filter.GetValue(fscale * (center - source)));
  235. if (c.mWeight == 0) continue;
  236. // Add weight to filter total
  237. filter_sum += c.mWeight;
  238. // Reflect the filter at the edges if the filter is not to be wrapped (clamp)
  239. if (!inZoomSettings.mWrapFilter && (c.mOffset < 0 || c.mOffset >= inOldLength))
  240. c.mOffset = -c.mOffset - 1;
  241. // Wrap the offset so that it falls within the image
  242. c.mOffset = (c.mOffset % inOldLength + inOldLength) % inOldLength;
  243. // Check that the offset falls within the image
  244. JPH_ASSERT(c.mOffset >= 0 && c.mOffset < inOldLength);
  245. // Multiply the offset with the specified factor
  246. c.mOffset *= inOffsetFactor;
  247. // Add the filter element
  248. a.push_back(c);
  249. }
  250. // Normalize the filter to 0.12 fixed point
  251. if (filter_sum != 0)
  252. for (uint n = 0; n < a.size(); ++n)
  253. a[n].mWeight = (a[n].mWeight * 4096) / filter_sum;
  254. }
  255. }
  256. static void sZoomHorizontal(RefConst<Surface> inSrc, Ref<Surface> ioDst, const ZoomSettings &inZoomSettings)
  257. {
  258. JPH_PROFILE("ZoomHorizontal");
  259. // Check zoom parameters
  260. JPH_ASSERT(inSrc->GetHeight() == ioDst->GetHeight());
  261. JPH_ASSERT(inSrc->GetFormat() == ioDst->GetFormat());
  262. const int width = ioDst->GetWidth();
  263. const int height = ioDst->GetHeight();
  264. const int components = ioDst->GetNumberOfComponents();
  265. const int delta_s = -components;
  266. const int delta_d = ioDst->GetBytesPerPixel() - components;
  267. // Pre-calculate filter contributions for a row
  268. Array<Array<Contrib>> contrib;
  269. sPrecalculateFilter(inZoomSettings, inSrc->GetWidth(), ioDst->GetWidth(), inSrc->GetBytesPerPixel(), contrib);
  270. // Do the zoom
  271. for (int y = 0; y < height; ++y)
  272. {
  273. const uint8 *s = inSrc->GetScanLine(y);
  274. uint8 *d = ioDst->GetScanLine(y);
  275. for (int x = 0; x < width; ++x)
  276. {
  277. const Array<Contrib> &line = contrib[x];
  278. const size_t line_size_min_one = line.size() - 1;
  279. int c = components;
  280. do
  281. {
  282. int pixel = 0;
  283. // Apply the filter for one color component
  284. size_t j = line_size_min_one;
  285. do
  286. {
  287. const Contrib &cmp = line[j];
  288. pixel += cmp.mWeight * s[cmp.mOffset];
  289. }
  290. while (j--);
  291. // Clamp the pixel value
  292. if (pixel <= 0)
  293. *d = 0;
  294. else if (pixel >= (255 << 12))
  295. *d = 255;
  296. else
  297. *d = uint8(pixel >> 12);
  298. ++s;
  299. ++d;
  300. }
  301. while (--c);
  302. // Skip unused components if there are any
  303. s += delta_s;
  304. d += delta_d;
  305. }
  306. }
  307. }
  308. static void sZoomVertical(RefConst<Surface> inSrc, Ref<Surface> ioDst, const ZoomSettings &inZoomSettings)
  309. {
  310. JPH_PROFILE("ZoomVertical");
  311. // Check zoom parameters
  312. JPH_ASSERT(inSrc->GetWidth() == ioDst->GetWidth());
  313. JPH_ASSERT(inSrc->GetFormat() == ioDst->GetFormat());
  314. const int width = ioDst->GetWidth();
  315. const int height = ioDst->GetHeight();
  316. const int components = ioDst->GetNumberOfComponents();
  317. const int delta_s = inSrc->GetBytesPerPixel() - components;
  318. const int delta_d = ioDst->GetBytesPerPixel() - components;
  319. // Pre-calculate filter contributions for a row
  320. Array<Array<Contrib>> contrib;
  321. sPrecalculateFilter(inZoomSettings, inSrc->GetHeight(), ioDst->GetHeight(), inSrc->GetStride(), contrib);
  322. // Do the zoom
  323. for (int y = 0; y < height; ++y)
  324. {
  325. const uint8 *s = inSrc->GetScanLine(0);
  326. uint8 *d = ioDst->GetScanLine(y);
  327. const Array<Contrib> &line = contrib[y];
  328. const size_t line_size_min_one = line.size() - 1;
  329. for (int x = 0; x < width; ++x)
  330. {
  331. int c = components;
  332. do
  333. {
  334. int pixel = 0;
  335. // Apply the filter for one color component
  336. size_t j = line_size_min_one;
  337. do
  338. {
  339. const Contrib &cmp = line[j];
  340. pixel += cmp.mWeight * s[cmp.mOffset];
  341. }
  342. while (j--);
  343. // Clamp the pixel value
  344. if (pixel <= 0)
  345. *d = 0;
  346. else if (pixel >= (255 << 12))
  347. *d = 255;
  348. else
  349. *d = uint8(pixel >> 12);
  350. ++s;
  351. ++d;
  352. }
  353. while (--c);
  354. // Skip unused components if there are any
  355. s += delta_s;
  356. d += delta_d;
  357. }
  358. }
  359. }
  360. bool ZoomImage(RefConst<Surface> inSrc, Ref<Surface> ioDst, const ZoomSettings &inZoomSettings)
  361. {
  362. JPH_PROFILE("ZoomImage");
  363. // Get filter
  364. const ImageFilter &filter = GetFilter(inZoomSettings.mFilter);
  365. // Determine the temporary format that will require the least amount of components to be zoomed and the least amount of bytes pushed around
  366. ESurfaceFormat tmp_format;
  367. ESurfaceFormat src_format = inSrc->GetClosest8BitFormat();
  368. ESurfaceFormat dst_format = ioDst->GetClosest8BitFormat();
  369. const FormatDescription &src_desc = GetFormatDescription(src_format);
  370. const FormatDescription &dst_desc = GetFormatDescription(dst_format);
  371. if (src_desc.GetNumberOfComponents() < dst_desc.GetNumberOfComponents())
  372. tmp_format = src_format;
  373. else if (src_desc.GetNumberOfComponents() > dst_desc.GetNumberOfComponents())
  374. tmp_format = dst_format;
  375. else if (src_desc.GetBytesPerPixel() < dst_desc.GetBytesPerPixel())
  376. tmp_format = src_format;
  377. else
  378. tmp_format = dst_format;
  379. // Create temporary source buffer if nessecary
  380. RefConst<Surface> src = inSrc;
  381. if (inSrc->GetFormat() != tmp_format)
  382. {
  383. Ref<Surface> tmp = new SoftwareSurface(inSrc->GetWidth(), inSrc->GetHeight(), tmp_format);
  384. if (!BlitSurface(inSrc, tmp))
  385. return false;
  386. src = tmp;
  387. }
  388. // Create temporary destination buffer if nessecary
  389. Ref<Surface> dst = ioDst;
  390. if (ioDst->GetFormat() != tmp_format)
  391. dst = new SoftwareSurface(ioDst->GetWidth(), ioDst->GetHeight(), tmp_format);
  392. src->Lock(ESurfaceLockMode::Read);
  393. dst->Lock(ESurfaceLockMode::Write);
  394. if (src->GetWidth() == dst->GetWidth())
  395. {
  396. // Only vertical zoom required
  397. sZoomVertical(src, dst, inZoomSettings);
  398. }
  399. else if (src->GetHeight() == dst->GetHeight())
  400. {
  401. // Only horizontal zoom required
  402. sZoomHorizontal(src, dst, inZoomSettings);
  403. }
  404. else
  405. {
  406. // Determine most optimal order
  407. float operations_vh = float(dst->GetWidth()) * (filter.GetSupport() * src->GetHeight() + filter.GetSupport() * dst->GetHeight());
  408. float operations_hv = float(dst->GetHeight()) * (filter.GetSupport() * src->GetWidth() + filter.GetSupport() * dst->GetWidth());
  409. if (operations_vh < operations_hv)
  410. {
  411. // Create temporary buffer to hold the vertical scale
  412. Ref<Surface> tmp = new SoftwareSurface(src->GetWidth(), dst->GetHeight(), tmp_format);
  413. tmp->Lock(ESurfaceLockMode::ReadWrite);
  414. // First scale vertically then horizontally
  415. sZoomVertical(src, tmp, inZoomSettings);
  416. sZoomHorizontal(tmp, dst, inZoomSettings);
  417. tmp->UnLock();
  418. }
  419. else
  420. {
  421. // Create temporary buffer to hold the horizontal scale
  422. Ref<Surface> tmp = new SoftwareSurface(dst->GetWidth(), src->GetHeight(), tmp_format);
  423. tmp->Lock(ESurfaceLockMode::ReadWrite);
  424. // First scale horizontally then vertically
  425. sZoomHorizontal(src, tmp, inZoomSettings);
  426. sZoomVertical(tmp, dst, inZoomSettings);
  427. tmp->UnLock();
  428. }
  429. }
  430. src->UnLock();
  431. dst->UnLock();
  432. // Convert to destination if required
  433. if (dst != ioDst)
  434. if (!BlitSurface(dst, ioDst))
  435. return false;
  436. return true;
  437. }