forked from vsg-dev/VulkanSceneGraph
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathViewer.cpp
More file actions
441 lines (371 loc) · 15.4 KB
/
Copy pathViewer.cpp
File metadata and controls
441 lines (371 loc) · 15.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
/* <editor-fold desc="MIT License">
Copyright(c) 2018 Robert Osfield
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
</editor-fold> */
#include <vsg/traversals/CompileTraversal.h>
#include <vsg/nodes/StateGroup.h>
#include <vsg/vk/Descriptor.h>
#include <vsg/viewer/Viewer.h>
#include <chrono>
#include <iostream>
#include <map>
#include <set>
using namespace vsg;
Viewer::Viewer()
{
_start_point = clock::now();
}
Viewer::~Viewer()
{
// don't kill window while devices are still active
for (auto& pair_pdo : _deviceMap)
{
vkDeviceWaitIdle(*pair_pdo.first);
}
}
void Viewer::addWindow(ref_ptr<Window> window)
{
_windows.push_back(window);
ref_ptr<Device> device(window->device());
PhysicalDevice* physicalDevice = window->physicalDevice();
if (_deviceMap.find(device) == _deviceMap.end())
{
auto [graphicsFamily, presentFamily] = physicalDevice->getQueueFamily(VK_QUEUE_GRAPHICS_BIT, window->surface());
// set up per device settings
PerDeviceObjects& new_pdo = _deviceMap[device];
new_pdo.renderFinishedSemaphore = vsg::Semaphore::create(device);
new_pdo.graphicsQueue = device->getQueue(graphicsFamily);
new_pdo.presentQueue = device->getQueue(presentFamily);
new_pdo.signalSemaphores.push_back(*new_pdo.renderFinishedSemaphore);
}
// add per window details to pdo
PerDeviceObjects& pdo = _deviceMap[device];
pdo.windows.push_back(window);
pdo.imageIndices.push_back(0); // to be filled in by submitFrame()
pdo.commandBuffers.push_back(0); // to be filled in by submitFrame()
pdo.swapchains.push_back(*(window->swapchain()));
}
bool Viewer::active() const
{
bool viewerIsActive = !_close;
if (viewerIsActive)
{
for (auto window : _windows)
{
if (!window->valid()) viewerIsActive = false;
}
}
if (!viewerIsActive)
{
// don't exit mainloop while the any devices are still active
for (auto& pair_pdo : _deviceMap)
{
vkDeviceWaitIdle(*pair_pdo.first);
}
return false;
}
else
{
return true;
}
}
bool Viewer::pollEvents(bool discardPreviousEvents)
{
bool result = false;
if (discardPreviousEvents) _events.clear();
for (auto& window : _windows)
{
if (window->pollEvents(_events)) result = true;
}
return result;
}
void Viewer::reassignFrameCache()
{
for (auto& pair_pdo : _deviceMap)
{
PerDeviceObjects& pdo = pair_pdo.second;
pdo.imageIndices.clear();
pdo.commandBuffers.clear();
pdo.swapchains.clear();
for (auto window : pdo.windows)
{
pdo.imageIndices.push_back(0); // to be filled in by submitFrame()
pdo.commandBuffers.push_back(0); // to be filled in by submitFrame()
pdo.swapchains.push_back(*(window->swapchain()));
}
}
}
void Viewer::advance()
{
// poll all the windows for events.
pollEvents(true);
// create FrameStamp for frame
auto time = vsg::clock::now();
_frameStamp = _frameStamp ? new vsg::FrameStamp(time, _frameStamp->frameCount + 1) : new vsg::FrameStamp(time, 0);
// create an event for the new frame.
_events.emplace_back(new FrameEvent(_frameStamp));
}
bool Viewer::advanceToNextFrame()
{
if (!active()) return false;
// poll all the windows for events.
pollEvents(true);
if (!acquireNextFrame()) return false;
// create FrameStamp for frame
auto time = vsg::clock::now();
_frameStamp = _frameStamp ? new vsg::FrameStamp(time, _frameStamp->frameCount + 1) : new vsg::FrameStamp(time, 0);
// create an event for the new frame.
_events.emplace_back(new FrameEvent(_frameStamp));
return true;
}
bool Viewer::acquireNextFrame()
{
if (_close) return false;
bool needToReassingFrameCache = false;
VkResult result = VK_SUCCESS;
for (auto& window : _windows)
{
unsigned int numTries = 0;
unsigned int maximumTries = 10;
while (((result = window->acquireNextImage()) == VK_ERROR_OUT_OF_DATE_KHR) && (numTries < maximumTries))
{
++numTries;
// wait till queue are empty before we resize.
for (auto& pair_pdo : _deviceMap)
{
PerDeviceObjects& pdo = pair_pdo.second;
pdo.presentQueue->waitIdle();
}
//std::cout<<"window->acquireNextImage(), result==VK_ERROR_OUT_OF_DATE_KHR rebuild swap chain : resized="<<window->resized()<<" numTries="<<numTries<<std::endl;
// resize to rebuild all the internal Vulkan objects associated with the window.
window->resize();
needToReassingFrameCache = true;
}
if (result != VK_SUCCESS) break;
}
if (needToReassingFrameCache)
{
// reassign frame cache
reassignFrameCache();
}
return result == VK_SUCCESS;
}
void Viewer::handleEvents()
{
for (auto& vsg_event : _events)
{
for (auto& handler : _eventHandlers)
{
vsg_event->accept(*handler);
}
}
}
void Viewer::compile(BufferPreferences bufferPreferences)
{
if (recordAndSubmitTasks.empty())
{
return;
}
struct DeviceResources
{
vsg::CollectDescriptorStats collectStats;
vsg::ref_ptr<vsg::DescriptorPool> descriptorPool;
vsg::ref_ptr<vsg::CompileTraversal> compile;
};
// find which devices are available
using DeviceResourceMap = std::map<vsg::Device*, DeviceResources>;
DeviceResourceMap deviceResourceMap;
for (auto& task : recordAndSubmitTasks)
{
for (auto& commandGraph : task->commandGraphs)
{
auto& deviceResources = deviceResourceMap[commandGraph->_device];
commandGraph->accept(deviceResources.collectStats);
}
}
// allocate DescriptorPool for each Device
for (auto& [device, deviceResource] : deviceResourceMap)
{
auto physicalDevice = device->getPhysicalDevice();
auto& collectStats = deviceResource.collectStats;
auto maxSets = collectStats.computeNumDescriptorSets();
const auto& descriptorPoolSizes = collectStats.computeDescriptorPoolSizes();
auto queueFamily = physicalDevice->getQueueFamily(VK_QUEUE_GRAPHICS_BIT); // TODO : could we just use transfer bit?
deviceResource.compile = new vsg::CompileTraversal(device, bufferPreferences);
deviceResource.compile->context.commandPool = vsg::CommandPool::create(device, queueFamily);
deviceResource.compile->context.graphicsQueue = device->getQueue(queueFamily);
if (descriptorPoolSizes.size() > 0) deviceResource.compile->context.descriptorPool = vsg::DescriptorPool::create(device, maxSets, descriptorPoolSizes);
}
// create the Vulkan objects
for (auto& task : recordAndSubmitTasks)
{
std::set<Device*> devices;
for (auto& commandGraph : task->commandGraphs)
{
if (commandGraph->_device) devices.insert(commandGraph->_device);
auto& deviceResource = deviceResourceMap[commandGraph->_device];
commandGraph->_maxSlot = deviceResource.collectStats.maxSlot;
commandGraph->accept(*deviceResource.compile);
}
if (task->databasePager)
{
// crude hack for taking first device as the one for the DatabasePager to compile resourcces for.
for (auto& commandGraph : task->commandGraphs)
{
auto& deviceResource = deviceResourceMap[commandGraph->_device];
task->databasePager->compileTraversal = deviceResource.compile;
break;
}
}
}
// dispatch any transfer commands commands
for (auto& dp : deviceResourceMap)
{
dp.second.compile->context.dispatch();
}
// wait for the transfers to complete
for (auto& dp : deviceResourceMap)
{
dp.second.compile->context.waitForCompletion();
}
// start any DatabasePagers
for (auto& task : recordAndSubmitTasks)
{
if (task->databasePager)
{
task->databasePager->start();
}
}
}
void Viewer::assignRecordAndSubmitTaskAndPresentation(CommandGraphs in_commandGraphs, DatabasePager* databasePager)
{
struct DeviceQueueFamily
{
Device* device = nullptr;
int queueFamily = -1;
int presentFamily = -1;
bool operator<(const DeviceQueueFamily& rhs) const
{
if (device < rhs.device) return true;
if (device > rhs.device) return false;
if (queueFamily < rhs.queueFamily) return true;
if (queueFamily > rhs.queueFamily) return false;
return presentFamily < rhs.presentFamily;
}
};
// place the input CommandGraphs into seperate groups associated with each device and queue family combination
std::map<DeviceQueueFamily, CommandGraphs> deviceCommandGraphsMap;
for (auto& commandGraph : in_commandGraphs)
{
deviceCommandGraphsMap[DeviceQueueFamily{commandGraph->_device.get(), commandGraph->_queueFamily, commandGraph->_presentFamily}].emplace_back(commandGraph);
}
// create the required RecordAndSubmitTask and any Presentation objecst that are required for each set of CommandGraphs
for (auto& [deviceQueueFamily, commandGraphs] : deviceCommandGraphsMap)
{
auto device = deviceQueueFamily.device;
if (deviceQueueFamily.presentFamily >= 0)
{
// collate all the unique Windows associaged with these commandGraphs
std::set<Window*> uniqueWindows;
for (auto& commanGraph : commandGraphs)
{
uniqueWindows.insert(commanGraph->window);
}
Windows windows(uniqueWindows.begin(), uniqueWindows.end());
auto renderFinishedSemaphore = vsg::Semaphore::create(device);
// set up Submission with CommandBuffer and signals
auto recordAndSubmitTask = vsg::RecordAndSubmitTask::create();
recordAndSubmitTask->commandGraphs = commandGraphs;
recordAndSubmitTask->signalSemaphores.emplace_back(renderFinishedSemaphore);
recordAndSubmitTask->databasePager = databasePager;
recordAndSubmitTask->windows = windows;
recordAndSubmitTask->queue = device->getQueue(deviceQueueFamily.queueFamily);
recordAndSubmitTasks.emplace_back(recordAndSubmitTask);
auto presentation = vsg::Presentation::create();
presentation->waitSemaphores.emplace_back(renderFinishedSemaphore);
presentation->windows = windows;
presentation->queue = device->getQueue(deviceQueueFamily.presentFamily);
presentations.emplace_back(presentation);
}
else
{
// with don't have a presentFamily so this set of commandGraphs aren't associated with a widnow
// set up Submission with CommandBuffer and signals
auto recordAndSubmitTask = vsg::RecordAndSubmitTask::create();
recordAndSubmitTask->commandGraphs = commandGraphs;
recordAndSubmitTask->databasePager = databasePager;
recordAndSubmitTask->queue = device->getQueue(deviceQueueFamily.queueFamily);
recordAndSubmitTasks.emplace_back(recordAndSubmitTask);
}
}
}
void Viewer::update()
{
for (auto& task : recordAndSubmitTasks)
{
if (task->databasePager)
{
task->databasePager->updateSceneGraph(_frameStamp);
}
}
}
void Viewer::recordAndSubmit()
{
// TODO : Seperate thread for each recordAndSubmitTasks?
// Or use a thread pool or local threads specifically for Viewer?
//
// How do we manage thread affinity?
// we want threads to have affinity with specific cores
// we want tasks/data to have affinity with specific cores
// affinity favours a single or a thread pool with a specific affinity.
// RecordAndSubmitTask to have user defined affinity
// Operations with that call submit should use the RecordAndSubmitTask affinity
// Operations with affinity to be run on threads/thread pools on specified affinity
//
// Should RecordAndSubmitTask (RAS_Task) have it's own Thread pool?
// pros: scales with numer of RAS_Tasks and encapsulates affinity issues
// const: constrains threading to only work within The RAS_Task
//
// Do we insert frame syncronization into threads? Or leave this to individual RAS_Tasks ?
// Do we use a Latch to sync the RAS_Task sbumission with subsequent presentation, or just wait within recordAndSubmit?
// Most straight forward would be to have barrier here in the Viewer::recordAndSubmit().
// This would preclude the calling thread from getting on with work while the RAS_Task do their work in background threads
// Start simple and then generalize?
//
//
// Possible CommandGraph centric approach:
// one thread per CommandGraph
// each thread is assigned an affinity
// require a start record traversal battier so that thread to sleep until new record traversal required
// require record traversal finished barrier to signal completion
// do we use an OperationThraads object per CommandGraph?
// RecordOperation to asssign to OperationThreads?
// Have a single Barrier that is shared between all the CommandGraph traversals that are happening and we need to wait for.
// Use a Latch as a Barrier = each RecordOperation increments the Latch at start, and decrements the Latch on completion
//
//
// If we have multiple recordAndSubmit tasks then we'll want to share Barrier's across them and sync after all have been traversed.
// What about inter traversal/CommandGraph dependencies?
// Nesting to enforce order?
// Order managed in Submissions via VkSemaphore/VkEvent?
//
// Need to create a set of multi-threading test cases to develop for:
// Multi-gpu
// Multi-pass
// Mulit-window/viewport
// Compute and Graphics
// All of the above with DatabasePaging
for (auto& recordAndSubmitTask : recordAndSubmitTasks)
{
recordAndSubmitTask->submit(_frameStamp);
}
}
void Viewer::present()
{
for (auto& presentation : presentations)
{
presentation->present();
}
}