summaryrefslogtreecommitdiff
path: root/retrace/metric_backend_opengl.cpp
blob: 9900a018bc71418128bb6d81b933f714a9904bce (plain)
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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
/**************************************************************************
 *
 * Copyright 2015 Alexander Trukhin
 * All Rights Reserved.
 *
 * 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.
 *
 **************************************************************************/

#include "metric_backend_opengl.hpp"
#include "os_time.hpp"
#include "os_memory.hpp"

void
MetricBackend_opengl::Storage::addData(QueryBoundary boundary, int64_t data) {
    this->data[boundary].push_back(data);
}

int64_t* MetricBackend_opengl::Storage::getData(QueryBoundary boundary,
                                                 unsigned eventId)
{
    return &(data[boundary][eventId]);
}

Metric_opengl::Metric_opengl(unsigned gId, unsigned id, const std::string &name,
                             const std::string &desc, MetricNumType nT, MetricType t)
    : m_gId(gId), m_id(id), m_name(name), m_desc(desc), m_nType(nT),
      m_type(t), available(false)
{
    for (int i = 0; i < QUERY_BOUNDARY_LIST_END; i++) {
        profiled[i] = false;
        enabled[i] = false;
    }
}

unsigned Metric_opengl::id() {
    return m_id;
}

unsigned Metric_opengl::groupId() {
    return m_gId;
}

std::string Metric_opengl::name() {
    return m_name;
}

std::string Metric_opengl::description() {
    return m_desc;
}

MetricNumType Metric_opengl::numType() {
    return m_nType;
}

MetricType Metric_opengl::type() {
    return m_type;
}

MetricBackend_opengl::MetricBackend_opengl(glretrace::Context* context,
                                           MmapAllocator<char> &alloc)
    : alloc(alloc)
{
    glfeatures::Profile currentProfile = context->actualProfile();
    supportsTimestamp   = currentProfile.versionGreaterOrEqual(glfeatures::API_GL, 3, 3) ||
                          context->hasExtension("GL_ARB_timer_query");
    supportsElapsed     = context->hasExtension("GL_EXT_timer_query") || supportsTimestamp;
    supportsOcclusion   = currentProfile.versionGreaterOrEqual(glfeatures::API_GL, 1, 5);

    #ifdef __APPLE__
        // GL_TIMESTAMP doesn't work on Apple.  GL_TIME_ELAPSED still does however.
        // http://lists.apple.com/archives/mac-opengl/2014/Nov/threads.html#00001
        supportsTimestamp   = false;
    #endif

    // Add metrics below
    metrics.emplace_back(0, 0, "CPU Start", "", CNT_NUM_INT64, CNT_TYPE_TIMESTAMP);
    metrics.emplace_back(0, 1, "CPU Duration", "", CNT_NUM_INT64, CNT_TYPE_DURATION);
    metrics.emplace_back(1, 0, "GPU Start", "", CNT_NUM_INT64, CNT_TYPE_TIMESTAMP);
    metrics.emplace_back(1, 1, "GPU Duration", "", CNT_NUM_INT64, CNT_TYPE_DURATION);
    metrics.emplace_back(1, 2, "Pixels Drawn", "", CNT_NUM_INT64, CNT_TYPE_GENERIC);
    metrics.emplace_back(0, 2, "VSIZE Start", "", CNT_NUM_INT64, CNT_TYPE_GENERIC);
    metrics.emplace_back(0, 3, "VSIZE Duration", "", CNT_NUM_INT64, CNT_TYPE_GENERIC);
    metrics.emplace_back(0, 4, "RSS Start", "", CNT_NUM_INT64, CNT_TYPE_GENERIC);
    metrics.emplace_back(0, 5, "RSS Duration", "", CNT_NUM_INT64, CNT_TYPE_GENERIC);

    metrics[METRIC_CPU_START].available = true;
    metrics[METRIC_CPU_DURATION].available = true;
    metrics[METRIC_CPU_VSIZE_START].available = true;
    metrics[METRIC_CPU_VSIZE_DURATION].available = true;
    metrics[METRIC_CPU_RSS_START].available = true;
    metrics[METRIC_CPU_RSS_DURATION].available = true;
    if (supportsTimestamp) metrics[METRIC_GPU_START].available = true;
    if (supportsElapsed) {
        GLint bits = 0;
        glGetQueryiv(GL_TIME_ELAPSED, GL_QUERY_COUNTER_BITS, &bits);
        if (bits) metrics[METRIC_GPU_DURATION].available = true;
    }
    if (supportsOcclusion) {
        metrics[METRIC_GPU_PIXELS].available = true;
    }

    // populate lookups
    for (auto &m : metrics) {
        idLookup[std::make_pair(m.groupId(), m.id())] = &m;
        nameLookup[m.name()] = &m;
    }
}

