1/****************************************************************************
2**
3** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB).
4** Copyright (C) 2016 The Qt Company Ltd and/or its subsidiary(-ies).
5** Contact: https://www.qt.io/licensing/
6**
7** This file is part of the Qt3D module of the Qt Toolkit.
8**
9** $QT_BEGIN_LICENSE:LGPL$
10** Commercial License Usage
11** Licensees holding valid commercial Qt licenses may use this file in
12** accordance with the commercial license agreement provided with the
13** Software or, alternatively, in accordance with the terms contained in
14** a written agreement between you and The Qt Company. For licensing terms
15** and conditions see https://www.qt.io/terms-conditions. For further
16** information use the contact form at https://www.qt.io/contact-us.
17**
18** GNU Lesser General Public License Usage
19** Alternatively, this file may be used under the terms of the GNU Lesser
20** General Public License version 3 as published by the Free Software
21** Foundation and appearing in the file LICENSE.LGPL3 included in the
22** packaging of this file. Please review the following information to
23** ensure the GNU Lesser General Public License version 3 requirements
24** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
25**
26** GNU General Public License Usage
27** Alternatively, this file may be used under the terms of the GNU
28** General Public License version 2.0 or (at your option) the GNU General
29** Public license version 3 or any later version approved by the KDE Free
30** Qt Foundation. The licenses are as published by the Free Software
31** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
32** included in the packaging of this file. Please review the following
33** information to ensure the GNU General Public License requirements will
34** be met: https://www.gnu.org/licenses/gpl-2.0.html and
35** https://www.gnu.org/licenses/gpl-3.0.html.
36**
37** $QT_END_LICENSE$
38**
39****************************************************************************/
40
41#ifndef QT3DRENDER_RENDER_OPENGL_RENDERER_H
42#define QT3DRENDER_RENDER_OPENGL_RENDERER_H
43
44//
45// W A R N I N G
46// -------------
47//
48// This file is not part of the Qt API. It exists for the convenience
49// of other Qt classes. This header file may change from version to
50// version without notice, or even be removed.
51//
52// We mean it.
53//
54
55#include <Qt3DRender/qrenderaspect.h>
56#include <Qt3DRender/qtechnique.h>
57#include <Qt3DRender/private/handle_types_p.h>
58#include <Qt3DRender/private/abstractrenderer_p.h>
59#include <Qt3DCore/qaspectjob.h>
60#include <Qt3DRender/private/qt3drender_global_p.h>
61#include <Qt3DRender/private/rendersettings_p.h>
62#include <Qt3DRender/private/updateshaderdatatransformjob_p.h>
63#include <Qt3DRender/private/framecleanupjob_p.h>
64#include <Qt3DRender/private/platformsurfacefilter_p.h>
65#include <Qt3DRender/private/sendbuffercapturejob_p.h>
66#include <Qt3DRender/private/genericlambdajob_p.h>
67#include <Qt3DRender/private/shaderbuilder_p.h>
68#include <Qt3DRender/private/lightgatherer_p.h>
69#include <Qt3DRender/private/texture_p.h>
70#include <Qt3DRender/private/filterentitybycomponentjob_p.h>
71#include <shaderparameterpack_p.h>
72#include <renderviewinitializerjob_p.h>
73#include <filtercompatibletechniquejob_p.h>
74#include <renderercache_p.h>
75#include <logging_p.h>
76#include <gl_handle_types_p.h>
77#include <glfence_p.h>
78#include <renderercache_p.h>
79
80#include <QHash>
81#include <QMatrix4x4>
82#include <QObject>
83
84#include <QOpenGLShaderProgram>
85#include <QOpenGLVertexArrayObject>
86#include <QOpenGLBuffer>
87#include <QMutex>
88#include <QWaitCondition>
89#include <QAtomicInt>
90#include <QScopedPointer>
91#include <QSemaphore>
92
93#include <functional>
94
95#if defined(QT_BUILD_INTERNAL)
96class tst_Renderer;
97#endif
98
99QT_BEGIN_NAMESPACE
100
101class QSurface;
102class QMouseEvent;
103class QScreen;
104
105namespace Qt3DCore {
106class QEntity;
107class QFrameAllocator;
108class QEventFilterService;
109}
110
111namespace Qt3DRender {
112
113class QCamera;
114class QMaterial;
115class QShaderProgram;
116class QMesh;
117class QRenderPass;
118class QAbstractShapeMesh;
119struct GraphicsApiFilterData;
120class QSceneImporter;
121
122namespace Debug {
123class CommandExecuter;
124}
125
126namespace Render {
127
128namespace Profiling {
129class FrameProfiler;
130}
131
132class CameraLens;
133class FrameGraphNode;
134class Material;
135class Technique;
136class Shader;
137class Entity;
138class Effect;
139class RenderPass;
140class RenderThread;
141class RenderStateSet;
142class VSyncFrameAdvanceService;
143class NodeManagers;
144class ResourceAccessor;
145
146using ComputableEntityFilter = FilterEntityByComponentJob<Render::ComputeCommand, Render::Material>;
147using ComputableEntityFilterPtr = QSharedPointer<ComputableEntityFilter>;
148using RenderableEntityFilter = FilterEntityByComponentJob<Render::GeometryRenderer, Render::Material>;
149using RenderableEntityFilterPtr = QSharedPointer<RenderableEntityFilter>;
150
151using SynchronizerJobPtr = GenericLambdaJobPtr<std::function<void()>>;
152using SynchronizerPostFramePtr = GenericLambdaJobAndPostFramePtr<std::function<void ()>, std::function<void (Qt3DCore::QAspectManager *)>>;
153#define CreateSynchronizerPostFramePtr(lambda, postlambda, type) \
154 SynchronizerPostFramePtr::create(lambda, postlambda, type, #type)
155
156namespace Debug {
157class ImGuiRenderer;
158}
159
160namespace OpenGL {
161
162class CommandThread;
163class SubmissionContext;
164class RenderCommand;
165class RenderQueue;
166class RenderView;
167class GLShader;
168class GLResourceManagers;
169
170class Q_AUTOTEST_EXPORT Renderer : public AbstractRenderer
171{
172public:
173 explicit Renderer(QRenderAspect::RenderType type);
174 ~Renderer();
175
176 void dumpInfo() const override;
177 API api() const override { return Qt3DRender::API::OpenGL; }
178
179 qint64 time() const override;
180 void setTime(qint64 time) override;
181 void setJobsInLastFrame(int jobsInLastFrame) override;
182
183 void setAspect(QRenderAspect *aspect) override;
184 void setNodeManagers(NodeManagers *managers) override;
185 void setServices(Qt3DCore::QServiceLocator *services) override;
186 void setSurfaceExposed(bool exposed) override;
187
188 QRenderAspect *aspect() const override;
189 NodeManagers *nodeManagers() const override;
190 Qt3DCore::QServiceLocator *services() const override { return m_services; }
191
192 void initialize() override;
193 void shutdown() override;
194 void releaseGraphicsResources() override;
195
196 void render() override;
197 void doRender(bool swapBuffers = true) override;
198 void cleanGraphicsResources() override;
199
200 bool isRunning() const override { return m_running.loadRelaxed(); }
201
202 void setSceneRoot(Entity *sgRoot) override;
203 Entity *sceneRoot() const override { return m_renderSceneRoot; }
204
205 FrameGraphNode *frameGraphRoot() const override;
206 RenderQueue *renderQueue() const { return m_renderQueue; }
207
208 void markDirty(BackendNodeDirtySet changes, BackendNode *node) override;
209 BackendNodeDirtySet dirtyBits() override;
210
211#if defined(QT_BUILD_INTERNAL)
212 void clearDirtyBits(BackendNodeDirtySet changes) override;
213#endif
214 bool shouldRender() const override;
215 void skipNextFrame() override;
216 void jobsDone(Qt3DCore::QAspectManager *manager) override;
217
218 void setPendingEvents(const QList<QPair<QObject *, QMouseEvent>> &mouseEvents, const QList<QKeyEvent> &keyEvents) override;
219
220 QVector<Qt3DCore::QAspectJobPtr> preRenderingJobs() override;
221 QVector<Qt3DCore::QAspectJobPtr> renderBinJobs() override;
222
223 inline FrameCleanupJobPtr frameCleanupJob() const { return m_cleanupJob; }
224 inline UpdateShaderDataTransformJobPtr updateShaderDataTransformJob() const { return m_updateShaderDataTransformJob; }
225 inline FilterCompatibleTechniqueJobPtr filterCompatibleTechniqueJob() const { return m_filterCompatibleTechniqueJob; }
226 inline SynchronizerPostFramePtr introspectShadersJob() const { return m_introspectShaderJob; }
227 inline Qt3DCore::QAspectJobPtr bufferGathererJob() const { return m_bufferGathererJob; }
228 inline Qt3DCore::QAspectJobPtr textureGathererJob() const { return m_textureGathererJob; }
229 inline LightGathererPtr lightGathererJob() const { return m_lightGathererJob; }
230 inline RenderableEntityFilterPtr renderableEntityFilterJob() const { return m_renderableEntityFilterJob; }
231 inline ComputableEntityFilterPtr computableEntityFilterJob() const { return m_computableEntityFilterJob; }
232
233 Qt3DCore::QAbstractFrameAdvanceService *frameAdvanceService() const override;
234
235 void setSettings(RenderSettings *settings) override;
236 RenderSettings *settings() const override;
237 QOpenGLContext *shareContext() const override;
238
239 inline GLResourceManagers *glResourceManagers() const { return m_glResourceManagers; }
240
241 // Executed in secondary GL thread
242 void loadShader(Shader *shader, Qt3DRender::Render::HShader shaderHandle) override;
243
244
245 void updateGLResources();
246 void updateTexture(Texture *texture);
247 void cleanupTexture(Qt3DCore::QNodeId cleanedUpTextureId);
248 void cleanupShader(const Shader *shader);
249 void downloadGLBuffers();
250 void blitFramebuffer(Qt3DCore::QNodeId inputRenderTargetId,
251 Qt3DCore::QNodeId outputRenderTargetId,
252 QRect inputRect,
253 QRect outputRect,
254 GLuint defaultFramebuffer);
255
256 void prepareCommandsSubmission(const QVector<RenderView *> &renderViews);
257 bool executeCommandsSubmission(RenderView *rv);
258 bool updateVAOWithAttributes(Geometry *geometry,
259 const RenderCommand *command,
260 GLShader *shader,
261 bool forceUpdate);
262
263 bool requiresVAOAttributeUpdate(Geometry *geometry,
264 const RenderCommand *command) const;
265
266 // For Scene2D rendering
267 void setOpenGLContext(QOpenGLContext *context) override;
268 bool accessOpenGLTexture(Qt3DCore::QNodeId nodeId,
269 QOpenGLTexture **texture,
270 QMutex **lock,
271 bool readonly) override;
272 QSharedPointer<RenderBackendResourceAccessor> resourceAccessor() const override;
273
274
275 const GraphicsApiFilterData *contextInfo() const override;
276 SubmissionContext *submissionContext() const;
277
278 inline RenderStateSet *defaultRenderState() const { return m_defaultRenderStateSet; }
279
280 void enqueueRenderView(RenderView *renderView, int submitOrder);
281 bool isReadyToSubmit();
282
283 QVariant executeCommand(const QStringList &args) override;
284 void setOffscreenSurfaceHelper(OffscreenSurfaceHelper *helper) override;
285 QSurfaceFormat format() override;
286
287 struct ViewSubmissionResultData
288 {
289 ViewSubmissionResultData()
290 : lastBoundFBOId(0)
291 , surface(nullptr)
292 {}
293
294 uint lastBoundFBOId;
295 QSurface *surface;
296 };
297
298 ViewSubmissionResultData submitRenderViews(const QVector<RenderView *> &renderViews);
299
300 RendererCache *cache() { return &m_cache; }
301 void setScreen(QScreen *scr) override;
302 QScreen *screen() const override;
303
304#ifdef QT3D_RENDER_UNIT_TESTS
305public:
306#else
307
308private:
309#endif
310 bool canRender() const;
311 Profiling::FrameProfiler *activeProfiler() const;
312
313 Qt3DCore::QServiceLocator *m_services;
314 QRenderAspect *m_aspect;
315 NodeManagers *m_nodesManager;
316
317 // Frame graph root
318 Qt3DCore::QNodeId m_frameGraphRootUuid;
319
320 Entity *m_renderSceneRoot;
321
322 // Fail safe values that we can use if a RenderCommand
323 // is missing a shader
324 RenderStateSet *m_defaultRenderStateSet;
325 ShaderParameterPack m_defaultUniformPack;
326
327 QScopedPointer<SubmissionContext> m_submissionContext;
328 QSurfaceFormat m_format;
329
330 RenderQueue *m_renderQueue;
331 QScopedPointer<RenderThread> m_renderThread;
332 QScopedPointer<VSyncFrameAdvanceService> m_vsyncFrameAdvanceService;
333
334 QSemaphore m_submitRenderViewsSemaphore;
335 QSemaphore m_waitForInitializationToBeCompleted;
336 QMutex m_hasBeenInitializedMutex;
337
338 QAtomicInt m_running;
339
340 QVector<Attribute *> m_dirtyAttributes;
341 QVector<Geometry *> m_dirtyGeometry;
342 QAtomicInt m_exposed;
343
344 struct DirtyBits {
345 BackendNodeDirtySet marked; // marked dirty since last job build
346 BackendNodeDirtySet remaining; // remaining dirty after jobs have finished
347 };
348 DirtyBits m_dirtyBits;
349
350 QAtomicInt m_lastFrameCorrect;
351 QOpenGLContext *m_glContext;
352 QOpenGLContext *m_shareContext;
353 mutable QMutex m_shareContextMutex;
354
355 qint64 m_time;
356
357 RenderSettings *m_settings;
358
359 UpdateShaderDataTransformJobPtr m_updateShaderDataTransformJob;
360 FrameCleanupJobPtr m_cleanupJob;
361 SendBufferCaptureJobPtr m_sendBufferCaptureJob;
362 FilterCompatibleTechniqueJobPtr m_filterCompatibleTechniqueJob;
363 LightGathererPtr m_lightGathererJob;
364 RenderableEntityFilterPtr m_renderableEntityFilterJob;
365 ComputableEntityFilterPtr m_computableEntityFilterJob;
366
367 QVector<Qt3DCore::QNodeId> m_pendingRenderCaptureSendRequests;
368
369 void performDraw(const RenderCommand *command);
370 void performCompute(const RenderView *rv, RenderCommand *command);
371 void createOrUpdateVAO(RenderCommand *command,
372 HVao *previousVAOHandle,
373 OpenGLVertexArrayObject **vao);
374
375 SynchronizerJobPtr m_bufferGathererJob;
376 SynchronizerJobPtr m_vaoGathererJob;
377 SynchronizerJobPtr m_textureGathererJob;
378 SynchronizerJobPtr m_sendSetFenceHandlesToFrontendJob;
379 SynchronizerPostFramePtr m_introspectShaderJob;
380
381 void lookForAbandonedVaos();
382 void lookForDirtyBuffers();
383 void lookForDownloadableBuffers();
384 void lookForDirtyTextures();
385 void reloadDirtyShaders();
386 void sendShaderChangesToFrontend(Qt3DCore::QAspectManager *manager);
387 void sendTextureChangesToFrontend(Qt3DCore::QAspectManager *manager);
388 void sendSetFenceHandlesToFrontend();
389 void sendDisablesToFrontend(Qt3DCore::QAspectManager *manager);
390
391 QMutex m_abandonedVaosMutex;
392 QVector<HVao> m_abandonedVaos;
393
394 QVector<HBuffer> m_dirtyBuffers;
395 QVector<Qt3DCore::QNodeId> m_downloadableBuffers;
396 QVector<HShader> m_dirtyShaders;
397 QVector<HTexture> m_dirtyTextures;
398 QVector<QPair<Texture::TextureUpdateInfo, Qt3DCore::QNodeIdVector>> m_updatedTextureProperties;
399 QVector<QPair<Qt3DCore::QNodeId, GLFence>> m_updatedSetFences;
400 QVector<Qt3DCore::QNodeId> m_updatedDisableSubtreeEnablers;
401 Qt3DCore::QNodeIdVector m_textureIdsToCleanup;
402 QVector<ShaderBuilderUpdate> m_shaderBuilderUpdates;
403 Qt3DCore::QNodeIdVector m_lastLoadedShaderIds;
404
405 bool m_ownedContext;
406
407 OffscreenSurfaceHelper *m_offscreenHelper;
408 GLResourceManagers *m_glResourceManagers;
409 QMutex m_offscreenSurfaceMutex;
410
411 QScopedPointer<Qt3DRender::Debug::CommandExecuter> m_commandExecuter;
412
413 mutable QScopedPointer<Qt3DRender::Render::Profiling::FrameProfiler> m_frameProfiler;
414
415#ifdef QT_BUILD_INTERNAL
416 friend class ::tst_Renderer;
417#endif
418
419 QMetaObject::Connection m_contextConnection;
420 RendererCache m_cache;
421 bool m_shouldSwapBuffers;
422
423 QVector<FrameGraphNode *> m_frameGraphLeaves;
424 QScreen *m_screen = nullptr;
425 QSharedPointer<ResourceAccessor> m_scene2DResourceAccessor;
426
427 Debug::ImGuiRenderer *m_imGuiRenderer;
428 QList<QPair<QObject *, QMouseEvent>> m_frameMouseEvents;
429 QList<QKeyEvent> m_frameKeyEvents;
430 QMutex m_frameEventsMutex;
431 int m_jobsInLastFrame;
432};
433
434} // namespace OpenGL
435} // namespace Render
436} // namespace Qt3DRender
437
438QT_END_NAMESPACE
439
440#endif // QT3DRENDER_RENDER_OPENGL_RENDERER_H
441

source code of qt3d/src/plugins/renderers/opengl/renderer/renderer_p.h