1/*
2 * Copyright 2011 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 "SkBitmapDevice.h"
9#include "SkCanvas.h"
10#include "SkColorPriv.h"
11#include "SkMathPriv.h"
12#include "SkRegion.h"
13#include "SkSurface.h"
14#include "Test.h"
15#include "sk_tool_utils.h"
16
17#if SK_SUPPORT_GPU
18#include "GrContextFactory.h"
19#include "SkGpuDevice.h"
20#else
21class GrContext;
22class GrContextFactory;
23#endif
24
25static const int DEV_W = 100, DEV_H = 100;
26static const SkIRect DEV_RECT = SkIRect::MakeWH(DEV_W, DEV_H);
27static const SkRect DEV_RECT_S = SkRect::MakeWH(DEV_W * SK_Scalar1,
28                                                DEV_H * SK_Scalar1);
29static const U8CPU DEV_PAD = 0xee;
30
31static SkPMColor getCanvasColor(int x, int y) {
32    SkASSERT(x >= 0 && x < DEV_W);
33    SkASSERT(y >= 0 && y < DEV_H);
34
35    U8CPU r = x;
36    U8CPU g = y;
37    U8CPU b = 0xc;
38
39    U8CPU a = 0x0;
40    switch ((x+y) % 5) {
41        case 0:
42            a = 0xff;
43            break;
44        case 1:
45            a = 0x80;
46            break;
47        case 2:
48            a = 0xCC;
49            break;
50        case 3:
51            a = 0x00;
52            break;
53        case 4:
54            a = 0x01;
55            break;
56    }
57    return SkPremultiplyARGBInline(a, r, g, b);
58}
59
60// assumes any premu/.unpremul has been applied
61static uint32_t packColorType(SkColorType ct, U8CPU a, U8CPU r, U8CPU g, U8CPU b) {
62    uint32_t r32;
63    uint8_t* result = reinterpret_cast<uint8_t*>(&r32);
64    switch (ct) {
65        case kBGRA_8888_SkColorType:
66            result[0] = b;
67            result[1] = g;
68            result[2] = r;
69            result[3] = a;
70            break;
71        case kRGBA_8888_SkColorType:
72            result[0] = r;
73            result[1] = g;
74            result[2] = b;
75            result[3] = a;
76            break;
77        default:
78            SkASSERT(0);
79            return 0;
80    }
81    return r32;
82}
83
84static uint32_t getBitmapColor(int x, int y, int w, SkColorType ct, SkAlphaType at) {
85    int n = y * w + x;
86    U8CPU b = n & 0xff;
87    U8CPU g = (n >> 8) & 0xff;
88    U8CPU r = (n >> 16) & 0xff;
89    U8CPU a = 0;
90    switch ((x+y) % 5) {
91        case 4:
92            a = 0xff;
93            break;
94        case 3:
95            a = 0x80;
96            break;
97        case 2:
98            a = 0xCC;
99            break;
100        case 1:
101            a = 0x01;
102            break;
103        case 0:
104            a = 0x00;
105            break;
106    }
107    if (kPremul_SkAlphaType == at) {
108        r = SkMulDiv255Ceiling(r, a);
109        g = SkMulDiv255Ceiling(g, a);
110        b = SkMulDiv255Ceiling(b, a);
111    }
112    return packColorType(ct, a, r, g , b);
113}
114
115static void fillCanvas(SkCanvas* canvas) {
116    SkBitmap bmp;
117    if (bmp.isNull()) {
118        bmp.allocN32Pixels(DEV_W, DEV_H);
119        for (int y = 0; y < DEV_H; ++y) {
120            for (int x = 0; x < DEV_W; ++x) {
121                *bmp.getAddr32(x, y) = getCanvasColor(x, y);
122            }
123        }
124    }
125    canvas->save();
126    canvas->setMatrix(SkMatrix::I());
127    canvas->clipRect(DEV_RECT_S, SkRegion::kReplace_Op);
128    SkPaint paint;
129    paint.setXfermodeMode(SkXfermode::kSrc_Mode);
130    canvas->drawBitmap(bmp, 0, 0, &paint);
131    canvas->restore();
132}
133
134/**
135 *  Lucky for us, alpha is always in the same spot (SK_A32_SHIFT), for both RGBA and BGRA.
136 *  Thus this routine doesn't need to know the exact colortype
137 */
138static uint32_t premul(uint32_t color) {
139    unsigned a = SkGetPackedA32(color);
140    // these next three are not necessarily r,g,b in that order, but they are r,g,b in some order.
141    unsigned c0 = SkGetPackedR32(color);
142    unsigned c1 = SkGetPackedG32(color);
143    unsigned c2 = SkGetPackedB32(color);
144    c0 = SkMulDiv255Ceiling(c0, a);
145    c1 = SkMulDiv255Ceiling(c1, a);
146    c2 = SkMulDiv255Ceiling(c2, a);
147    return SkPackARGB32NoCheck(a, c0, c1, c2);
148}
149
150static SkPMColor convert_to_PMColor(SkColorType ct, SkAlphaType at, uint32_t color) {
151    if (kUnpremul_SkAlphaType == at) {
152        color = premul(color);
153    }
154    switch (ct) {
155        case kRGBA_8888_SkColorType:
156            color = SkSwizzle_RGBA_to_PMColor(color);
157            break;
158        case kBGRA_8888_SkColorType:
159            color = SkSwizzle_BGRA_to_PMColor(color);
160            break;
161        default:
162            SkASSERT(0);
163            break;
164    }
165    return color;
166}
167
168static bool checkPixel(SkPMColor a, SkPMColor b, bool didPremulConversion) {
169    if (!didPremulConversion) {
170        return a == b;
171    }
172    int32_t aA = static_cast<int32_t>(SkGetPackedA32(a));
173    int32_t aR = static_cast<int32_t>(SkGetPackedR32(a));
174    int32_t aG = static_cast<int32_t>(SkGetPackedG32(a));
175    int32_t aB = SkGetPackedB32(a);
176
177    int32_t bA = static_cast<int32_t>(SkGetPackedA32(b));
178    int32_t bR = static_cast<int32_t>(SkGetPackedR32(b));
179    int32_t bG = static_cast<int32_t>(SkGetPackedG32(b));
180    int32_t bB = static_cast<int32_t>(SkGetPackedB32(b));
181
182    return aA == bA &&
183           SkAbs32(aR - bR) <= 1 &&
184           SkAbs32(aG - bG) <= 1 &&
185           SkAbs32(aB - bB) <= 1;
186}
187
188static bool check_write(skiatest::Reporter* reporter, SkCanvas* canvas, const SkBitmap& bitmap,
189                       int writeX, int writeY) {
190    const SkImageInfo canvasInfo = canvas->imageInfo();
191    size_t canvasRowBytes;
192    const uint32_t* canvasPixels;
193
194    // Can't use canvas->peekPixels(), as we are trying to look at GPU pixels sometimes as well.
195    // At some point this will be unsupported, as we won't allow accessBitmap() to magically call
196    // readPixels for the client.
197    SkBitmap secretDevBitmap;
198    canvas->readPixels(SkIRect::MakeWH(canvasInfo.width(), canvasInfo.height()), &secretDevBitmap);
199
200    SkAutoLockPixels alp(secretDevBitmap);
201    canvasRowBytes = secretDevBitmap.rowBytes();
202    canvasPixels = static_cast<const uint32_t*>(secretDevBitmap.getPixels());
203
204    if (NULL == canvasPixels) {
205        return false;
206    }
207
208    if (canvasInfo.width() != DEV_W ||
209        canvasInfo.height() != DEV_H ||
210        canvasInfo.colorType() != kN32_SkColorType) {
211        return false;
212    }
213
214    const SkImageInfo bmInfo = bitmap.info();
215
216    SkIRect writeRect = SkIRect::MakeXYWH(writeX, writeY, bitmap.width(), bitmap.height());
217    for (int cy = 0; cy < DEV_H; ++cy) {
218        for (int cx = 0; cx < DEV_W; ++cx) {
219            SkPMColor canvasPixel = canvasPixels[cx];
220            if (writeRect.contains(cx, cy)) {
221                int bx = cx - writeX;
222                int by = cy - writeY;
223                uint32_t bmpColor8888 = getBitmapColor(bx, by, bitmap.width(),
224                                                       bmInfo.colorType(), bmInfo.alphaType());
225                bool mul = (kUnpremul_SkAlphaType == bmInfo.alphaType());
226                SkPMColor bmpPMColor = convert_to_PMColor(bmInfo.colorType(), bmInfo.alphaType(),
227                                                          bmpColor8888);
228                bool check = checkPixel(bmpPMColor, canvasPixel, mul);
229                REPORTER_ASSERT(reporter, check);
230                if (!check) {
231                    return false;
232                }
233            } else {
234                bool check;
235                SkPMColor testColor = getCanvasColor(cx, cy);
236                REPORTER_ASSERT(reporter, check = (canvasPixel == testColor));
237                if (!check) {
238                    return false;
239                }
240            }
241        }
242        if (cy != DEV_H -1) {
243            const char* pad = reinterpret_cast<const char*>(canvasPixels + DEV_W);
244            for (size_t px = 0; px < canvasRowBytes - 4 * DEV_W; ++px) {
245                bool check;
246                REPORTER_ASSERT(reporter, check = (pad[px] == static_cast<char>(DEV_PAD)));
247                if (!check) {
248                    return false;
249                }
250            }
251        }
252        canvasPixels += canvasRowBytes/4;
253    }
254
255    return true;
256}
257
258enum DevType {
259    kRaster_DevType,
260#if SK_SUPPORT_GPU
261    kGpu_BottomLeft_DevType,
262    kGpu_TopLeft_DevType,
263#endif
264};
265
266struct CanvasConfig {
267    DevType fDevType;
268    bool fTightRowBytes;
269};
270
271static const CanvasConfig gCanvasConfigs[] = {
272    {kRaster_DevType, true},
273    {kRaster_DevType, false},
274#if SK_SUPPORT_GPU
275    {kGpu_BottomLeft_DevType, true}, // row bytes has no meaning on gpu devices
276    {kGpu_TopLeft_DevType, true}, // row bytes has no meaning on gpu devices
277#endif
278};
279
280#include "SkMallocPixelRef.h"
281
282// This is a tricky pattern, because we have to setConfig+rowBytes AND specify
283// a custom pixelRef (which also has to specify its rowBytes), so we have to be
284// sure that the two rowBytes match (and the infos match).
285//
286static bool allocRowBytes(SkBitmap* bm, const SkImageInfo& info, size_t rowBytes) {
287    if (!bm->setInfo(info, rowBytes)) {
288        return false;
289    }
290    SkPixelRef* pr = SkMallocPixelRef::NewAllocate(info, rowBytes, NULL);
291    bm->setPixelRef(pr)->unref();
292    return true;
293}
294
295static void free_pixels(void* pixels, void* ctx) {
296    sk_free(pixels);
297}
298
299static SkSurface* create_surface(const CanvasConfig& c, GrContext* grCtx) {
300    SkImageInfo info = SkImageInfo::MakeN32Premul(DEV_W, DEV_H);
301    switch (c.fDevType) {
302        case kRaster_DevType: {
303            const size_t rowBytes = c.fTightRowBytes ? info.minRowBytes() : 4 * DEV_W + 100;
304            const size_t size = info.getSafeSize(rowBytes);
305            void* pixels = sk_malloc_throw(size);
306            // if rowBytes isn't tight then set the padding to a known value
307            if (!c.fTightRowBytes) {
308                memset(pixels, DEV_PAD, size);
309            }
310            return SkSurface::NewRasterDirectReleaseProc(info, pixels, rowBytes, free_pixels, NULL);
311        }
312#if SK_SUPPORT_GPU
313        case kGpu_BottomLeft_DevType:
314        case kGpu_TopLeft_DevType:
315            GrTextureDesc desc;
316            desc.fFlags = kRenderTarget_GrTextureFlagBit;
317            desc.fWidth = DEV_W;
318            desc.fHeight = DEV_H;
319            desc.fConfig = kSkia8888_GrPixelConfig;
320            desc.fOrigin = kGpu_TopLeft_DevType == c.fDevType ?
321                kTopLeft_GrSurfaceOrigin : kBottomLeft_GrSurfaceOrigin;
322            GrAutoScratchTexture ast(grCtx, desc, GrContext::kExact_ScratchTexMatch);
323            SkAutoTUnref<GrTexture> tex(ast.detach());
324            return SkSurface::NewRenderTargetDirect(tex->asRenderTarget());
325#endif
326    }
327    return NULL;
328}
329
330static bool setup_bitmap(SkBitmap* bm, SkColorType ct, SkAlphaType at, int w, int h, int tightRB) {
331    size_t rowBytes = tightRB ? 0 : 4 * w + 60;
332    SkImageInfo info = SkImageInfo::Make(w, h, ct, at);
333    if (!allocRowBytes(bm, info, rowBytes)) {
334        return false;
335    }
336    SkAutoLockPixels alp(*bm);
337    for (int y = 0; y < h; ++y) {
338        for (int x = 0; x < w; ++x) {
339            *bm->getAddr32(x, y) = getBitmapColor(x, y, w, ct, at);
340        }
341    }
342    return true;
343}
344
345static void call_writepixels(SkCanvas* canvas) {
346    const SkImageInfo info = SkImageInfo::MakeN32Premul(1, 1);
347    SkPMColor pixel = 0;
348    canvas->writePixels(info, &pixel, sizeof(SkPMColor), 0, 0);
349}
350
351static void test_surface_genid(skiatest::Reporter* reporter) {
352    const SkImageInfo info = SkImageInfo::MakeN32Premul(100, 100);
353    SkAutoTUnref<SkSurface> surface(SkSurface::NewRaster(info));
354    uint32_t genID1 = surface->generationID();
355    call_writepixels(surface->getCanvas());
356    uint32_t genID2 = surface->generationID();
357    REPORTER_ASSERT(reporter, genID1 != genID2);
358}
359
360DEF_GPUTEST(WritePixels, reporter, factory) {
361    test_surface_genid(reporter);
362
363    SkCanvas canvas;
364
365    const SkIRect testRects[] = {
366        // entire thing
367        DEV_RECT,
368        // larger on all sides
369        SkIRect::MakeLTRB(-10, -10, DEV_W + 10, DEV_H + 10),
370        // fully contained
371        SkIRect::MakeLTRB(DEV_W / 4, DEV_H / 4, 3 * DEV_W / 4, 3 * DEV_H / 4),
372        // outside top left
373        SkIRect::MakeLTRB(-10, -10, -1, -1),
374        // touching top left corner
375        SkIRect::MakeLTRB(-10, -10, 0, 0),
376        // overlapping top left corner
377        SkIRect::MakeLTRB(-10, -10, DEV_W / 4, DEV_H / 4),
378        // overlapping top left and top right corners
379        SkIRect::MakeLTRB(-10, -10, DEV_W  + 10, DEV_H / 4),
380        // touching entire top edge
381        SkIRect::MakeLTRB(-10, -10, DEV_W  + 10, 0),
382        // overlapping top right corner
383        SkIRect::MakeLTRB(3 * DEV_W / 4, -10, DEV_W  + 10, DEV_H / 4),
384        // contained in x, overlapping top edge
385        SkIRect::MakeLTRB(DEV_W / 4, -10, 3 * DEV_W  / 4, DEV_H / 4),
386        // outside top right corner
387        SkIRect::MakeLTRB(DEV_W + 1, -10, DEV_W + 10, -1),
388        // touching top right corner
389        SkIRect::MakeLTRB(DEV_W, -10, DEV_W + 10, 0),
390        // overlapping top left and bottom left corners
391        SkIRect::MakeLTRB(-10, -10, DEV_W / 4, DEV_H + 10),
392        // touching entire left edge
393        SkIRect::MakeLTRB(-10, -10, 0, DEV_H + 10),
394        // overlapping bottom left corner
395        SkIRect::MakeLTRB(-10, 3 * DEV_H / 4, DEV_W / 4, DEV_H + 10),
396        // contained in y, overlapping left edge
397        SkIRect::MakeLTRB(-10, DEV_H / 4, DEV_W / 4, 3 * DEV_H / 4),
398        // outside bottom left corner
399        SkIRect::MakeLTRB(-10, DEV_H + 1, -1, DEV_H + 10),
400        // touching bottom left corner
401        SkIRect::MakeLTRB(-10, DEV_H, 0, DEV_H + 10),
402        // overlapping bottom left and bottom right corners
403        SkIRect::MakeLTRB(-10, 3 * DEV_H / 4, DEV_W + 10, DEV_H + 10),
404        // touching entire left edge
405        SkIRect::MakeLTRB(0, DEV_H, DEV_W, DEV_H + 10),
406        // overlapping bottom right corner
407        SkIRect::MakeLTRB(3 * DEV_W / 4, 3 * DEV_H / 4, DEV_W + 10, DEV_H + 10),
408        // overlapping top right and bottom right corners
409        SkIRect::MakeLTRB(3 * DEV_W / 4, -10, DEV_W + 10, DEV_H + 10),
410    };
411
412    for (size_t i = 0; i < SK_ARRAY_COUNT(gCanvasConfigs); ++i) {
413        int glCtxTypeCnt = 1;
414#if SK_SUPPORT_GPU
415        bool isGPUDevice = kGpu_TopLeft_DevType == gCanvasConfigs[i].fDevType ||
416                           kGpu_BottomLeft_DevType == gCanvasConfigs[i].fDevType;
417        if (isGPUDevice) {
418            glCtxTypeCnt = GrContextFactory::kGLContextTypeCnt;
419        }
420#endif
421        for (int glCtxType = 0; glCtxType < glCtxTypeCnt; ++glCtxType) {
422            GrContext* context = NULL;
423#if SK_SUPPORT_GPU
424            if (isGPUDevice) {
425                GrContextFactory::GLContextType type =
426                    static_cast<GrContextFactory::GLContextType>(glCtxType);
427                if (!GrContextFactory::IsRenderingGLContext(type)) {
428                    continue;
429                }
430                context = factory->get(type);
431                if (NULL == context) {
432                    continue;
433                }
434            }
435#endif
436
437            SkAutoTUnref<SkSurface> surface(create_surface(gCanvasConfigs[i], context));
438            SkCanvas& canvas = *surface->getCanvas();
439
440            static const struct {
441                SkColorType fColorType;
442                SkAlphaType fAlphaType;
443            } gSrcConfigs[] = {
444                { kRGBA_8888_SkColorType, kPremul_SkAlphaType },
445                { kRGBA_8888_SkColorType, kUnpremul_SkAlphaType },
446                { kBGRA_8888_SkColorType, kPremul_SkAlphaType },
447                { kBGRA_8888_SkColorType, kUnpremul_SkAlphaType },
448            };
449            for (size_t r = 0; r < SK_ARRAY_COUNT(testRects); ++r) {
450                const SkIRect& rect = testRects[r];
451                for (int tightBmp = 0; tightBmp < 2; ++tightBmp) {
452                    for (size_t c = 0; c < SK_ARRAY_COUNT(gSrcConfigs); ++c) {
453                        const SkColorType ct = gSrcConfigs[c].fColorType;
454                        const SkAlphaType at = gSrcConfigs[c].fAlphaType;
455
456                        fillCanvas(&canvas);
457                        SkBitmap bmp;
458                        REPORTER_ASSERT(reporter, setup_bitmap(&bmp, ct, at, rect.width(),
459                                                               rect.height(), SkToBool(tightBmp)));
460                        uint32_t idBefore = surface->generationID();
461
462                       // sk_tool_utils::write_pixels(&canvas, bmp, rect.fLeft, rect.fTop, ct, at);
463                        canvas.writePixels(bmp, rect.fLeft, rect.fTop);
464
465                        uint32_t idAfter = surface->generationID();
466                        REPORTER_ASSERT(reporter, check_write(reporter, &canvas, bmp,
467                                                              rect.fLeft, rect.fTop));
468
469                        // we should change the genID iff pixels were actually written.
470                        SkIRect canvasRect = SkIRect::MakeSize(canvas.getDeviceSize());
471                        SkIRect writeRect = SkIRect::MakeXYWH(rect.fLeft, rect.fTop,
472                                                              bmp.width(), bmp.height());
473                        bool intersects = SkIRect::Intersects(canvasRect, writeRect) ;
474                        REPORTER_ASSERT(reporter, intersects == (idBefore != idAfter));
475                    }
476                }
477            }
478        }
479    }
480}
481