int64_t MetricBackend_opengl::getCurrentTime(void) {
    if (supportsTimestamp && cpugpuSync) {
        /* Get the current GL time without stalling */
        GLint64 timestamp = 0;
        glGetInteger64v(GL_TIMESTAMP, &timestamp);
        return timestamp;
    } else {
        return os::getTime();
    }
}

int64_t MetricBackend_opengl::getTimeFrequency(void) {
    if (supportsTimestamp && cpugpuSync) {
        return 1000000000;
    } else {
        return os::timeFrequency;
    }
}


bool MetricBackend_opengl::isSupported() {
    return true;
    // though individual metrics might be not supported
}

void MetricBackend_opengl::enumGroups(enumGroupsCallback callback, void* userData) {
    callback(0, 0, userData); // cpu group
    callback(1, 0, userData); // gpu group
}

std::string MetricBackend_opengl::getGroupName(unsigned group) {
    switch(group) {
        case 0:
            return "CPU";
        case 1:
            return "GPU";
        default:
            return "";
    }
}

void MetricBackend_opengl::enumMetrics(unsigned group, enumMetricsCallback callback, void* userData) {
    for (auto &m : metrics) {
        if (m.groupId() == group && m.available) {
            callback(&m, 0, userData);
        }
    }
}

std::unique_ptr<Metric>
MetricBackend_opengl::getMetricById(unsigned groupId, unsigned metricId) {
    auto entryToCopy = idLookup.find(std::make_pair(groupId, metricId));
    if (entryToCopy != idLookup.end()) {
        return std::unique_ptr<Metric>(new Metric_opengl(*entryToCopy->second));
    } else {
        return nullptr;
    }
}

std::unique_ptr<Metric>
MetricBackend_opengl::getMetricByName(std::string metricName) {
    auto entryToCopy = nameLookup.find(metricName);
    if (entryToCopy != nameLookup.end()) {
        return std::unique_ptr<Metric>(new Metric_opengl(*entryToCopy->second));
    } else {
        return nullptr;
    }
}


int MetricBackend_opengl::enableMetric(Metric* metric, QueryBoundary pollingRule) {
    // metric is not necessarily the same object as in metrics[]
    auto entry = idLookup.find(std::make_pair(metric->groupId(), metric->id()));
    if ((entry != idLookup.end()) && entry->second->available) {
        entry->second->enabled[pollingRule] = true;
        return 0;
    }
    return 1;
}

