Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / gpu / command_buffer / client / gles2_implementation.h
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #ifndef GPU_COMMAND_BUFFER_CLIENT_GLES2_IMPLEMENTATION_H_
6 #define GPU_COMMAND_BUFFER_CLIENT_GLES2_IMPLEMENTATION_H_
7
8 #include <GLES2/gl2.h>
9
10 #include <list>
11 #include <map>
12 #include <queue>
13 #include <set>
14 #include <string>
15 #include <utility>
16 #include <vector>
17
18 #include "base/compiler_specific.h"
19 #include "base/memory/scoped_ptr.h"
20 #include "base/memory/weak_ptr.h"
21 #include "gpu/command_buffer/client/buffer_tracker.h"
22 #include "gpu/command_buffer/client/client_context_state.h"
23 #include "gpu/command_buffer/client/context_support.h"
24 #include "gpu/command_buffer/client/gles2_cmd_helper.h"
25 #include "gpu/command_buffer/client/gles2_impl_export.h"
26 #include "gpu/command_buffer/client/gles2_interface.h"
27 #include "gpu/command_buffer/client/mapped_memory.h"
28 #include "gpu/command_buffer/client/query_tracker.h"
29 #include "gpu/command_buffer/client/ref_counted.h"
30 #include "gpu/command_buffer/client/ring_buffer.h"
31 #include "gpu/command_buffer/client/share_group.h"
32 #include "gpu/command_buffer/common/capabilities.h"
33 #include "gpu/command_buffer/common/debug_marker_manager.h"
34 #include "gpu/command_buffer/common/gles2_cmd_utils.h"
35 #include "gpu/command_buffer/common/id_allocator.h"
36
37 #if !defined(NDEBUG) && !defined(__native_client__) && !defined(GLES2_CONFORMANCE_TESTS)  // NOLINT
38   #if defined(GLES2_INLINE_OPTIMIZATION)
39     // TODO(gman): Replace with macros that work with inline optmization.
40     #define GPU_CLIENT_SINGLE_THREAD_CHECK()
41     #define GPU_CLIENT_LOG(args)
42     #define GPU_CLIENT_LOG_CODE_BLOCK(code)
43     #define GPU_CLIENT_DCHECK_CODE_BLOCK(code)
44   #else
45     #include "base/logging.h"
46     #define GPU_CLIENT_SINGLE_THREAD_CHECK() SingleThreadChecker checker(this);
47     #define GPU_CLIENT_LOG(args)  DLOG_IF(INFO, debug_) << args;
48     #define GPU_CLIENT_LOG_CODE_BLOCK(code) code
49     #define GPU_CLIENT_DCHECK_CODE_BLOCK(code) code
50     #define GPU_CLIENT_DEBUG
51   #endif
52 #else
53   #define GPU_CLIENT_SINGLE_THREAD_CHECK()
54   #define GPU_CLIENT_LOG(args)
55   #define GPU_CLIENT_LOG_CODE_BLOCK(code)
56   #define GPU_CLIENT_DCHECK_CODE_BLOCK(code)
57 #endif
58
59 #if defined(GPU_CLIENT_DEBUG)
60   // Set to 1 to have the client fail when a GL error is generated.
61   // This helps find bugs in the renderer since the debugger stops on the error.
62 #  if 0
63 #    define GL_CLIENT_FAIL_GL_ERRORS
64 #  endif
65 #endif
66
67 // Check that destination pointers point to initialized memory.
68 // When the context is lost, calling GL function has no effect so if destination
69 // pointers point to initialized memory it can often lead to crash bugs. eg.
70 //
71 // GLsizei len;
72 // glGetShaderSource(shader, max_size, &len, buffer);
73 // std::string src(buffer, buffer + len);  // len can be uninitialized here!!!
74 //
75 // Because this check is not official GL this check happens only on Chrome code,
76 // not Pepper.
77 //
78 // If it was up to us we'd just always write to the destination but the OpenGL
79 // spec defines the behavior of OpenGL functions, not us. :-(
80 #if defined(__native_client__) || defined(GLES2_CONFORMANCE_TESTS)
81   #define GPU_CLIENT_VALIDATE_DESTINATION_INITALIZATION_ASSERT(v)
82   #define GPU_CLIENT_DCHECK(v)
83 #elif defined(GPU_DCHECK)
84   #define GPU_CLIENT_VALIDATE_DESTINATION_INITALIZATION_ASSERT(v) GPU_DCHECK(v)
85   #define GPU_CLIENT_DCHECK(v) GPU_DCHECK(v)
86 #elif defined(DCHECK)
87   #define GPU_CLIENT_VALIDATE_DESTINATION_INITALIZATION_ASSERT(v) DCHECK(v)
88   #define GPU_CLIENT_DCHECK(v) DCHECK(v)
89 #else
90   #define GPU_CLIENT_VALIDATE_DESTINATION_INITALIZATION_ASSERT(v) ASSERT(v)
91   #define GPU_CLIENT_DCHECK(v) ASSERT(v)
92 #endif
93
94 #define GPU_CLIENT_VALIDATE_DESTINATION_INITALIZATION(type, ptr) \
95     GPU_CLIENT_VALIDATE_DESTINATION_INITALIZATION_ASSERT(ptr && \
96         (ptr[0] == static_cast<type>(0) || ptr[0] == static_cast<type>(-1)));
97
98 #define GPU_CLIENT_VALIDATE_DESTINATION_OPTIONAL_INITALIZATION(type, ptr) \
99     GPU_CLIENT_VALIDATE_DESTINATION_INITALIZATION_ASSERT(!ptr || \
100         (ptr[0] == static_cast<type>(0) || ptr[0] == static_cast<type>(-1)));
101
102 struct GLUniformDefinitionCHROMIUM;
103
104 namespace gpu {
105
106 class GpuControl;
107 class ScopedTransferBufferPtr;
108 class TransferBufferInterface;
109
110 namespace gles2 {
111
112 class ImageFactory;
113 class VertexArrayObjectManager;
114
115 class GLES2ImplementationErrorMessageCallback {
116  public:
117   virtual ~GLES2ImplementationErrorMessageCallback() { }
118   virtual void OnErrorMessage(const char* msg, int id) = 0;
119 };
120
121 // This class emulates GLES2 over command buffers. It can be used by a client
122 // program so that the program does not need deal with shared memory and command
123 // buffer management. See gl2_lib.h.  Note that there is a performance gain to
124 // be had by changing your code to use command buffers directly by using the
125 // GLES2CmdHelper but that entails changing your code to use and deal with
126 // shared memory and synchronization issues.
127 class GLES2_IMPL_EXPORT GLES2Implementation
128     : NON_EXPORTED_BASE(public GLES2Interface),
129       NON_EXPORTED_BASE(public ContextSupport) {
130  public:
131   enum MappedMemoryLimit {
132     kNoLimit = MappedMemoryManager::kNoLimit,
133   };
134
135   // Stores GL state that never changes.
136   struct GLES2_IMPL_EXPORT GLStaticState {
137     GLStaticState();
138     ~GLStaticState();
139
140     struct GLES2_IMPL_EXPORT IntState {
141       IntState();
142       GLint max_combined_texture_image_units;
143       GLint max_cube_map_texture_size;
144       GLint max_fragment_uniform_vectors;
145       GLint max_renderbuffer_size;
146       GLint max_texture_image_units;
147       GLint max_texture_size;
148       GLint max_varying_vectors;
149       GLint max_vertex_attribs;
150       GLint max_vertex_texture_image_units;
151       GLint max_vertex_uniform_vectors;
152       GLint num_compressed_texture_formats;
153       GLint num_shader_binary_formats;
154       GLint bind_generates_resource_chromium;
155     };
156     IntState int_state;
157
158     typedef std::pair<GLenum, GLenum> ShaderPrecisionKey;
159     typedef std::map<ShaderPrecisionKey,
160                      cmds::GetShaderPrecisionFormat::Result>
161         ShaderPrecisionMap;
162     ShaderPrecisionMap shader_precisions;
163   };
164
165   // The maxiumum result size from simple GL get commands.
166   static const size_t kMaxSizeOfSimpleResult = 16 * sizeof(uint32);  // NOLINT.
167
168   // used for testing only. If more things are reseved add them here.
169   static const unsigned int kStartingOffset = kMaxSizeOfSimpleResult;
170
171   // Size in bytes to issue async flush for transfer buffer.
172   static const unsigned int kSizeToFlush = 256 * 1024;
173
174   // The bucket used for results. Public for testing only.
175   static const uint32 kResultBucketId = 1;
176
177   // Alignment of allocations.
178   static const unsigned int kAlignment = 4;
179
180   // GL names for the buffers used to emulate client side buffers.
181   static const GLuint kClientSideArrayId = 0xFEDCBA98u;
182   static const GLuint kClientSideElementArrayId = 0xFEDCBA99u;
183
184   // Number of swap buffers allowed before waiting.
185   static const size_t kMaxSwapBuffers = 2;
186
187   GLES2Implementation(GLES2CmdHelper* helper,
188                       ShareGroup* share_group,
189                       TransferBufferInterface* transfer_buffer,
190                       bool bind_generates_resource,
191                       bool lose_context_when_out_of_memory,
192                       bool support_client_side_arrays,
193                       GpuControl* gpu_control);
194
195   ~GLES2Implementation() override;
196
197   bool Initialize(
198       unsigned int starting_transfer_buffer_size,
199       unsigned int min_transfer_buffer_size,
200       unsigned int max_transfer_buffer_size,
201       unsigned int mapped_memory_limit);
202
203   // The GLES2CmdHelper being used by this GLES2Implementation. You can use
204   // this to issue cmds at a lower level for certain kinds of optimization.
205   GLES2CmdHelper* helper() const;
206
207   // Gets client side generated errors.
208   GLenum GetClientSideGLError();
209
210   // Include the auto-generated part of this class. We split this because
211   // it means we can easily edit the non-auto generated parts right here in
212   // this file instead of having to edit some template or the code generator.
213   #include "gpu/command_buffer/client/gles2_implementation_autogen.h"
214
215   void DisableVertexAttribArray(GLuint index) override;
216   void EnableVertexAttribArray(GLuint index) override;
217   void GetVertexAttribfv(GLuint index, GLenum pname, GLfloat* params) override;
218   void GetVertexAttribiv(GLuint index, GLenum pname, GLint* params) override;
219
220   // ContextSupport implementation.
221   void Swap() override;
222   void PartialSwapBuffers(const gfx::Rect& sub_buffer) override;
223   void ScheduleOverlayPlane(int plane_z_order,
224                             gfx::OverlayTransform plane_transform,
225                             unsigned overlay_texture_id,
226                             const gfx::Rect& display_bounds,
227                             const gfx::RectF& uv_rect) override;
228   GLuint InsertFutureSyncPointCHROMIUM() override;
229   void RetireSyncPointCHROMIUM(GLuint sync_point) override;
230
231   void GetProgramInfoCHROMIUMHelper(GLuint program, std::vector<int8>* result);
232   GLint GetAttribLocationHelper(GLuint program, const char* name);
233   GLint GetUniformLocationHelper(GLuint program, const char* name);
234   bool GetActiveAttribHelper(
235       GLuint program, GLuint index, GLsizei bufsize, GLsizei* length,
236       GLint* size, GLenum* type, char* name);
237   bool GetActiveUniformHelper(
238       GLuint program, GLuint index, GLsizei bufsize, GLsizei* length,
239       GLint* size, GLenum* type, char* name);
240
241   void FreeUnusedSharedMemory();
242   void FreeEverything();
243
244   // ContextSupport implementation.
245   void SignalSyncPoint(uint32 sync_point,
246                        const base::Closure& callback) override;
247   void SignalQuery(uint32 query, const base::Closure& callback) override;
248   void SetSurfaceVisible(bool visible) override;
249
250   void SetErrorMessageCallback(
251       GLES2ImplementationErrorMessageCallback* callback) {
252     error_message_callback_ = callback;
253   }
254
255   ShareGroup* share_group() const {
256     return share_group_.get();
257   }
258
259   const Capabilities& capabilities() const {
260     return capabilities_;
261   }
262
263   GpuControl* gpu_control() {
264     return gpu_control_;
265   }
266
267   ShareGroupContextData* share_group_context_data() {
268     return &share_group_context_data_;
269   }
270
271  private:
272   friend class GLES2ImplementationTest;
273   friend class VertexArrayObjectManager;
274
275   // Used to track whether an extension is available
276   enum ExtensionStatus {
277       kAvailableExtensionStatus,
278       kUnavailableExtensionStatus,
279       kUnknownExtensionStatus
280   };
281
282   // Base class for mapped resources.
283   struct MappedResource {
284     MappedResource(GLenum _access, int _shm_id, void* mem, unsigned int offset)
285         : access(_access),
286           shm_id(_shm_id),
287           shm_memory(mem),
288           shm_offset(offset) {
289     }
290
291     // access mode. Currently only GL_WRITE_ONLY is valid
292     GLenum access;
293
294     // Shared memory ID for buffer.
295     int shm_id;
296
297     // Address of shared memory
298     void* shm_memory;
299
300     // Offset of shared memory
301     unsigned int shm_offset;
302   };
303
304   // Used to track mapped textures.
305   struct MappedTexture : public MappedResource {
306     MappedTexture(
307         GLenum access,
308         int shm_id,
309         void* shm_mem,
310         unsigned int shm_offset,
311         GLenum _target,
312         GLint _level,
313         GLint _xoffset,
314         GLint _yoffset,
315         GLsizei _width,
316         GLsizei _height,
317         GLenum _format,
318         GLenum _type)
319         : MappedResource(access, shm_id, shm_mem, shm_offset),
320           target(_target),
321           level(_level),
322           xoffset(_xoffset),
323           yoffset(_yoffset),
324           width(_width),
325           height(_height),
326           format(_format),
327           type(_type) {
328     }
329
330     // These match the arguments to TexSubImage2D.
331     GLenum target;
332     GLint level;
333     GLint xoffset;
334     GLint yoffset;
335     GLsizei width;
336     GLsizei height;
337     GLenum format;
338     GLenum type;
339   };
340
341   // Used to track mapped buffers.
342   struct MappedBuffer : public MappedResource {
343     MappedBuffer(
344         GLenum access,
345         int shm_id,
346         void* shm_mem,
347         unsigned int shm_offset,
348         GLenum _target,
349         GLintptr _offset,
350         GLsizeiptr _size)
351         : MappedResource(access, shm_id, shm_mem, shm_offset),
352           target(_target),
353           offset(_offset),
354           size(_size) {
355     }
356
357     // These match the arguments to BufferSubData.
358     GLenum target;
359     GLintptr offset;
360     GLsizeiptr size;
361   };
362
363   struct TextureUnit {
364     TextureUnit()
365         : bound_texture_2d(0),
366           bound_texture_cube_map(0),
367           bound_texture_external_oes(0) {}
368
369     // texture currently bound to this unit's GL_TEXTURE_2D with glBindTexture
370     GLuint bound_texture_2d;
371
372     // texture currently bound to this unit's GL_TEXTURE_CUBE_MAP with
373     // glBindTexture
374     GLuint bound_texture_cube_map;
375
376     // texture currently bound to this unit's GL_TEXTURE_EXTERNAL_OES with
377     // glBindTexture
378     GLuint bound_texture_external_oes;
379   };
380
381   // Checks for single threaded access.
382   class SingleThreadChecker {
383    public:
384     explicit SingleThreadChecker(GLES2Implementation* gles2_implementation);
385     ~SingleThreadChecker();
386
387    private:
388     GLES2Implementation* gles2_implementation_;
389   };
390
391   // Gets the value of the result.
392   template <typename T>
393   T GetResultAs() {
394     return static_cast<T>(GetResultBuffer());
395   }
396
397   void* GetResultBuffer();
398   int32 GetResultShmId();
399   uint32 GetResultShmOffset();
400
401   bool QueryAndCacheStaticState();
402
403   // Helpers used to batch synchronous GetIntergerv calls with other
404   // synchronous calls.
405   struct GetMultipleIntegervState {
406     GetMultipleIntegervState(const GLenum* pnames, GLuint pnames_count,
407                              GLint* results, GLsizeiptr results_size)
408        : pnames(pnames),
409          pnames_count(pnames_count),
410          results(results),
411          results_size(results_size)
412     { }
413     // inputs
414     const GLenum* pnames;
415     GLuint pnames_count;
416     // outputs
417     GLint* results;
418     GLsizeiptr results_size;
419     // transfer buffer
420     int num_results;
421     int transfer_buffer_size_needed;
422     void* buffer;
423     void* results_buffer;
424   };
425   bool GetMultipleIntegervSetup(
426       GetMultipleIntegervState* state);
427   void GetMultipleIntegervRequest(
428       GetMultipleIntegervState* state);
429   void GetMultipleIntegervOnCompleted(
430       GetMultipleIntegervState* state);
431
432   // Helpers used to batch synchronous GetShaderPrecision calls with other
433   // synchronous calls.
434   struct GetAllShaderPrecisionFormatsState {
435     GetAllShaderPrecisionFormatsState(
436         const GLenum (*precision_params)[2],
437         int precision_params_count)
438         : precision_params(precision_params),
439           precision_params_count(precision_params_count)
440     { }
441     const GLenum (*precision_params)[2];
442     int precision_params_count;
443     int transfer_buffer_size_needed;
444     void* results_buffer;
445   };
446   void GetAllShaderPrecisionFormatsSetup(
447       GetAllShaderPrecisionFormatsState* state);
448   void GetAllShaderPrecisionFormatsRequest(
449       GetAllShaderPrecisionFormatsState* state);
450   void GetAllShaderPrecisionFormatsOnCompleted(
451       GetAllShaderPrecisionFormatsState* state);
452
453   // Lazily determines if GL_ANGLE_pack_reverse_row_order is available
454   bool IsAnglePackReverseRowOrderAvailable();
455   bool IsChromiumFramebufferMultisampleAvailable();
456
457   bool IsExtensionAvailableHelper(
458       const char* extension, ExtensionStatus* status);
459
460   // Gets the GLError through our wrapper.
461   GLenum GetGLError();
462
463   // Sets our wrapper for the GLError.
464   void SetGLError(GLenum error, const char* function_name, const char* msg);
465   void SetGLErrorInvalidEnum(
466       const char* function_name, GLenum value, const char* label);
467
468   // Returns the last error and clears it. Useful for debugging.
469   const std::string& GetLastError() {
470     return last_error_;
471   }
472
473   // Waits for all commands to execute.
474   void WaitForCmd();
475
476   // TODO(gman): These bucket functions really seem like they belong in
477   // CommandBufferHelper (or maybe BucketHelper?). Unfortunately they need
478   // a transfer buffer to function which is currently managed by this class.
479
480   // Gets the contents of a bucket.
481   bool GetBucketContents(uint32 bucket_id, std::vector<int8>* data);
482
483   // Sets the contents of a bucket.
484   void SetBucketContents(uint32 bucket_id, const void* data, size_t size);
485
486   // Sets the contents of a bucket as a string.
487   void SetBucketAsCString(uint32 bucket_id, const char* str);
488
489   // Gets the contents of a bucket as a string. Returns false if there is no
490   // string available which is a separate case from the empty string.
491   bool GetBucketAsString(uint32 bucket_id, std::string* str);
492
493   // Sets the contents of a bucket as a string.
494   void SetBucketAsString(uint32 bucket_id, const std::string& str);
495
496   // Returns true if id is reserved.
497   bool IsBufferReservedId(GLuint id);
498   bool IsFramebufferReservedId(GLuint id) { return false; }
499   bool IsRenderbufferReservedId(GLuint id) { return false; }
500   bool IsTextureReservedId(GLuint id) { return false; }
501   bool IsVertexArrayReservedId(GLuint id) { return false; }
502   bool IsProgramReservedId(GLuint id) { return false; }
503   bool IsValuebufferReservedId(GLuint id) { return false; }
504
505   bool BindBufferHelper(GLenum target, GLuint texture);
506   bool BindFramebufferHelper(GLenum target, GLuint texture);
507   bool BindRenderbufferHelper(GLenum target, GLuint texture);
508   bool BindTextureHelper(GLenum target, GLuint texture);
509   bool BindVertexArrayOESHelper(GLuint array);
510   bool BindValuebufferCHROMIUMHelper(GLenum target, GLuint valuebuffer);
511   bool UseProgramHelper(GLuint program);
512
513   void GenBuffersHelper(GLsizei n, const GLuint* buffers);
514   void GenFramebuffersHelper(GLsizei n, const GLuint* framebuffers);
515   void GenRenderbuffersHelper(GLsizei n, const GLuint* renderbuffers);
516   void GenTexturesHelper(GLsizei n, const GLuint* textures);
517   void GenVertexArraysOESHelper(GLsizei n, const GLuint* arrays);
518   void GenQueriesEXTHelper(GLsizei n, const GLuint* queries);
519   void GenValuebuffersCHROMIUMHelper(GLsizei n, const GLuint* valuebuffers);
520
521   void DeleteBuffersHelper(GLsizei n, const GLuint* buffers);
522   void DeleteFramebuffersHelper(GLsizei n, const GLuint* framebuffers);
523   void DeleteRenderbuffersHelper(GLsizei n, const GLuint* renderbuffers);
524   void DeleteTexturesHelper(GLsizei n, const GLuint* textures);
525   bool DeleteProgramHelper(GLuint program);
526   bool DeleteShaderHelper(GLuint shader);
527   void DeleteQueriesEXTHelper(GLsizei n, const GLuint* queries);
528   void DeleteVertexArraysOESHelper(GLsizei n, const GLuint* arrays);
529   void DeleteValuebuffersCHROMIUMHelper(GLsizei n, const GLuint* valuebuffers);
530
531   void DeleteBuffersStub(GLsizei n, const GLuint* buffers);
532   void DeleteFramebuffersStub(GLsizei n, const GLuint* framebuffers);
533   void DeleteRenderbuffersStub(GLsizei n, const GLuint* renderbuffers);
534   void DeleteTexturesStub(GLsizei n, const GLuint* textures);
535   void DeleteProgramStub(GLsizei n, const GLuint* programs);
536   void DeleteShaderStub(GLsizei n, const GLuint* shaders);
537   void DeleteVertexArraysOESStub(GLsizei n, const GLuint* arrays);
538   void DeleteValuebuffersCHROMIUMStub(GLsizei n, const GLuint* valuebuffers);
539
540   void BufferDataHelper(
541       GLenum target, GLsizeiptr size, const void* data, GLenum usage);
542   void BufferSubDataHelper(
543       GLenum target, GLintptr offset, GLsizeiptr size, const void* data);
544   void BufferSubDataHelperImpl(
545       GLenum target, GLintptr offset, GLsizeiptr size, const void* data,
546       ScopedTransferBufferPtr* buffer);
547
548   GLuint CreateImageCHROMIUMHelper(ClientBuffer buffer,
549                                    GLsizei width,
550                                    GLsizei height,
551                                    GLenum internalformat);
552   void DestroyImageCHROMIUMHelper(GLuint image_id);
553   GLuint CreateGpuMemoryBufferImageCHROMIUMHelper(GLsizei width,
554                                                   GLsizei height,
555                                                   GLenum internalformat,
556                                                   GLenum usage);
557
558   // Helper for GetVertexAttrib
559   bool GetVertexAttribHelper(GLuint index, GLenum pname, uint32* param);
560
561   GLuint GetMaxValueInBufferCHROMIUMHelper(
562       GLuint buffer_id, GLsizei count, GLenum type, GLuint offset);
563
564   void RestoreElementAndArrayBuffers(bool restore);
565   void RestoreArrayBuffer(bool restrore);
566
567   // The pixels pointer should already account for unpack skip rows and skip
568   // pixels.
569   void TexSubImage2DImpl(
570       GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width,
571       GLsizei height, GLenum format, GLenum type, uint32 unpadded_row_size,
572       const void* pixels, uint32 pixels_padded_row_size, GLboolean internal,
573       ScopedTransferBufferPtr* buffer, uint32 buffer_padded_row_size);
574
575   // Helpers for query functions.
576   bool GetHelper(GLenum pname, GLint* params);
577   bool GetBooleanvHelper(GLenum pname, GLboolean* params);
578   bool GetBufferParameterivHelper(GLenum target, GLenum pname, GLint* params);
579   bool GetFloatvHelper(GLenum pname, GLfloat* params);
580   bool GetFramebufferAttachmentParameterivHelper(
581       GLenum target, GLenum attachment, GLenum pname, GLint* params);
582   bool GetIntegervHelper(GLenum pname, GLint* params);
583   bool GetProgramivHelper(GLuint program, GLenum pname, GLint* params);
584   bool GetRenderbufferParameterivHelper(
585       GLenum target, GLenum pname, GLint* params);
586   bool GetShaderivHelper(GLuint shader, GLenum pname, GLint* params);
587   bool GetTexParameterfvHelper(GLenum target, GLenum pname, GLfloat* params);
588   bool GetTexParameterivHelper(GLenum target, GLenum pname, GLint* params);
589   const GLubyte* GetStringHelper(GLenum name);
590
591   bool IsExtensionAvailable(const char* ext);
592
593   // Caches certain capabilties state. Return true if cached.
594   bool SetCapabilityState(GLenum cap, bool enabled);
595
596   IdHandlerInterface* GetIdHandler(int id_namespace) const;
597   // IdAllocators for objects that can't be shared among contexts.
598   // For now, used only for Queries. TODO(hj.r.chung) Should be added for
599   // Framebuffer and Vertex array objects.
600   IdAllocator* GetIdAllocator(int id_namespace) const;
601
602   void FinishHelper();
603
604   void RunIfContextNotLost(const base::Closure& callback);
605
606   // Validate if an offset is valid, i.e., non-negative and fit into 32-bit.
607   // If not, generate an approriate error, and return false.
608   bool ValidateOffset(const char* func, GLintptr offset);
609
610   // Validate if a size is valid, i.e., non-negative and fit into 32-bit.
611   // If not, generate an approriate error, and return false.
612   bool ValidateSize(const char* func, GLsizeiptr offset);
613
614   // Remove the transfer buffer from the buffer tracker. For buffers used
615   // asynchronously the memory is free:ed if the upload has completed. For
616   // other buffers, the memory is either free:ed immediately or free:ed pending
617   // a token.
618   void RemoveTransferBuffer(BufferTracker::Buffer* buffer);
619
620   // Returns true if the async upload token has passed.
621   //
622   // NOTE: This will detect wrapped async tokens by checking if the most
623   // significant  bit of async token to check is 1 but the last read is 0, i.e.
624   // the uint32 wrapped.
625   bool HasAsyncUploadTokenPassed(uint32 token) const {
626     return async_upload_sync_->HasAsyncUploadTokenPassed(token);
627   }
628
629   // Get the next async upload token.
630   uint32 NextAsyncUploadToken();
631
632   // Ensure that the shared memory used for synchronizing async upload tokens
633   // has been mapped.
634   //
635   // Returns false on error, true on success.
636   bool EnsureAsyncUploadSync();
637
638   // Checks the last read asynchronously upload token and frees any unmanaged
639   // transfer buffer that has its async token passed.
640   void PollAsyncUploads();
641
642   // Free every async upload buffer. If some async upload buffer is still in use
643   // wait for them to finish before freeing.
644   void FreeAllAsyncUploadBuffers();
645
646   bool GetBoundPixelTransferBuffer(
647       GLenum target, const char* function_name, GLuint* buffer_id);
648   BufferTracker::Buffer* GetBoundPixelUnpackTransferBufferIfValid(
649       GLuint buffer_id,
650       const char* function_name, GLuint offset, GLsizei size);
651
652   const std::string& GetLogPrefix() const;
653
654 #if defined(GL_CLIENT_FAIL_GL_ERRORS)
655   void CheckGLError();
656   void FailGLError(GLenum error);
657 #else
658   void CheckGLError() { }
659   void FailGLError(GLenum /* error */) { }
660 #endif
661
662   GLES2Util util_;
663   GLES2CmdHelper* helper_;
664   TransferBufferInterface* transfer_buffer_;
665   std::string last_error_;
666   DebugMarkerManager debug_marker_manager_;
667   std::string this_in_hex_;
668
669   std::queue<int32> swap_buffers_tokens_;
670   std::queue<int32> rate_limit_tokens_;
671
672   ExtensionStatus angle_pack_reverse_row_order_status_;
673   ExtensionStatus chromium_framebuffer_multisample_;
674
675   GLStaticState static_state_;
676   ClientContextState state_;
677
678   // pack alignment as last set by glPixelStorei
679   GLint pack_alignment_;
680
681   // unpack alignment as last set by glPixelStorei
682   GLint unpack_alignment_;
683
684   // unpack yflip as last set by glPixelstorei
685   bool unpack_flip_y_;
686
687   // unpack row length as last set by glPixelStorei
688   GLint unpack_row_length_;
689
690   // unpack skip rows as last set by glPixelStorei
691   GLint unpack_skip_rows_;
692
693   // unpack skip pixels as last set by glPixelStorei
694   GLint unpack_skip_pixels_;
695
696   // pack reverse row order as last set by glPixelstorei
697   bool pack_reverse_row_order_;
698
699   scoped_ptr<TextureUnit[]> texture_units_;
700
701   // 0 to gl_state_.max_combined_texture_image_units.
702   GLuint active_texture_unit_;
703
704   GLuint bound_framebuffer_;
705   GLuint bound_read_framebuffer_;
706   GLuint bound_renderbuffer_;
707   GLuint bound_valuebuffer_;
708
709   // The program in use by glUseProgram
710   GLuint current_program_;
711
712   // The currently bound array buffer.
713   GLuint bound_array_buffer_id_;
714
715   // The currently bound pixel transfer buffers.
716   GLuint bound_pixel_pack_transfer_buffer_id_;
717   GLuint bound_pixel_unpack_transfer_buffer_id_;
718
719   // The current asynchronous pixel buffer upload token.
720   uint32 async_upload_token_;
721
722   // The shared memory used for synchronizing asynchronous upload tokens.
723   AsyncUploadSync* async_upload_sync_;
724   int32 async_upload_sync_shm_id_;
725   unsigned int async_upload_sync_shm_offset_;
726
727   // Unmanaged pixel transfer buffer memory pending asynchronous upload token.
728   typedef std::list<std::pair<void*, uint32> > DetachedAsyncUploadMemoryList;
729   DetachedAsyncUploadMemoryList detached_async_upload_memory_;
730
731   // Client side management for vertex array objects. Needed to correctly
732   // track client side arrays.
733   scoped_ptr<VertexArrayObjectManager> vertex_array_object_manager_;
734
735   GLuint reserved_ids_[2];
736
737   // Current GL error bits.
738   uint32 error_bits_;
739
740   // Whether or not to print debugging info.
741   bool debug_;
742
743   // When true, the context is lost when a GL_OUT_OF_MEMORY error occurs.
744   bool lose_context_when_out_of_memory_;
745
746   // Whether or not to support client side arrays.
747   bool support_client_side_arrays_;
748
749   // Used to check for single threaded access.
750   int use_count_;
751
752   // Map of GLenum to Strings for glGetString.  We need to cache these because
753   // the pointer passed back to the client has to remain valid for eternity.
754   typedef std::map<uint32, std::set<std::string> > GLStringMap;
755   GLStringMap gl_strings_;
756
757   // Similar cache for glGetRequestableExtensionsCHROMIUM. We don't
758   // have an enum for this so handle it separately.
759   std::set<std::string> requestable_extensions_set_;
760
761   typedef std::map<const void*, MappedBuffer> MappedBufferMap;
762   MappedBufferMap mapped_buffers_;
763
764   typedef std::map<const void*, MappedTexture> MappedTextureMap;
765   MappedTextureMap mapped_textures_;
766
767   scoped_ptr<MappedMemoryManager> mapped_memory_;
768
769   scoped_refptr<ShareGroup> share_group_;
770   ShareGroupContextData share_group_context_data_;
771
772   scoped_ptr<QueryTracker> query_tracker_;
773   typedef std::map<GLuint, QueryTracker::Query*> QueryMap;
774   QueryMap current_queries_;
775   scoped_ptr<IdAllocator> query_id_allocator_;
776
777   scoped_ptr<BufferTracker> buffer_tracker_;
778
779   GLES2ImplementationErrorMessageCallback* error_message_callback_;
780
781   scoped_ptr<std::string> current_trace_name_;
782
783   GpuControl* gpu_control_;
784
785   Capabilities capabilities_;
786
787   base::WeakPtrFactory<GLES2Implementation> weak_ptr_factory_;
788
789   DISALLOW_COPY_AND_ASSIGN(GLES2Implementation);
790 };
791
792 inline bool GLES2Implementation::GetBufferParameterivHelper(
793     GLenum /* target */, GLenum /* pname */, GLint* /* params */) {
794   return false;
795 }
796
797 inline bool GLES2Implementation::GetFramebufferAttachmentParameterivHelper(
798     GLenum /* target */,
799     GLenum /* attachment */,
800     GLenum /* pname */,
801     GLint* /* params */) {
802   return false;
803 }
804
805 inline bool GLES2Implementation::GetRenderbufferParameterivHelper(
806     GLenum /* target */, GLenum /* pname */, GLint* /* params */) {
807   return false;
808 }
809
810 inline bool GLES2Implementation::GetShaderivHelper(
811     GLuint /* shader */, GLenum /* pname */, GLint* /* params */) {
812   return false;
813 }
814
815 inline bool GLES2Implementation::GetTexParameterfvHelper(
816     GLenum /* target */, GLenum /* pname */, GLfloat* /* params */) {
817   return false;
818 }
819
820 inline bool GLES2Implementation::GetTexParameterivHelper(
821     GLenum /* target */, GLenum /* pname */, GLint* /* params */) {
822   return false;
823 }
824
825 }  // namespace gles2
826 }  // namespace gpu
827
828 #endif  // GPU_COMMAND_BUFFER_CLIENT_GLES2_IMPLEMENTATION_H_