1
2/*
3 * Copyright 2010 Google Inc.
4 *
5 * Use of this source code is governed by a BSD-style license that can be
6 * found in the LICENSE file.
7 */
8
9
10
11#ifndef GrTypes_DEFINED
12#define GrTypes_DEFINED
13
14#include "SkTypes.h"
15#include "GrConfig.h"
16
17////////////////////////////////////////////////////////////////////////////////
18
19/**
20 * Defines overloaded bitwise operators to make it easier to use an enum as a
21 * bitfield.
22 */
23#define GR_MAKE_BITFIELD_OPS(X) \
24    inline X operator | (X a, X b) { \
25        return (X) (+a | +b); \
26    } \
27    \
28    inline X operator & (X a, X b) { \
29        return (X) (+a & +b); \
30    } \
31    template <typename T> \
32    inline X operator & (T a, X b) { \
33        return (X) (+a & +b); \
34    } \
35    template <typename T> \
36    inline X operator & (X a, T b) { \
37        return (X) (+a & +b); \
38    } \
39
40#define GR_DECL_BITFIELD_OPS_FRIENDS(X) \
41    friend X operator | (X a, X b); \
42    \
43    friend X operator & (X a, X b); \
44    \
45    template <typename T> \
46    friend X operator & (T a, X b); \
47    \
48    template <typename T> \
49    friend X operator & (X a, T b); \
50////////////////////////////////////////////////////////////////////////////////
51
52
53/**
54 *  Macro to round n up to the next multiple of 4, or return it unchanged if
55 *  n is already a multiple of 4
56 */
57#define GrALIGN4(n)     SkAlign4(n)
58#define GrIsALIGN4(n)   SkIsAlign4(n)
59
60template <typename T> const T& GrMin(const T& a, const T& b) {
61	return (a < b) ? a : b;
62}
63
64template <typename T> const T& GrMax(const T& a, const T& b) {
65	return (b < a) ? a : b;
66}
67
68// compile time versions of min/max
69#define GR_CT_MAX(a, b) (((b) < (a)) ? (a) : (b))
70#define GR_CT_MIN(a, b) (((b) < (a)) ? (b) : (a))
71
72/**
73 *  divide, rounding up
74 */
75static inline int32_t GrIDivRoundUp(int x, int y) {
76    GrAssert(y > 0);
77    return (x + (y-1)) / y;
78}
79static inline uint32_t GrUIDivRoundUp(uint32_t x, uint32_t y) {
80    return (x + (y-1)) / y;
81}
82static inline size_t GrSizeDivRoundUp(size_t x, uint32_t y) {
83    return (x + (y-1)) / y;
84}
85
86/**
87 *  align up
88 */
89static inline uint32_t GrUIAlignUp(uint32_t x, uint32_t alignment) {
90    return GrUIDivRoundUp(x, alignment) * alignment;
91}
92static inline uint32_t GrSizeAlignUp(size_t x, uint32_t alignment) {
93    return GrSizeDivRoundUp(x, alignment) * alignment;
94}
95
96/**
97 * amount of pad needed to align up
98 */
99static inline uint32_t GrUIAlignUpPad(uint32_t x, uint32_t alignment) {
100    return (alignment - x % alignment) % alignment;
101}
102static inline size_t GrSizeAlignUpPad(size_t x, uint32_t alignment) {
103    return (alignment - x % alignment) % alignment;
104}
105
106/**
107 *  align down
108 */
109static inline uint32_t GrUIAlignDown(uint32_t x, uint32_t alignment) {
110    return (x / alignment) * alignment;
111}
112static inline uint32_t GrSizeAlignDown(size_t x, uint32_t alignment) {
113    return (x / alignment) * alignment;
114}
115
116/**
117 *  Count elements in an array
118 */
119#define GR_ARRAY_COUNT(array)  SK_ARRAY_COUNT(array)
120
121//!< allocate a block of memory, will never return NULL
122extern void* GrMalloc(size_t bytes);
123
124//!< free block allocated by GrMalloc. ptr may be NULL
125extern void GrFree(void* ptr);
126
127static inline void Gr_bzero(void* dst, size_t size) {
128    memset(dst, 0, size);
129}
130
131///////////////////////////////////////////////////////////////////////////////
132
133/**
134 *  Return the number of leading zeros in n
135 */
136extern int Gr_clz(uint32_t n);
137
138/**
139 *  Return true if n is a power of 2
140 */
141static inline bool GrIsPow2(unsigned n) {
142    return n && 0 == (n & (n - 1));
143}
144
145/**
146 *  Return the next power of 2 >= n.
147 */
148static inline uint32_t GrNextPow2(uint32_t n) {
149    return n ? (1 << (32 - Gr_clz(n - 1))) : 1;
150}
151
152static inline int GrNextPow2(int n) {
153    GrAssert(n >= 0); // this impl only works for non-neg.
154    return n ? (1 << (32 - Gr_clz(n - 1))) : 1;
155}
156
157///////////////////////////////////////////////////////////////////////////////
158
159/**
160 *  16.16 fixed point type
161 */
162typedef int32_t GrFixed;
163
164#if GR_DEBUG
165
166static inline int16_t GrToS16(intptr_t x) {
167    GrAssert((int16_t)x == x);
168    return (int16_t)x;
169}
170
171#else
172
173#define GrToS16(x)  x
174
175#endif
176
177
178///////////////////////////////////////////////////////////////////////////////
179
180/**
181 * Possible 3D APIs that may be used by Ganesh.
182 */
183enum GrEngine {
184    kOpenGL_Shaders_GrEngine,
185    kOpenGL_Fixed_GrEngine,
186};
187
188/**
189 * Engine-specific 3D context handle
190 *      GrGLInterface* for OpenGL. If NULL will use the default GL interface.
191 */
192typedef intptr_t GrPlatform3DContext;
193
194///////////////////////////////////////////////////////////////////////////////
195
196/**
197 * Type used to describe format of vertices in arrays
198 * Values are defined in GrDrawTarget
199 */
200typedef int GrVertexLayout;
201
202/**
203* Geometric primitives used for drawing.
204*/
205enum GrPrimitiveType {
206    kTriangles_PrimitiveType,
207    kTriangleStrip_PrimitiveType,
208    kTriangleFan_PrimitiveType,
209    kPoints_PrimitiveType,
210    kLines_PrimitiveType,     // 1 pix wide only
211    kLineStrip_PrimitiveType  // 1 pix wide only
212};
213
214static inline bool GrIsPrimTypeLines(GrPrimitiveType type) {
215    return kLines_PrimitiveType == type || kLineStrip_PrimitiveType == type;
216}
217
218static inline bool GrIsPrimTypeTris(GrPrimitiveType type) {
219    return kTriangles_PrimitiveType == type     ||
220           kTriangleStrip_PrimitiveType == type ||
221           kTriangleFan_PrimitiveType == type;
222}
223
224/**
225 * Coeffecients for alpha-blending.
226 */
227enum GrBlendCoeff {
228    kZero_BlendCoeff,    //<! 0
229    kOne_BlendCoeff,     //<! 1
230    kSC_BlendCoeff,      //<! src color
231    kISC_BlendCoeff,     //<! one minus src color
232    kDC_BlendCoeff,      //<! dst color
233    kIDC_BlendCoeff,     //<! one minus dst color
234    kSA_BlendCoeff,      //<! src alpha
235    kISA_BlendCoeff,     //<! one minus src alpha
236    kDA_BlendCoeff,      //<! dst alpha
237    kIDA_BlendCoeff,     //<! one minus dst alpha
238    kConstC_BlendCoeff,  //<! constant color
239    kIConstC_BlendCoeff, //<! one minus constant color
240    kConstA_BlendCoeff,  //<! constant color alpha
241    kIConstA_BlendCoeff, //<! one minus constant color alpha
242
243    kPublicBlendCoeffCount
244};
245
246/**
247 *  Formats for masks, used by the font cache.
248 *  Important that these are 0-based.
249 */
250enum GrMaskFormat {
251    kA8_GrMaskFormat,    //!< 1-byte per pixel
252    kA565_GrMaskFormat,  //!< 2-bytes per pixel
253    kA888_GrMaskFormat,  //!< 4-bytes per pixel
254
255    kCount_GrMaskFormats //!< used to allocate arrays sized for mask formats
256};
257
258/**
259 *  Return the number of bytes-per-pixel for the specified mask format.
260 */
261static inline int GrMaskFormatBytesPerPixel(GrMaskFormat format) {
262    GrAssert((unsigned)format <= 2);
263    // kA8   (0) -> 1
264    // kA565 (1) -> 2
265    // kA888 (2) -> 4
266    return 1 << (int)format;
267}
268
269/**
270 * Pixel configurations.
271 *
272 * Unpremultiplied configs are intended for converting pixel data in and out
273 * from skia. Surfaces with these configs have limited support. As an input
274 * (GrPaint texture) the corresponding GrSamplerState must have its filter set
275 * to kNearest_Filter. Otherwise, the draw will fail. When the render target
276 * has an unpremultiplied config draws must use blend coeffs 1,0 (AKA src-mode).
277 * Other coeffs will cause the draw to fail.
278 */
279enum GrPixelConfig {
280    kUnknown_GrPixelConfig,
281    kAlpha_8_GrPixelConfig,
282    kIndex_8_GrPixelConfig,
283    kRGB_565_GrPixelConfig,
284    /**
285     * Premultiplied
286     */
287    kRGBA_4444_GrPixelConfig,
288    /**
289     * Premultiplied. Byte order is r,g,b,a
290     */
291    kRGBA_8888_PM_GrPixelConfig,
292    /**
293     * Unpremultiplied. Byte order is r,g,b,a
294     */
295    kRGBA_8888_UPM_GrPixelConfig,
296    /**
297     * Premultiplied. Byte order is b,g,r,a
298     */
299    kBGRA_8888_PM_GrPixelConfig,
300    /**
301     * Unpremultiplied. Byte order is b,g,r,a
302     */
303    kBGRA_8888_UPM_GrPixelConfig,
304
305    kGrPixelConfigCount
306};
307
308// Aliases for pixel configs that match skia's byte order
309#ifndef SK_CPU_LENDIAN
310    #error "Skia gpu currently assumes little endian"
311#endif
312#if 24 == SK_A32_SHIFT && 16 == SK_R32_SHIFT && \
313     8 == SK_G32_SHIFT &&  0 == SK_B32_SHIFT
314    static const GrPixelConfig kSkia8888_PM_GrPixelConfig = kBGRA_8888_PM_GrPixelConfig;
315    static const GrPixelConfig kSkia8888_UPM_GrPixelConfig = kBGRA_8888_UPM_GrPixelConfig;
316#elif 24 == SK_A32_SHIFT && 16 == SK_B32_SHIFT && \
317       8 == SK_G32_SHIFT &&  0 == SK_R32_SHIFT
318    static const GrPixelConfig kSkia8888_PM_GrPixelConfig = kRGBA_8888_PM_GrPixelConfig;
319    static const GrPixelConfig kSkia8888_UPM_GrPixelConfig = kRGBA_8888_UPM_GrPixelConfig;
320#else
321    #error "SK_*32_SHIFT values must correspond to GL_BGRA or GL_RGBA format."
322#endif
323
324// WebKit is relying on this old name for the native skia PM config. This will
325// be deleted ASAP because it is so similar to kRGBA_PM_8888_GrPixelConfig but
326// has a different interpretation when skia is compiled BGRA.
327static const GrPixelConfig kRGBA_8888_GrPixelConfig = kSkia8888_PM_GrPixelConfig;
328
329// Returns true if the pixel config has 8bit r,g,b,a components in that byte
330// order
331static inline bool GrPixelConfigIsRGBA8888(GrPixelConfig config) {
332    switch (config) {
333        case kRGBA_8888_PM_GrPixelConfig:
334        case kRGBA_8888_UPM_GrPixelConfig:
335            return true;
336        default:
337            return false;
338    }
339}
340
341// Returns true if the pixel config has 8bit b,g,r,a components in that byte
342// order
343static inline bool GrPixelConfigIsBGRA8888(GrPixelConfig config) {
344    switch (config) {
345        case kBGRA_8888_PM_GrPixelConfig:
346        case kBGRA_8888_UPM_GrPixelConfig:
347            return true;
348        default:
349            return false;
350    }
351}
352
353// Returns true if the pixel config is 32 bits per pixel
354static inline bool GrPixelConfigIs32Bit(GrPixelConfig config) {
355    switch (config) {
356        case kRGBA_8888_PM_GrPixelConfig:
357        case kRGBA_8888_UPM_GrPixelConfig:
358        case kBGRA_8888_PM_GrPixelConfig:
359        case kBGRA_8888_UPM_GrPixelConfig:
360            return true;
361        default:
362            return false;
363    }
364}
365
366// Takes a config and returns the equivalent config with the R and B order
367// swapped if such a config exists. Otherwise, kUnknown_GrPixelConfig
368static inline GrPixelConfig GrPixelConfigSwapRAndB(GrPixelConfig config) {
369    switch (config) {
370        case kBGRA_8888_PM_GrPixelConfig:
371            return kRGBA_8888_PM_GrPixelConfig;
372        case kBGRA_8888_UPM_GrPixelConfig:
373            return kRGBA_8888_UPM_GrPixelConfig;
374        case kRGBA_8888_PM_GrPixelConfig:
375            return kBGRA_8888_PM_GrPixelConfig;
376        case kRGBA_8888_UPM_GrPixelConfig:
377            return kBGRA_8888_UPM_GrPixelConfig;
378        default:
379            return kUnknown_GrPixelConfig;
380    }
381}
382
383static inline size_t GrBytesPerPixel(GrPixelConfig config) {
384    switch (config) {
385        case kAlpha_8_GrPixelConfig:
386        case kIndex_8_GrPixelConfig:
387            return 1;
388        case kRGB_565_GrPixelConfig:
389        case kRGBA_4444_GrPixelConfig:
390            return 2;
391        case kRGBA_8888_PM_GrPixelConfig:
392        case kRGBA_8888_UPM_GrPixelConfig:
393        case kBGRA_8888_PM_GrPixelConfig:
394        case kBGRA_8888_UPM_GrPixelConfig:
395            return 4;
396        default:
397            return 0;
398    }
399}
400
401static inline bool GrPixelConfigIsOpaque(GrPixelConfig config) {
402    switch (config) {
403        case kRGB_565_GrPixelConfig:
404            return true;
405        default:
406            return false;
407    }
408}
409
410/**
411 * Premultiplied alpha is the usual for skia. Therefore, configs that are
412 * ambiguous (alpha-only or color-only) are considered premultiplied.
413 */
414static inline bool GrPixelConfigIsUnpremultiplied(GrPixelConfig config) {
415    switch (config) {
416        case kRGBA_8888_UPM_GrPixelConfig:
417        case kBGRA_8888_UPM_GrPixelConfig:
418            return true;
419        default:
420            return false;
421    }
422}
423
424static inline bool GrPixelConfigIsAlphaOnly(GrPixelConfig config) {
425    switch (config) {
426        case kAlpha_8_GrPixelConfig:
427            return true;
428        default:
429            return false;
430    }
431}
432
433/**
434 * DEPRECATED: This will be removed as soon as WebKit no longer references
435 * this (former) enum value.
436 */
437static const int kNone_GrAALevel = 0;
438
439/**
440 * Optional bitfield flags that can be passed to createTexture.
441 */
442enum GrTextureFlags {
443    kNone_GrTextureFlags            = 0x0,
444    /**
445     * Creates a texture that can be rendered to as a GrRenderTarget. Use
446     * GrTexture::asRenderTarget() to access.
447     */
448    kRenderTarget_GrTextureFlagBit  = 0x1,
449    /**
450     * By default all render targets have an associated stencil buffer that
451     * may be required for path filling. This flag overrides stencil buffer
452     * creation.
453     * MAKE THIS PRIVATE?
454     */
455    kNoStencil_GrTextureFlagBit     = 0x2,
456    /**
457     * Hint that the CPU may modify this texture after creation.
458     */
459    kDynamicUpdate_GrTextureFlagBit = 0x4,
460};
461
462GR_MAKE_BITFIELD_OPS(GrTextureFlags)
463
464enum {
465   /**
466    *  For Index8 pixel config, the colortable must be 256 entries
467    */
468    kGrColorTableSize = 256 * 4 //sizeof(GrColor)
469};
470
471/**
472 * Describes a texture to be created.
473 */
474struct GrTextureDesc {
475    GrTextureFlags         fFlags;  //!< bitfield of TextureFlags
476    int                    fWidth;  //!< Width of the texture
477    int                    fHeight; //!< Height of the texture
478
479    /**
480     * Format of source data of the texture. Not guaraunteed to be the same as
481     * internal format used by 3D API.
482     */
483    GrPixelConfig          fConfig;
484
485    /**
486     * The number of samples per pixel or 0 to disable full scene AA. This only
487     * applies if the kRenderTarget_GrTextureFlagBit is set. The actual number
488     * of samples may not exactly match the request. The request will be rounded
489     * up to the next supported sample count, or down if it is larger than the
490     * max supportex count.
491     */
492    union {
493        /**
494         * This field has two names for legacy reasons. Use the fSampleCnt name.
495         * fAALevel is deprecated and will be removed as soon as WebKit no
496         * longer uses it.
497         */
498        int fSampleCnt;
499        int fAALevel;
500    };
501};
502
503/**
504 * Set Operations used to construct clips.
505 */
506enum GrSetOp {
507    kReplace_SetOp,
508    kIntersect_SetOp,
509    kUnion_SetOp,
510    kXor_SetOp,
511    kDifference_SetOp,
512    kReverseDifference_SetOp,
513};
514
515/**
516 * Clips are composed from these objects.
517 */
518enum GrClipType {
519    kRect_ClipType,
520    kPath_ClipType
521};
522
523/**
524 * Commands used to describe a path. Each command
525 * is accompanied by some number of points.
526 */
527enum GrPathCmd {
528    kMove_PathCmd,      //!< Starts a new subpath at
529                        //   at the returned point
530                        // 1 point
531    kLine_PathCmd,      //!< Adds a line segment
532                        // 2 points
533    kQuadratic_PathCmd, //!< Adds a quadratic segment
534                        // 3 points
535    kCubic_PathCmd,     //!< Adds a cubic segment
536                        // 4 points
537    kClose_PathCmd,     //!< Closes the current subpath
538                        //   by connecting a line to the
539                        //   starting point.
540                        // 0 points
541    kEnd_PathCmd        //!< Indicates the end of the last subpath
542                        //   when iterating
543                        // 0 points.
544};
545
546/**
547 * Gets the number of points associated with a path command.
548 */
549static int inline NumPathCmdPoints(GrPathCmd cmd) {
550    static const int gNumPoints[] = {
551        1, 2, 3, 4, 0, 0
552    };
553    return gNumPoints[cmd];
554}
555
556/**
557 * Path filling rules
558 */
559enum GrPathFill {
560    kWinding_PathFill,
561    kEvenOdd_PathFill,
562    kInverseWinding_PathFill,
563    kInverseEvenOdd_PathFill,
564    kHairLine_PathFill,
565
566    kPathFillCount
567};
568
569static inline GrPathFill GrNonInvertedFill(GrPathFill fill) {
570    static const GrPathFill gNonInvertedFills[] = {
571        kWinding_PathFill, // kWinding_PathFill
572        kEvenOdd_PathFill, // kEvenOdd_PathFill
573        kWinding_PathFill, // kInverseWinding_PathFill
574        kEvenOdd_PathFill, // kInverseEvenOdd_PathFill
575        kHairLine_PathFill,// kHairLine_PathFill
576    };
577    GR_STATIC_ASSERT(0 == kWinding_PathFill);
578    GR_STATIC_ASSERT(1 == kEvenOdd_PathFill);
579    GR_STATIC_ASSERT(2 == kInverseWinding_PathFill);
580    GR_STATIC_ASSERT(3 == kInverseEvenOdd_PathFill);
581    GR_STATIC_ASSERT(4 == kHairLine_PathFill);
582    GR_STATIC_ASSERT(5 == kPathFillCount);
583    return gNonInvertedFills[fill];
584}
585
586static inline bool GrIsFillInverted(GrPathFill fill) {
587    static const bool gIsFillInverted[] = {
588        false, // kWinding_PathFill
589        false, // kEvenOdd_PathFill
590        true,  // kInverseWinding_PathFill
591        true,  // kInverseEvenOdd_PathFill
592        false, // kHairLine_PathFill
593    };
594    GR_STATIC_ASSERT(0 == kWinding_PathFill);
595    GR_STATIC_ASSERT(1 == kEvenOdd_PathFill);
596    GR_STATIC_ASSERT(2 == kInverseWinding_PathFill);
597    GR_STATIC_ASSERT(3 == kInverseEvenOdd_PathFill);
598    GR_STATIC_ASSERT(4 == kHairLine_PathFill);
599    GR_STATIC_ASSERT(5 == kPathFillCount);
600    return gIsFillInverted[fill];
601}
602
603///////////////////////////////////////////////////////////////////////////////
604
605// opaque type for 3D API object handles
606typedef intptr_t GrPlatform3DObject;
607
608/**
609 * Gr can wrap an existing texture created by the client with a GrTexture
610 * object. The client is responsible for ensuring that the texture lives at
611 * least as long as the GrTexture object wrapping it. We require the client to
612 * explicitly provide information about the texture, such as width, height,
613 * and pixel config, rather than querying the 3D APIfor these values. We expect
614 * these to be immutable even if the 3D API doesn't require this (OpenGL).
615 *
616 * Textures that are also render targets are supported as well. Gr will manage
617 * any ancillary 3D API (stencil buffer, FBO id, etc) objects necessary for
618 * Gr to draw into the render target. To access the render target object
619 * call GrTexture::asRenderTarget().
620 *
621 * If in addition to the render target flag, the caller also specifies a sample
622 * count Gr will create an MSAA buffer that resolves into the texture. Gr auto-
623 * resolves when it reads from the texture. The client can explictly resolve
624 * using the GrRenderTarget interface.
625 */
626
627enum GrPlatformTextureFlags {
628    /**
629     * No flags enabled
630     */
631    kNone_GrPlatformTextureFlag              = 0x0,
632    /**
633     * Indicates that the texture is also a render target, and thus should have
634     * a GrRenderTarget object.
635     *
636     * D3D (future): client must have created the texture with flags that allow
637     * it to be used as a render target.
638     */
639    kRenderTarget_GrPlatformTextureFlag      = 0x1,
640};
641GR_MAKE_BITFIELD_OPS(GrPlatformTextureFlags)
642
643struct GrPlatformTextureDesc {
644    GrPlatformTextureDesc() { memset(this, 0, sizeof(*this)); }
645    GrPlatformTextureFlags          fFlags;
646    int                             fWidth;         //<! width in pixels
647    int                             fHeight;        //<! height in pixels
648    GrPixelConfig                   fConfig;        //<! color format
649    /**
650     * If the render target flag is set and sample count is greater than 0
651     * then Gr will create an MSAA buffer that resolves to the texture.
652     */
653    int                             fSampleCnt;
654    /**
655     * Handle to the 3D API object.
656     * OpenGL: Texture ID.
657     */
658    GrPlatform3DObject              fTextureHandle;
659};
660
661///////////////////////////////////////////////////////////////////////////////
662
663/**
664 * Gr can wrap an existing render target created by the client in the 3D API
665 * with a GrRenderTarget object. The client is responsible for ensuring that the
666 * underlying 3D API object lives at least as long as the GrRenderTarget object
667 * wrapping it. We require the client to explicitly provide information about
668 * the target, such as width, height, and pixel config rather than querying the
669 * 3D API for these values. We expect these properties to be immutable even if
670 * the 3D API doesn't require this (OpenGL).
671 */
672
673struct GrPlatformRenderTargetDesc {
674    GrPlatformRenderTargetDesc() { memset(this, 0, sizeof(*this)); }
675    int                             fWidth;         //<! width in pixels
676    int                             fHeight;        //<! height in pixels
677    GrPixelConfig                   fConfig;        //<! color format
678    /**
679     * The number of samples per pixel. Gr uses this to influence decisions
680     * about applying other forms of antialiasing.
681     */
682    int                             fSampleCnt;
683    /**
684     * Number of bits of stencil per-pixel.
685     */
686    int                             fStencilBits;
687    /**
688     * Handle to the 3D API object.
689     * OpenGL: FBO ID
690     */
691    GrPlatform3DObject              fRenderTargetHandle;
692};
693
694
695///////////////////////////////////////////////////////////////////////////////
696
697// this is included only to make it easy to use this debugging facility
698#include "GrInstanceCounter.h"
699
700#endif
701