unsigned MetricBackend_opengl::generatePasses() {
    // draw calls profiling not needed if all calls are profiled
    for (int i = 0; i < METRIC_LIST_END; i++) {
        if (metrics[i].enabled[QUERY_BOUNDARY_CALL]) {
            metrics[i].enabled[QUERY_BOUNDARY_DRAWCALL] = false;
        }
    }
    // setup storage for profiled metrics
    for (int i = 0; i < METRIC_LIST_END; i++) {
        for (int j = 0; j < QUERY_BOUNDARY_LIST_END; j++) {
            if (metrics[i].enabled[j]) {
                data[i][j] = std::unique_ptr<Storage>(new Storage(alloc));
            }
        }
    }
    // check if GL queries are needed
    glQueriesNeededAnyBoundary = false;
    for (int i = 0; i < QUERY_BOUNDARY_LIST_END; i++) {
        if (metrics[METRIC_GPU_START].enabled[i] ||
            metrics[METRIC_GPU_DURATION].enabled[i] ||
            metrics[METRIC_GPU_PIXELS].enabled[i])
        {
            glQueriesNeeded[i] = true;
            glQueriesNeededAnyBoundary = true;
        } else {
            glQueriesNeeded[i] = false;
        }
    }
    // check if CPU <-> GPU sync is required
    // this is the case if any gpu time is requested
    cpugpuSync = false;
    for (int i = 0; i < QUERY_BOUNDARY_LIST_END; i++) {
        if (metrics[METRIC_GPU_START].enabled[i] ||
            metrics[METRIC_GPU_DURATION].enabled[i])
        {
            cpugpuSync = true;
            break;
        }
    }
    // check if two passes are needed
    // GL_TIME_ELAPSED (gpu dur) and GL_SAMPLES_PASSED (pixels) cannot be nested
    if (!supportsTimestamp &&
        metrics[METRIC_GPU_DURATION].enabled[QUERY_BOUNDARY_FRAME] &&
       (metrics[METRIC_GPU_DURATION].enabled[QUERY_BOUNDARY_CALL] ||
        metrics[METRIC_GPU_DURATION].enabled[QUERY_BOUNDARY_DRAWCALL]))
    {
        twoPasses = true;
    }
    if (metrics[METRIC_GPU_PIXELS].enabled[QUERY_BOUNDARY_FRAME] &&
       (metrics[METRIC_GPU_PIXELS].enabled[QUERY_BOUNDARY_CALL] ||
        metrics[METRIC_GPU_PIXELS].enabled[QUERY_BOUNDARY_DRAWCALL]))
    {
        twoPasses = true;
    }

    curPass = 1;
    return twoPasses ? 2 : 1;
}

void MetricBackend_opengl::beginPass() {
    if (curPass == 1) {
        for (int i = 0; i < QUERY_BOUNDARY_LIST_END; i++) {
            for (auto &m : metrics) {
                if (m.enabled[i]) m.profiled[i] = true;
            }
        }
        // profile frames in first pass
        if (twoPasses) {
            if (!supportsTimestamp) {
                metrics[METRIC_GPU_DURATION].profiled[QUERY_BOUNDARY_DRAWCALL] = false;
                metrics[METRIC_GPU_DURATION].profiled[QUERY_BOUNDARY_CALL] = false;
            }
            metrics[METRIC_GPU_PIXELS].profiled[QUERY_BOUNDARY_DRAWCALL] = false;
            metrics[METRIC_GPU_PIXELS].profiled[QUERY_BOUNDARY_CALL] = false;
        }
    }
    else if (curPass == 2) {
        for (int i = 0; i < QUERY_BOUNDARY_LIST_END; i++) {
            for (auto &m : metrics) {
                m.profiled[i] = false;
            }
        }
        // profile calls/draw calls in second pass
        if (!supportsTimestamp) {
            if (metrics[METRIC_GPU_DURATION].enabled[QUERY_BOUNDARY_DRAWCALL]) {
                metrics[METRIC_GPU_DURATION].profiled[QUERY_BOUNDARY_DRAWCALL] = true;
            }
            if (metrics[METRIC_GPU_DURATION].enabled[QUERY_BOUNDARY_CALL]) {
                metrics[METRIC_GPU_DURATION].profiled[QUERY_BOUNDARY_CALL] = true;
            }
        }
        if (metrics[METRIC_GPU_PIXELS].enabled[QUERY_BOUNDARY_DRAWCALL]) {
            metrics[METRIC_GPU_PIXELS].profiled[QUERY_BOUNDARY_DRAWCALL] = true;
        }
        if (metrics[METRIC_GPU_PIXELS].enabled[QUERY_BOUNDARY_CALL]) {
            metrics[METRIC_GPU_PIXELS].profiled[QUERY_BOUNDARY_CALL] = true;
        }
    }
    // setup times
    cpuTimeScale = 1.0E9 / getTimeFrequency();
    baseTime = getCurrentTime() * cpuTimeScale;
}

