blob: 3ce0120ec5fa29e6c4577896d1dd3d2d677b533c [file] [log] [blame]
krajcevski6c354882014-07-22 07:44:00 -07001/*
2 * Copyright 2014 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8#include "SkTextureCompressor.h"
9
10#include "SkEndian.h"
11
12// #define COMPRESS_R11_EAC_SLOW 1
13// #define COMPRESS_R11_EAC_FAST 1
14#define COMPRESS_R11_EAC_FASTEST 1
15
16// Blocks compressed into R11 EAC are represented as follows:
17// 0000000000000000000000000000000000000000000000000000000000000000
18// |base_cw|mod|mul| ----------------- indices -------------------
19//
20// To reconstruct the value of a given pixel, we use the formula:
21// clamp[0, 2047](base_cw * 8 + 4 + mod_val*mul*8)
22//
23// mod_val is chosen from a palette of values based on the index of the
24// given pixel. The palette is chosen by the value stored in mod.
25// This formula returns a value between 0 and 2047, which is converted
26// to a float from 0 to 1 in OpenGL.
27//
28// If mul is zero, then we set mul = 1/8, so that the formula becomes
29// clamp[0, 2047](base_cw * 8 + 4 + mod_val)
30
31#if COMPRESS_R11_EAC_SLOW
32
33static const int kNumR11EACPalettes = 16;
34static const int kR11EACPaletteSize = 8;
35static const int kR11EACModifierPalettes[kNumR11EACPalettes][kR11EACPaletteSize] = {
36 {-3, -6, -9, -15, 2, 5, 8, 14},
37 {-3, -7, -10, -13, 2, 6, 9, 12},
38 {-2, -5, -8, -13, 1, 4, 7, 12},
39 {-2, -4, -6, -13, 1, 3, 5, 12},
40 {-3, -6, -8, -12, 2, 5, 7, 11},
41 {-3, -7, -9, -11, 2, 6, 8, 10},
42 {-4, -7, -8, -11, 3, 6, 7, 10},
43 {-3, -5, -8, -11, 2, 4, 7, 10},
44 {-2, -6, -8, -10, 1, 5, 7, 9},
45 {-2, -5, -8, -10, 1, 4, 7, 9},
46 {-2, -4, -8, -10, 1, 3, 7, 9},
47 {-2, -5, -7, -10, 1, 4, 6, 9},
48 {-3, -4, -7, -10, 2, 3, 6, 9},
49 {-1, -2, -3, -10, 0, 1, 2, 9},
50 {-4, -6, -8, -9, 3, 5, 7, 8},
51 {-3, -5, -7, -9, 2, 4, 6, 8}
52};
53
54// Pack the base codeword, palette, and multiplier into the 64 bits necessary
55// to decode it.
56static uint64_t pack_r11eac_block(uint16_t base_cw, uint16_t palette, uint16_t multiplier,
57 uint64_t indices) {
58 SkASSERT(palette < 16);
59 SkASSERT(multiplier < 16);
60 SkASSERT(indices < (static_cast<uint64_t>(1) << 48));
61
62 const uint64_t b = static_cast<uint64_t>(base_cw) << 56;
63 const uint64_t m = static_cast<uint64_t>(multiplier) << 52;
64 const uint64_t p = static_cast<uint64_t>(palette) << 48;
65 return SkEndian_SwapBE64(b | m | p | indices);
66}
67
68// Given a base codeword, a modifier, and a multiplier, compute the proper
69// pixel value in the range [0, 2047].
70static uint16_t compute_r11eac_pixel(int base_cw, int modifier, int multiplier) {
71 int ret = (base_cw * 8 + 4) + (modifier * multiplier * 8);
72 return (ret > 2047)? 2047 : ((ret < 0)? 0 : ret);
73}
74
75// Compress a block into R11 EAC format.
76// The compression works as follows:
77// 1. Find the center of the span of the block's values. Use this as the base codeword.
78// 2. Choose a multiplier based roughly on the size of the span of block values
79// 3. Iterate through each palette and choose the one with the most accurate
80// modifiers.
81static inline uint64_t compress_heterogeneous_r11eac_block(const uint8_t block[16]) {
82 // Find the center of the data...
83 uint16_t bmin = block[0];
84 uint16_t bmax = block[0];
85 for (int i = 1; i < 16; ++i) {
86 bmin = SkTMin<uint16_t>(bmin, block[i]);
87 bmax = SkTMax<uint16_t>(bmax, block[i]);
88 }
89
90 uint16_t center = (bmax + bmin) >> 1;
91 SkASSERT(center <= 255);
92
93 // Based on the min and max, we can guesstimate a proper multiplier
94 // This is kind of a magic choice to start with.
95 uint16_t multiplier = (bmax - center) / 10;
96
97 // Now convert the block to 11 bits and transpose it to match
98 // the proper layout
99 uint16_t cblock[16];
100 for (int i = 0; i < 4; ++i) {
101 for (int j = 0; j < 4; ++j) {
102 int srcIdx = i*4+j;
103 int dstIdx = j*4+i;
104 cblock[dstIdx] = (block[srcIdx] << 3) | (block[srcIdx] >> 5);
105 }
106 }
107
108 // Finally, choose the proper palette and indices
109 uint32_t bestError = 0xFFFFFFFF;
110 uint64_t bestIndices = 0;
111 uint16_t bestPalette = 0;
112 for (uint16_t paletteIdx = 0; paletteIdx < kNumR11EACPalettes; ++paletteIdx) {
113 const int *palette = kR11EACModifierPalettes[paletteIdx];
114
115 // Iterate through each pixel to find the best palette index
116 // and update the indices with the choice. Also store the error
117 // for this palette to be compared against the best error...
118 uint32_t error = 0;
119 uint64_t indices = 0;
120 for (int pixelIdx = 0; pixelIdx < 16; ++pixelIdx) {
121 const uint16_t pixel = cblock[pixelIdx];
122
123 // Iterate through each palette value to find the best index
124 // for this particular pixel for this particular palette.
125 uint16_t bestPixelError =
126 abs_diff(pixel, compute_r11eac_pixel(center, palette[0], multiplier));
127 int bestIndex = 0;
128 for (int i = 1; i < kR11EACPaletteSize; ++i) {
129 const uint16_t p = compute_r11eac_pixel(center, palette[i], multiplier);
130 const uint16_t perror = abs_diff(pixel, p);
131
132 // Is this index better?
133 if (perror < bestPixelError) {
134 bestIndex = i;
135 bestPixelError = perror;
136 }
137 }
138
139 SkASSERT(bestIndex < 8);
140
141 error += bestPixelError;
142 indices <<= 3;
143 indices |= bestIndex;
144 }
145
146 SkASSERT(indices < (static_cast<uint64_t>(1) << 48));
147
148 // Is this palette better?
149 if (error < bestError) {
150 bestPalette = paletteIdx;
151 bestIndices = indices;
152 bestError = error;
153 }
154 }
155
156 // Finally, pack everything together...
157 return pack_r11eac_block(center, bestPalette, multiplier, bestIndices);
158}
159#endif // COMPRESS_R11_EAC_SLOW
160
161#if COMPRESS_R11_EAC_FAST
162// This function takes into account that most blocks that we compress have a gradation from
163// fully opaque to fully transparent. The compression scheme works by selecting the
164// palette and multiplier that has the tightest fit to the 0-255 range. This is encoded
165// as the block header (0x8490). The indices are then selected by considering the top
166// three bits of each alpha value. For alpha masks, this reduces the dynamic range from
167// 17 to 8, but the quality is still acceptable.
168//
169// There are a few caveats that need to be taken care of...
170//
171// 1. The block is read in as scanlines, so the indices are stored as:
172// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
173// However, the decomrpession routine reads them in column-major order, so they
174// need to be packed as:
175// 0 4 8 12 1 5 9 13 2 6 10 14 3 7 11 15
176// So when reading, they must be transposed.
177//
178// 2. We cannot use the top three bits as an index directly, since the R11 EAC palettes
179// above store the modulation values first decreasing and then increasing:
180// e.g. {-3, -6, -9, -15, 2, 5, 8, 14}
181// Hence, we need to convert the indices with the following mapping:
182// From: 0 1 2 3 4 5 6 7
183// To: 3 2 1 0 4 5 6 7
184static inline uint64_t compress_heterogeneous_r11eac_block(const uint8_t block[16]) {
185 uint64_t retVal = static_cast<uint64_t>(0x8490) << 48;
186 for(int i = 0; i < 4; ++i) {
187 for(int j = 0; j < 4; ++j) {
188 const int shift = 45-3*(j*4+i);
189 SkASSERT(shift <= 45);
190 const uint64_t idx = block[i*4+j] >> 5;
191 SkASSERT(idx < 8);
192
193 // !SPEED! This is slightly faster than having an if-statement.
194 switch(idx) {
195 case 0:
196 case 1:
197 case 2:
198 case 3:
199 retVal |= (3-idx) << shift;
200 break;
201 default:
202 retVal |= idx << shift;
203 break;
204 }
205 }
206 }
207
208 return SkEndian_SwapBE64(retVal);
209}
210#endif // COMPRESS_R11_EAC_FAST
211
212#if (COMPRESS_R11_EAC_SLOW) || (COMPRESS_R11_EAC_FAST)
213static uint64_t compress_r11eac_block(const uint8_t block[16]) {
214 // Are all blocks a solid color?
215 bool solid = true;
216 for (int i = 1; i < 16; ++i) {
217 if (block[i] != block[0]) {
218 solid = false;
219 break;
220 }
221 }
222
223 if (solid) {
224 switch(block[0]) {
225 // Fully transparent? We know the encoding...
226 case 0:
227 // (0x0020 << 48) produces the following:
228 // basw_cw: 0
229 // mod: 0, palette: {-3, -6, -9, -15, 2, 5, 8, 14}
230 // multiplier: 2
231 // mod_val: -3
232 //
233 // this gives the following formula:
234 // clamp[0, 2047](0*8+4+(-3)*2*8) = 0
235 //
236 // Furthermore, it is impervious to endianness:
237 // 0x0020000000002000ULL
238 // Will produce one pixel with index 2, which gives:
239 // clamp[0, 2047](0*8+4+(-9)*2*8) = 0
240 return 0x0020000000002000ULL;
241
242 // Fully opaque? We know this encoding too...
243 case 255:
244
245 // -1 produces the following:
246 // basw_cw: 255
247 // mod: 15, palette: {-3, -5, -7, -9, 2, 4, 6, 8}
248 // mod_val: 8
249 //
250 // this gives the following formula:
251 // clamp[0, 2047](255*8+4+8*8*8) = clamp[0, 2047](2556) = 2047
252 return 0xFFFFFFFFFFFFFFFFULL;
253
254 default:
255 // !TODO! krajcevski:
256 // This will probably never happen, since we're using this format
257 // primarily for compressing alpha maps. Usually the only
258 // non-fullly opaque or fully transparent blocks are not a solid
259 // intermediate color. If we notice that they are, then we can
260 // add another optimization...
261 break;
262 }
263 }
264
265 return compress_heterogeneous_r11eac_block(block);
266}
267
268// This function is used by R11 EAC to compress 4x4 blocks
269// of 8-bit alpha into 64-bit values that comprise the compressed data.
270// We need to make sure that the dimensions of the src pixels are divisible
271// by 4, and copy 4x4 blocks one at a time for compression.
272typedef uint64_t (*A84x4To64BitProc)(const uint8_t block[]);
273
274static bool compress_4x4_a8_to_64bit(uint8_t* dst, const uint8_t* src,
275 int width, int height, int rowBytes,
276 A84x4To64BitProc proc) {
277 // Make sure that our data is well-formed enough to be considered for compression
278 if (0 == width || 0 == height || (width % 4) != 0 || (height % 4) != 0) {
279 return false;
280 }
281
282 int blocksX = width >> 2;
283 int blocksY = height >> 2;
284
285 uint8_t block[16];
286 uint64_t* encPtr = reinterpret_cast<uint64_t*>(dst);
287 for (int y = 0; y < blocksY; ++y) {
288 for (int x = 0; x < blocksX; ++x) {
289 // Load block
290 for (int k = 0; k < 4; ++k) {
291 memcpy(block + k*4, src + k*rowBytes + 4*x, 4);
292 }
293
294 // Compress it
295 *encPtr = proc(block);
296 ++encPtr;
297 }
298 src += 4 * rowBytes;
299 }
300
301 return true;
302}
303#endif // (COMPRESS_R11_EAC_SLOW) || (COMPRESS_R11_EAC_FAST)
304
305#if COMPRESS_R11_EAC_FASTEST
306template<unsigned shift>
307static inline uint64_t swap_shift(uint64_t x, uint64_t mask) {
308 const uint64_t t = (x ^ (x >> shift)) & mask;
309 return x ^ t ^ (t << shift);
310}
311
312static inline uint64_t interleave6(uint64_t topRows, uint64_t bottomRows) {
313 // If our 3-bit block indices are laid out as:
314 // a b c d
315 // e f g h
316 // i j k l
317 // m n o p
318 //
319 // This function expects topRows and bottomRows to contain the first two rows
320 // of indices interleaved in the least significant bits of a and b. In other words...
321 //
322 // If the architecture is big endian, then topRows and bottomRows will contain the following:
323 // Bits 31-0:
324 // a: 00 a e 00 b f 00 c g 00 d h
325 // b: 00 i m 00 j n 00 k o 00 l p
326 //
327 // If the architecture is little endian, then topRows and bottomRows will contain
328 // the following:
329 // Bits 31-0:
330 // a: 00 d h 00 c g 00 b f 00 a e
331 // b: 00 l p 00 k o 00 j n 00 i m
332 //
333 // This function returns a 48-bit packing of the form:
334 // a e i m b f j n c g k o d h l p
335 //
336 // !SPEED! this function might be even faster if certain SIMD intrinsics are
337 // used..
338
339 // For both architectures, we can figure out a packing of the bits by
340 // using a shuffle and a few shift-rotates...
341 uint64_t x = (static_cast<uint64_t>(topRows) << 32) | static_cast<uint64_t>(bottomRows);
342
343 // x: 00 a e 00 b f 00 c g 00 d h 00 i m 00 j n 00 k o 00 l p
344
345 x = swap_shift<10>(x, 0x3FC0003FC00000ULL);
346
347 // x: b f 00 00 00 a e c g i m 00 00 00 d h j n 00 k o 00 l p
348
349 x = (x | ((x << 52) & (0x3FULL << 52)) | ((x << 20) & (0x3FULL << 28))) >> 16;
350
351 // x: 00 00 00 00 00 00 00 00 b f l p a e c g i m k o d h j n
352
353 x = swap_shift<6>(x, 0xFC0000ULL);
354
355#if defined (SK_CPU_BENDIAN)
356 // x: 00 00 00 00 00 00 00 00 b f l p a e i m c g k o d h j n
357
358 x = swap_shift<36>(x, 0x3FULL);
359
360 // x: 00 00 00 00 00 00 00 00 b f j n a e i m c g k o d h l p
361
362 x = swap_shift<12>(x, 0xFFF000000ULL);
363#else
364 // If our CPU is little endian, then the above logic will
365 // produce the following indices:
366 // x: 00 00 00 00 00 00 00 00 c g i m d h l p b f j n a e k o
367
368 x = swap_shift<36>(x, 0xFC0ULL);
369
370 // x: 00 00 00 00 00 00 00 00 a e i m d h l p b f j n c g k o
371
372 x = (x & (0xFFFULL << 36)) | ((x & 0xFFFFFFULL) << 12) | ((x >> 24) & 0xFFFULL);
373#endif
374
375 // x: 00 00 00 00 00 00 00 00 a e i m b f j n c g k o d h l p
376 return x;
377}
378
379// This function converts an integer containing four bytes of alpha
380// values into an integer containing four bytes of indices into R11 EAC.
381// Note, there needs to be a mapping of indices:
382// 0 1 2 3 4 5 6 7
383// 3 2 1 0 4 5 6 7
384//
385// To compute this, we first negate each byte, and then add three, which
386// gives the mapping
387// 3 2 1 0 -1 -2 -3 -4
388//
389// Then we mask out the negative values, take their absolute value, and
390// add three.
391//
392// Most of the voodoo in this function comes from Hacker's Delight, section 2-18
393static inline uint32_t convert_indices(uint32_t x) {
394 // Take the top three bits...
395 x = (x & 0xE0E0E0E0) >> 5;
396
397 // Negate...
398 x = ~((0x80808080 - x) ^ 0x7F7F7F7F);
399
400 // Add three
401 const uint32_t s = (x & 0x7F7F7F7F) + 0x03030303;
402 x = ((x ^ 0x03030303) & 0x80808080) ^ s;
403
404 // Absolute value
405 const uint32_t a = x & 0x80808080;
406 const uint32_t b = a >> 7;
407
408 // Aside: mask negatives (m is three if the byte was negative)
409 const uint32_t m = (a >> 6) | b;
410
411 // .. continue absolute value
412 x = (x ^ ((a - b) | a)) + b;
413
414 // Add three
415 return x + m;
416}
417
418// This function follows the same basic procedure as compress_heterogeneous_r11eac_block
419// above when COMPRESS_R11_EAC_FAST is defined, but it avoids a few loads/stores and
420// tries to optimize where it can using SIMD.
421static uint64_t compress_r11eac_block_fast(const uint8_t* src, int rowBytes) {
422 // Store each row of alpha values in an integer
423 const uint32_t alphaRow1 = *(reinterpret_cast<const uint32_t*>(src));
424 const uint32_t alphaRow2 = *(reinterpret_cast<const uint32_t*>(src + rowBytes));
425 const uint32_t alphaRow3 = *(reinterpret_cast<const uint32_t*>(src + 2*rowBytes));
426 const uint32_t alphaRow4 = *(reinterpret_cast<const uint32_t*>(src + 3*rowBytes));
427
428 // Check for solid blocks. The explanations for these values
429 // can be found in the comments of compress_r11eac_block above
430 if (alphaRow1 == alphaRow2 && alphaRow1 == alphaRow3 && alphaRow1 == alphaRow4) {
431 if (0 == alphaRow1) {
432 // Fully transparent block
433 return 0x0020000000002000ULL;
434 } else if (0xFFFFFFFF == alphaRow1) {
435 // Fully opaque block
436 return 0xFFFFFFFFFFFFFFFFULL;
437 }
438 }
439
440 // Convert each integer of alpha values into an integer of indices
441 const uint32_t indexRow1 = convert_indices(alphaRow1);
442 const uint32_t indexRow2 = convert_indices(alphaRow2);
443 const uint32_t indexRow3 = convert_indices(alphaRow3);
444 const uint32_t indexRow4 = convert_indices(alphaRow4);
445
446 // Interleave the indices from the top two rows and bottom two rows
447 // prior to passing them to interleave6. Since each index is at most
448 // three bits, then each byte can hold two indices... The way that the
449 // compression scheme expects the packing allows us to efficiently pack
450 // the top two rows and bottom two rows. Interleaving each 6-bit sequence
451 // and tightly packing it into a uint64_t is a little trickier, which is
452 // taken care of in interleave6.
453 const uint32_t r1r2 = (indexRow1 << 3) | indexRow2;
454 const uint32_t r3r4 = (indexRow3 << 3) | indexRow4;
455 const uint64_t indices = interleave6(r1r2, r3r4);
456
457 // Return the packed incdices in the least significant bits with the magic header
458 return SkEndian_SwapBE64(0x8490000000000000ULL | indices);
459}
460
461static bool compress_a8_to_r11eac_fast(uint8_t* dst, const uint8_t* src,
462 int width, int height, int rowBytes) {
463 // Make sure that our data is well-formed enough to be considered for compression
464 if (0 == width || 0 == height || (width % 4) != 0 || (height % 4) != 0) {
465 return false;
466 }
467
468 const int blocksX = width >> 2;
469 const int blocksY = height >> 2;
470
471 uint64_t* encPtr = reinterpret_cast<uint64_t*>(dst);
472 for (int y = 0; y < blocksY; ++y) {
473 for (int x = 0; x < blocksX; ++x) {
474 // Compress it
475 *encPtr = compress_r11eac_block_fast(src + 4*x, rowBytes);
476 ++encPtr;
477 }
478 src += 4 * rowBytes;
479 }
480 return true;
481}
482#endif // COMPRESS_R11_EAC_FASTEST
483
484////////////////////////////////////////////////////////////////////////////////
485//
486// Utility functions used by the blitter
487//
488////////////////////////////////////////////////////////////////////////////////
489
490// The R11 EAC format expects that indices are given in column-major order. Since
491// we receive alpha values in raster order, this usually means that we have to use
492// pack6 above to properly pack our indices. However, if our indices come from the
493// blitter, then each integer will be a column of indices, and hence can be efficiently
494// packed. This function takes the bottom three bits of each byte and places them in
495// the least significant 12 bits of the resulting integer.
496static inline uint32_t pack_indices_vertical(uint32_t x) {
497#if defined (SK_CPU_BENDIAN)
498 return
499 (x & 7) |
500 ((x >> 5) & (7 << 3)) |
501 ((x >> 10) & (7 << 6)) |
502 ((x >> 15) & (7 << 9));
503#else
504 return
505 ((x >> 24) & 7) |
506 ((x >> 13) & (7 << 3)) |
507 ((x >> 2) & (7 << 6)) |
508 ((x << 9) & (7 << 9));
509#endif
510}
511
512// This function returns the compressed format of a block given as four columns of
513// alpha values. Each column is assumed to be loaded from top to bottom, and hence
514// must first be converted to indices and then packed into the resulting 64-bit
515// integer.
516static inline uint64_t compress_block_vertical(const uint32_t alphaColumn0,
517 const uint32_t alphaColumn1,
518 const uint32_t alphaColumn2,
519 const uint32_t alphaColumn3) {
520
521 if (alphaColumn0 == alphaColumn1 &&
522 alphaColumn2 == alphaColumn3 &&
523 alphaColumn0 == alphaColumn2) {
524
525 if (0 == alphaColumn0) {
526 // Transparent
527 return 0x0020000000002000ULL;
528 }
529 else if (0xFFFFFFFF == alphaColumn0) {
530 // Opaque
531 return 0xFFFFFFFFFFFFFFFFULL;
532 }
533 }
534
535 const uint32_t indexColumn0 = convert_indices(alphaColumn0);
536 const uint32_t indexColumn1 = convert_indices(alphaColumn1);
537 const uint32_t indexColumn2 = convert_indices(alphaColumn2);
538 const uint32_t indexColumn3 = convert_indices(alphaColumn3);
539
540 const uint32_t packedIndexColumn0 = pack_indices_vertical(indexColumn0);
541 const uint32_t packedIndexColumn1 = pack_indices_vertical(indexColumn1);
542 const uint32_t packedIndexColumn2 = pack_indices_vertical(indexColumn2);
543 const uint32_t packedIndexColumn3 = pack_indices_vertical(indexColumn3);
544
545 return SkEndian_SwapBE64(0x8490000000000000ULL |
546 (static_cast<uint64_t>(packedIndexColumn0) << 36) |
547 (static_cast<uint64_t>(packedIndexColumn1) << 24) |
548 static_cast<uint64_t>(packedIndexColumn2 << 12) |
549 static_cast<uint64_t>(packedIndexColumn3));
550
551}
552
553// Updates the block whose columns are stored in blockColN. curAlphai is expected
554// to store, as an integer, the four alpha values that will be placed within each
555// of the columns in the range [col, col+colsLeft).
556static inline void update_block_columns(uint32_t* block, const int col,
557 const int colsLeft, const uint32_t curAlphai) {
558 SkASSERT(NULL != block);
559 SkASSERT(col + colsLeft <= 4);
560
561 for (int i = col; i < (col + colsLeft); ++i) {
562 block[i] = curAlphai;
563 }
564}
565
566////////////////////////////////////////////////////////////////////////////////
567
568namespace SkTextureCompressor {
569
570bool CompressA8ToR11EAC(uint8_t* dst, const uint8_t* src, int width, int height, int rowBytes) {
571
572#if (COMPRESS_R11_EAC_SLOW) || (COMPRESS_R11_EAC_FAST)
573
574 return compress_4x4_a8_to_64bit(dst, src, width, height, rowBytes, compress_r11eac_block);
575
576#elif COMPRESS_R11_EAC_FASTEST
577
578 return compress_a8_to_r11eac_fast(dst, src, width, height, rowBytes);
579
580#else
581#error "Must choose R11 EAC algorithm"
582#endif
583}
584
585// This class implements a blitter that blits directly into a buffer that will
586// be used as an R11 EAC compressed texture. We compute this buffer by
587// buffering four scan lines and then outputting them all at once. This blitter
588// is only expected to be used with alpha masks, i.e. kAlpha8_SkColorType.
589class R11_EACBlitter : public SkBlitter {
590public:
591 R11_EACBlitter(int width, int height, void *compressedBuffer);
592 virtual ~R11_EACBlitter() { this->flushRuns(); }
593
594 // Blit a horizontal run of one or more pixels.
595 virtual void blitH(int x, int y, int width) SK_OVERRIDE {
596 // This function is intended to be called from any standard RGB
597 // buffer, so we should never encounter it. However, if some code
598 // path does end up here, then this needs to be investigated.
599 SkFAIL("Not implemented!");
600 }
601
602 // Blit a horizontal run of antialiased pixels; runs[] is a *sparse*
603 // zero-terminated run-length encoding of spans of constant alpha values.
604 virtual void blitAntiH(int x, int y,
605 const SkAlpha antialias[],
606 const int16_t runs[]) SK_OVERRIDE;
607
608 // Blit a vertical run of pixels with a constant alpha value.
609 virtual void blitV(int x, int y, int height, SkAlpha alpha) SK_OVERRIDE {
610 // This function is currently not implemented. It is not explicitly
611 // required by the contract, but if at some time a code path runs into
612 // this function (which is entirely possible), it needs to be implemented.
613 //
614 // TODO (krajcevski):
615 // This function will be most easily implemented in one of two ways:
616 // 1. Buffer each vertical column value and then construct a list
617 // of alpha values and output all of the blocks at once. This only
618 // requires a write to the compressed buffer
619 // 2. Replace the indices of each block with the proper indices based
620 // on the alpha value. This requires a read and write of the compressed
621 // buffer, but much less overhead.
622 SkFAIL("Not implemented!");
623 }
624
625 // Blit a solid rectangle one or more pixels wide.
626 virtual void blitRect(int x, int y, int width, int height) SK_OVERRIDE {
627 // Analogous to blitRow, this function is intended for RGB targets
628 // and should never be called by this blitter. Any calls to this function
629 // are probably a bug and should be investigated.
630 SkFAIL("Not implemented!");
631 }
632
633 // Blit a rectangle with one alpha-blended column on the left,
634 // width (zero or more) opaque pixels, and one alpha-blended column
635 // on the right. The result will always be at least two pixels wide.
636 virtual void blitAntiRect(int x, int y, int width, int height,
637 SkAlpha leftAlpha, SkAlpha rightAlpha) SK_OVERRIDE {
638 // This function is currently not implemented. It is not explicitly
639 // required by the contract, but if at some time a code path runs into
640 // this function (which is entirely possible), it needs to be implemented.
641 //
642 // TODO (krajcevski):
643 // This function will be most easily implemented as follows:
644 // 1. If width/height are smaller than a block, then update the
645 // indices of the affected blocks.
646 // 2. If width/height are larger than a block, then construct a 9-patch
647 // of block encodings that represent the rectangle, and write them
648 // to the compressed buffer as necessary. Whether or not the blocks
649 // are overwritten by zeros or just their indices are updated is up
650 // to debate.
651 SkFAIL("Not implemented!");
652 }
653
654 // Blit a pattern of pixels defined by a rectangle-clipped mask;
655 // typically used for text.
656 virtual void blitMask(const SkMask&, const SkIRect& clip) SK_OVERRIDE {
657 // This function is currently not implemented. It is not explicitly
658 // required by the contract, but if at some time a code path runs into
659 // this function (which is entirely possible), it needs to be implemented.
660 //
661 // TODO (krajcevski):
662 // This function will be most easily implemented in the same way as
663 // blitAntiRect above.
664 SkFAIL("Not implemented!");
665 }
666
667 // If the blitter just sets a single value for each pixel, return the
668 // bitmap it draws into, and assign value. If not, return NULL and ignore
669 // the value parameter.
670 virtual const SkBitmap* justAnOpaqueColor(uint32_t* value) SK_OVERRIDE {
671 return NULL;
672 }
673
674 /**
675 * Compressed texture blitters only really work correctly if they get
676 * four blocks at a time. That being said, this blitter tries it's best
677 * to preserve semantics if blitAntiH doesn't get called in too many
678 * weird ways...
679 */
680 virtual int requestRowsPreserved() const { return kR11_EACBlockSz; }
681
682protected:
683 virtual void onNotifyFinished() { this->flushRuns(); }
684
685private:
686 static const int kR11_EACBlockSz = 4;
687 static const int kPixelsPerBlock = kR11_EACBlockSz * kR11_EACBlockSz;
688
689 // The longest possible run of pixels that this blitter will receive.
690 // This is initialized in the constructor to 0x7FFE, which is one less
691 // than the largest positive 16-bit integer. We make sure that it's one
692 // less for debugging purposes. We also don't make this variable static
693 // in order to make sure that we can construct a valid pointer to it.
694 const int16_t kLongestRun;
695
696 // Usually used in conjunction with kLongestRun. This is initialized to
697 // zero.
698 const SkAlpha kZeroAlpha;
699
700 // This is the information that we buffer whenever we're asked to blit
701 // a row with this blitter.
702 struct BufferedRun {
703 const SkAlpha* fAlphas;
704 const int16_t* fRuns;
705 int fX, fY;
706 } fBufferedRuns[kR11_EACBlockSz];
707
708 // The next row (0-3) that we need to blit. This value should never exceed
709 // the number of rows that we have (kR11_EACBlockSz)
710 int fNextRun;
711
712 // The width and height of the image that we're blitting
713 const int fWidth;
714 const int fHeight;
715
716 // The R11 EAC buffer that we're blitting into. It is assumed that the buffer
717 // is large enough to store a compressed image of size fWidth*fHeight.
718 uint64_t* const fBuffer;
719
720 // Various utility functions
721 int blocksWide() const { return fWidth / kR11_EACBlockSz; }
722 int blocksTall() const { return fHeight / kR11_EACBlockSz; }
723 int totalBlocks() const { return (fWidth * fHeight) / kPixelsPerBlock; }
724
725 // Returns the block index for the block containing pixel (x, y). Block
726 // indices start at zero and proceed in raster order.
727 int getBlockOffset(int x, int y) const {
728 SkASSERT(x < fWidth);
729 SkASSERT(y < fHeight);
730 const int blockCol = x / kR11_EACBlockSz;
731 const int blockRow = y / kR11_EACBlockSz;
732 return blockRow * this->blocksWide() + blockCol;
733 }
734
735 // Returns a pointer to the block containing pixel (x, y)
736 uint64_t *getBlock(int x, int y) const {
737 return fBuffer + this->getBlockOffset(x, y);
738 }
739
740 // The following function writes the buffered runs to compressed blocks.
741 // If fNextRun < 4, then we fill the runs that we haven't buffered with
742 // the constant zero buffer.
743 void flushRuns();
744};
745
746
747R11_EACBlitter::R11_EACBlitter(int width, int height, void *latcBuffer)
748 // 0x7FFE is one minus the largest positive 16-bit int. We use it for
749 // debugging to make sure that we're properly setting the nextX distance
750 // in flushRuns().
751 : kLongestRun(0x7FFE), kZeroAlpha(0)
752 , fNextRun(0)
753 , fWidth(width)
754 , fHeight(height)
755 , fBuffer(reinterpret_cast<uint64_t*const>(latcBuffer))
756{
757 SkASSERT((width % kR11_EACBlockSz) == 0);
758 SkASSERT((height % kR11_EACBlockSz) == 0);
759}
760
761void R11_EACBlitter::blitAntiH(int x, int y,
762 const SkAlpha* antialias,
763 const int16_t* runs) {
764 // Make sure that the new row to blit is either the first
765 // row that we're blitting, or it's exactly the next scan row
766 // since the last row that we blit. This is to ensure that when
767 // we go to flush the runs, that they are all the same four
768 // runs.
769 if (fNextRun > 0 &&
770 ((x != fBufferedRuns[fNextRun-1].fX) ||
771 (y-1 != fBufferedRuns[fNextRun-1].fY))) {
772 this->flushRuns();
773 }
774
775 // Align the rows to a block boundary. If we receive rows that
776 // are not on a block boundary, then fill in the preceding runs
777 // with zeros. We do this by producing a single RLE that says
778 // that we have 0x7FFE pixels of zero (0x7FFE = 32766).
779 const int row = y & ~3;
780 while ((row + fNextRun) < y) {
781 fBufferedRuns[fNextRun].fAlphas = &kZeroAlpha;
782 fBufferedRuns[fNextRun].fRuns = &kLongestRun;
783 fBufferedRuns[fNextRun].fX = 0;
784 fBufferedRuns[fNextRun].fY = row + fNextRun;
785 ++fNextRun;
786 }
787
788 // Make sure that our assumptions aren't violated...
789 SkASSERT(fNextRun == (y & 3));
790 SkASSERT(fNextRun == 0 || fBufferedRuns[fNextRun - 1].fY < y);
791
792 // Set the values of the next run
793 fBufferedRuns[fNextRun].fAlphas = antialias;
794 fBufferedRuns[fNextRun].fRuns = runs;
795 fBufferedRuns[fNextRun].fX = x;
796 fBufferedRuns[fNextRun].fY = y;
797
798 // If we've output four scanlines in a row that don't violate our
799 // assumptions, then it's time to flush them...
800 if (4 == ++fNextRun) {
801 this->flushRuns();
802 }
803}
804
805void R11_EACBlitter::flushRuns() {
806
807 // If we don't have any runs, then just return.
808 if (0 == fNextRun) {
809 return;
810 }
811
812#ifndef NDEBUG
813 // Make sure that if we have any runs, they all match
814 for (int i = 1; i < fNextRun; ++i) {
815 SkASSERT(fBufferedRuns[i].fY == fBufferedRuns[i-1].fY + 1);
816 SkASSERT(fBufferedRuns[i].fX == fBufferedRuns[i-1].fX);
817 }
818#endif
819
820 // If we dont have as many runs as we have rows, fill in the remaining
821 // runs with constant zeros.
822 for (int i = fNextRun; i < kR11_EACBlockSz; ++i) {
823 fBufferedRuns[i].fY = fBufferedRuns[0].fY + i;
824 fBufferedRuns[i].fX = fBufferedRuns[0].fX;
825 fBufferedRuns[i].fAlphas = &kZeroAlpha;
826 fBufferedRuns[i].fRuns = &kLongestRun;
827 }
828
829 // Make sure that our assumptions aren't violated.
830 SkASSERT(fNextRun > 0 && fNextRun <= 4);
831 SkASSERT((fBufferedRuns[0].fY & 3) == 0);
832
833 // The following logic walks four rows at a time and outputs compressed
834 // blocks to the buffer passed into the constructor.
835 // We do the following:
836 //
837 // c1 c2 c3 c4
838 // -----------------------------------------------------------------------
839 // ... | | | | | ----> fBufferedRuns[0]
840 // -----------------------------------------------------------------------
841 // ... | | | | | ----> fBufferedRuns[1]
842 // -----------------------------------------------------------------------
843 // ... | | | | | ----> fBufferedRuns[2]
844 // -----------------------------------------------------------------------
845 // ... | | | | | ----> fBufferedRuns[3]
846 // -----------------------------------------------------------------------
847 //
848 // curX -- the macro X value that we've gotten to.
849 // c1, c2, c3, c4 -- the integers that represent the columns of the current block
850 // that we're operating on
851 // curAlphaColumn -- integer containing the column of alpha values from fBufferedRuns.
852 // nextX -- for each run, the next point at which we need to update curAlphaColumn
853 // after the value of curX.
854 // finalX -- the minimum of all the nextX values.
855 //
856 // curX advances to finalX outputting any blocks that it passes along
857 // the way. Since finalX will not change when we reach the end of a
858 // run, the termination criteria will be whenever curX == finalX at the
859 // end of a loop.
860
861 // Setup:
862 uint32_t c[4] = { 0, 0, 0, 0 };
863 uint32_t curAlphaColumn = 0;
864 SkAlpha *curAlpha = reinterpret_cast<SkAlpha*>(&curAlphaColumn);
865
866 int nextX[kR11_EACBlockSz];
867 for (int i = 0; i < kR11_EACBlockSz; ++i) {
868 nextX[i] = 0x7FFFFF;
869 }
870
871 uint64_t* outPtr = this->getBlock(fBufferedRuns[0].fX, fBufferedRuns[0].fY);
872
873 // Populate the first set of runs and figure out how far we need to
874 // advance on the first step
875 int curX = 0;
876 int finalX = 0xFFFFF;
877 for (int i = 0; i < kR11_EACBlockSz; ++i) {
878 nextX[i] = *(fBufferedRuns[i].fRuns);
879 curAlpha[i] = *(fBufferedRuns[i].fAlphas);
880
881 finalX = SkMin32(nextX[i], finalX);
882 }
883
884 // Make sure that we have a valid right-bound X value
885 SkASSERT(finalX < 0xFFFFF);
886
887 // Run the blitter...
888 while (curX != finalX) {
889 SkASSERT(finalX >= curX);
890
891 // Do we need to populate the rest of the block?
892 if ((finalX - (curX & ~3)) >= kR11_EACBlockSz) {
893 const int col = curX & 3;
894 const int colsLeft = 4 - col;
895 SkASSERT(curX + colsLeft <= finalX);
896
897 update_block_columns(c, col, colsLeft, curAlphaColumn);
898
899 // Write this block
900 *outPtr = compress_block_vertical(c[0], c[1], c[2], c[3]);
901 ++outPtr;
902 curX += colsLeft;
903 }
904
905 // If we can advance even further, then just keep memsetting the block
906 if ((finalX - curX) >= kR11_EACBlockSz) {
907 SkASSERT((curX & 3) == 0);
908
909 const int col = 0;
910 const int colsLeft = kR11_EACBlockSz;
911
912 update_block_columns(c, col, colsLeft, curAlphaColumn);
913
914 // While we can keep advancing, just keep writing the block.
915 uint64_t lastBlock = compress_block_vertical(c[0], c[1], c[2], c[3]);
916 while((finalX - curX) >= kR11_EACBlockSz) {
917 *outPtr = lastBlock;
918 ++outPtr;
919 curX += kR11_EACBlockSz;
920 }
921 }
922
923 // If we haven't advanced within the block then do so.
924 if (curX < finalX) {
925 const int col = curX & 3;
926 const int colsLeft = finalX - curX;
927
928 update_block_columns(c, col, colsLeft, curAlphaColumn);
929
930 curX += colsLeft;
931 }
932
933 SkASSERT(curX == finalX);
934
935 // Figure out what the next advancement is...
936 for (int i = 0; i < kR11_EACBlockSz; ++i) {
937 if (nextX[i] == finalX) {
938 const int16_t run = *(fBufferedRuns[i].fRuns);
939 fBufferedRuns[i].fRuns += run;
940 fBufferedRuns[i].fAlphas += run;
941 curAlpha[i] = *(fBufferedRuns[i].fAlphas);
942 nextX[i] += *(fBufferedRuns[i].fRuns);
943 }
944 }
945
946 finalX = 0xFFFFF;
947 for (int i = 0; i < kR11_EACBlockSz; ++i) {
948 finalX = SkMin32(nextX[i], finalX);
949 }
950 }
951
952 // If we didn't land on a block boundary, output the block...
953 if ((curX & 3) > 1) {
954 *outPtr = compress_block_vertical(c[0], c[1], c[2], c[3]);
955 }
956
957 fNextRun = 0;
958}
959
960SkBlitter* CreateR11EACBlitter(int width, int height, void* outputBuffer) {
961 return new R11_EACBlitter(width, height, outputBuffer);
962}
963
964} // namespace SkTextureCompressor