GLRenderer.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  1. /*
  2. Copyright (c) 2013 Daniele Bartolini, Michele Rossi
  3. Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto
  4. Permission is hereby granted, free of charge, to any person
  5. obtaining a copy of this software and associated documentation
  6. files (the "Software"), to deal in the Software without
  7. restriction, including without limitation the rights to use,
  8. copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. copies of the Software, and to permit persons to whom the
  10. Software is furnished to do so, subject to the following
  11. conditions:
  12. The above copyright notice and this permission notice shall be
  13. included in all copies or substantial portions of the Software.
  14. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  15. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  16. OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  17. NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  18. HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  19. WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  20. FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  21. OTHER DEALINGS IN THE SOFTWARE.
  22. */
  23. #include <GL/glew.h>
  24. #include <algorithm>
  25. #include "Config.h"
  26. #include "Allocator.h"
  27. #include "Assert.h"
  28. #include "Types.h"
  29. #include "GLRenderer.h"
  30. #include "Log.h"
  31. #include "Vec4.h"
  32. #include "Mat3.h"
  33. #include "Mat4.h"
  34. #include "Device.h"
  35. #include "Hash.h"
  36. #include "StringUtils.h"
  37. namespace crown
  38. {
  39. //-----------------------------------------------------------------------------
  40. const GLenum PRIMITIVE_TYPE_TABLE[] =
  41. {
  42. GL_TRIANGLES,
  43. GL_POINTS,
  44. GL_LINES
  45. };
  46. //-----------------------------------------------------------------------------
  47. const GLenum TEXTURE_MIN_FILTER_TABLE[] =
  48. {
  49. 0, // Unused
  50. GL_NEAREST,
  51. GL_LINEAR,
  52. GL_NEAREST_MIPMAP_LINEAR,
  53. GL_LINEAR_MIPMAP_LINEAR
  54. };
  55. //-----------------------------------------------------------------------------
  56. const GLenum TEXTURE_MAG_FILTER_TABLE[] =
  57. {
  58. 0, // Unused
  59. GL_NEAREST,
  60. GL_LINEAR,
  61. GL_LINEAR,
  62. GL_LINEAR
  63. };
  64. //-----------------------------------------------------------------------------
  65. const GLenum TEXTURE_WRAP_TABLE[] =
  66. {
  67. 0, // Unused
  68. GL_CLAMP,
  69. GL_CLAMP_TO_EDGE,
  70. GL_CLAMP_TO_BORDER,
  71. GL_REPEAT
  72. };
  73. /// OpenGL renderer
  74. class RendererImplementation
  75. {
  76. public:
  77. //-----------------------------------------------------------------------------
  78. RendererImplementation()
  79. : m_max_texture_size(0), m_max_texture_units(0), m_max_vertex_indices(0), m_max_vertex_vertices(0),
  80. m_max_anisotropy(0.0f)
  81. {
  82. m_min_max_point_size[0] = 0.0f;
  83. m_min_max_point_size[1] = 0.0f;
  84. m_min_max_line_width[0] = 0.0f;
  85. m_min_max_line_width[1] = 0.0f;
  86. }
  87. //-----------------------------------------------------------------------------
  88. ~RendererImplementation()
  89. {
  90. }
  91. //-----------------------------------------------------------------------------
  92. void init()
  93. {
  94. m_gl_context.create_context();
  95. GLenum err = glewInit();
  96. CE_ASSERT(err == GLEW_OK, "Failed to initialize GLEW");
  97. GL_CHECK(glGetIntegerv(GL_MAX_TEXTURE_SIZE, &m_max_texture_size));
  98. GL_CHECK(glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &m_max_texture_units));
  99. GL_CHECK(glGetIntegerv(GL_MAX_ELEMENTS_INDICES, &m_max_vertex_indices));
  100. GL_CHECK(glGetIntegerv(GL_MAX_ELEMENTS_VERTICES, &m_max_vertex_vertices));
  101. GL_CHECK(glGetFloatv(GL_ALIASED_POINT_SIZE_RANGE, &m_min_max_point_size[0]));
  102. GL_CHECK(glGetFloatv(GL_LINE_WIDTH_RANGE, &m_min_max_line_width[0]));
  103. Log::i("OpenGL Vendor : %s", glGetString(GL_VENDOR));
  104. Log::i("OpenGL Renderer : %s", glGetString(GL_RENDERER));
  105. Log::i("OpenGL Version : %s", glGetString(GL_VERSION));
  106. Log::i("GLSL Version : %s", glGetString(GL_SHADING_LANGUAGE_VERSION));
  107. Log::d("Min Point Size : %f", m_min_max_point_size[0]);
  108. Log::d("Max Point Size : %f", m_min_max_point_size[1]);
  109. Log::d("Min Line Width : %f", m_min_max_line_width[0]);
  110. Log::d("Max Line Width : %f", m_min_max_line_width[1]);
  111. Log::d("Max Texture Size : %dx%d", m_max_texture_size, m_max_texture_size);
  112. Log::d("Max Texture Units : %d", m_max_texture_units);
  113. Log::d("Max Vertex Indices : %d", m_max_vertex_indices);
  114. Log::d("Max Vertex Vertices : %d", m_max_vertex_vertices);
  115. GL_CHECK(glDisable(GL_BLEND));
  116. GL_CHECK(glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA));
  117. GL_CHECK(glBlendEquation(GL_FUNC_ADD));
  118. GL_CHECK(glShadeModel(GL_SMOOTH));
  119. // Enable depth test
  120. GL_CHECK(glEnable(GL_DEPTH_TEST));
  121. GL_CHECK(glDepthFunc(GL_LEQUAL));
  122. GL_CHECK(glClearDepth(1.0));
  123. // Point sprites enabled by default
  124. GL_CHECK(glEnable(GL_POINT_SPRITE));
  125. GL_CHECK(glTexEnvi(GL_POINT_SPRITE, GL_COORD_REPLACE, GL_TRUE));
  126. Log::i("OpenGL Renderer initialized.");
  127. }
  128. //-----------------------------------------------------------------------------
  129. void shutdown()
  130. {
  131. m_gl_context.destroy_context();
  132. }
  133. //-----------------------------------------------------------------------------
  134. void render(RenderContext& context)
  135. {
  136. //RenderTargetId old_rt;
  137. //old_rt.id = INVALID_ID;
  138. uint8_t layer = 0xFF;
  139. for (uint32_t s = 0; s < context.m_num_states; s++)
  140. {
  141. const uint64_t key_s = context.m_keys[s];
  142. RenderKey key;
  143. key.decode(key_s);
  144. const RenderState& cur_state = context.m_states[s];
  145. const uint64_t flags = cur_state.m_flags;
  146. //const RenderTargetId& cur_rt = context.m_targets[layer];
  147. // Check if layer changed
  148. if (key.m_layer != layer)
  149. {
  150. layer = key.m_layer;
  151. // Viewport
  152. const ViewRect& viewport = context.m_viewports[layer];
  153. GL_CHECK(glViewport(viewport.m_x, viewport.m_y, viewport.m_width, viewport.m_height));
  154. // Clear frame/depth buffer
  155. const ClearState& clear = context.m_clears[layer];
  156. if (clear.m_flags & (CLEAR_COLOR | CLEAR_DEPTH))
  157. {
  158. GLbitfield gl_clear = (clear.m_flags & CLEAR_COLOR) ? GL_COLOR_BUFFER_BIT : 0;
  159. gl_clear |= (clear.m_flags & CLEAR_DEPTH) ? GL_DEPTH_BUFFER_BIT : 0;
  160. GL_CHECK(glClearColor(clear.m_color.r, clear.m_color.g, clear.m_color.b, clear.m_color.a));
  161. GL_CHECK(glClearDepth(clear.m_depth));
  162. GL_CHECK(glClear(gl_clear));
  163. }
  164. }
  165. // Scissor
  166. const ViewRect& scissor = context.m_scissors[layer];
  167. if (scissor.area() != 0)
  168. {
  169. GL_CHECK(glEnable(GL_SCISSOR_TEST));
  170. GL_CHECK(glScissor(scissor.m_x, scissor.m_y, scissor.m_width, scissor.m_height));
  171. }
  172. else
  173. {
  174. GL_CHECK(glDisable(GL_SCISSOR_TEST));
  175. }
  176. // Depth write
  177. if (flags & (STATE_DEPTH_WRITE))
  178. {
  179. GL_CHECK(glDepthMask(flags & STATE_DEPTH_WRITE));
  180. }
  181. // Color/Alpha write
  182. if (flags & (STATE_COLOR_WRITE | STATE_ALPHA_WRITE))
  183. {
  184. GLboolean cw = !!(flags & STATE_COLOR_WRITE);
  185. GLboolean aw = !!(flags & STATE_ALPHA_WRITE);
  186. GL_CHECK(glColorMask(cw, cw, cw, aw));
  187. }
  188. // Face culling
  189. if (flags & (STATE_CULL_CW | STATE_CULL_CCW))
  190. {
  191. if (flags & STATE_CULL_CW)
  192. {
  193. GL_CHECK(glEnable(GL_CULL_FACE));
  194. GL_CHECK(glCullFace(GL_BACK));
  195. }
  196. else if (flags & STATE_CULL_CCW)
  197. {
  198. GL_CHECK(glEnable(GL_CULL_FACE));
  199. GL_CHECK(glCullFace(GL_FRONT));
  200. }
  201. }
  202. else
  203. {
  204. GL_CHECK(glDisable(GL_CULL_FACE));
  205. }
  206. // Bind GPU program
  207. if (cur_state.program.id != INVALID_ID)
  208. {
  209. const GPUProgram& gpu_program = m_gpu_programs[cur_state.program.index];
  210. GL_CHECK(glUseProgram(gpu_program.m_id));
  211. for (uint8_t uniform = 0; uniform < gpu_program.m_num_stock_uniforms; uniform++)
  212. {
  213. const GLint& uniform_location = gpu_program.m_stock_uniform_locations[uniform];
  214. const Mat4& view = context.m_view_matrices[layer];
  215. const Mat4& projection = context.m_projection_matrices[layer];
  216. switch (gpu_program.m_stock_uniforms[uniform])
  217. {
  218. case UNIFORM_VIEW:
  219. {
  220. GL_CHECK(glUniformMatrix4fv(uniform_location, 1, GL_FALSE, view.to_float_ptr()));
  221. break;
  222. }
  223. case UNIFORM_MODEL:
  224. {
  225. GL_CHECK(glUniformMatrix4fv(uniform_location, 1, GL_FALSE, cur_state.pose.to_float_ptr()));
  226. break;
  227. }
  228. case UNIFORM_MODEL_VIEW:
  229. {
  230. GL_CHECK(glUniformMatrix4fv(uniform_location, 1, GL_FALSE, (view *
  231. cur_state.pose).to_float_ptr()));
  232. break;
  233. }
  234. case UNIFORM_MODEL_VIEW_PROJECTION:
  235. {
  236. GL_CHECK(glUniformMatrix4fv(uniform_location, 1, GL_FALSE, (projection * view *
  237. cur_state.pose).to_float_ptr()));
  238. break;
  239. }
  240. case UNIFORM_TIME_SINCE_START:
  241. {
  242. GL_CHECK(glUniform1f(uniform_location, device()->time_since_start()));
  243. break;
  244. }
  245. default:
  246. {
  247. CE_ASSERT(false, "Oops, wrong stock uniform!");
  248. break;
  249. }
  250. }
  251. }
  252. }
  253. else
  254. {
  255. GL_CHECK(glUseProgram(0));
  256. }
  257. // Bind array buffers
  258. const VertexBufferId& vb = cur_state.vb;
  259. if (vb.id != INVALID_ID)
  260. {
  261. const VertexBuffer& vertex_buffer = m_vertex_buffers[vb.index];
  262. glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer.m_id);
  263. const GPUProgram& gpu_program = m_gpu_programs[cur_state.program.index];
  264. gpu_program.bind_attributes(vertex_buffer.m_format);
  265. }
  266. else
  267. {
  268. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, 0));
  269. }
  270. const IndexBufferId& ib = cur_state.ib;
  271. if (ib.id != INVALID_ID)
  272. {
  273. const IndexBuffer& index_buffer = m_index_buffers[ib.index];
  274. uint32_t prim_type = (flags & STATE_PRIMITIVE_MASK) >> STATE_PRIMITIVE_SHIFT;
  275. GLenum gl_prim_type = PRIMITIVE_TYPE_TABLE[prim_type];
  276. GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, index_buffer.m_id));
  277. GL_CHECK(glDrawElements(gl_prim_type, index_buffer.m_index_count, GL_UNSIGNED_SHORT, 0));
  278. }
  279. else
  280. {
  281. GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0));
  282. }
  283. // Bind textures
  284. {
  285. uint64_t flags = STATE_TEXTURE_0;
  286. for (uint32_t unit = 0; unit < STATE_MAX_TEXTURES; unit++)
  287. {
  288. const Sampler& sampler = cur_state.samplers[unit];
  289. if (sampler.sampler_id.id != INVALID_ID)
  290. {
  291. switch (sampler.flags & SAMPLER_MASK)
  292. {
  293. case SAMPLER_TEXTURE:
  294. {
  295. Texture& texture = m_textures[sampler.sampler_id.index];
  296. texture.commit(unit, sampler.flags);
  297. break;
  298. }
  299. default:
  300. {
  301. CE_ASSERT(false, "Oops, sampler unknown");
  302. break;
  303. }
  304. }
  305. }
  306. flags <<= 1;
  307. }
  308. }
  309. }
  310. GL_CHECK(glFinish());
  311. context.clear();
  312. m_gl_context.swap_buffers();
  313. }
  314. private:
  315. GLContext m_gl_context;
  316. // Limits
  317. int32_t m_max_texture_size;
  318. int32_t m_max_texture_units;
  319. int32_t m_max_vertex_indices;
  320. int32_t m_max_vertex_vertices;
  321. float m_max_anisotropy;
  322. float m_min_max_point_size[2];
  323. float m_min_max_line_width[2];
  324. VertexBuffer m_vertex_buffers[CROWN_MAX_VERTEX_BUFFERS];
  325. IndexBuffer m_index_buffers[CROWN_MAX_INDEX_BUFFERS];
  326. Texture m_textures[CROWN_MAX_TEXTURES];
  327. Shader m_shaders[CROWN_MAX_SHADERS];
  328. GPUProgram m_gpu_programs[CROWN_MAX_GPU_PROGRAMS];
  329. Uniform m_uniforms[CROWN_MAX_UNIFORMS];
  330. RenderTarget m_render_targets[CROWN_MAX_RENDER_TARGETS];
  331. private:
  332. friend class Renderer;
  333. };
  334. //-----------------------------------------------------------------------------
  335. Renderer::Renderer(Allocator& a)
  336. : m_allocator(a), m_impl(NULL), m_submit(&m_contexts[0]), m_draw(&m_contexts[1]), m_is_initialized(false)
  337. {
  338. m_impl = CE_NEW(a, RendererImplementation);
  339. }
  340. //-----------------------------------------------------------------------------
  341. Renderer::~Renderer()
  342. {
  343. CE_DELETE(m_allocator, m_impl);
  344. }
  345. //-----------------------------------------------------------------------------
  346. void Renderer::init_impl()
  347. {
  348. m_impl->init();
  349. }
  350. //-----------------------------------------------------------------------------
  351. void Renderer::shutdown_impl()
  352. {
  353. m_impl->shutdown();
  354. }
  355. //-----------------------------------------------------------------------------
  356. void Renderer::render_impl()
  357. {
  358. m_impl->render(*m_draw);
  359. }
  360. //-----------------------------------------------------------------------------
  361. void Renderer::create_vertex_buffer_impl(VertexBufferId id, size_t count, VertexFormat format, const void* vertices)
  362. {
  363. m_impl->m_vertex_buffers[id.index].create(count, format, vertices);
  364. }
  365. //-----------------------------------------------------------------------------
  366. void Renderer::update_vertex_buffer_impl(VertexBufferId id, size_t offset, size_t count, const void* vertices)
  367. {
  368. m_impl->m_vertex_buffers[id.index].update(offset, count, vertices);
  369. }
  370. //-----------------------------------------------------------------------------
  371. void Renderer::destroy_vertex_buffer_impl(VertexBufferId id)
  372. {
  373. m_impl->m_vertex_buffers[id.index].destroy();
  374. }
  375. //-----------------------------------------------------------------------------
  376. void Renderer::create_index_buffer_impl(IndexBufferId id, size_t count, const void* indices)
  377. {
  378. m_impl->m_index_buffers[id.index].create(count, indices);
  379. }
  380. //-----------------------------------------------------------------------------
  381. void Renderer::destroy_index_buffer_impl(IndexBufferId id)
  382. {
  383. m_impl->m_index_buffers[id.index].destroy();
  384. }
  385. //-----------------------------------------------------------------------------
  386. void Renderer::create_texture_impl(TextureId id, uint32_t width, uint32_t height, PixelFormat format, const void* data)
  387. {
  388. m_impl->m_textures[id.index].create(width, height, format, data);
  389. }
  390. //-----------------------------------------------------------------------------
  391. void Renderer::update_texture_impl(TextureId id, uint32_t x, uint32_t y, uint32_t width, uint32_t height, const void* data)
  392. {
  393. m_impl->m_textures[id.index].update(x, y, width, height, data);
  394. }
  395. //-----------------------------------------------------------------------------
  396. void Renderer::destroy_texture_impl(TextureId id)
  397. {
  398. m_impl->m_textures[id.index].destroy();
  399. }
  400. //-----------------------------------------------------------------------------
  401. void Renderer::create_shader_impl(ShaderId id, ShaderType type, const char* text)
  402. {
  403. m_impl->m_shaders[id.index].create(type, text);
  404. }
  405. //-----------------------------------------------------------------------------
  406. void Renderer::destroy_shader_impl(ShaderId id)
  407. {
  408. m_impl->m_shaders[id.index].destroy();
  409. }
  410. //-----------------------------------------------------------------------------
  411. void Renderer::create_gpu_program_impl(GPUProgramId id, ShaderId vertex, ShaderId pixel)
  412. {
  413. Shader& vs = m_impl->m_shaders[vertex.index];
  414. Shader& ps = m_impl->m_shaders[pixel.index];
  415. m_impl->m_gpu_programs[id.index].create(vs, ps);
  416. }
  417. //-----------------------------------------------------------------------------
  418. void Renderer::destroy_gpu_program_impl(GPUProgramId id)
  419. {
  420. m_impl->m_gpu_programs[id.index].destroy();
  421. }
  422. // //-----------------------------------------------------------------------------
  423. // void Renderer::create_uniform_impl(UniformId id, const char* name, UniformType type)
  424. // {
  425. // }
  426. // //-----------------------------------------------------------------------------
  427. // void Renderer::destroy_uniform_impl(UniformId id)
  428. // {
  429. // }
  430. // //-----------------------------------------------------------------------------
  431. // void Renderer::create_render_target_impl(RenderTargetId id, uint16_t width, uint16_t height, RenderTargetFormat format)
  432. // {
  433. // }
  434. // //-----------------------------------------------------------------------------
  435. // void Renderer::destroy_render_target_impl(RenderTargetId id)
  436. // {
  437. // }
  438. } // namespace crown