void MetricBackend_opengl::processQueries() {
    int64_t gpuStart, gpuEnd, pixels;
    for (int i = 0; i < QUERY_BOUNDARY_LIST_END; i++) {
        QueryBoundary boundary = static_cast<QueryBoundary>(i);
        while (!queries[i].empty()) {
            auto &query = queries[i].front();
            if (metrics[METRIC_GPU_START].profiled[i]) {
                glGetQueryObjecti64v(query[QUERY_GPU_START], GL_QUERY_RESULT,
                                     &gpuStart);
                int64_t value = gpuStart - baseTime;
                data[METRIC_GPU_START][i]->addData(boundary, value);
            }
            if (metrics[METRIC_GPU_DURATION].profiled[i]) {
                if (supportsTimestamp) {
                    glGetQueryObjecti64v(query[QUERY_GPU_DURATION], GL_QUERY_RESULT,
                                         &gpuEnd);
                    gpuEnd -= gpuStart;
                } else {
                    glGetQueryObjecti64vEXT(query[QUERY_GPU_DURATION], GL_QUERY_RESULT,
                                            &gpuEnd);
                }
                data[METRIC_GPU_DURATION][i]->addData(boundary, gpuEnd);
            }
            if (metrics[METRIC_GPU_PIXELS].profiled[i]) {
                if (supportsTimestamp) {
                    glGetQueryObjecti64v(query[QUERY_OCCLUSION], GL_QUERY_RESULT, &pixels);
                } else if (supportsElapsed) {
                    glGetQueryObjecti64vEXT(query[QUERY_OCCLUSION], GL_QUERY_RESULT, &pixels);
                } else {
                    uint32_t pixels32;
                    glGetQueryObjectuiv(query[QUERY_OCCLUSION], GL_QUERY_RESULT, &pixels32);
                    pixels = static_cast<int64_t>(pixels32);
                }
                data[METRIC_GPU_PIXELS][i]->addData(boundary, pixels);
            }
            glDeleteQueries(QUERY_LIST_END, query.data());
            queries[i].pop();
        }
    }
}

void MetricBackend_opengl::endPass() {
    // process rest of the queries (it can be the last frame)
    processQueries();
    curPass++;
}

void MetricBackend_opengl::pausePass() {
    if (queryInProgress[QUERY_BOUNDARY_FRAME]) endQuery(QUERY_BOUNDARY_FRAME);
    processQueries();
}

void MetricBackend_opengl::continuePass() {
    // TODO if context switches check what it actually supports
}

void MetricBackend_opengl::beginQuery(QueryBoundary boundary) {
    // GPU related
    if (glQueriesNeeded[boundary]) {
        std::array<GLuint, QUERY_LIST_END> query;
        glGenQueries(QUERY_LIST_END, query.data());

        if (metrics[METRIC_GPU_START].profiled[boundary] ||
           (metrics[METRIC_GPU_DURATION].profiled[boundary] && supportsTimestamp))
        {
            glQueryCounter(query[QUERY_GPU_START], GL_TIMESTAMP);
        }
        if (metrics[METRIC_GPU_DURATION].profiled[boundary] && !supportsTimestamp) {
            glBeginQuery(GL_TIME_ELAPSED, query[QUERY_GPU_DURATION]);
        }
        if (metrics[METRIC_GPU_PIXELS].profiled[boundary]) {
            glBeginQuery(GL_SAMPLES_PASSED, query[QUERY_OCCLUSION]);
        }
        queries[boundary].push(std::move(query));
    }


    // CPU related
    if (metrics[METRIC_CPU_START].profiled[boundary] ||
        metrics[METRIC_CPU_DURATION].profiled[boundary])
    {
        cpuStart[boundary] = getCurrentTime();
        if (metrics[METRIC_CPU_START].profiled[boundary]) {
            int64_t time = cpuStart[boundary] * cpuTimeScale - baseTime;
            data[METRIC_CPU_START][boundary]->addData(boundary, time);
        }
    }
    if (metrics[METRIC_CPU_VSIZE_START].profiled[boundary] ||
        metrics[METRIC_CPU_VSIZE_DURATION].profiled[boundary])
    {
        vsizeStart[boundary] = os::getVsize();
        if (metrics[METRIC_CPU_VSIZE_START].profiled[boundary]) {
            int64_t time = vsizeStart[boundary];
            data[METRIC_CPU_VSIZE_START][boundary]->addData(boundary, time);
        }
    }
    if (metrics[METRIC_CPU_RSS_START].profiled[boundary] ||
        metrics[METRIC_CPU_RSS_DURATION].profiled[boundary])
    {
        rssStart[boundary] = os::getRss();
        if (metrics[METRIC_CPU_RSS_START].profiled[boundary]) {
            int64_t time = rssStart[boundary];
            data[METRIC_CPU_RSS_START][boundary]->addData(boundary, time);
        }
    }
    queryInProgress[boundary] = true;
    // DRAWCALL is a CALL
    if (boundary == QUERY_BOUNDARY_DRAWCALL) beginQuery(QUERY_BOUNDARY_CALL);
}

