GLS  1.0.0
GL Stuff - A library aimed at reducing the boilerplate OpenGL code you always have to write.
query.hpp
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2  * License, v. 2.0. If a copy of the MPL was not distributed with this
3  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4 
5 #pragma once
6 
7 #include <gls/headercheck.hpp>
8 #include <gls/errorcheck.hpp>
9 #include <gls/objects/object.hpp>
10 #include <cassert>
11 
12 namespace gls {
13 
14 namespace priv {
15  void gen_queries( GLsizei size, GLuint* name ) { glGenQueries( size, name ); }
16  void delete_queries( GLsizei size, const GLuint* name ) { glDeleteQueries( size, name ); }
17 }
18 
25 template<GLenum Target>
26 class query {
27 public:
34  GLuint name() const {
35  return m_object.name();
36  }
37 
51  template<typename T>
52  void run( T callable ) {
53  if( m_waiting ) {
54  callable();
55  return;
56  }
57 
58  m_waiting = true;
59 
60  check_gl_error( glBeginQuery( Target, m_object.name() ) );
61  callable();
62  check_gl_error( glEndQuery( Target ) );
63  }
64 
72  void begin() {
73  if( m_waiting ) {
74  return;
75  }
76 
77  m_waiting = true;
78 
79  check_gl_error( glBeginQuery( Target, m_object.name() ) );
80  }
81 
89  void end() {
90  check_gl_error( glEndQuery( Target ) );
91  }
92 
105  bool poll_result( GLint& result ) {
106  if( m_waiting && !ready() ) {
107  return false;
108  }
109 
110  check_gl_error( glGetQueryObjectiv( name(), GL_QUERY_RESULT, &result ) );
111 
112  return true;
113  }
114 
127  bool poll_result( GLuint& result ) {
128  if( m_waiting && !ready() ) {
129  return false;
130  }
131 
132  check_gl_error( glGetQueryObjectuiv( name(), GL_QUERY_RESULT, &result ) );
133 
134  return true;
135  }
136 
137 private:
138  bool ready() {
139  auto result_ready = GLuint();
140 
141  check_gl_error( glGetQueryObjectuiv( name(), GL_QUERY_RESULT_AVAILABLE, &result_ready ) );
142 
143  m_waiting = ( result_ready == GL_FALSE );
144 
145  return result_ready == GL_TRUE;
146  }
147 
148  object<priv::gen_queries, priv::delete_queries> m_object;
149  bool m_waiting = false;
150 };
151 
152 }
153 
void run(T callable)
Run the query on the provided callable.
Definition: query.hpp:52
void end()
Mark the end of the query block.
Definition: query.hpp:89
bool poll_result(GLuint &result)
Poll the result of the query.
Definition: query.hpp:127
GLuint name() const
Retrieve the OpenGL name of this query.
Definition: query.hpp:34
Class encapsulating an OpenGL query object.
Definition: query.hpp:26
bool poll_result(GLint &result)
Poll the result of the query.
Definition: query.hpp:105
void begin()
Mark the begin of the query block.
Definition: query.hpp:72
Definition: buffer.hpp:12