RenderingThread.h 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. // Copyright (C) 2009-2021, Panagiotis Christopoulos Charitos and contributors.
  2. // All rights reserved.
  3. // Code licensed under the BSD License.
  4. // http://www.anki3d.org/LICENSE
  5. #pragma once
  6. #include <AnKi/Gr/CommandBuffer.h>
  7. #include <AnKi/Util/Thread.h>
  8. namespace anki
  9. {
  10. /// @addtogroup opengl
  11. /// @{
  12. /// Command queue. It's essentialy a queue of command buffers waiting for execution and a server
  13. class RenderingThread
  14. {
  15. friend class SyncCommand;
  16. friend class SwapBuffersCommand;
  17. public:
  18. RenderingThread(GrManagerImpl* device);
  19. ~RenderingThread();
  20. /// Start the working thread
  21. /// @note Don't free the context before calling #stop
  22. void start();
  23. /// Stop the working thread
  24. void stop();
  25. /// Push a command buffer to the queue for deferred execution
  26. void flushCommandBuffer(CommandBufferPtr commands, FencePtr* fence);
  27. /// Push a command buffer to the queue and wait for it
  28. void finishCommandBuffer(CommandBufferPtr commands);
  29. /// Sync the client and server
  30. void syncClientServer();
  31. /// Return true if this is the main thread
  32. Bool isServerThread() const
  33. {
  34. return m_serverThreadId == Thread::getCurrentThreadId();
  35. }
  36. /// Swap buffers
  37. void swapBuffers();
  38. private:
  39. WeakPtr<GrManagerImpl> m_manager;
  40. static const U QUEUE_SIZE = 1024 * 2;
  41. DynamicArray<CommandBufferPtr> m_queue; ///< Command queue
  42. U64 m_tail; ///< Tail of queue
  43. U64 m_head; ///< Head of queue. Points to the end
  44. U8 m_renderingThreadSignal; ///< Signal to the thread
  45. Mutex m_mtx; ///< Wake the thread
  46. ConditionVariable m_condVar; ///< To wake up the thread
  47. Thread m_thread;
  48. /// @name Swap_buffers_vars
  49. /// @{
  50. CommandBufferPtr m_swapBuffersCommands;
  51. ConditionVariable m_frameCondVar;
  52. Mutex m_frameMtx;
  53. Bool m_frameWait = false;
  54. /// @}
  55. ThreadId m_serverThreadId;
  56. /// A special command buffer that is called every time we want to wait for the server
  57. CommandBufferPtr m_syncCommands;
  58. Barrier m_syncBarrier{2};
  59. SpinLock m_syncLock;
  60. /// Command buffer with an empty command.
  61. CommandBufferPtr m_emptyCmdb;
  62. /// The function that the thread runs
  63. static ANKI_USE_RESULT Error threadCallback(ThreadCallbackInfo&);
  64. void threadLoop();
  65. void prepare();
  66. void finish();
  67. void swapBuffersInternal();
  68. };
  69. /// @}
  70. } // end namespace anki