void MetricBackend_opengl::endQuery(QueryBoundary boundary) {
    if (queryInProgress[boundary]) {
        // CPU related
        if (metrics[METRIC_CPU_DURATION].profiled[boundary])
        {
            cpuEnd[boundary] = getCurrentTime();
            int64_t time = (cpuEnd[boundary] - cpuStart[boundary]) * cpuTimeScale;
            data[METRIC_CPU_DURATION][boundary]->addData(boundary, time);
        }
        if (metrics[METRIC_CPU_VSIZE_DURATION].profiled[boundary])
        {
            vsizeEnd[boundary] = os::getVsize();
            int64_t time = vsizeEnd[boundary] - vsizeStart[boundary];
            data[METRIC_CPU_VSIZE_DURATION][boundary]->addData(boundary, time);
        }
        if (metrics[METRIC_CPU_RSS_DURATION].profiled[boundary])
        {
            rssEnd[boundary] = os::getRss();
            int64_t time = rssEnd[boundary] - rssStart[boundary];
            data[METRIC_CPU_RSS_DURATION][boundary]->addData(boundary, time);
        }
        // GPU related
        if (glQueriesNeeded[boundary]) {
            std::array<GLuint, QUERY_LIST_END> &query = queries[boundary].back();
            if (metrics[METRIC_GPU_DURATION].profiled[boundary] && supportsTimestamp) {
                // GL_TIME_ELAPSED cannot be used in nested queries
                // so prefer this if timestamps are supported
                glQueryCounter(query[QUERY_GPU_DURATION], GL_TIMESTAMP);
            }
            if (metrics[METRIC_GPU_PIXELS].profiled[boundary]) {
                glEndQuery(GL_SAMPLES_PASSED);
            }
        }
        queryInProgress[boundary] = false;
    }
    // DRAWCALL is a CALL
    if (boundary == QUERY_BOUNDARY_DRAWCALL) endQuery(QUERY_BOUNDARY_CALL);
    // clear queries after each frame
    if (boundary == QUERY_BOUNDARY_FRAME && glQueriesNeededAnyBoundary) {
        processQueries();
    }
}

void MetricBackend_opengl::enumDataQueryId(unsigned id, enumDataCallback callback,
                                           QueryBoundary boundary, void* userData) {
    for (int i = 0; i < METRIC_LIST_END; i++) {
        Metric_opengl &metric = metrics[i];
        if (metric.enabled[boundary]) {
            callback(&metric, id, data[i][boundary]->getData(boundary, id), 0,
                     userData);
        }
    }
}

unsigned MetricBackend_opengl::getNumPasses() {
    return twoPasses ? 2 : 1;
}

MetricBackend_opengl&
MetricBackend_opengl::getInstance(glretrace::Context* context, MmapAllocator<char> &alloc) {
    static MetricBackend_opengl backend(context, alloc);
    return backend;
}