Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / platform / graphics / gpu / DrawingBuffer.h
1 /*
2  * Copyright (c) 2010, Google Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions are
6  * met:
7  *
8  *     * Redistributions of source code must retain the above copyright
9  * notice, this list of conditions and the following disclaimer.
10  *     * Redistributions in binary form must reproduce the above
11  * copyright notice, this list of conditions and the following disclaimer
12  * in the documentation and/or other materials provided with the
13  * distribution.
14  *     * Neither the name of Google Inc. nor the names of its
15  * contributors may be used to endorse or promote products derived from
16  * this software without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30
31 #ifndef DrawingBuffer_h
32 #define DrawingBuffer_h
33
34 #include "platform/PlatformExport.h"
35 #include "platform/geometry/IntSize.h"
36 #include "platform/graphics/GraphicsTypes3D.h"
37 #include "platform/graphics/gpu/WebGLImageConversion.h"
38 #include "public/platform/WebExternalTextureLayerClient.h"
39 #include "public/platform/WebExternalTextureMailbox.h"
40 #include "public/platform/WebGraphicsContext3D.h"
41 #include "third_party/khronos/GLES2/gl2.h"
42 #include "third_party/khronos/GLES2/gl2ext.h"
43 #include "third_party/skia/include/core/SkBitmap.h"
44 #include "wtf/Deque.h"
45 #include "wtf/Noncopyable.h"
46 #include "wtf/OwnPtr.h"
47 #include "wtf/PassOwnPtr.h"
48
49 namespace blink {
50
51 class Extensions3DUtil;
52 class ImageBuffer;
53 class WebExternalBitmap;
54 class WebExternalTextureLayer;
55 class WebGraphicsContext3D;
56 class WebLayer;
57
58 // Abstract interface to allow basic context eviction management
59 class PLATFORM_EXPORT ContextEvictionManager : public RefCounted<ContextEvictionManager> {
60 public:
61     virtual ~ContextEvictionManager() {};
62
63     virtual void forciblyLoseOldestContext(const String& reason) = 0;
64     virtual IntSize oldestContextSize() = 0;
65 };
66
67 // Manages a rendering target (framebuffer + attachment) for a canvas.  Can publish its rendering
68 // results to a WebLayer for compositing.
69 class PLATFORM_EXPORT DrawingBuffer : public RefCounted<DrawingBuffer>, public WebExternalTextureLayerClient  {
70     // If we used CHROMIUM_image as the backing storage for our buffers,
71     // we need to know the mapping from texture id to image.
72     struct TextureInfo {
73         Platform3DObject textureId;
74         WGC3Duint imageId;
75
76         TextureInfo()
77             : textureId(0)
78             , imageId(0)
79         {
80         }
81     };
82
83     struct MailboxInfo : public RefCounted<MailboxInfo> {
84         WebExternalTextureMailbox mailbox;
85         TextureInfo textureInfo;
86         IntSize size;
87         // This keeps the parent drawing buffer alive as long as the compositor is
88         // referring to one of the mailboxes DrawingBuffer produced. The parent drawing buffer is
89         // cleared when the compositor returns the mailbox. See mailboxReleased().
90         RefPtr<DrawingBuffer> m_parentDrawingBuffer;
91     };
92 public:
93     enum PreserveDrawingBuffer {
94         Preserve,
95         Discard
96     };
97
98     static PassRefPtr<DrawingBuffer> create(PassOwnPtr<WebGraphicsContext3D>, const IntSize&, PreserveDrawingBuffer, WebGraphicsContext3D::Attributes requestedAttributes, PassRefPtr<ContextEvictionManager>);
99
100     virtual ~DrawingBuffer();
101
102     // Destruction will be completed after all mailboxes are released.
103     void beginDestruction();
104
105     // Issues a glClear() on all framebuffers associated with this DrawingBuffer. The caller is responsible for
106     // making the context current and setting the clear values and masks. Modifies the framebuffer binding.
107     void clearFramebuffers(GLbitfield clearMask);
108
109     // Given the desired buffer size, provides the largest dimensions that will fit in the pixel budget.
110     static IntSize adjustSize(const IntSize& desiredSize, const IntSize& curSize, int maxTextureSize);
111     bool reset(const IntSize&);
112     void bind();
113     IntSize size() const { return m_size; }
114
115     // Copies the multisample color buffer to the normal color buffer and leaves m_fbo bound.
116     void commit(long x = 0, long y = 0, long width = -1, long height = -1);
117
118     // commit should copy the full multisample buffer, and not respect the
119     // current scissor bounds. Track the state of the scissor test so that it
120     // can be disabled during calls to commit.
121     void setScissorEnabled(bool scissorEnabled) { m_scissorEnabled = scissorEnabled; }
122
123     // The DrawingBuffer needs to track the texture bound to texture unit 0.
124     // The bound texture is tracked to avoid costly queries during rendering.
125     void setTexture2DBinding(Platform3DObject texture) { m_texture2DBinding = texture; }
126
127     // The DrawingBuffer needs to track the currently bound framebuffer so it
128     // restore the binding when needed.
129     void setFramebufferBinding(Platform3DObject fbo) { m_framebufferBinding = fbo; }
130
131     // Track the currently active texture unit. Texture unit 0 is used as host for a scratch
132     // texture.
133     void setActiveTextureUnit(GLint textureUnit) { m_activeTextureUnit = textureUnit; }
134
135     bool multisample() const;
136
137     Platform3DObject framebuffer() const;
138
139     bool discardFramebufferSupported() const { return m_discardFramebufferSupported; }
140
141     void markContentsChanged();
142     void markLayerComposited();
143     bool layerComposited() const;
144     void setIsHidden(bool);
145
146     WebLayer* platformLayer();
147     void paintCompositedResultsToCanvas(ImageBuffer*);
148
149     WebGraphicsContext3D* context();
150
151     // Returns the actual context attributes for this drawing buffer which may differ from the
152     // requested context attributes due to implementation limits.
153     WebGraphicsContext3D::Attributes getActualAttributes() const { return m_actualAttributes; }
154
155     // WebExternalTextureLayerClient implementation.
156     virtual bool prepareMailbox(WebExternalTextureMailbox*, WebExternalBitmap*) override;
157     virtual void mailboxReleased(const WebExternalTextureMailbox&, bool lostResource = false) override;
158
159     // Destroys the TEXTURE_2D binding for the owned context
160     bool copyToPlatformTexture(WebGraphicsContext3D*, Platform3DObject texture, GLenum internalFormat,
161         GLenum destType, GLint level, bool premultiplyAlpha, bool flipY, bool fromFrontBuffer = false);
162
163     void setPackAlignment(GLint param);
164
165     void paintRenderingResultsToCanvas(ImageBuffer*);
166     PassRefPtr<Uint8ClampedArray> paintRenderingResultsToImageData(int&, int&);
167
168 protected: // For unittests
169     DrawingBuffer(
170         PassOwnPtr<WebGraphicsContext3D>,
171         PassOwnPtr<Extensions3DUtil>,
172         bool multisampleExtensionSupported,
173         bool packedDepthStencilExtensionSupported,
174         bool discardFramebufferSupported,
175         PreserveDrawingBuffer,
176         WebGraphicsContext3D::Attributes requestedAttributes,
177         PassRefPtr<ContextEvictionManager>);
178
179     bool initialize(const IntSize&);
180
181 private:
182     void mailboxReleasedWithoutRecycling(const WebExternalTextureMailbox&);
183
184     unsigned createColorTexture();
185     // Create the depth/stencil and multisample buffers, if needed.
186     void createSecondaryBuffers();
187     bool resizeFramebuffer(const IntSize&);
188     bool resizeMultisampleFramebuffer(const IntSize&);
189     void resizeDepthStencil(const IntSize&);
190
191     // Bind to the m_framebufferBinding if it's not 0.
192     void restoreFramebufferBinding();
193
194     void clearPlatformLayer();
195
196     PassRefPtr<MailboxInfo> recycledMailbox();
197     PassRefPtr<MailboxInfo> createNewMailbox(const TextureInfo&);
198     void deleteMailbox(const WebExternalTextureMailbox&);
199     void freeRecycledMailboxes();
200
201     // Updates the current size of the buffer, ensuring that s_currentResourceUsePixels is updated.
202     void setSize(const IntSize& size);
203
204     // Calculates the difference in pixels between the current buffer size and the proposed size.
205     static int pixelDelta(const IntSize& newSize, const IntSize& curSize);
206
207     // Given the desired buffer size, provides the largest dimensions that will fit in the pixel budget
208     // Returns true if the buffer will only fit if the oldest WebGL context is forcibly lost
209     IntSize adjustSizeWithContextEviction(const IntSize&, bool& evictContext);
210
211     void paintFramebufferToCanvas(int framebuffer, int width, int height, bool premultiplyAlpha, ImageBuffer*);
212
213     // This is the order of bytes to use when doing a readback.
214     enum ReadbackOrder {
215         ReadbackRGBA,
216         ReadbackSkia
217     };
218
219     // Helper function which does a readback from the currently-bound
220     // framebuffer into a buffer of a certain size with 4-byte pixels.
221     void readBackFramebuffer(unsigned char* pixels, int width, int height, ReadbackOrder, WebGLImageConversion::AlphaOp);
222
223     // Helper function to flip a bitmap vertically.
224     void flipVertically(uint8_t* data, int width, int height);
225
226     // Helper to texImage2D with pixel==0 case: pixels are initialized to 0.
227     // By default, alignment is 4, the OpenGL default setting.
228     void texImage2DResourceSafe(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, GLint alignment = 4);
229     // Allocate buffer storage to be sent to compositor using either texImage2D or CHROMIUM_image based on available support.
230     void allocateTextureMemory(TextureInfo*, const IntSize&);
231     void deleteChromiumImageForTexture(TextureInfo*);
232
233     PreserveDrawingBuffer m_preserveDrawingBuffer;
234     bool m_scissorEnabled;
235     Platform3DObject m_texture2DBinding;
236     Platform3DObject m_framebufferBinding;
237     GLenum m_activeTextureUnit;
238
239     OwnPtr<WebGraphicsContext3D> m_context;
240     OwnPtr<Extensions3DUtil> m_extensionsUtil;
241     IntSize m_size;
242     WebGraphicsContext3D::Attributes m_requestedAttributes;
243     bool m_multisampleExtensionSupported;
244     bool m_packedDepthStencilExtensionSupported;
245     bool m_discardFramebufferSupported;
246     Platform3DObject m_fbo;
247     // DrawingBuffer's output is double-buffered. m_colorBuffer is the back buffer.
248     TextureInfo m_colorBuffer;
249     struct FrontBufferInfo {
250         TextureInfo texInfo;
251         WebExternalTextureMailbox mailbox;
252     };
253     FrontBufferInfo m_frontColorBuffer;
254
255     // This is used when we have OES_packed_depth_stencil.
256     Platform3DObject m_depthStencilBuffer;
257
258     // These are used when we don't.
259     Platform3DObject m_depthBuffer;
260     Platform3DObject m_stencilBuffer;
261
262     // For multisampling.
263     Platform3DObject m_multisampleFBO;
264     Platform3DObject m_multisampleColorBuffer;
265
266     // True if our contents have been modified since the last presentation of this buffer.
267     bool m_contentsChanged;
268
269     // True if commit() has been called since the last time markContentsChanged() had been called.
270     bool m_contentsChangeCommitted;
271     bool m_layerComposited;
272
273     enum MultisampleMode {
274         None,
275         ImplicitResolve,
276         ExplicitResolve,
277     };
278
279     MultisampleMode m_multisampleMode;
280
281     WebGraphicsContext3D::Attributes m_actualAttributes;
282     unsigned m_internalColorFormat;
283     unsigned m_colorFormat;
284     unsigned m_internalRenderbufferFormat;
285     int m_maxTextureSize;
286     int m_sampleCount;
287     int m_packAlignment;
288     bool m_destructionInProgress;
289     bool m_isHidden;
290
291     OwnPtr<WebExternalTextureLayer> m_layer;
292
293     // All of the mailboxes that this DrawingBuffer has ever created.
294     Vector<RefPtr<MailboxInfo> > m_textureMailboxes;
295     // Mailboxes that were released by the compositor can be used again by this DrawingBuffer.
296     Deque<WebExternalTextureMailbox> m_recycledMailboxQueue;
297
298     RefPtr<ContextEvictionManager> m_contextEvictionManager;
299
300     // If the width and height of the Canvas's backing store don't
301     // match those that we were given in the most recent call to
302     // reshape(), then we need an intermediate bitmap to read back the
303     // frame buffer into. This seems to happen when CSS styles are
304     // used to resize the Canvas.
305     SkBitmap m_resizingBitmap;
306
307     // Used to flip a bitmap vertically.
308     Vector<uint8_t> m_scanline;
309 };
310
311 } // namespace blink
312
313 #endif // DrawingBuffer_h