• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //
2 // Copyright 2002 The ANGLE Project Authors. All rights reserved.
3 // Use of this source code is governed by a BSD-style license that can be
4 // found in the LICENSE file.
5 //
6 
7 // Context.h: Defines the gl::Context class, managing all GL state and performing
8 // rendering operations. It is the GLES2 specific implementation of EGLContext.
9 
10 #ifndef LIBANGLE_CONTEXT_H_
11 #define LIBANGLE_CONTEXT_H_
12 
13 #include <mutex>
14 #include <set>
15 #include <string>
16 
17 #include "angle_gl.h"
18 #include "common/MemoryBuffer.h"
19 #include "common/PackedEnums.h"
20 #include "common/angleutils.h"
21 #include "libANGLE/Caps.h"
22 #include "libANGLE/Constants.h"
23 #include "libANGLE/Context_gl_1_autogen.h"
24 #include "libANGLE/Context_gl_2_autogen.h"
25 #include "libANGLE/Context_gl_3_autogen.h"
26 #include "libANGLE/Context_gl_4_autogen.h"
27 #include "libANGLE/Context_gles_1_0_autogen.h"
28 #include "libANGLE/Context_gles_2_0_autogen.h"
29 #include "libANGLE/Context_gles_3_0_autogen.h"
30 #include "libANGLE/Context_gles_3_1_autogen.h"
31 #include "libANGLE/Context_gles_3_2_autogen.h"
32 #include "libANGLE/Context_gles_ext_autogen.h"
33 #include "libANGLE/Error.h"
34 #include "libANGLE/HandleAllocator.h"
35 #include "libANGLE/RefCountObject.h"
36 #include "libANGLE/ResourceManager.h"
37 #include "libANGLE/ResourceMap.h"
38 #include "libANGLE/State.h"
39 #include "libANGLE/VertexAttribute.h"
40 #include "libANGLE/WorkerThread.h"
41 #include "libANGLE/angletypes.h"
42 
43 namespace angle
44 {
45 class FrameCapture;
46 class FrameCaptureShared;
47 struct FrontendFeatures;
48 }  // namespace angle
49 
50 namespace rx
51 {
52 class ContextImpl;
53 class EGLImplFactory;
54 }  // namespace rx
55 
56 namespace egl
57 {
58 class AttributeMap;
59 class Surface;
60 struct Config;
61 class Thread;
62 }  // namespace egl
63 
64 namespace gl
65 {
66 class Buffer;
67 class Compiler;
68 class FenceNV;
69 class Framebuffer;
70 class GLES1Renderer;
71 class MemoryProgramCache;
72 class MemoryObject;
73 class Program;
74 class ProgramPipeline;
75 class Query;
76 class Renderbuffer;
77 class Sampler;
78 class Semaphore;
79 class Shader;
80 class Sync;
81 class Texture;
82 class TransformFeedback;
83 class VertexArray;
84 struct VertexAttribute;
85 
86 class ErrorSet : angle::NonCopyable
87 {
88   public:
89     explicit ErrorSet(Context *context);
90     ~ErrorSet();
91 
92     bool empty() const;
93     GLenum popError();
94 
95     void handleError(GLenum errorCode,
96                      const char *message,
97                      const char *file,
98                      const char *function,
99                      unsigned int line);
100 
101     void validationError(angle::EntryPoint entryPoint, GLenum errorCode, const char *message);
102 
103   private:
104     Context *mContext;
105     std::set<GLenum> mErrors;
106 };
107 
108 enum class VertexAttribTypeCase
109 {
110     Invalid        = 0,
111     Valid          = 1,
112     ValidSize4Only = 2,
113     ValidSize3or4  = 3,
114 };
115 
116 // Helper class for managing cache variables and state changes.
117 class StateCache final : angle::NonCopyable
118 {
119   public:
120     StateCache();
121     ~StateCache();
122 
123     void initialize(Context *context);
124 
125     // Places that can trigger updateActiveAttribsMask:
126     // 1. onVertexArrayBindingChange.
127     // 2. onProgramExecutableChange.
128     // 3. onVertexArrayStateChange.
129     // 4. onGLES1ClientStateChange.
getActiveBufferedAttribsMask()130     AttributesMask getActiveBufferedAttribsMask() const { return mCachedActiveBufferedAttribsMask; }
getActiveClientAttribsMask()131     AttributesMask getActiveClientAttribsMask() const { return mCachedActiveClientAttribsMask; }
getActiveDefaultAttribsMask()132     AttributesMask getActiveDefaultAttribsMask() const { return mCachedActiveDefaultAttribsMask; }
hasAnyEnabledClientAttrib()133     bool hasAnyEnabledClientAttrib() const { return mCachedHasAnyEnabledClientAttrib; }
hasAnyActiveClientAttrib()134     bool hasAnyActiveClientAttrib() const { return mCachedActiveClientAttribsMask.any(); }
135 
136     // Places that can trigger updateVertexElementLimits:
137     // 1. onVertexArrayBindingChange.
138     // 2. onProgramExecutableChange.
139     // 3. onVertexArrayFormatChange.
140     // 4. onVertexArrayBufferChange.
141     // 5. onVertexArrayStateChange.
getNonInstancedVertexElementLimit()142     GLint64 getNonInstancedVertexElementLimit() const
143     {
144         return mCachedNonInstancedVertexElementLimit;
145     }
getInstancedVertexElementLimit()146     GLint64 getInstancedVertexElementLimit() const { return mCachedInstancedVertexElementLimit; }
147 
148     // Places that can trigger updateBasicDrawStatesError:
149     // 1. onVertexArrayBindingChange.
150     // 2. onProgramExecutableChange.
151     // 3. onVertexArrayBufferContentsChange.
152     // 4. onVertexArrayStateChange.
153     // 5. onVertexArrayBufferStateChange.
154     // 6. onDrawFramebufferChange.
155     // 7. onContextCapChange.
156     // 8. onStencilStateChange.
157     // 9. onDefaultVertexAttributeChange.
158     // 10. onActiveTextureChange.
159     // 11. onQueryChange.
160     // 12. onActiveTransformFeedbackChange.
161     // 13. onUniformBufferStateChange.
162     // 14. onColorMaskChange.
163     // 15. onBufferBindingChange.
164     // 16. onBlendFuncIndexedChange.
hasBasicDrawStatesError(Context * context)165     bool hasBasicDrawStatesError(Context *context) const
166     {
167         if (mCachedBasicDrawStatesError == 0)
168         {
169             return false;
170         }
171         if (mCachedBasicDrawStatesError != kInvalidPointer)
172         {
173             return true;
174         }
175         return getBasicDrawStatesErrorImpl(context) != 0;
176     }
177 
getBasicDrawStatesError(const Context * context)178     intptr_t getBasicDrawStatesError(const Context *context) const
179     {
180         if (mCachedBasicDrawStatesError != kInvalidPointer)
181         {
182             return mCachedBasicDrawStatesError;
183         }
184 
185         return getBasicDrawStatesErrorImpl(context);
186     }
187 
188     // Places that can trigger updateBasicDrawElementsError:
189     // 1. onActiveTransformFeedbackChange.
190     // 2. onVertexArrayBufferStateChange.
191     // 3. onBufferBindingChange.
192     // 4. onVertexArrayStateChange.
193     // 5. onVertexArrayBindingStateChange.
getBasicDrawElementsError(const Context * context)194     intptr_t getBasicDrawElementsError(const Context *context) const
195     {
196         if (mCachedBasicDrawElementsError != kInvalidPointer)
197         {
198             return mCachedBasicDrawElementsError;
199         }
200 
201         return getBasicDrawElementsErrorImpl(context);
202     }
203 
204     // Places that can trigger updateValidDrawModes:
205     // 1. onProgramExecutableChange.
206     // 2. onActiveTransformFeedbackChange.
isValidDrawMode(PrimitiveMode primitiveMode)207     bool isValidDrawMode(PrimitiveMode primitiveMode) const
208     {
209         return mCachedValidDrawModes[primitiveMode];
210     }
211 
212     // Cannot change except on Context/Extension init.
isValidBindTextureType(TextureType type)213     bool isValidBindTextureType(TextureType type) const
214     {
215         return mCachedValidBindTextureTypes[type];
216     }
217 
218     // Cannot change except on Context/Extension init.
isValidDrawElementsType(DrawElementsType type)219     bool isValidDrawElementsType(DrawElementsType type) const
220     {
221         return mCachedValidDrawElementsTypes[type];
222     }
223 
224     // Places that can trigger updateTransformFeedbackActiveUnpaused:
225     // 1. onActiveTransformFeedbackChange.
isTransformFeedbackActiveUnpaused()226     bool isTransformFeedbackActiveUnpaused() const
227     {
228         return mCachedTransformFeedbackActiveUnpaused;
229     }
230 
231     // Cannot change except on Context/Extension init.
getVertexAttribTypeValidation(VertexAttribType type)232     VertexAttribTypeCase getVertexAttribTypeValidation(VertexAttribType type) const
233     {
234         return mCachedVertexAttribTypesValidation[type];
235     }
236 
getIntegerVertexAttribTypeValidation(VertexAttribType type)237     VertexAttribTypeCase getIntegerVertexAttribTypeValidation(VertexAttribType type) const
238     {
239         return mCachedIntegerVertexAttribTypesValidation[type];
240     }
241 
242     // Places that can trigger updateActiveShaderStorageBufferIndices:
243     // 1. onProgramExecutableChange.
getActiveShaderStorageBufferIndices()244     StorageBuffersMask getActiveShaderStorageBufferIndices() const
245     {
246         return mCachedActiveShaderStorageBufferIndices;
247     }
248 
249     // Places that can trigger updateActiveImageUnitIndices:
250     // 1. onProgramExecutableChange.
getActiveImageUnitIndices()251     const ImageUnitMask &getActiveImageUnitIndices() const { return mCachedActiveImageUnitIndices; }
252 
253     // Places that can trigger updateCanDraw:
254     // 1. onProgramExecutableChange.
getCanDraw()255     bool getCanDraw() const { return mCachedCanDraw; }
256 
257     // State change notifications.
258     void onVertexArrayBindingChange(Context *context);
259     void onProgramExecutableChange(Context *context);
260     void onVertexArrayFormatChange(Context *context);
261     void onVertexArrayBufferContentsChange(Context *context);
262     void onVertexArrayStateChange(Context *context);
263     void onVertexArrayBufferStateChange(Context *context);
264     void onGLES1ClientStateChange(Context *context);
265     void onDrawFramebufferChange(Context *context);
266     void onContextCapChange(Context *context);
267     void onStencilStateChange(Context *context);
268     void onDefaultVertexAttributeChange(Context *context);
269     void onActiveTextureChange(Context *context);
270     void onQueryChange(Context *context);
271     void onActiveTransformFeedbackChange(Context *context);
272     void onUniformBufferStateChange(Context *context);
273     void onAtomicCounterBufferStateChange(Context *context);
274     void onShaderStorageBufferStateChange(Context *context);
275     void onColorMaskChange(Context *context);
276     void onBufferBindingChange(Context *context);
277     void onBlendFuncIndexedChange(Context *context);
278 
279   private:
280     // Cache update functions.
281     void updateActiveAttribsMask(Context *context);
282     void updateVertexElementLimits(Context *context);
283     void updateVertexElementLimitsImpl(Context *context);
284     void updateValidDrawModes(Context *context);
285     void updateValidBindTextureTypes(Context *context);
286     void updateValidDrawElementsTypes(Context *context);
287     void updateBasicDrawStatesError();
288     void updateBasicDrawElementsError();
289     void updateTransformFeedbackActiveUnpaused(Context *context);
290     void updateVertexAttribTypesValidation(Context *context);
291     void updateActiveShaderStorageBufferIndices(Context *context);
292     void updateActiveImageUnitIndices(Context *context);
293     void updateCanDraw(Context *context);
294 
295     void setValidDrawModes(bool pointsOK,
296                            bool linesOK,
297                            bool trisOK,
298                            bool lineAdjOK,
299                            bool triAdjOK,
300                            bool patchOK);
301 
302     intptr_t getBasicDrawStatesErrorImpl(const Context *context) const;
303     intptr_t getBasicDrawElementsErrorImpl(const Context *context) const;
304 
305     static constexpr intptr_t kInvalidPointer = 1;
306 
307     AttributesMask mCachedActiveBufferedAttribsMask;
308     AttributesMask mCachedActiveClientAttribsMask;
309     AttributesMask mCachedActiveDefaultAttribsMask;
310     bool mCachedHasAnyEnabledClientAttrib;
311     GLint64 mCachedNonInstancedVertexElementLimit;
312     GLint64 mCachedInstancedVertexElementLimit;
313     mutable intptr_t mCachedBasicDrawStatesError;
314     mutable intptr_t mCachedBasicDrawElementsError;
315     bool mCachedTransformFeedbackActiveUnpaused;
316     StorageBuffersMask mCachedActiveShaderStorageBufferIndices;
317     ImageUnitMask mCachedActiveImageUnitIndices;
318 
319     // Reserve an extra slot at the end of these maps for invalid enum.
320     angle::PackedEnumMap<PrimitiveMode, bool, angle::EnumSize<PrimitiveMode>() + 1>
321         mCachedValidDrawModes;
322     angle::PackedEnumMap<TextureType, bool, angle::EnumSize<TextureType>() + 1>
323         mCachedValidBindTextureTypes;
324     angle::PackedEnumMap<DrawElementsType, bool, angle::EnumSize<DrawElementsType>() + 1>
325         mCachedValidDrawElementsTypes;
326     angle::PackedEnumMap<VertexAttribType,
327                          VertexAttribTypeCase,
328                          angle::EnumSize<VertexAttribType>() + 1>
329         mCachedVertexAttribTypesValidation;
330     angle::PackedEnumMap<VertexAttribType,
331                          VertexAttribTypeCase,
332                          angle::EnumSize<VertexAttribType>() + 1>
333         mCachedIntegerVertexAttribTypesValidation;
334 
335     bool mCachedCanDraw;
336 };
337 
338 using VertexArrayMap       = ResourceMap<VertexArray, VertexArrayID>;
339 using QueryMap             = ResourceMap<Query, QueryID>;
340 using TransformFeedbackMap = ResourceMap<TransformFeedback, TransformFeedbackID>;
341 
342 class Context final : public egl::LabeledObject, angle::NonCopyable, public angle::ObserverInterface
343 {
344   public:
345     Context(egl::Display *display,
346             const egl::Config *config,
347             const Context *shareContext,
348             TextureManager *shareTextures,
349             SemaphoreManager *shareSemaphores,
350             MemoryProgramCache *memoryProgramCache,
351             const EGLenum clientType,
352             const egl::AttributeMap &attribs,
353             const egl::DisplayExtensions &displayExtensions,
354             const egl::ClientExtensions &clientExtensions);
355 
356     // Use for debugging.
id()357     ContextID id() const { return mState.getContextID(); }
358 
359     egl::Error initialize();
360 
361     egl::Error onDestroy(const egl::Display *display);
362     ~Context() override;
363 
364     void setLabel(EGLLabelKHR label) override;
365     EGLLabelKHR getLabel() const override;
366 
367     egl::Error makeCurrent(egl::Display *display,
368                            egl::Surface *drawSurface,
369                            egl::Surface *readSurface);
370     egl::Error unMakeCurrent(const egl::Display *display);
371 
372     // These create and destroy methods pass through to ResourceManager, which owns these objects.
373     BufferID createBuffer();
374     TextureID createTexture();
375     RenderbufferID createRenderbuffer();
376     ProgramPipelineID createProgramPipeline();
377     MemoryObjectID createMemoryObject();
378     SemaphoreID createSemaphore();
379 
380     void deleteBuffer(BufferID buffer);
381     void deleteTexture(TextureID texture);
382     void deleteRenderbuffer(RenderbufferID renderbuffer);
383     void deleteProgramPipeline(ProgramPipelineID pipeline);
384     void deleteMemoryObject(MemoryObjectID memoryObject);
385     void deleteSemaphore(SemaphoreID semaphore);
386 
387     void bindReadFramebuffer(FramebufferID framebufferHandle);
388     void bindDrawFramebuffer(FramebufferID framebufferHandle);
389 
390     Buffer *getBuffer(BufferID handle) const;
391     FenceNV *getFenceNV(FenceNVID handle) const;
392     Sync *getSync(GLsync handle) const;
getTexture(TextureID handle)393     ANGLE_INLINE Texture *getTexture(TextureID handle) const
394     {
395         return mState.mTextureManager->getTexture(handle);
396     }
397 
398     Framebuffer *getFramebuffer(FramebufferID handle) const;
399     Renderbuffer *getRenderbuffer(RenderbufferID handle) const;
400     VertexArray *getVertexArray(VertexArrayID handle) const;
401     Sampler *getSampler(SamplerID handle) const;
402     Query *getOrCreateQuery(QueryID handle, QueryType type);
403     Query *getQuery(QueryID handle) const;
404     TransformFeedback *getTransformFeedback(TransformFeedbackID handle) const;
405     ProgramPipeline *getProgramPipeline(ProgramPipelineID handle) const;
406     MemoryObject *getMemoryObject(MemoryObjectID handle) const;
407     Semaphore *getSemaphore(SemaphoreID handle) const;
408 
409     Texture *getTextureByType(TextureType type) const;
410     Texture *getTextureByTarget(TextureTarget target) const;
411     Texture *getSamplerTexture(unsigned int sampler, TextureType type) const;
412 
413     Compiler *getCompiler() const;
414 
415     bool isVertexArrayGenerated(VertexArrayID vertexArray) const;
416     bool isTransformFeedbackGenerated(TransformFeedbackID transformFeedback) const;
417 
isExternal()418     bool isExternal() const { return mIsExternal; }
saveAndRestoreState()419     bool saveAndRestoreState() const { return mSaveAndRestoreState; }
420 
421     void getBooleanvImpl(GLenum pname, GLboolean *params) const;
422     void getFloatvImpl(GLenum pname, GLfloat *params) const;
423     void getIntegervImpl(GLenum pname, GLint *params) const;
424     void getInteger64vImpl(GLenum pname, GLint64 *params) const;
425     void getIntegerVertexAttribImpl(GLenum pname, GLenum attribpname, GLint *params) const;
426     void getVertexAttribivImpl(GLuint index, GLenum pname, GLint *params) const;
427 
428     // Framebuffers are owned by the Context, so these methods do not pass through
429     FramebufferID createFramebuffer();
430     void deleteFramebuffer(FramebufferID framebuffer);
431 
432     bool hasActiveTransformFeedback(ShaderProgramID program) const;
433 
434     // Desktop GL entry point interface
435     ANGLE_GL_1_CONTEXT_API
436     ANGLE_GL_2_CONTEXT_API
437     ANGLE_GL_3_CONTEXT_API
438     ANGLE_GL_4_CONTEXT_API
439 
440     // GLES entry point interface
441     ANGLE_GLES_1_0_CONTEXT_API
442     ANGLE_GLES_2_0_CONTEXT_API
443     ANGLE_GLES_3_0_CONTEXT_API
444     ANGLE_GLES_3_1_CONTEXT_API
445     ANGLE_GLES_3_2_CONTEXT_API
446     ANGLE_GLES_EXT_CONTEXT_API
447 
448     angle::Result handleNoopDrawEvent();
449 
450     // Consumes an error.
451     void handleError(GLenum errorCode,
452                      const char *message,
453                      const char *file,
454                      const char *function,
455                      unsigned int line);
456 
457     void validationError(angle::EntryPoint entryPoint, GLenum errorCode, const char *message) const;
458 
459     void markContextLost(GraphicsResetStatus status);
460 
isContextLost()461     bool isContextLost() const { return mContextLost; }
462     void setContextLost();
463 
getGraphicsResetStrategy()464     GLenum getGraphicsResetStrategy() const { return mResetStrategy; }
465     bool isResetNotificationEnabled() const;
466 
467     const egl::Config *getConfig() const;
468     EGLenum getClientType() const;
469     EGLenum getRenderBuffer() const;
470     EGLenum getContextPriority() const;
471 
472     const GLubyte *getString(GLenum name) const;
473     const GLubyte *getStringi(GLenum name, GLuint index) const;
474 
475     size_t getExtensionStringCount() const;
476 
477     bool isExtensionRequestable(const char *name) const;
478     bool isExtensionDisablable(const char *name) const;
479     size_t getRequestableExtensionStringCount() const;
480     void setExtensionEnabled(const char *name, bool enabled);
481     void reinitializeAfterExtensionsChanged();
482 
getImplementation()483     rx::ContextImpl *getImplementation() const { return mImplementation.get(); }
484 
485     ANGLE_NO_DISCARD bool getScratchBuffer(size_t requestedSizeBytes,
486                                            angle::MemoryBuffer **scratchBufferOut) const;
487     ANGLE_NO_DISCARD bool getZeroFilledBuffer(size_t requstedSizeBytes,
488                                               angle::MemoryBuffer **zeroBufferOut) const;
489     angle::ScratchBuffer *getScratchBuffer() const;
490 
491     angle::Result prepareForCopyImage();
492     angle::Result prepareForDispatch();
493     angle::Result prepareForInvalidate(GLenum target);
494 
getMemoryProgramCache()495     MemoryProgramCache *getMemoryProgramCache() const { return mMemoryProgramCache; }
496     std::mutex &getProgramCacheMutex() const;
497 
hasBeenCurrent()498     bool hasBeenCurrent() const { return mHasBeenCurrent; }
getDisplay()499     egl::Display *getDisplay() const { return mDisplay; }
getCurrentDrawSurface()500     egl::Surface *getCurrentDrawSurface() const { return mCurrentDrawSurface; }
getCurrentReadSurface()501     egl::Surface *getCurrentReadSurface() const { return mCurrentReadSurface; }
502 
isRobustResourceInitEnabled()503     bool isRobustResourceInitEnabled() const { return mState.isRobustResourceInitEnabled(); }
504 
505     bool isCurrentTransformFeedback(const TransformFeedback *tf) const;
506 
isCurrentVertexArray(const VertexArray * va)507     bool isCurrentVertexArray(const VertexArray *va) const
508     {
509         return mState.isCurrentVertexArray(va);
510     }
511 
isShared()512     ANGLE_INLINE bool isShared() const { return mShared; }
513     // Once a context is setShared() it cannot be undone
setShared()514     void setShared() { mShared = true; }
515 
getState()516     const State &getState() const { return mState; }
getClientMajorVersion()517     GLint getClientMajorVersion() const { return mState.getClientMajorVersion(); }
getClientMinorVersion()518     GLint getClientMinorVersion() const { return mState.getClientMinorVersion(); }
getClientVersion()519     const Version &getClientVersion() const { return mState.getClientVersion(); }
getCaps()520     const Caps &getCaps() const { return mState.getCaps(); }
getTextureCaps()521     const TextureCapsMap &getTextureCaps() const { return mState.getTextureCaps(); }
getExtensions()522     const Extensions &getExtensions() const { return mState.getExtensions(); }
getLimitations()523     const Limitations &getLimitations() const { return mState.getLimitations(); }
524     bool isGLES1() const;
525 
skipValidation()526     bool skipValidation() const
527     {
528         // Ensure we don't skip validation when context becomes lost, since implementations
529         // generally assume a non-lost context, non-null objects, etc.
530         ASSERT(!isContextLost() || !mSkipValidation);
531         return mSkipValidation;
532     }
533 
534     // Specific methods needed for validation.
535     bool getQueryParameterInfo(GLenum pname, GLenum *type, unsigned int *numParams) const;
536     bool getIndexedQueryParameterInfo(GLenum target, GLenum *type, unsigned int *numParams) const;
537 
getProgramResolveLink(ShaderProgramID handle)538     ANGLE_INLINE Program *getProgramResolveLink(ShaderProgramID handle) const
539     {
540         Program *program = mState.mShaderProgramManager->getProgram(handle);
541         if (program)
542         {
543             program->resolveLink(this);
544         }
545         return program;
546     }
547 
548     Program *getProgramNoResolveLink(ShaderProgramID handle) const;
549     Shader *getShader(ShaderProgramID handle) const;
550 
isTextureGenerated(TextureID texture)551     ANGLE_INLINE bool isTextureGenerated(TextureID texture) const
552     {
553         return mState.mTextureManager->isHandleGenerated(texture);
554     }
555 
isBufferGenerated(BufferID buffer)556     ANGLE_INLINE bool isBufferGenerated(BufferID buffer) const
557     {
558         return mState.mBufferManager->isHandleGenerated(buffer);
559     }
560 
561     bool isRenderbufferGenerated(RenderbufferID renderbuffer) const;
562     bool isFramebufferGenerated(FramebufferID framebuffer) const;
563     bool isProgramPipelineGenerated(ProgramPipelineID pipeline) const;
564     bool isQueryGenerated(QueryID query) const;
565 
566     bool usingDisplayTextureShareGroup() const;
567     bool usingDisplaySemaphoreShareGroup() const;
568 
569     // Hack for the special WebGL 1 "DEPTH_STENCIL" internal format.
570     GLenum getConvertedRenderbufferFormat(GLenum internalformat) const;
571 
isWebGL()572     bool isWebGL() const { return mState.isWebGL(); }
isWebGL1()573     bool isWebGL1() const { return mState.isWebGL1(); }
574 
isValidBufferBinding(BufferBinding binding)575     bool isValidBufferBinding(BufferBinding binding) const { return mValidBufferBindings[binding]; }
576 
577     // GLES1 emulation: Renderer level (for validation)
578     int vertexArrayIndex(ClientVertexArrayType type) const;
579     static int TexCoordArrayIndex(unsigned int unit);
580 
581     // GL_KHR_parallel_shader_compile
getWorkerThreadPool()582     std::shared_ptr<angle::WorkerThreadPool> getWorkerThreadPool() const { return mThreadPool; }
583 
getStateCache()584     const StateCache &getStateCache() const { return mStateCache; }
getStateCache()585     StateCache &getStateCache() { return mStateCache; }
586 
587     void onSubjectStateChange(angle::SubjectIndex index, angle::SubjectMessage message) override;
588 
589     void onSamplerUniformChange(size_t textureUnitIndex);
590 
isBufferAccessValidationEnabled()591     bool isBufferAccessValidationEnabled() const { return mBufferAccessValidationEnabled; }
592 
593     const angle::FrontendFeatures &getFrontendFeatures() const;
594 
getFrameCapture()595     angle::FrameCapture *getFrameCapture() const { return mFrameCapture.get(); }
596 
getVertexArraysForCapture()597     const VertexArrayMap &getVertexArraysForCapture() const { return mVertexArrayMap; }
getQueriesForCapture()598     const QueryMap &getQueriesForCapture() const { return mQueryMap; }
getTransformFeedbacksForCapture()599     const TransformFeedbackMap &getTransformFeedbacksForCapture() const
600     {
601         return mTransformFeedbackMap;
602     }
603 
604     void onPreSwap() const;
605 
606     Program *getActiveLinkedProgram() const;
607 
608     // EGL_ANGLE_power_preference implementation.
609     egl::Error releaseHighPowerGPU();
610     egl::Error reacquireHighPowerGPU();
611     void onGPUSwitch();
612 
613     bool noopDraw(PrimitiveMode mode, GLsizei count) const;
614     bool noopDrawInstanced(PrimitiveMode mode, GLsizei count, GLsizei instanceCount) const;
615 
616     bool isClearBufferMaskedOut(GLenum buffer, GLint drawbuffer) const;
617     bool noopClearBuffer(GLenum buffer, GLint drawbuffer) const;
618 
addRef()619     void addRef() const { mRefCount++; }
release()620     void release() const { mRefCount--; }
getRefCount()621     size_t getRefCount() const { return mRefCount; }
622 
getShareGroup()623     egl::ShareGroup *getShareGroup() const { return mState.getShareGroup(); }
624 
625     bool supportsGeometryOrTesselation() const;
626     void dirtyAllState();
627 
isDestroyed()628     bool isDestroyed() const { return mIsDestroyed; }
setIsDestroyed()629     void setIsDestroyed() { mIsDestroyed = true; }
630 
631     // Needed by capture serialization logic that works with a "const" Context pointer.
632     void finishImmutable() const;
633 
634   private:
635     void initializeDefaultResources();
636 
637     angle::Result prepareForDraw(PrimitiveMode mode);
638     angle::Result prepareForClear(GLbitfield mask);
639     angle::Result prepareForClearBuffer(GLenum buffer, GLint drawbuffer);
640     angle::Result syncState(const State::DirtyBits &bitMask,
641                             const State::DirtyObjects &objectMask,
642                             Command command);
643     angle::Result syncDirtyBits(Command command);
644     angle::Result syncDirtyBits(const State::DirtyBits &bitMask, Command command);
645     angle::Result syncDirtyObjects(const State::DirtyObjects &objectMask, Command command);
646     angle::Result syncStateForReadPixels();
647     angle::Result syncStateForTexImage();
648     angle::Result syncStateForBlit();
649     angle::Result syncStateForClear();
650     angle::Result syncTextureForCopy(Texture *texture);
651 
652     VertexArray *checkVertexArrayAllocation(VertexArrayID vertexArrayHandle);
653     TransformFeedback *checkTransformFeedbackAllocation(TransformFeedbackID transformFeedback);
654 
655     angle::Result onProgramLink(Program *programObject);
656 
657     void detachBuffer(Buffer *buffer);
658     void detachTexture(TextureID texture);
659     void detachFramebuffer(FramebufferID framebuffer);
660     void detachRenderbuffer(RenderbufferID renderbuffer);
661     void detachVertexArray(VertexArrayID vertexArray);
662     void detachTransformFeedback(TransformFeedbackID transformFeedback);
663     void detachSampler(SamplerID sampler);
664     void detachProgramPipeline(ProgramPipelineID pipeline);
665 
666     egl::Error setDefaultFramebuffer(egl::Surface *drawSurface, egl::Surface *readSurface);
667     egl::Error unsetDefaultFramebuffer();
668 
669     void initRendererString();
670     void initVersionStrings();
671     void initExtensionStrings();
672 
673     Extensions generateSupportedExtensions() const;
674     void initCaps();
675     void updateCaps();
676 
677     gl::LabeledObject *getLabeledObject(GLenum identifier, GLuint name) const;
678     gl::LabeledObject *getLabeledObjectFromPtr(const void *ptr) const;
679 
680     void setUniform1iImpl(Program *program,
681                           UniformLocation location,
682                           GLsizei count,
683                           const GLint *v);
684     void renderbufferStorageMultisampleImpl(GLenum target,
685                                             GLsizei samples,
686                                             GLenum internalformat,
687                                             GLsizei width,
688                                             GLsizei height,
689                                             MultisamplingMode mode);
690 
691     State mState;
692     bool mShared;
693     bool mSkipValidation;
694     bool mDisplayTextureShareGroup;
695     bool mDisplaySemaphoreShareGroup;
696 
697     // Recorded errors
698     ErrorSet mErrors;
699 
700     // Stores for each buffer binding type whether is it allowed to be used in this context.
701     angle::PackedEnumBitSet<BufferBinding> mValidBufferBindings;
702 
703     std::unique_ptr<rx::ContextImpl> mImplementation;
704 
705     EGLLabelKHR mLabel;
706 
707     // Extensions supported by the implementation plus extensions that are implemented entirely
708     // within the frontend.
709     Extensions mSupportedExtensions;
710 
711     // Shader compiler. Lazily initialized hence the mutable value.
712     mutable BindingPointer<Compiler> mCompiler;
713 
714     const egl::Config *mConfig;
715 
716     TextureMap mZeroTextures;
717 
718     ResourceMap<FenceNV, FenceNVID> mFenceNVMap;
719     HandleAllocator mFenceNVHandleAllocator;
720 
721     QueryMap mQueryMap;
722     HandleAllocator mQueryHandleAllocator;
723 
724     VertexArrayMap mVertexArrayMap;
725     HandleAllocator mVertexArrayHandleAllocator;
726 
727     TransformFeedbackMap mTransformFeedbackMap;
728     HandleAllocator mTransformFeedbackHandleAllocator;
729 
730     const char *mVersionString;
731     const char *mShadingLanguageString;
732     const char *mRendererString;
733     const char *mExtensionString;
734     std::vector<const char *> mExtensionStrings;
735     const char *mRequestableExtensionString;
736     std::vector<const char *> mRequestableExtensionStrings;
737 
738     // GLES1 renderer state
739     std::unique_ptr<GLES1Renderer> mGLES1Renderer;
740 
741     // Current/lost context flags
742     bool mHasBeenCurrent;
743     bool mContextLost;  // Set with setContextLost so that we also set mSkipValidation=false.
744     GraphicsResetStatus mResetStatus;
745     bool mContextLostForced;
746     GLenum mResetStrategy;
747     const bool mRobustAccess;
748     const bool mSurfacelessSupported;
749     egl::Surface *mCurrentDrawSurface;
750     egl::Surface *mCurrentReadSurface;
751     egl::Display *mDisplay;
752     const bool mWebGLContext;
753     bool mBufferAccessValidationEnabled;
754     const bool mExtensionsEnabled;
755     MemoryProgramCache *mMemoryProgramCache;
756 
757     State::DirtyObjects mDrawDirtyObjects;
758 
759     StateCache mStateCache;
760 
761     State::DirtyBits mAllDirtyBits;
762     State::DirtyBits mTexImageDirtyBits;
763     State::DirtyObjects mTexImageDirtyObjects;
764     State::DirtyBits mReadPixelsDirtyBits;
765     State::DirtyObjects mReadPixelsDirtyObjects;
766     State::DirtyBits mClearDirtyBits;
767     State::DirtyObjects mClearDirtyObjects;
768     State::DirtyBits mBlitDirtyBits;
769     State::DirtyObjects mBlitDirtyObjects;
770     State::DirtyBits mComputeDirtyBits;
771     State::DirtyObjects mComputeDirtyObjects;
772     State::DirtyBits mCopyImageDirtyBits;
773     State::DirtyObjects mCopyImageDirtyObjects;
774     State::DirtyBits mInvalidateDirtyBits;
775 
776     // Binding to container objects that use dependent state updates.
777     angle::ObserverBinding mVertexArrayObserverBinding;
778     angle::ObserverBinding mDrawFramebufferObserverBinding;
779     angle::ObserverBinding mReadFramebufferObserverBinding;
780     angle::ObserverBinding mProgramPipelineObserverBinding;
781     std::vector<angle::ObserverBinding> mUniformBufferObserverBindings;
782     std::vector<angle::ObserverBinding> mAtomicCounterBufferObserverBindings;
783     std::vector<angle::ObserverBinding> mShaderStorageBufferObserverBindings;
784     std::vector<angle::ObserverBinding> mSamplerObserverBindings;
785     std::vector<angle::ObserverBinding> mImageObserverBindings;
786 
787     // Not really a property of context state. The size and contexts change per-api-call.
788     mutable Optional<angle::ScratchBuffer> mScratchBuffer;
789     mutable Optional<angle::ScratchBuffer> mZeroFilledBuffer;
790 
791     std::shared_ptr<angle::WorkerThreadPool> mThreadPool;
792 
793     // Note: we use a raw pointer here so we can exclude frame capture sources from the build.
794     std::unique_ptr<angle::FrameCapture> mFrameCapture;
795 
796     // Cache representation of the serialized context string.
797     mutable std::string mCachedSerializedStateString;
798 
799     mutable size_t mRefCount;
800 
801     OverlayType mOverlay;
802 
803     const bool mIsExternal;
804     const bool mSaveAndRestoreState;
805 
806     bool mIsDestroyed;
807 };
808 
809 class ScopedContextRef
810 {
811   public:
ScopedContextRef(Context * context)812     ScopedContextRef(Context *context) : mContext(context)
813     {
814         if (mContext)
815         {
816             mContext->addRef();
817         }
818     }
~ScopedContextRef()819     ~ScopedContextRef()
820     {
821         if (mContext)
822         {
823             mContext->release();
824         }
825     }
826 
827   private:
828     Context *const mContext;
829 };
830 
831 // Thread-local current valid context bound to the thread.
832 #if defined(ANGLE_PLATFORM_APPLE)
833 extern Context *GetCurrentValidContextTLS();
834 extern void SetCurrentValidContextTLS(Context *context);
835 #else
836 extern thread_local Context *gCurrentValidContext;
837 #endif
838 
839 }  // namespace gl
840 
841 #endif  // LIBANGLE_CONTEXT_H_
842