blob: cccc14f428c05c7de1d4fd19c93ae73633066b0d [file] [log] [blame]
bsalomon@google.com27847de2011-02-22 20:59:41 +00001/*
2 Copyright 2010 Google Inc.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17#ifndef GrContext_DEFINED
18#define GrContext_DEFINED
19
20#include "GrClip.h"
21#include "GrGpu.h"
22#include "GrTextureCache.h"
23#include "GrPaint.h"
bsalomon@google.comdfe75bc2011-03-25 12:31:16 +000024#include "GrPathRenderer.h"
bsalomon@google.com27847de2011-02-22 20:59:41 +000025
26class GrFontCache;
27class GrPathIter;
28class GrVertexBufferAllocPool;
29class GrIndexBufferAllocPool;
30class GrInOrderDrawBuffer;
bsalomon@google.com27847de2011-02-22 20:59:41 +000031
bsalomon@google.com91826102011-03-21 19:51:57 +000032class GR_API GrContext : public GrRefCnt {
bsalomon@google.com27847de2011-02-22 20:59:41 +000033public:
34 /**
35 * Creates a GrContext from within a 3D context.
36 */
37 static GrContext* Create(GrGpu::Engine engine,
38 GrGpu::Platform3DContext context3D);
39
40 /**
41 * Helper to create a opengl-shader based context
42 */
43 static GrContext* CreateGLShaderContext();
44
45 virtual ~GrContext();
46
47 /**
48 * The GrContext normally assumes that no outsider is setting state
49 * within the underlying 3D API's context/device/whatever. This call informs
50 * the context that the state was modified and it should resend. Shouldn't
51 * be called frequently for good performance.
52 */
53 void resetContext();
54
bsalomon@google.com8fe72472011-03-30 21:26:44 +000055 /**
56 * Abandons all gpu resources, assumes 3D API state is unknown. Call this
57 * if you have lost the associated GPU context, and thus internal texture,
58 * buffer, etc. references/IDs are now invalid. Should be called even when
59 * GrContext is no longer going to be used for two reasons:
60 * 1) ~GrContext will not try to free the objects in the 3D API.
61 * 2) If you've created GrResources that outlive the GrContext they will
62 * be marked as invalid (GrResource::isValid()) and won't attempt to
63 * free their underlying resource in the 3D API.
64 * Content drawn since the last GrContext::flush() may be lost.
65 */
66 void contextLost();
bsalomon@google.com27847de2011-02-22 20:59:41 +000067
68 /**
bsalomon@google.com8fe72472011-03-30 21:26:44 +000069 * Frees gpu created by the context. Can be called to reduce GPU memory
70 * pressure.
bsalomon@google.com27847de2011-02-22 20:59:41 +000071 */
bsalomon@google.com8fe72472011-03-30 21:26:44 +000072 void freeGpuResources();
73
74 ///////////////////////////////////////////////////////////////////////////
75 // Textures
bsalomon@google.com27847de2011-02-22 20:59:41 +000076
77 /**
78 * Search for an entry with the same Key. If found, "lock" it and return it.
79 * If not found, return null.
80 */
81 GrTextureEntry* findAndLockTexture(GrTextureKey*,
82 const GrSamplerState&);
83
84
85 /**
86 * Create a new entry, based on the specified key and texture, and return
87 * its "locked" entry.
88 *
89 * Ownership of the texture is transferred to the Entry, which will unref()
90 * it when we are purged or deleted.
91 */
92 GrTextureEntry* createAndLockTexture(GrTextureKey* key,
93 const GrSamplerState&,
94 const GrGpu::TextureDesc&,
95 void* srcData, size_t rowBytes);
96
97 /**
98 * When done with an entry, call unlockTexture(entry) on it, which returns
99 * it to the cache, where it may be purged.
100 */
101 void unlockTexture(GrTextureEntry* entry);
102
103 /**
104 * Removes an texture from the cache. This prevents the texture from
105 * being found by a subsequent findAndLockTexture() until it is
106 * reattached. The entry still counts against the cache's budget and should
107 * be reattached when exclusive access is no longer needed.
108 */
109 void detachCachedTexture(GrTextureEntry*);
110
111 /**
112 * Reattaches a texture to the cache and unlocks it. Allows it to be found
113 * by a subsequent findAndLock or be purged (provided its lock count is
114 * now 0.)
115 */
116 void reattachAndUnlockCachedTexture(GrTextureEntry*);
117
118 /**
119 * Creates a texture that is outside the cache. Does not count against
120 * cache's budget.
121 */
122 GrTexture* createUncachedTexture(const GrGpu::TextureDesc&,
123 void* srcData,
124 size_t rowBytes);
125
126 /**
127 * Returns true if the specified use of an indexed texture is supported.
128 */
129 bool supportsIndex8PixelConfig(const GrSamplerState&, int width, int height);
130
131 /**
132 * Return the current texture cache limits.
133 *
134 * @param maxTextures If non-null, returns maximum number of textures that
135 * can be held in the cache.
136 * @param maxTextureBytes If non-null, returns maximum number of bytes of
137 * texture memory that can be held in the cache.
138 */
139 void getTextureCacheLimits(int* maxTextures, size_t* maxTextureBytes) const;
140
141 /**
142 * Specify the texture cache limits. If the current cache exceeds either
143 * of these, it will be purged (LRU) to keep the cache within these limits.
144 *
145 * @param maxTextures The maximum number of textures that can be held in
146 * the cache.
147 * @param maxTextureBytes The maximum number of bytes of texture memory
148 * that can be held in the cache.
149 */
150 void setTextureCacheLimits(int maxTextures, size_t maxTextureBytes);
151
152 /**
153 * Return the max width or height of a texture supported by the current gpu
154 */
155 int getMaxTextureDimension();
156
157 ///////////////////////////////////////////////////////////////////////////
158 // Render targets
159
160 /**
161 * Wraps an externally-created rendertarget in a GrRenderTarget.
162 * @param platformRenderTarget 3D API-specific render target identifier
bsalomon@google.coma7f84e12011-03-10 14:13:19 +0000163 * e.g. in GL platforamRenderTarget is an FBO
bsalomon@google.com27847de2011-02-22 20:59:41 +0000164 * id.
165 * @param stencilBits the number of stencil bits that the render
166 * target has.
167 * @param width width of the render target.
168 * @param height height of the render target.
169 */
170 GrRenderTarget* createPlatformRenderTarget(intptr_t platformRenderTarget,
171 int stencilBits,
172 int width, int height);
173
174 /**
175 * Reads the current target object (e.g. FBO or IDirect3DSurface9*) and
176 * viewport state from the underlying 3D API and wraps it in a
177 * GrRenderTarget. The GrRenderTarget will not attempt to delete/destroy the
178 * underlying object in its destructor and it is up to caller to guarantee
179 * that it remains valid while the GrRenderTarget is used.
180 *
181 * @return the newly created GrRenderTarget
182 */
183 GrRenderTarget* createRenderTargetFrom3DApiState() {
184 return fGpu->createRenderTargetFrom3DApiState();
185 }
186
187 /**
188 * Sets the render target.
189 * @param target the render target to set. (should not be NULL.)
190 */
191 void setRenderTarget(GrRenderTarget* target);
192
193 /**
194 * Gets the current render target.
195 * @return the currently bound render target. Should never be NULL.
196 */
197 const GrRenderTarget* getRenderTarget() const;
198 GrRenderTarget* getRenderTarget();
199
200 ///////////////////////////////////////////////////////////////////////////
201 // Matrix state
202
203 /**
204 * Gets the current transformation matrix.
205 * @return the current matrix.
206 */
207 const GrMatrix& getMatrix() const;
208
209 /**
210 * Sets the transformation matrix.
211 * @param m the matrix to set.
212 */
213 void setMatrix(const GrMatrix& m);
214
215 /**
216 * Concats the current matrix. The passed matrix is applied before the
217 * current matrix.
218 * @param m the matrix to concat.
219 */
220 void concatMatrix(const GrMatrix& m) const;
221
222
223 ///////////////////////////////////////////////////////////////////////////
224 // Clip state
225 /**
226 * Gets the current clip.
227 * @return the current clip.
228 */
229 const GrClip& getClip() const { return fGpu->getClip(); }
230
231 /**
232 * Sets the clip.
233 * @param clip the clip to set.
234 */
235 void setClip(const GrClip& clip);
236
237 /**
238 * Convenience method for setting the clip to a rect.
239 * @param rect the rect to set as the new clip.
240 */
241 void setClip(const GrIRect& rect);
242
243 ///////////////////////////////////////////////////////////////////////////
244 // Draws
245
246 /**
247 * Erase the entire render target, ignoring any clips
248 */
249 void eraseColor(GrColor color);
250
251 /**
252 * Draw everywhere (respecting the clip) with the paint.
253 */
254 void drawPaint(const GrPaint& paint);
255
256 /**
257 * Draw the rect using a paint.
258 * @param paint describes how to color pixels.
259 * @param strokeWidth If strokeWidth < 0, then the rect is filled, else
260 * the rect is mitered stroked based on strokeWidth. If
261 * strokeWidth == 0, then the stroke is always a single
262 * pixel thick.
263 * @param matrix Optional matrix applied to the rect. Applied before
264 * context's matrix or the paint's matrix.
265 * The rects coords are used to access the paint (through texture matrix)
266 */
267 void drawRect(const GrPaint& paint,
268 const GrRect&,
269 GrScalar strokeWidth = -1,
270 const GrMatrix* matrix = NULL);
271
272 /**
273 * Maps a rect of paint coordinates onto the a rect of destination
274 * coordinates. Each rect can optionally be transformed. The srcRect
275 * is stretched over the dstRect. The dstRect is transformed by the
276 * context's matrix and the srcRect is transformed by the paint's matrix.
277 * Additional optional matrices can be provided by parameters.
278 *
279 * @param paint describes how to color pixels.
280 * @param dstRect the destination rect to draw.
281 * @param srcRect rect of paint coordinates to be mapped onto dstRect
282 * @param dstMatrix Optional matrix to transform dstRect. Applied before
283 * context's matrix.
284 * @param srcMatrix Optional matrix to transform srcRect Applied before
285 * paint's matrix.
286 */
287 void drawRectToRect(const GrPaint& paint,
288 const GrRect& dstRect,
289 const GrRect& srcRect,
290 const GrMatrix* dstMatrix = NULL,
291 const GrMatrix* srcMatrix = NULL);
292
293 /**
bsalomon@google.comd302f142011-03-03 13:54:13 +0000294 * Draws a path.
bsalomon@google.com27847de2011-02-22 20:59:41 +0000295 *
296 * @param paint describes how to color pixels.
bsalomon@google.comd302f142011-03-03 13:54:13 +0000297 * @param pathIter the path to draw
bsalomon@google.com27847de2011-02-22 20:59:41 +0000298 * @param fill the path filling rule to use.
299 * @param translate optional additional translation applied to the
300 * path.
301 */
302 void drawPath(const GrPaint& paint,
bsalomon@google.comd302f142011-03-03 13:54:13 +0000303 GrPathIter* pathIter,
304 GrPathFill fill,
305 const GrPoint* translate = NULL);
306 /**
307 * Helper version of drawPath that takes a GrPath
308 */
309 void drawPath(const GrPaint& paint,
310 const GrPath& path,
bsalomon@google.com27847de2011-02-22 20:59:41 +0000311 GrPathFill fill,
312 const GrPoint* translate = NULL);
313 /**
314 * Draws vertices with a paint.
315 *
316 * @param paint describes how to color pixels.
317 * @param primitiveType primitives type to draw.
318 * @param vertexCount number of vertices.
319 * @param positions array of vertex positions, required.
320 * @param texCoords optional array of texture coordinates used
321 * to access the paint.
322 * @param colors optional array of per-vertex colors, supercedes
323 * the paint's color field.
324 * @param indices optional array of indices. If NULL vertices
325 * are drawn non-indexed.
326 * @param indexCount if indices is non-null then this is the
327 * number of indices.
328 */
329 void drawVertices(const GrPaint& paint,
330 GrPrimitiveType primitiveType,
331 int vertexCount,
332 const GrPoint positions[],
333 const GrPoint texs[],
334 const GrColor colors[],
335 const uint16_t indices[],
336 int indexCount);
337
338 /**
339 * Similar to drawVertices but caller provides objects that convert to Gr
340 * types. The count of vertices is given by posSrc.
341 *
342 * @param paint describes how to color pixels.
343 * @param primitiveType primitives type to draw.
344 * @param posSrc Source of vertex positions. Must implement
345 * int count() const;
346 * void writeValue(int i, GrPoint* point) const;
347 * count returns the total number of vertices and
348 * writeValue writes a vertex position to point.
349 * @param texSrc optional, pass NULL to not use explicit tex
350 * coords. If present provides tex coords with
351 * method:
352 * void writeValue(int i, GrPoint* point) const;
353 * @param texSrc optional, pass NULL to not use per-vertex colors
354 * If present provides colors with method:
355 * void writeValue(int i, GrColor* point) const;
356 * @param indices optional, pass NULL for non-indexed drawing. If
357 * present supplies indices for indexed drawing
358 * with following methods:
359 * int count() const;
360 * void writeValue(int i, uint16_t* point) const;
361 * count returns the number of indices and
362 * writeValue supplies each index.
363 */
364 template <typename POS_SRC,
365 typename TEX_SRC,
366 typename COL_SRC,
367 typename IDX_SRC>
368 void drawCustomVertices(const GrPaint& paint,
369 GrPrimitiveType primitiveType,
370 const POS_SRC& posSrc,
371 const TEX_SRC* texCoordSrc,
372 const COL_SRC* colorSrc,
373 const IDX_SRC* idxSrc);
374 /**
375 * To avoid the problem of having to create a typename for NULL parameters,
376 * these reduced versions of drawCustomVertices are provided.
377 */
378 template <typename POS_SRC>
379 void drawCustomVertices(const GrPaint& paint,
380 GrPrimitiveType primitiveType,
381 const POS_SRC& posSrc);
382 template <typename POS_SRC, typename TEX_SRC>
383 void drawCustomVertices(const GrPaint& paint,
384 GrPrimitiveType primitiveType,
385 const POS_SRC& posSrc,
386 const TEX_SRC* texCoordSrc);
387 template <typename POS_SRC, typename TEX_SRC, typename COL_SRC>
388 void drawCustomVertices(const GrPaint& paint,
389 GrPrimitiveType primitiveType,
390 const POS_SRC& posSrc,
391 const TEX_SRC* texCoordSrc,
392 const COL_SRC* colorSrc);
393
394
395 ///////////////////////////////////////////////////////////////////////////
396 // Misc.
397
398 /**
bsalomon@google.coma7f84e12011-03-10 14:13:19 +0000399 * Flags that affect flush() behavior.
400 */
401 enum FlushBits {
402 /**
403 * A client may want Gr to bind a GrRenderTarget in the 3D API so that
404 * it can be rendered to directly. However, Gr lazily sets state. Simply
405 * calling setRenderTarget() followed by flush() without flags may not
406 * bind the render target. This flag forces the context to bind the last
407 * set render target in the 3D API.
408 */
409 kForceCurrentRenderTarget_FlushBit = 0x1,
410 /**
411 * A client may reach a point where it has partially rendered a frame
412 * through a GrContext that it knows the user will never see. This flag
413 * causes the flush to skip submission of deferred content to the 3D API
414 * during the flush.
415 */
416 kDiscard_FlushBit = 0x2,
417 };
418
419 /**
bsalomon@google.com27847de2011-02-22 20:59:41 +0000420 * Call to ensure all drawing to the context has been issued to the
421 * underlying 3D API.
bsalomon@google.coma7f84e12011-03-10 14:13:19 +0000422 * @param flagsBitfield flags that control the flushing behavior. See
423 * FlushBits.
bsalomon@google.com27847de2011-02-22 20:59:41 +0000424 */
bsalomon@google.com8fe72472011-03-30 21:26:44 +0000425 void flush(int flagsBitfield = 0);
bsalomon@google.com27847de2011-02-22 20:59:41 +0000426 /**
427 * Return true on success, i.e. if we could copy the specified range of
428 * pixels from the current render-target into the buffer, converting into
429 * the specified pixel-config.
430 */
431 bool readPixels(int left, int top, int width, int height,
432 GrTexture::PixelConfig, void* buffer);
433
434 /**
435 * Copy the src pixels [buffer, stride, pixelconfig] into the current
436 * render-target at the specified rectangle.
437 */
438 void writePixels(int left, int top, int width, int height,
439 GrTexture::PixelConfig, const void* buffer, size_t stride);
440
441
442 ///////////////////////////////////////////////////////////////////////////
443 // Statistics
444
445 void resetStats();
446
447 const GrGpu::Stats& getStats() const;
448
449 void printStats() const;
450
451 ///////////////////////////////////////////////////////////////////////////
452 // Helpers
453
454 class AutoRenderTarget : ::GrNoncopyable {
455 public:
456 AutoRenderTarget(GrContext* context, GrRenderTarget* target) {
457 fContext = NULL;
458 fPrevTarget = context->getRenderTarget();
459 if (fPrevTarget != target) {
460 context->setRenderTarget(target);
461 fContext = context;
462 }
463 }
464 ~AutoRenderTarget() {
465 if (fContext) {
466 fContext->setRenderTarget(fPrevTarget);
467 }
468 }
469 private:
470 GrContext* fContext;
471 GrRenderTarget* fPrevTarget;
472 };
473
474
475 ///////////////////////////////////////////////////////////////////////////
476 // Functions intended for internal use only.
477 GrGpu* getGpu() { return fGpu; }
478 GrFontCache* getFontCache() { return fFontCache; }
479 GrDrawTarget* getTextTarget(const GrPaint& paint);
480 void flushText();
481 const GrIndexBuffer* getQuadIndexBuffer() const;
482
483private:
484 // used to keep track of when we need to flush the draw buffer
485 enum DrawCategory {
486 kBuffered_DrawCategory, // last draw was inserted in draw buffer
487 kUnbuffered_DrawCategory, // last draw was not inserted in the draw buffer
488 kText_DrawCategory // text context was last to draw
489 };
490 DrawCategory fLastDrawCategory;
491
492 GrGpu* fGpu;
493 GrTextureCache* fTextureCache;
494 GrFontCache* fFontCache;
bsalomon@google.comdfe75bc2011-03-25 12:31:16 +0000495
496 GrPathRenderer* fCustomPathRenderer;
497 GrDefaultPathRenderer fDefaultPathRenderer;
bsalomon@google.com27847de2011-02-22 20:59:41 +0000498
499 GrVertexBufferAllocPool* fDrawBufferVBAllocPool;
500 GrIndexBufferAllocPool* fDrawBufferIBAllocPool;
501 GrInOrderDrawBuffer* fDrawBuffer;
502
503 GrContext(GrGpu* gpu);
bsalomon@google.comdfe75bc2011-03-25 12:31:16 +0000504
bsalomon@google.com8fe72472011-03-30 21:26:44 +0000505 void setupDrawBuffer();
506
bsalomon@google.com27847de2011-02-22 20:59:41 +0000507 void flushDrawBuffer();
508
509 static void SetPaint(const GrPaint& paint, GrDrawTarget* target);
510
511 bool finalizeTextureKey(GrTextureKey*, const GrSamplerState&) const;
bsalomon@google.coma7f84e12011-03-10 14:13:19 +0000512
bsalomon@google.com27847de2011-02-22 20:59:41 +0000513 GrDrawTarget* prepareToDraw(const GrPaint& paint, DrawCategory drawType);
514
515 void drawClipIntoStencil();
bsalomon@google.comdfe75bc2011-03-25 12:31:16 +0000516
517 GrPathRenderer* getPathRenderer(const GrDrawTarget* target,
518 GrPathIter* path,
519 GrPathFill fill);
520
bsalomon@google.com27847de2011-02-22 20:59:41 +0000521};
522
523/**
524 * Save/restore the view-matrix in the context.
525 */
526class GrAutoMatrix : GrNoncopyable {
527public:
528 GrAutoMatrix(GrContext* ctx) : fContext(ctx) {
529 fMatrix = ctx->getMatrix();
530 }
531 GrAutoMatrix(GrContext* ctx, const GrMatrix& matrix) : fContext(ctx) {
532 fMatrix = ctx->getMatrix();
533 ctx->setMatrix(matrix);
534 }
535 ~GrAutoMatrix() {
536 fContext->setMatrix(fMatrix);
537 }
538
539private:
540 GrContext* fContext;
541 GrMatrix fMatrix;
542};
543
544#endif
545
546#include "GrContext_impl.h"