avpcl_mode7.cpp 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094
  1. /*
  2. Copyright 2007 nVidia, Inc.
  3. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
  4. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
  5. Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS,
  6. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7. See the License for the specific language governing permissions and limitations under the License.
  8. */
  9. // Thanks to Jacob Munkberg ([email protected]) for the shortcut of using SVD to do the equivalent of principal components analysis
  10. // x10000000 5555.1x4 64p 2bi (30b)
  11. #include "bits.h"
  12. #include "tile.h"
  13. #include "avpcl.h"
  14. #include "nvcore/debug.h"
  15. #include "nvmath/vector.inl"
  16. #include "nvmath/matrix.inl"
  17. #include "nvmath/fitting.h"
  18. #include "avpcl_utils.h"
  19. #include "endpts.h"
  20. #include <string.h>
  21. #include <float.h>
  22. #include "shapes_two.h"
  23. using namespace nv;
  24. using namespace AVPCL;
  25. #define NLSBMODES 4 // number of different lsb modes per region. since we have two .1 per region, that can have 4 values
  26. #define NINDICES 4
  27. #define INDEXBITS 2
  28. #define HIGH_INDEXBIT (1<<(INDEXBITS-1))
  29. #define DENOM (NINDICES-1)
  30. #define BIAS (DENOM/2)
  31. // WORK: determine optimal traversal pattern to search for best shape -- what does the error curve look like?
  32. // i.e. can we search shapes in a particular order so we can see the global error minima easily and
  33. // stop without having to touch all shapes?
  34. #define POS_TO_X(pos) ((pos)&3)
  35. #define POS_TO_Y(pos) (((pos)>>2)&3)
  36. #define NBITSIZES (NREGIONS*2)
  37. #define ABITINDEX(region) (2*(region)+0)
  38. #define BBITINDEX(region) (2*(region)+1)
  39. struct ChanBits
  40. {
  41. int nbitsizes[NBITSIZES]; // bitsizes for one channel
  42. };
  43. struct Pattern
  44. {
  45. ChanBits chan[NCHANNELS_RGBA];// bit patterns used per channel
  46. int transformed; // if 0, deltas are unsigned and no transform; otherwise, signed and transformed
  47. int mode; // associated mode value
  48. int modebits; // number of mode bits
  49. const char *encoding; // verilog description of encoding for this mode
  50. };
  51. #define NPATTERNS 1
  52. #define NREGIONS 2
  53. static Pattern patterns[NPATTERNS] =
  54. {
  55. // red green blue alpha xfm mode mb
  56. 5,5,5,5, 5,5,5,5, 5,5,5,5, 5,5,5,5, 0, 0x80, 8, "",
  57. };
  58. struct RegionPrec
  59. {
  60. int endpt_a_prec[NCHANNELS_RGBA];
  61. int endpt_b_prec[NCHANNELS_RGBA];
  62. };
  63. struct PatternPrec
  64. {
  65. RegionPrec region_precs[NREGIONS];
  66. };
  67. // this is the precision for each channel and region
  68. // NOTE: this MUST match the corresponding data in "patterns" above -- WARNING: there is NO nvAssert to check this!
  69. static PatternPrec pattern_precs[NPATTERNS] =
  70. {
  71. 5,5,5,5, 5,5,5,5, 5,5,5,5, 5,5,5,5,
  72. };
  73. // return # of bits needed to store n. handle signed or unsigned cases properly
  74. static int nbits(int n, bool issigned)
  75. {
  76. int nb;
  77. if (n==0)
  78. return 0; // no bits needed for 0, signed or not
  79. else if (n > 0)
  80. {
  81. for (nb=0; n; ++nb, n>>=1) ;
  82. return nb + (issigned?1:0);
  83. }
  84. else
  85. {
  86. nvAssert (issigned);
  87. for (nb=0; n<-1; ++nb, n>>=1) ;
  88. return nb + 1;
  89. }
  90. }
  91. static void transform_forward(IntEndptsRGBA_2 ep[NREGIONS])
  92. {
  93. nvUnreachable();
  94. }
  95. static void transform_inverse(IntEndptsRGBA_2 ep[NREGIONS])
  96. {
  97. nvUnreachable();
  98. }
  99. /*
  100. we're using this table to assign lsbs
  101. abgr >=2 correct
  102. 0000 0 0
  103. 0001 0 0
  104. 0010 0 0
  105. 0011 1 x1
  106. 0100 0 0
  107. 0101 1 x1
  108. 0110 1 x1
  109. 0111 1 1
  110. 1000 0 0
  111. 1001 1 x0
  112. 1010 1 x0
  113. 1011 1 1
  114. 1100 1 x0
  115. 1101 1 1
  116. 1110 1 1
  117. 1111 1 1
  118. we need 8 0's and 8 1's. the x's can be either 0 or 1 as long as you get 8/8.
  119. I choose to assign the lsbs so that the rgb channels are as good as possible.
  120. */
  121. // 6666 ->5555.1, use the "correct" column above to assign the lsb
  122. static void compress_one(const IntEndptsRGBA& endpts, IntEndptsRGBA_2& compr_endpts)
  123. {
  124. int onescnt;
  125. onescnt = 0;
  126. for (int j=0; j<NCHANNELS_RGBA; ++j)
  127. {
  128. // ignore the alpha channel in the count
  129. onescnt += (j==CHANNEL_A) ? 0 : (endpts.A[j] & 1);
  130. compr_endpts.A[j] = endpts.A[j] >> 1;
  131. nvAssert (compr_endpts.A[j] < 32);
  132. }
  133. compr_endpts.a_lsb = onescnt >= 2;
  134. onescnt = 0;
  135. for (int j=0; j<NCHANNELS_RGBA; ++j)
  136. {
  137. onescnt += (j==CHANNEL_A) ? 0 : (endpts.B[j] & 1);
  138. compr_endpts.B[j] = endpts.B[j] >> 1;
  139. nvAssert (compr_endpts.B[j] < 32);
  140. }
  141. compr_endpts.b_lsb = onescnt >= 2;
  142. }
  143. static void uncompress_one(const IntEndptsRGBA_2& compr_endpts, IntEndptsRGBA& endpts)
  144. {
  145. for (int j=0; j<NCHANNELS_RGBA; ++j)
  146. {
  147. endpts.A[j] = (compr_endpts.A[j] << 1) | compr_endpts.a_lsb;
  148. endpts.B[j] = (compr_endpts.B[j] << 1) | compr_endpts.b_lsb;
  149. }
  150. }
  151. static void uncompress_endpoints(const IntEndptsRGBA_2 compr_endpts[NREGIONS], IntEndptsRGBA endpts[NREGIONS])
  152. {
  153. for (int i=0; i<NREGIONS; ++i)
  154. uncompress_one(compr_endpts[i], endpts[i]);
  155. }
  156. static void compress_endpoints(const IntEndptsRGBA endpts[NREGIONS], IntEndptsRGBA_2 compr_endpts[NREGIONS])
  157. {
  158. for (int i=0; i<NREGIONS; ++i)
  159. compress_one(endpts[i], compr_endpts[i]);
  160. }
  161. static void quantize_endpts(const FltEndpts endpts[NREGIONS], const PatternPrec &pattern_prec, IntEndptsRGBA_2 q_endpts[NREGIONS])
  162. {
  163. IntEndptsRGBA full_endpts[NREGIONS];
  164. for (int region = 0; region < NREGIONS; ++region)
  165. {
  166. full_endpts[region].A[0] = Utils::quantize(endpts[region].A.x, pattern_prec.region_precs[region].endpt_a_prec[0]+1); // +1 since we are in uncompressed space
  167. full_endpts[region].A[1] = Utils::quantize(endpts[region].A.y, pattern_prec.region_precs[region].endpt_a_prec[1]+1);
  168. full_endpts[region].A[2] = Utils::quantize(endpts[region].A.z, pattern_prec.region_precs[region].endpt_a_prec[2]+1);
  169. full_endpts[region].A[3] = Utils::quantize(endpts[region].A.w, pattern_prec.region_precs[region].endpt_a_prec[3]+1);
  170. full_endpts[region].B[0] = Utils::quantize(endpts[region].B.x, pattern_prec.region_precs[region].endpt_b_prec[0]+1);
  171. full_endpts[region].B[1] = Utils::quantize(endpts[region].B.y, pattern_prec.region_precs[region].endpt_b_prec[1]+1);
  172. full_endpts[region].B[2] = Utils::quantize(endpts[region].B.z, pattern_prec.region_precs[region].endpt_b_prec[2]+1);
  173. full_endpts[region].B[3] = Utils::quantize(endpts[region].B.w, pattern_prec.region_precs[region].endpt_b_prec[3]+1);
  174. compress_one(full_endpts[region], q_endpts[region]);
  175. }
  176. }
  177. // swap endpoints as needed to ensure that the indices at index_one and index_two have a 0 high-order bit
  178. // index_two is 0 at x=0 y=0 and 15 at x=3 y=3 so y = (index >> 2) & 3 and x = index & 3
  179. static void swap_indices(IntEndptsRGBA_2 endpts[NREGIONS], int indices[Tile::TILE_H][Tile::TILE_W], int shapeindex)
  180. {
  181. for (int region = 0; region < NREGIONS; ++region)
  182. {
  183. int position = SHAPEINDEX_TO_COMPRESSED_INDICES(shapeindex,region);
  184. int x = POS_TO_X(position);
  185. int y = POS_TO_Y(position);
  186. nvAssert(REGION(x,y,shapeindex) == region); // double check the table
  187. if (indices[y][x] & HIGH_INDEXBIT)
  188. {
  189. // high bit is set, swap the endpts and indices for this region
  190. int t;
  191. for (int i=0; i<NCHANNELS_RGBA; ++i)
  192. {
  193. t = endpts[region].A[i]; endpts[region].A[i] = endpts[region].B[i]; endpts[region].B[i] = t;
  194. }
  195. t = endpts[region].a_lsb; endpts[region].a_lsb = endpts[region].b_lsb; endpts[region].b_lsb = t;
  196. for (int y = 0; y < Tile::TILE_H; y++)
  197. for (int x = 0; x < Tile::TILE_W; x++)
  198. if (REGION(x,y,shapeindex) == region)
  199. indices[y][x] = NINDICES - 1 - indices[y][x];
  200. }
  201. }
  202. }
  203. static bool endpts_fit(IntEndptsRGBA_2 endpts[NREGIONS], const Pattern &p)
  204. {
  205. return true;
  206. }
  207. static void write_header(const IntEndptsRGBA_2 endpts[NREGIONS], int shapeindex, const Pattern &p, Bits &out)
  208. {
  209. out.write(p.mode, p.modebits);
  210. out.write(shapeindex, SHAPEBITS);
  211. for (int j=0; j<NCHANNELS_RGBA; ++j)
  212. for (int i=0; i<NREGIONS; ++i)
  213. {
  214. out.write(endpts[i].A[j], p.chan[j].nbitsizes[ABITINDEX(i)]);
  215. out.write(endpts[i].B[j], p.chan[j].nbitsizes[BBITINDEX(i)]);
  216. }
  217. for (int i=0; i<NREGIONS; ++i)
  218. {
  219. out.write(endpts[i].a_lsb, 1);
  220. out.write(endpts[i].b_lsb, 1);
  221. }
  222. nvAssert (out.getptr() == 98);
  223. }
  224. static void read_header(Bits &in, IntEndptsRGBA_2 endpts[NREGIONS], int &shapeindex, Pattern &p, int &pat_index)
  225. {
  226. int mode = AVPCL::getmode(in);
  227. pat_index = 0;
  228. nvAssert (pat_index >= 0 && pat_index < NPATTERNS);
  229. nvAssert (in.getptr() == patterns[pat_index].modebits);
  230. shapeindex = in.read(SHAPEBITS);
  231. p = patterns[pat_index];
  232. for (int j=0; j<NCHANNELS_RGBA; ++j)
  233. for (int i=0; i<NREGIONS; ++i)
  234. {
  235. endpts[i].A[j] = in.read(p.chan[j].nbitsizes[ABITINDEX(i)]);
  236. endpts[i].B[j] = in.read(p.chan[j].nbitsizes[BBITINDEX(i)]);
  237. }
  238. for (int i=0; i<NREGIONS; ++i)
  239. {
  240. endpts[i].a_lsb = in.read(1);
  241. endpts[i].b_lsb = in.read(1);
  242. }
  243. nvAssert (in.getptr() == 98);
  244. }
  245. // WORK PLACEHOLDER -- keep it simple for now
  246. static void write_indices(const int indices[Tile::TILE_H][Tile::TILE_W], int shapeindex, Bits &out)
  247. {
  248. int positions[NREGIONS];
  249. for (int r = 0; r < NREGIONS; ++r)
  250. positions[r] = SHAPEINDEX_TO_COMPRESSED_INDICES(shapeindex,r);
  251. for (int pos = 0; pos < Tile::TILE_TOTAL; ++pos)
  252. {
  253. int x = POS_TO_X(pos);
  254. int y = POS_TO_Y(pos);
  255. bool match = false;
  256. for (int r = 0; r < NREGIONS; ++r)
  257. if (positions[r] == pos) { match = true; break; }
  258. out.write(indices[y][x], INDEXBITS - (match ? 1 : 0));
  259. }
  260. }
  261. static void read_indices(Bits &in, int shapeindex, int indices[Tile::TILE_H][Tile::TILE_W])
  262. {
  263. int positions[NREGIONS];
  264. for (int r = 0; r < NREGIONS; ++r)
  265. positions[r] = SHAPEINDEX_TO_COMPRESSED_INDICES(shapeindex,r);
  266. for (int pos = 0; pos < Tile::TILE_TOTAL; ++pos)
  267. {
  268. int x = POS_TO_X(pos);
  269. int y = POS_TO_Y(pos);
  270. bool match = false;
  271. for (int r = 0; r < NREGIONS; ++r)
  272. if (positions[r] == pos) { match = true; break; }
  273. indices[y][x]= in.read(INDEXBITS - (match ? 1 : 0));
  274. }
  275. }
  276. static void emit_block(const IntEndptsRGBA_2 endpts[NREGIONS], int shapeindex, const Pattern &p, const int indices[Tile::TILE_H][Tile::TILE_W], char *block)
  277. {
  278. Bits out(block, AVPCL::BITSIZE);
  279. write_header(endpts, shapeindex, p, out);
  280. write_indices(indices, shapeindex, out);
  281. nvAssert(out.getptr() == AVPCL::BITSIZE);
  282. }
  283. static void generate_palette_quantized(const IntEndptsRGBA_2 &endpts_2, const RegionPrec &region_prec, Vector4 palette[NINDICES])
  284. {
  285. IntEndptsRGBA endpts;
  286. uncompress_one(endpts_2, endpts);
  287. // scale endpoints
  288. int a, b; // really need a IntVec4...
  289. a = Utils::unquantize(endpts.A[0], region_prec.endpt_a_prec[0]+1); // +1 since we are in uncompressed space
  290. b = Utils::unquantize(endpts.B[0], region_prec.endpt_b_prec[0]+1);
  291. // interpolate
  292. for (int i = 0; i < NINDICES; ++i)
  293. palette[i].x = float(Utils::lerp(a, b, i, BIAS, DENOM));
  294. a = Utils::unquantize(endpts.A[1], region_prec.endpt_a_prec[1]+1);
  295. b = Utils::unquantize(endpts.B[1], region_prec.endpt_b_prec[1]+1);
  296. // interpolate
  297. for (int i = 0; i < NINDICES; ++i)
  298. palette[i].y = float(Utils::lerp(a, b, i, BIAS, DENOM));
  299. a = Utils::unquantize(endpts.A[2], region_prec.endpt_a_prec[2]+1);
  300. b = Utils::unquantize(endpts.B[2], region_prec.endpt_b_prec[2]+1);
  301. // interpolate
  302. for (int i = 0; i < NINDICES; ++i)
  303. palette[i].z = float(Utils::lerp(a, b, i, BIAS, DENOM));
  304. a = Utils::unquantize(endpts.A[3], region_prec.endpt_a_prec[3]+1);
  305. b = Utils::unquantize(endpts.B[3], region_prec.endpt_b_prec[3]+1);
  306. // interpolate
  307. for (int i = 0; i < NINDICES; ++i)
  308. palette[i].w = float(Utils::lerp(a, b, i, BIAS, DENOM));
  309. }
  310. // sign extend but only if it was transformed
  311. static void sign_extend(Pattern &p, IntEndptsRGBA_2 endpts[NREGIONS])
  312. {
  313. nvUnreachable();
  314. }
  315. void AVPCL::decompress_mode7(const char *block, Tile &t)
  316. {
  317. Bits in(block, AVPCL::BITSIZE);
  318. Pattern p;
  319. IntEndptsRGBA_2 endpts[NREGIONS];
  320. int shapeindex, pat_index;
  321. read_header(in, endpts, shapeindex, p, pat_index);
  322. if (p.transformed)
  323. {
  324. sign_extend(p, endpts);
  325. transform_inverse(endpts);
  326. }
  327. Vector4 palette[NREGIONS][NINDICES];
  328. for (int r = 0; r < NREGIONS; ++r)
  329. generate_palette_quantized(endpts[r], pattern_precs[pat_index].region_precs[r], &palette[r][0]);
  330. int indices[Tile::TILE_H][Tile::TILE_W];
  331. read_indices(in, shapeindex, indices);
  332. nvAssert(in.getptr() == AVPCL::BITSIZE);
  333. // lookup
  334. for (int y = 0; y < Tile::TILE_H; y++)
  335. for (int x = 0; x < Tile::TILE_W; x++)
  336. t.data[y][x] = palette[REGION(x,y,shapeindex)][indices[y][x]];
  337. }
  338. // given a collection of colors and quantized endpoints, generate a palette, choose best entries, and return a single toterr
  339. static float map_colors(const Vector4 colors[], const float importance[], int np, const IntEndptsRGBA_2 &endpts, const RegionPrec &region_prec, float current_err, int indices[Tile::TILE_TOTAL])
  340. {
  341. Vector4 palette[NINDICES];
  342. float toterr = 0;
  343. Vector4 err;
  344. generate_palette_quantized(endpts, region_prec, palette);
  345. for (int i = 0; i < np; ++i)
  346. {
  347. float err, besterr = FLT_MAX;
  348. for (int j = 0; j < NINDICES && besterr > 0; ++j)
  349. {
  350. err = !AVPCL::flag_premult ? Utils::metric4(colors[i], palette[j]) :
  351. Utils::metric4premult(colors[i], palette[j]) ;
  352. if (err > besterr) // error increased, so we're done searching
  353. break;
  354. if (err < besterr)
  355. {
  356. besterr = err;
  357. indices[i] = j;
  358. }
  359. }
  360. toterr += besterr;
  361. // check for early exit
  362. if (toterr > current_err)
  363. {
  364. // fill out bogus index values so it's initialized at least
  365. for (int k = i; k < np; ++k)
  366. indices[k] = -1;
  367. return FLT_MAX;
  368. }
  369. }
  370. return toterr;
  371. }
  372. // assign indices given a tile, shape, and quantized endpoints, return toterr for each region
  373. static void assign_indices(const Tile &tile, int shapeindex, IntEndptsRGBA_2 endpts[NREGIONS], const PatternPrec &pattern_prec,
  374. int indices[Tile::TILE_H][Tile::TILE_W], float toterr[NREGIONS])
  375. {
  376. // build list of possibles
  377. Vector4 palette[NREGIONS][NINDICES];
  378. for (int region = 0; region < NREGIONS; ++region)
  379. {
  380. generate_palette_quantized(endpts[region], pattern_prec.region_precs[region], &palette[region][0]);
  381. toterr[region] = 0;
  382. }
  383. Vector4 err;
  384. for (int y = 0; y < tile.size_y; y++)
  385. for (int x = 0; x < tile.size_x; x++)
  386. {
  387. int region = REGION(x,y,shapeindex);
  388. float err, besterr = FLT_MAX;
  389. for (int i = 0; i < NINDICES && besterr > 0; ++i)
  390. {
  391. err = !AVPCL::flag_premult ? Utils::metric4(tile.data[y][x], palette[region][i]) :
  392. Utils::metric4premult(tile.data[y][x], palette[region][i]) ;
  393. if (err > besterr) // error increased, so we're done searching
  394. break;
  395. if (err < besterr)
  396. {
  397. besterr = err;
  398. indices[y][x] = i;
  399. }
  400. }
  401. toterr[region] += besterr;
  402. }
  403. }
  404. // note: indices are valid only if the value returned is less than old_err; otherwise they contain -1's
  405. // this function returns either old_err or a value smaller (if it was successful in improving the error)
  406. static float perturb_one(const Vector4 colors[], const float importance[], int np, int ch, const RegionPrec &region_prec, const IntEndptsRGBA_2 &old_endpts, IntEndptsRGBA_2 &new_endpts,
  407. float old_err, int do_b, int indices[Tile::TILE_TOTAL])
  408. {
  409. // we have the old endpoints: old_endpts
  410. // we have the perturbed endpoints: new_endpts
  411. // we have the temporary endpoints: temp_endpts
  412. IntEndptsRGBA_2 temp_endpts;
  413. float min_err = old_err; // start with the best current error
  414. int beststep;
  415. int temp_indices[Tile::TILE_TOTAL];
  416. for (int i=0; i<np; ++i)
  417. indices[i] = -1;
  418. // copy real endpoints so we can perturb them
  419. temp_endpts = new_endpts = old_endpts;
  420. int prec = do_b ? region_prec.endpt_b_prec[ch] : region_prec.endpt_a_prec[ch];
  421. // do a logarithmic search for the best error for this endpoint (which)
  422. for (int step = 1 << (prec-1); step; step >>= 1)
  423. {
  424. bool improved = false;
  425. for (int sign = -1; sign <= 1; sign += 2)
  426. {
  427. if (do_b == 0)
  428. {
  429. temp_endpts.A[ch] = new_endpts.A[ch] + sign * step;
  430. if (temp_endpts.A[ch] < 0 || temp_endpts.A[ch] >= (1 << prec))
  431. continue;
  432. }
  433. else
  434. {
  435. temp_endpts.B[ch] = new_endpts.B[ch] + sign * step;
  436. if (temp_endpts.B[ch] < 0 || temp_endpts.B[ch] >= (1 << prec))
  437. continue;
  438. }
  439. float err = map_colors(colors, importance, np, temp_endpts, region_prec, min_err, temp_indices);
  440. if (err < min_err)
  441. {
  442. improved = true;
  443. min_err = err;
  444. beststep = sign * step;
  445. for (int i=0; i<np; ++i)
  446. indices[i] = temp_indices[i];
  447. }
  448. }
  449. // if this was an improvement, move the endpoint and continue search from there
  450. if (improved)
  451. {
  452. if (do_b == 0)
  453. new_endpts.A[ch] += beststep;
  454. else
  455. new_endpts.B[ch] += beststep;
  456. }
  457. }
  458. return min_err;
  459. }
  460. // the larger the error the more time it is worth spending on an exhaustive search.
  461. // perturb the endpoints at least -3 to 3.
  462. // if err > 5000 perturb endpoints 50% of precision
  463. // if err > 1000 25%
  464. // if err > 200 12.5%
  465. // if err > 40 6.25%
  466. // for np = 16 -- adjust error thresholds as a function of np
  467. // always ensure endpoint ordering is preserved (no need to overlap the scan)
  468. // if orig_err returned from this is less than its input value, then indices[] will contain valid indices
  469. static float exhaustive(const Vector4 colors[], const float importance[], int np, int ch, const RegionPrec &region_prec, float orig_err, IntEndptsRGBA_2 &opt_endpts, int indices[Tile::TILE_TOTAL])
  470. {
  471. IntEndptsRGBA_2 temp_endpts;
  472. float best_err = orig_err;
  473. int aprec = region_prec.endpt_a_prec[ch];
  474. int bprec = region_prec.endpt_b_prec[ch];
  475. int good_indices[Tile::TILE_TOTAL];
  476. int temp_indices[Tile::TILE_TOTAL];
  477. for (int i=0; i<np; ++i)
  478. indices[i] = -1;
  479. float thr_scale = (float)np / (float)Tile::TILE_TOTAL;
  480. if (orig_err == 0) return orig_err;
  481. int adelta = 0, bdelta = 0;
  482. if (orig_err > 5000.0*thr_scale) { adelta = (1 << aprec)/2; bdelta = (1 << bprec)/2; }
  483. else if (orig_err > 1000.0*thr_scale) { adelta = (1 << aprec)/4; bdelta = (1 << bprec)/4; }
  484. else if (orig_err > 200.0*thr_scale) { adelta = (1 << aprec)/8; bdelta = (1 << bprec)/8; }
  485. else if (orig_err > 40.0*thr_scale) { adelta = (1 << aprec)/16; bdelta = (1 << bprec)/16; }
  486. adelta = max(adelta, 3);
  487. bdelta = max(bdelta, 3);
  488. #ifdef DISABLE_EXHAUSTIVE
  489. adelta = bdelta = 3;
  490. #endif
  491. temp_endpts = opt_endpts;
  492. // ok figure out the range of A and B
  493. int alow = max(0, opt_endpts.A[ch] - adelta);
  494. int ahigh = min((1<<aprec)-1, opt_endpts.A[ch] + adelta);
  495. int blow = max(0, opt_endpts.B[ch] - bdelta);
  496. int bhigh = min((1<<bprec)-1, opt_endpts.B[ch] + bdelta);
  497. // now there's no need to swap the ordering of A and B
  498. bool a_le_b = opt_endpts.A[ch] <= opt_endpts.B[ch];
  499. int amin, bmin;
  500. if (opt_endpts.A[ch] <= opt_endpts.B[ch])
  501. {
  502. // keep a <= b
  503. for (int a = alow; a <= ahigh; ++a)
  504. for (int b = max(a, blow); b < bhigh; ++b)
  505. {
  506. temp_endpts.A[ch] = a;
  507. temp_endpts.B[ch] = b;
  508. float err = map_colors(colors, importance, np, temp_endpts, region_prec, best_err, temp_indices);
  509. if (err < best_err)
  510. {
  511. amin = a;
  512. bmin = b;
  513. best_err = err;
  514. for (int i=0; i<np; ++i)
  515. good_indices[i] = temp_indices[i];
  516. }
  517. }
  518. }
  519. else
  520. {
  521. // keep b <= a
  522. for (int b = blow; b < bhigh; ++b)
  523. for (int a = max(b, alow); a <= ahigh; ++a)
  524. {
  525. temp_endpts.A[ch] = a;
  526. temp_endpts.B[ch] = b;
  527. float err = map_colors(colors, importance, np, temp_endpts, region_prec, best_err, temp_indices);
  528. if (err < best_err)
  529. {
  530. amin = a;
  531. bmin = b;
  532. best_err = err;
  533. for (int i=0; i<np; ++i)
  534. good_indices[i] = temp_indices[i];
  535. }
  536. }
  537. }
  538. if (best_err < orig_err)
  539. {
  540. opt_endpts.A[ch] = amin;
  541. opt_endpts.B[ch] = bmin;
  542. orig_err = best_err;
  543. // if we actually improved, update the indices
  544. for (int i=0; i<np; ++i)
  545. indices[i] = good_indices[i];
  546. }
  547. return best_err;
  548. }
  549. static float optimize_one(const Vector4 colors[], const float importance[], int np, float orig_err, const IntEndptsRGBA_2 &orig_endpts, const RegionPrec &region_prec, IntEndptsRGBA_2 &opt_endpts)
  550. {
  551. float opt_err = orig_err;
  552. opt_endpts = orig_endpts;
  553. /*
  554. err0 = perturb(rgb0, delta0)
  555. err1 = perturb(rgb1, delta1)
  556. if (err0 < err1)
  557. if (err0 >= initial_error) break
  558. rgb0 += delta0
  559. next = 1
  560. else
  561. if (err1 >= initial_error) break
  562. rgb1 += delta1
  563. next = 0
  564. initial_err = map()
  565. for (;;)
  566. err = perturb(next ? rgb1:rgb0, delta)
  567. if (err >= initial_err) break
  568. next? rgb1 : rgb0 += delta
  569. initial_err = err
  570. */
  571. IntEndptsRGBA_2 new_a, new_b;
  572. IntEndptsRGBA_2 new_endpt;
  573. int do_b;
  574. int orig_indices[Tile::TILE_TOTAL];
  575. int new_indices[Tile::TILE_TOTAL];
  576. int temp_indices0[Tile::TILE_TOTAL];
  577. int temp_indices1[Tile::TILE_TOTAL];
  578. // now optimize each channel separately
  579. // for the first error improvement, we save the indices. then, for any later improvement, we compare the indices
  580. // if they differ, we restart the loop (which then falls back to looking for a first improvement.)
  581. for (int ch = 0; ch < NCHANNELS_RGBA; ++ch)
  582. {
  583. // figure out which endpoint when perturbed gives the most improvement and start there
  584. // if we just alternate, we can easily end up in a local minima
  585. float err0 = perturb_one(colors, importance, np, ch, region_prec, opt_endpts, new_a, opt_err, 0, temp_indices0); // perturb endpt A
  586. float err1 = perturb_one(colors, importance, np, ch, region_prec, opt_endpts, new_b, opt_err, 1, temp_indices1); // perturb endpt B
  587. if (err0 < err1)
  588. {
  589. if (err0 >= opt_err)
  590. continue;
  591. for (int i=0; i<np; ++i)
  592. {
  593. new_indices[i] = orig_indices[i] = temp_indices0[i];
  594. nvAssert (orig_indices[i] != -1);
  595. }
  596. opt_endpts.A[ch] = new_a.A[ch];
  597. opt_err = err0;
  598. do_b = 1; // do B next
  599. }
  600. else
  601. {
  602. if (err1 >= opt_err)
  603. continue;
  604. for (int i=0; i<np; ++i)
  605. {
  606. new_indices[i] = orig_indices[i] = temp_indices1[i];
  607. nvAssert (orig_indices[i] != -1);
  608. }
  609. opt_endpts.B[ch] = new_b.B[ch];
  610. opt_err = err1;
  611. do_b = 0; // do A next
  612. }
  613. // now alternate endpoints and keep trying until there is no improvement
  614. for (;;)
  615. {
  616. float err = perturb_one(colors, importance, np, ch, region_prec, opt_endpts, new_endpt, opt_err, do_b, temp_indices0);
  617. if (err >= opt_err)
  618. break;
  619. for (int i=0; i<np; ++i)
  620. {
  621. new_indices[i] = temp_indices0[i];
  622. nvAssert (new_indices[i] != -1);
  623. }
  624. if (do_b == 0)
  625. opt_endpts.A[ch] = new_endpt.A[ch];
  626. else
  627. opt_endpts.B[ch] = new_endpt.B[ch];
  628. opt_err = err;
  629. do_b = 1 - do_b; // now move the other endpoint
  630. }
  631. // see if the indices have changed
  632. int i;
  633. for (i=0; i<np; ++i)
  634. if (orig_indices[i] != new_indices[i])
  635. break;
  636. if (i<np)
  637. ch = -1; // start over
  638. }
  639. // finally, do a small exhaustive search around what we think is the global minima to be sure
  640. // note this is independent of the above search, so we don't care about the indices from the above
  641. // we don't care about the above because if they differ, so what? we've already started at ch=0
  642. bool first = true;
  643. for (int ch = 0; ch < NCHANNELS_RGBA; ++ch)
  644. {
  645. float new_err = exhaustive(colors, importance, np, ch, region_prec, opt_err, opt_endpts, temp_indices0);
  646. if (new_err < opt_err)
  647. {
  648. opt_err = new_err;
  649. if (first)
  650. {
  651. for (int i=0; i<np; ++i)
  652. {
  653. orig_indices[i] = temp_indices0[i];
  654. nvAssert (orig_indices[i] != -1);
  655. }
  656. first = false;
  657. }
  658. else
  659. {
  660. // see if the indices have changed
  661. int i;
  662. for (i=0; i<np; ++i)
  663. if (orig_indices[i] != temp_indices0[i])
  664. break;
  665. if (i<np)
  666. {
  667. ch = -1; // start over
  668. first = true;
  669. }
  670. }
  671. }
  672. }
  673. return opt_err;
  674. }
  675. static void optimize_endpts(const Tile &tile, int shapeindex, const float orig_err[NREGIONS],
  676. IntEndptsRGBA_2 orig_endpts[NREGIONS], const PatternPrec &pattern_prec, float opt_err[NREGIONS], IntEndptsRGBA_2 opt_endpts[NREGIONS])
  677. {
  678. Vector4 pixels[Tile::TILE_TOTAL];
  679. float importance[Tile::TILE_TOTAL];
  680. IntEndptsRGBA_2 temp_in, temp_out;
  681. int temp_indices[Tile::TILE_TOTAL];
  682. for (int region=0; region<NREGIONS; ++region)
  683. {
  684. // collect the pixels in the region
  685. int np = 0;
  686. for (int y = 0; y < tile.size_y; y++) {
  687. for (int x = 0; x < tile.size_x; x++) {
  688. if (REGION(x, y, shapeindex) == region) {
  689. pixels[np] = tile.data[y][x];
  690. importance[np] = tile.importance_map[y][x];
  691. np++;
  692. }
  693. }
  694. }
  695. opt_endpts[region] = temp_in = orig_endpts[region];
  696. opt_err[region] = orig_err[region];
  697. float best_err = orig_err[region];
  698. // try all lsb modes as we search for better endpoints
  699. for (int lsbmode=0; lsbmode<NLSBMODES; ++lsbmode)
  700. {
  701. temp_in.a_lsb = lsbmode & 1;
  702. temp_in.b_lsb = (lsbmode >> 1) & 1;
  703. // make sure we have a valid error for temp_in
  704. // we use FLT_MAX here because we want an accurate temp_in_err, no shortcuts
  705. // (mapcolors will compute a mapping but will stop if the error exceeds the value passed in the FLT_MAX position)
  706. float temp_in_err = map_colors(pixels, importance, np, temp_in, pattern_prec.region_precs[region], FLT_MAX, temp_indices);
  707. // now try to optimize these endpoints
  708. float temp_out_err = optimize_one(pixels, importance, np, temp_in_err, temp_in, pattern_prec.region_precs[region], temp_out);
  709. // if we find an improvement, update the best so far and correct the output endpoints and errors
  710. if (temp_out_err < best_err)
  711. {
  712. best_err = temp_out_err;
  713. opt_err[region] = temp_out_err;
  714. opt_endpts[region] = temp_out;
  715. }
  716. }
  717. }
  718. }
  719. /* optimization algorithm
  720. for each pattern
  721. convert endpoints using pattern precision
  722. assign indices and get initial error
  723. compress indices (and possibly reorder endpoints)
  724. transform endpoints
  725. if transformed endpoints fit pattern
  726. get original endpoints back
  727. optimize endpoints, get new endpoints, new indices, and new error // new error will almost always be better
  728. compress new indices
  729. transform new endpoints
  730. if new endpoints fit pattern AND if error is improved
  731. emit compressed block with new data
  732. else
  733. emit compressed block with original data // to try to preserve maximum endpoint precision
  734. */
  735. static float refine(const Tile &tile, int shapeindex_best, const FltEndpts endpts[NREGIONS], char *block)
  736. {
  737. float orig_err[NREGIONS], opt_err[NREGIONS], orig_toterr, opt_toterr, expected_opt_err[NREGIONS];
  738. IntEndptsRGBA_2 orig_endpts[NREGIONS], opt_endpts[NREGIONS];
  739. int orig_indices[Tile::TILE_H][Tile::TILE_W], opt_indices[Tile::TILE_H][Tile::TILE_W];
  740. for (int sp = 0; sp < NPATTERNS; ++sp)
  741. {
  742. quantize_endpts(endpts, pattern_precs[sp], orig_endpts);
  743. assign_indices(tile, shapeindex_best, orig_endpts, pattern_precs[sp], orig_indices, orig_err);
  744. swap_indices(orig_endpts, orig_indices, shapeindex_best);
  745. if (patterns[sp].transformed)
  746. transform_forward(orig_endpts);
  747. // apply a heuristic here -- we check if the endpoints fit before we try to optimize them.
  748. // the assumption made is that if they don't fit now, they won't fit after optimizing.
  749. if (endpts_fit(orig_endpts, patterns[sp]))
  750. {
  751. if (patterns[sp].transformed)
  752. transform_inverse(orig_endpts);
  753. optimize_endpts(tile, shapeindex_best, orig_err, orig_endpts, pattern_precs[sp], expected_opt_err, opt_endpts);
  754. assign_indices(tile, shapeindex_best, opt_endpts, pattern_precs[sp], opt_indices, opt_err);
  755. // (nreed) Commented out asserts because they go off all the time...not sure why
  756. //for (int i=0; i<NREGIONS; ++i)
  757. // nvAssert(expected_opt_err[i] == opt_err[i]);
  758. swap_indices(opt_endpts, opt_indices, shapeindex_best);
  759. if (patterns[sp].transformed)
  760. transform_forward(opt_endpts);
  761. orig_toterr = opt_toterr = 0;
  762. for (int i=0; i < NREGIONS; ++i) { orig_toterr += orig_err[i]; opt_toterr += opt_err[i]; }
  763. if (endpts_fit(opt_endpts, patterns[sp]) && opt_toterr < orig_toterr)
  764. {
  765. emit_block(opt_endpts, shapeindex_best, patterns[sp], opt_indices, block);
  766. return opt_toterr;
  767. }
  768. else
  769. {
  770. // either it stopped fitting when we optimized it, or there was no improvement
  771. // so go back to the unoptimized endpoints which we know will fit
  772. if (patterns[sp].transformed)
  773. transform_forward(orig_endpts);
  774. emit_block(orig_endpts, shapeindex_best, patterns[sp], orig_indices, block);
  775. return orig_toterr;
  776. }
  777. }
  778. }
  779. nvAssert(false); //throw "No candidate found, should never happen (mode avpcl 7).";
  780. return FLT_MAX;
  781. }
  782. static void clamp(Vector4 &v)
  783. {
  784. if (v.x < 0.0f) v.x = 0.0f;
  785. if (v.x > 255.0f) v.x = 255.0f;
  786. if (v.y < 0.0f) v.y = 0.0f;
  787. if (v.y > 255.0f) v.y = 255.0f;
  788. if (v.z < 0.0f) v.z = 0.0f;
  789. if (v.z > 255.0f) v.z = 255.0f;
  790. if (v.w < 0.0f) v.w = 0.0f;
  791. if (v.w > 255.0f) v.w = 255.0f;
  792. }
  793. static void generate_palette_unquantized(const FltEndpts endpts[NREGIONS], Vector4 palette[NREGIONS][NINDICES])
  794. {
  795. for (int region = 0; region < NREGIONS; ++region)
  796. for (int i = 0; i < NINDICES; ++i)
  797. palette[region][i] = Utils::lerp(endpts[region].A, endpts[region].B, i, 0, DENOM);
  798. }
  799. // generate a palette from unquantized endpoints, then pick best palette color for all pixels in each region, return toterr for all regions combined
  800. static float map_colors(const Tile &tile, int shapeindex, const FltEndpts endpts[NREGIONS])
  801. {
  802. // build list of possibles
  803. Vector4 palette[NREGIONS][NINDICES];
  804. generate_palette_unquantized(endpts, palette);
  805. float toterr = 0;
  806. Vector4 err;
  807. for (int y = 0; y < tile.size_y; y++)
  808. for (int x = 0; x < tile.size_x; x++)
  809. {
  810. int region = REGION(x,y,shapeindex);
  811. float err, besterr = FLT_MAX;
  812. for (int i = 0; i < NINDICES && besterr > 0; ++i)
  813. {
  814. err = Utils::metric4(tile.data[y][x], palette[region][i]);
  815. if (err > besterr) // error increased, so we're done searching. this works for most norms.
  816. break;
  817. if (err < besterr)
  818. besterr = err;
  819. }
  820. toterr += besterr;
  821. }
  822. return toterr;
  823. }
  824. static float rough(const Tile &tile, int shapeindex, FltEndpts endpts[NREGIONS])
  825. {
  826. for (int region=0; region<NREGIONS; ++region)
  827. {
  828. int np = 0;
  829. Vector4 colors[Tile::TILE_TOTAL];
  830. Vector4 mean(0,0,0,0);
  831. for (int y = 0; y < tile.size_y; y++)
  832. for (int x = 0; x < tile.size_x; x++)
  833. if (REGION(x,y,shapeindex) == region)
  834. {
  835. colors[np] = tile.data[y][x];
  836. mean += tile.data[y][x];
  837. ++np;
  838. }
  839. // handle simple cases
  840. if (np == 0)
  841. {
  842. Vector4 zero(0,0,0,255.0f);
  843. endpts[region].A = zero;
  844. endpts[region].B = zero;
  845. continue;
  846. }
  847. else if (np == 1)
  848. {
  849. endpts[region].A = colors[0];
  850. endpts[region].B = colors[0];
  851. continue;
  852. }
  853. else if (np == 2)
  854. {
  855. endpts[region].A = colors[0];
  856. endpts[region].B = colors[1];
  857. continue;
  858. }
  859. mean /= float(np);
  860. Vector4 direction = Fit::computePrincipalComponent_EigenSolver(np, colors);
  861. // project each pixel value along the principal direction
  862. float minp = FLT_MAX, maxp = -FLT_MAX;
  863. for (int i = 0; i < np; i++)
  864. {
  865. float dp = dot(colors[i]-mean, direction);
  866. if (dp < minp) minp = dp;
  867. if (dp > maxp) maxp = dp;
  868. }
  869. // choose as endpoints 2 points along the principal direction that span the projections of all of the pixel values
  870. endpts[region].A = mean + minp*direction;
  871. endpts[region].B = mean + maxp*direction;
  872. // clamp endpoints
  873. // the argument for clamping is that the actual endpoints need to be clamped and thus we need to choose the best
  874. // shape based on endpoints being clamped
  875. clamp(endpts[region].A);
  876. clamp(endpts[region].B);
  877. }
  878. return map_colors(tile, shapeindex, endpts);
  879. }
  880. static void swap(float *list1, int *list2, int i, int j)
  881. {
  882. float t = list1[i]; list1[i] = list1[j]; list1[j] = t;
  883. int t1 = list2[i]; list2[i] = list2[j]; list2[j] = t1;
  884. }
  885. float AVPCL::compress_mode7(const Tile &t, char *block)
  886. {
  887. // number of rough cases to look at. reasonable values of this are 1, NSHAPES/4, and NSHAPES
  888. // NSHAPES/4 gets nearly all the cases; you can increase that a bit (say by 3 or 4) if you really want to squeeze the last bit out
  889. const int NITEMS=NSHAPES/4;
  890. // pick the best NITEMS shapes and refine these.
  891. struct {
  892. FltEndpts endpts[NREGIONS];
  893. } all[NSHAPES];
  894. float roughmse[NSHAPES];
  895. int index[NSHAPES];
  896. char tempblock[AVPCL::BLOCKSIZE];
  897. float msebest = FLT_MAX;
  898. for (int i=0; i<NSHAPES; ++i)
  899. {
  900. roughmse[i] = rough(t, i, &all[i].endpts[0]);
  901. index[i] = i;
  902. }
  903. // bubble sort -- only need to bubble up the first NITEMS items
  904. for (int i=0; i<NITEMS; ++i)
  905. for (int j=i+1; j<NSHAPES; ++j)
  906. if (roughmse[i] > roughmse[j])
  907. swap(roughmse, index, i, j);
  908. for (int i=0; i<NITEMS && msebest>0; ++i)
  909. {
  910. int shape = index[i];
  911. float mse = refine(t, shape, &all[shape].endpts[0], tempblock);
  912. if (mse < msebest)
  913. {
  914. memcpy(block, tempblock, sizeof(tempblock));
  915. msebest = mse;
  916. }
  917. }
  918. return msebest;
  919. }