Advertisement
Guest User

Untitled

a guest
Dec 9th, 2016
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.46 KB | None | 0 0
  1. template <typename T>
  2. static T RoundToPowerOfTwo(T x)
  3. {
  4. T n = 1;
  5. while (n < x)
  6. n <<= 1;
  7. return n;
  8. }
  9. static int InterpolateColor(int c1, int c2, float alpha)
  10. {
  11. int a1 = (c1 & 0xff000000) >> 24;
  12. int b1 = (c1 & 0xff0000) >> 16;
  13. int g1 = (c1 & 0x00ff00) >> 8;
  14. int r1 = (c1 & 0x0000ff);
  15. int a2 = (c2 & 0xff000000) >> 24;
  16. int b2 = (c2 & 0xff0000) >> 16;
  17. int g2 = (c2 & 0x00ff00) >> 8;
  18. int r2 = (c2 & 0x0000ff);
  19. int r = r1 + (int)((r2-r1)*alpha);
  20. int g = g1 + (int)((g2-g1)*alpha);
  21. int b = b1 + (int)((b2-b1)*alpha);
  22. int a = a1 + (int)((a2-a1)*alpha);
  23. return (a << 24) | (b << 16) | (g << 8) | r;
  24. }
  25. static void MakePotTextureFromNpot(int& width, int& height, std::vector<unsigned char>& vdata)
  26. {
  27. if (((width & (width-1)) != 0) || ((height & (height-1)) != 0))
  28. {
  29. // Need to make POT
  30. unsigned int * data = reinterpret_cast<unsigned int*>(&vdata[0]);
  31. int w2 = RoundToPowerOfTwo(width);
  32. int h2 = RoundToPowerOfTwo(height);
  33.  
  34. // Rescale image to power of 2
  35. int new_size = w2 * h2;
  36. std::vector<unsigned char> new_vdata;
  37. new_vdata.resize(new_size*4);
  38. unsigned int * new_data = reinterpret_cast<unsigned int*>(&new_vdata[0]);
  39. for (int dh2 = 0; dh2 < h2; ++dh2)
  40. {
  41. float rh = (float)dh2 / (float)h2;
  42. float y = rh * (float)height;
  43. int dh = (int)y;
  44. int dh1 = std::min<int>(dh+1, height-1);
  45. float ry = y - (float)dh; // fract part of y
  46. for (int dw2 = 0; dw2 < w2; ++dw2)
  47. {
  48. float rw = (float)dw2 / (float)w2;
  49. float x = rw * (float)width;
  50. int dw = (int)x;
  51. int dw1 = std::min<int>(dw+1, width-1);
  52. float rx = x - (float)dw; // fract part of x
  53.  
  54. // We will use bilinear interpolation
  55. int sample1 = (int) data[dw +width*dh ];
  56. int sample2 = (int) data[dw1+width*dh ];
  57. int sample3 = (int) data[dw +width*dh1];
  58. int sample4 = (int) data[dw1+width*dh1];
  59.  
  60. int color1 = InterpolateColor(sample1, sample2, rx);
  61. int color2 = InterpolateColor(sample3, sample4, rx);;
  62. int color3 = InterpolateColor(color1, color2, ry);
  63. new_data[dw2+w2*dh2] = (unsigned int)color3;
  64. }
  65. }
  66. // Finally
  67. width = w2;
  68. height = h2;
  69. vdata.swap(new_vdata);
  70. }
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement