File: Colour3DPlotRenderer.cpp

package info (click to toggle)
sonic-visualiser 5.2.1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 24,744 kB
  • sloc: cpp: 158,888; ansic: 11,920; sh: 1,785; makefile: 517; xml: 64; perl: 31
file content (1640 lines) | stat: -rw-r--r-- 57,549 bytes parent folder | download | duplicates (2)
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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
/* -*- c-basic-offset: 4 indent-tabs-mode: nil -*-  vi:set ts=8 sts=4 sw=4: */

/*
    Sonic Visualiser
    An audio file viewer and annotation editor.
    Centre for Digital Music, Queen Mary, University of London.
    This file copyright 2006-2016 Chris Cannam and QMUL.
    
    This program is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License as
    published by the Free Software Foundation; either version 2 of the
    License, or (at your option) any later version.  See the file
    COPYING included with this distribution for more information.
*/

#include "Colour3DPlotRenderer.h"
#include "RenderTimer.h"

#include "base/Profiler.h"
#include "base/HitCount.h"

#include "data/model/DenseThreeDimensionalModel.h"
#include "data/model/Dense3DModelPeakCache.h"
#include "data/model/FFTModel.h"

#include "LayerGeometryProvider.h"
#include "VerticalBinLayer.h"
#include "PaintAssistant.h"
#include "ImageRegionFinder.h"

#include "view/ViewManager.h" // for main model sample rate. Pity

#include <vector>

#include <utility>
namespace sv {

using namespace std::rel_ops;

//#define DEBUG_COLOUR_PLOT_REPAINT 1
//#define DEBUG_COLOUR_PLOT_CACHE_SELECTION 1

using namespace std;

static vector<QRgb>
makeColourmap(const Colour3DPlotRenderer::Parameters &parameters)
{
    vector<QRgb> colourmap;
    colourmap.reserve(256);
    for (int pixel = 0; pixel < 256; ++pixel) {
        QColor c = parameters.colourScale.getColourForPixel
            (pixel, parameters.colourRotation);
        if (!parameters.opaque) {
            c.setAlpha(20 + (pixel * 220) / 256);
        }
        colourmap.push_back(c.rgba());
    }
    return colourmap;
}

Colour3DPlotRenderer::Colour3DPlotRenderer(Sources sources,
                                           Parameters parameters) :
    m_sources(sources),
    m_params(parameters),
    m_colourmap(makeColourmap(parameters)),
    m_secondsPerXPixel(0.0),
    m_secondsPerXPixelValid(false)
{
#ifdef DEBUG_COLOUR_PLOT_REPAINT
    SVDEBUG << "Colour3DPlotRenderer[" << this << "]::Colour3DPlotRenderer("
            << m_sources.source << ")" << endl;
#endif
}

Colour3DPlotRenderer::~Colour3DPlotRenderer()
{
#ifdef DEBUG_COLOUR_PLOT_REPAINT
    SVDEBUG << "Colour3DPlotRenderer[" << this << "]::~Colour3DPlotRenderer()"
            << endl;
#endif
}

Colour3DPlotRenderer::RenderResult
Colour3DPlotRenderer::render(const LayerGeometryProvider *v, QPainter &paint, QRect rect)
{
    return render(v, paint, rect, false);
}

Colour3DPlotRenderer::RenderResult
Colour3DPlotRenderer::renderTimeConstrained(const LayerGeometryProvider *v,
                                            QPainter &paint, QRect rect)
{
    return render(v, paint, rect, true);
}

QRect
Colour3DPlotRenderer::getLargestUncachedRect(const LayerGeometryProvider *v)
{
    RenderType renderType = decideRenderType(v);

    if (renderType == DirectTranslucent) {
        return QRect(); // never cached
    }

    int h = m_cache.getSize().height();

    QRect areaLeft(0, 0, m_cache.getValidLeft(), h);
    QRect areaRight(m_cache.getValidRight(), 0,
                    m_cache.getSize().width() - m_cache.getValidRight(), h);

    if (areaRight.width() > areaLeft.width()) {
        return areaRight;
    } else {
        return areaLeft;
    }
}

bool
Colour3DPlotRenderer::geometryChanged(const LayerGeometryProvider *v)
{
    RenderType renderType = decideRenderType(v);

    if (renderType == DirectTranslucent) {
        return true; // never cached
    }

    // Use getRawZoomLevel to pass to the cache, because the scaled
    // version (getRoundedZoomLevel) does not always correctly
    // indicate a change in zoom
    if (m_cache.getSize() == v->getPaintSize() &&
        m_cache.getZoomLevel() == v->getRawZoomLevel() &&
        m_cache.getStartFrame() == v->getStartFrame()) {
        return false;
    } else {
        return true;
    }
}

Colour3DPlotRenderer::RenderResult
Colour3DPlotRenderer::render(const LayerGeometryProvider *v,
                             QPainter &paint, QRect rect, bool timeConstrained)
{
    RenderType renderType = decideRenderType(v);

    if (timeConstrained) {
        if (renderType != DrawBufferPixelResolution) {
            // Rendering should be fast in bin-resolution and direct
            // draw cases because we are quite well zoomed-in, and the
            // sums are easier this way. Calculating boundaries later
            // will be fiddly for partial paints otherwise.
            timeConstrained = false;
        }
    }
            
    int x0 = v->getXForViewX(rect.x());
    int x1 = v->getXForViewX(rect.x() + rect.width());
    if (x0 < 0) x0 = 0;
    if (x0 > v->getPaintWidth()) x0 = v->getPaintWidth();
    if (x1 < 0) x1 = 0;
    if (x1 > v->getPaintWidth()) x1 = v->getPaintWidth();

    sv_frame_t startFrame = v->getStartFrame();

#ifdef DEBUG_COLOUR_PLOT_REPAINT
    SVDEBUG << "render " << m_sources.source
            << ": rect is " << rect.x() << "," << rect.y()
            << " " << rect.width() << "x" << rect.height() << "; paint width = "
            << v->getPaintWidth() << ", x0 = " << x0 << ", x1 = " << x1
            << endl;
#endif

#ifdef DEBUG_COLOUR_PLOT_REPAINT
    SVDEBUG << "render " << m_sources.source
            << ": cache size is " << m_cache.getSize().width()
            << "x" << m_cache.getSize().height()
            << " at raw zoom level " << m_cache.getZoomLevel()
            << endl;
#endif

#ifdef DEBUG_COLOUR_PLOT_REPAINT
    {
        bool justCreated = m_cache.getSize().isEmpty();
        bool justInvalidated =
            (m_cache.getSize() != v->getPaintSize() ||
             m_cache.getZoomLevel() != v->getRawZoomLevel());
        SVDEBUG << "render " << m_sources.source
                << ": justCreated = " << justCreated
                << ", justInvalidated = " << justInvalidated
                << endl;
    }
#endif
    
    m_cache.resize(v->getPaintSize());
    m_cache.setZoomLevel(v->getRawZoomLevel());

    m_magCache.resize(v->getPaintSize().width());
    m_magCache.setZoomLevel(v->getRawZoomLevel());
    
    if (renderType == DirectTranslucent) {
        MagnitudeRange range = renderDirectTranslucent(v, paint, rect);
        return { rect, range };
    }
    
#ifdef DEBUG_COLOUR_PLOT_REPAINT
    SVDEBUG << "render " << m_sources.source
            << ": cache start " << m_cache.getStartFrame()
            << " valid left " << m_cache.getValidLeft()
            << " valid right " << m_cache.getValidRight()
            << endl;
    SVDEBUG << "render " << m_sources.source
            << ": view start " << startFrame
            << " x0 " << x0
            << " x1 " << x1
            << endl;
#endif

    static HitCount count("Colour3DPlotRenderer: image cache");

    if (m_cache.isValid()) { // some part of the cache is valid

        if (v->getXForFrame(m_cache.getStartFrame()) ==
            v->getXForFrame(startFrame) &&
            m_cache.getValidLeft() <= x0 &&
            m_cache.getValidRight() >= x1) {

#ifdef DEBUG_COLOUR_PLOT_REPAINT
            SVDEBUG << "render " << m_sources.source
                    << ": cache hit" << endl;
#endif
            count.hit();
            
            // cache is valid for the complete requested area
            paint.drawImage(rect, m_cache.getImage(), rect);

            MagnitudeRange range = m_magCache.getRange(x0, x1 - x0);

            return { rect, range };

        } else {
#ifdef DEBUG_COLOUR_PLOT_REPAINT
            SVDEBUG << "render " << m_sources.source
                    << ": cache partial hit" << endl;
#endif
            count.partial();
            
            // cache doesn't begin at the right frame or doesn't
            // contain the complete view, but might be scrollable or
            // partially usable
            m_cache.scrollTo(v, startFrame);
            m_magCache.scrollTo(v, startFrame);

            // if we are not time-constrained, then we want to paint
            // the whole area in one go; we don't return a partial
            // paint. To avoid providing the more complex logic to
            // handle painting discontiguous areas, if the only valid
            // part of cache is in the middle, just make the whole
            // thing invalid and start again.
            if (!timeConstrained) {
                if (m_cache.getValidLeft() > x0 &&
                    m_cache.getValidRight() < x1) {
                    m_cache.invalidate();
                }
            }
        }
    } else {
        // cache is completely invalid
#ifdef DEBUG_COLOUR_PLOT_REPAINT
        SVDEBUG << "render " << m_sources.source
                << ": cache miss" << endl;
#endif
        count.miss();
        m_cache.setStartFrame(startFrame);
        m_magCache.setStartFrame(startFrame);
    }

    bool rightToLeft = false;

    int reqx0 = x0;
    int reqx1 = x1;
    
    if (!m_cache.isValid() && timeConstrained) {
        if (x0 == 0 && x1 == v->getPaintWidth()) {
            
            // When rendering the whole area, in a context where we
            // might not be able to complete the work, start from
            // somewhere near the middle so that the region of
            // interest appears first.
            //
            // This is very useful if we actually are slow to render,
            // but if we're not sure how fast we'll be, we should
            // prefer not to because it can be distracting to render
            // fast from the middle and then jump back to fill in the
            // start. That is:
            //
            // - if our seconds-per-x-pixel count is invalid, then we
            // don't do this: we've probably only just been created
            // and don't know how fast we'll be yet (this happens
            // often while zooming rapidly in and out). The exception
            // to the exception is if we're displaying peak
            // frequencies; this we can assume to be slow. (Note that
            // if the seconds-per-x-pixel is valid and we know we're
            // fast, then we've already set timeConstrained false
            // above so this doesn't apply)
            // 
            // - if we're using a peak cache, we don't do this;
            // drawing from peak cache is often (even if not always)
            // fast.

            bool drawFromTheMiddle = true;

            if (!m_secondsPerXPixelValid &&
                (m_params.binDisplay != BinDisplay::PeakFrequencies)) {
                drawFromTheMiddle = false;
            } else {
                int peakCacheIndex = -1, binsPerPeak = -1;
                getPreferredPeakCache(v, peakCacheIndex, binsPerPeak);
                if (peakCacheIndex >= 0) { // have a peak cache
                    drawFromTheMiddle = false;
                }
            }

            if (drawFromTheMiddle) {
                double offset = 0.5 * (double(rand()) / double(RAND_MAX));
                x0 = int(x1 * offset);
            }
        }
    }

    if (m_cache.isValid()) {
            
        // When rendering only a part of the cache, we need to make
        // sure that the part we're rendering is adjacent to (or
        // overlapping) a valid area of cache, if we have one. The
        // alternative is to ditch the valid area of cache and render
        // only the requested area, but that's risky because this can
        // happen when just waving the pointer over a small part of
        // the view -- if we lose the partly-built cache every time
        // the user does that, we'll never finish building it.
        int left = x0;
        int width = x1 - x0;
        bool isLeftOfValidArea = false;
        m_cache.adjustToTouchValidArea(left, width, isLeftOfValidArea);
        x0 = left;
        x1 = x0 + width;

        // That call also told us whether we should be painting
        // sub-regions of our target region in right-to-left order in
        // order to ensure contiguity
        rightToLeft = isLeftOfValidArea;
    }
    
    // Note, we always paint the full height to cache. We want to
    // ensure the cache is coherent without having to worry about
    // vertical matching of required and valid areas as well as
    // horizontal.

    if (renderType == DrawBufferBinResolution) {

        renderToCacheBinResolution(v, x0, x1 - x0);

    } else { // must be DrawBufferPixelResolution, handled DirectTranslucent earlier

/*!!! This is not desirable behaviour when using threaded repaint - we
      don't actually know for sure here whether we're doing that, but
      it is the default, and the worst case if we aren't is less bad
      than it used to be
  
        if (timeConstrained && !justCreated && justInvalidated) {
            SVDEBUG << "render " << m_sources.source
                    << ": invalidated cache in time-constrained context, that's all we're doing for now - wait for next update to start filling" << endl;
        } else {
*/
        
            renderToCachePixelResolution(v, x0, x1 - x0, rightToLeft, timeConstrained);
/*        } */
    }

    QRect pr = rect & m_cache.getValidArea();
    paint.drawImage(pr.x(), pr.y(), m_cache.getImage(),
                    pr.x(), pr.y(), pr.width(), pr.height());

    if (!timeConstrained && (pr != rect)) {
        QRect cva = m_cache.getValidArea();
        SVCERR << "WARNING: failed to render entire requested rect "
               << "even when not time-constrained: wanted "
               << rect.x() << "," << rect.y() << " "
               << rect.width() << "x" << rect.height() << ", got "
               << pr.x() << "," << pr.y() << " "
               << pr.width() << "x" << pr.height()
               << ", after request of width " << (x1 - x0)
               << endl
               << "(cache valid area is "
               << cva.x() << "," << cva.y() << " "
               << cva.width() << "x" << cva.height() << ")"
               << endl;
    }

    MagnitudeRange range = m_magCache.getRange(reqx0, reqx1 - reqx0);

#ifdef DEBUG_COLOUR_PLOT_REPAINT
    SVDEBUG << "render " << m_sources.source
            << ": returning rect rendered as " << pr.x() << "," << pr.y()
            << " " << pr.width() << "x" << pr.height() << endl;
    SVDEBUG << "render " << m_sources.source
            << ": mag range from cache in x-range " << reqx0
            << " to " << reqx1 << " is " << range.getMin() << " -> "
            << range.getMax() << endl;
#endif
    
    return { pr, range };
}

bool
Colour3DPlotRenderer::getBinResolutions(const LayerGeometryProvider *v,
                                        int &binResolution,
                                        double &renderBinResolution) const
{
    auto model = ModelById::getAs<DenseThreeDimensionalModel>(m_sources.source);
    if (!model || !v || !(v->getViewManager())) {
        binResolution = 1;
        renderBinResolution = 1.0;
        return false;
    }

    binResolution = model->getResolution();
    sv_samplerate_t modelRate = model->getSampleRate();

    double rateRatio = v->getViewManager()->getMainModelSampleRate() / modelRate;
    renderBinResolution = binResolution * rateRatio;

#ifdef DEBUG_COLOUR_PLOT_REPAINT
    SVDEBUG << "Colour3DPlotRenderer: binResolution " << binResolution
            << ", modelRate " << modelRate
            << ", main model rate " << v->getViewManager()->getMainModelSampleRate()
            << ", rateRatio " << rateRatio << ", renderBinResolution "
            << renderBinResolution << endl;
#endif

    return true;
}

Colour3DPlotRenderer::RenderType
Colour3DPlotRenderer::decideRenderType(const LayerGeometryProvider *v) const
{
    auto model = ModelById::getAs<DenseThreeDimensionalModel>(m_sources.source);
    if (!model || !v || !(v->getViewManager())) {
        return DrawBufferPixelResolution; // or anything
    }

    int binResolution;
    double renderBinResolution;
    if (!getBinResolutions(v, binResolution, renderBinResolution)) {
        return DrawBufferPixelResolution; // or anything
    }

    if (m_params.binDisplay == BinDisplay::PeakFrequencies) {
        // no alternative works here
#ifdef DEBUG_COLOUR_PLOT_REPAINT
        SVDEBUG << "decideRenderType: binDisplay is PeakFrequencies, must use pixel resolution" << endl;
#endif
        return DrawBufferPixelResolution;
    }

    ZoomLevel zoomLevel = v->getRoundedZoomLevel();

    if (!m_params.opaque && !m_params.interpolate) {

        // consider explicit translucent cell option -- only if not
        // smoothing & not requested opaque & sufficiently zoomed-in

        ZoomLevel threshold(ZoomLevel::FramesPerPixel,
                            int(round(renderBinResolution / 3)));
        
        if (model->getHeight() * 3 < v->getPaintHeight() &&
            zoomLevel < threshold) {
#ifdef DEBUG_COLOUR_PLOT_REPAINT
            SVDEBUG << "decideRenderType: zoomLevel " << zoomLevel
                    << " < threshold " << threshold
                    << " and not opaque or smoothed; "
                    << "using DirectTranslucent mode" << endl;
#endif
            return DirectTranslucent;
        }
    }

    ZoomLevel threshold(ZoomLevel::FramesPerPixel,
                        int(round(renderBinResolution)));

    if (zoomLevel < threshold) {
#ifdef DEBUG_COLOUR_PLOT_REPAINT
        SVDEBUG << "decideRenderType: zoomLevel " << zoomLevel
                << " < threshold " << threshold
                << ", drawing at bin resolution" << endl;
#endif
        return DrawBufferBinResolution;
    } else {
#ifdef DEBUG_COLOUR_PLOT_REPAINT
        SVDEBUG << "decideRenderType: zoomLevel " << zoomLevel
                << " >= threshold " << threshold
                << ", drawing at pixel resolution" << endl;
#endif
        return DrawBufferPixelResolution;
    }
}

ColumnOp::Column
Colour3DPlotRenderer::getColumn(int sx, int minbin, int nbins,
                                bool suppressCache,
                                shared_ptr<DenseThreeDimensionalModel> source) const
{
    Profiler profiler("Colour3DPlotRenderer::getColumn");

    // order:
    // get column -> scale -> normalise -> record extents ->
    // peak pick -> distribute/interpolate -> apply display gain

    // we do the first bit here:
    // get column -> scale -> normalise

    ColumnOp::Column column;
    
    if (m_params.showDerivative && sx > 0) {

        auto prev = getColumnRaw(sx - 1, minbin, nbins, suppressCache, source);
        column = getColumnRaw(sx, minbin, nbins, suppressCache, source);
        
        for (int i = 0; i < nbins; ++i) {
            column[i] -= prev[i];
        }

    } else {
        column = getColumnRaw(sx, minbin, nbins, suppressCache, source);
    }

    if (m_params.colourScale.getScale() == ColourScaleType::Phase &&
        !m_sources.fft.isNone()) {
        return column;
    } else {
        return ColumnOp::normalize(ColumnOp::applyGain(column,
                                                       m_params.scaleFactor),
                                   m_params.normalization);
    }
}

ColumnOp::Column
Colour3DPlotRenderer::getColumnRaw(int sx, int minbin, int nbins,
                                   bool suppressCache,
                                   shared_ptr<DenseThreeDimensionalModel> source) const
{
    Profiler profiler("Colour3DPlotRenderer::getColumnRaw");

    if (m_params.colourScale.getScale() == ColourScaleType::Phase) {
        auto fftModel = ModelById::getAs<FFTModel>(m_sources.fft);
        if (fftModel) {
            auto fullColumn = fftModel->getPhases(sx);
            return ColumnOp::Column(fullColumn.data() + minbin,
                                    fullColumn.data() + minbin + nbins);
        }
    }

    if (suppressCache) {
        auto fftModel = dynamic_cast<FFTModel *>(source.get());
        if (fftModel) {
            return fftModel->getColumnWithoutCache(sx, minbin, nbins);
        } else {
            return source->getColumn(sx, minbin, nbins);
        }
    } else {
        return source->getColumn(sx, minbin, nbins);
    }
}

MagnitudeRange
Colour3DPlotRenderer::renderDirectTranslucent(const LayerGeometryProvider *v,
                                              QPainter &paint,
                                              QRect rect)
{
    Profiler profiler("Colour3DPlotRenderer::renderDirectTranslucent");

    MagnitudeRange magRange;
    
    QPoint illuminatePos;
    bool illuminate = v->shouldIlluminateLocalFeatures
        (m_sources.verticalBinLayer, illuminatePos);

    auto model = ModelById::getAs<DenseThreeDimensionalModel>(m_sources.source);
    if (!model) return magRange;
    
    int x0 = rect.left();
    int x1 = x0 + rect.width();

    int h = v->getPaintHeight();

    sv_frame_t modelStart = model->getStartFrame();
    sv_frame_t modelEnd = model->getEndFrame();
    int modelResolution = model->getResolution();

    double rateRatio =
        v->getViewManager()->getMainModelSampleRate() / model->getSampleRate();

    // the s-prefix values are source, i.e. model, column and bin numbers
    int sx0 = int((double(v->getFrameForX(x0)) / rateRatio - double(modelStart))
                  / modelResolution);
    int sx1 = int((double(v->getFrameForX(x1)) / rateRatio - double(modelStart))
                  / modelResolution);

    int sh = model->getHeight();

    const int buflen = 40;
    char labelbuf[buflen];

    int minbin = m_sources.verticalBinLayer->getIBinForY(v, h);
    if (minbin >= sh) minbin = sh - 1;
    if (minbin < 0) minbin = 0;
    
    int nbins  = m_sources.verticalBinLayer->getIBinForY(v, 0) - minbin + 1;
    if (minbin + nbins > sh) nbins = sh - minbin;

    int psx = -1;

    ColumnOp::Column preparedColumn;

    int modelWidth = model->getWidth();

    for (int sx = sx0; sx <= sx1; ++sx) {

        if (sx < 0 || sx >= modelWidth) {
            continue;
        }

        if (sx != psx) {

            // order:
            // get column -> scale -> normalise -> record extents ->
            // peak pick -> distribute/interpolate -> apply display gain

            // this does the first three:
            preparedColumn = getColumn(sx, minbin, nbins, false, model);
            
            magRange.sample(preparedColumn);

            if (m_params.binDisplay == BinDisplay::PeakBins) {
                preparedColumn = ColumnOp::peakPick(preparedColumn);
            }

            // Display gain belongs to the colour scale and is
            // applied by the colour scale object when mapping it

            psx = sx;
        }

        sv_frame_t fx = sx * modelResolution + modelStart;

        if (fx + modelResolution <= modelStart || fx > modelEnd) continue;

        int rx0 = v->getXForFrame(int(double(fx) * rateRatio));
        int rx1 = v->getXForFrame(int(double(fx + modelResolution + 1) * rateRatio));

        int rw = rx1 - rx0;
        if (rw < 1) rw = 1;

        bool showLabel = (rw > 10 &&
                          paint.fontMetrics().horizontalAdvance("0.000000") < rw - 3 &&
                          paint.fontMetrics().height() < (h / sh));
        
        for (int sy = minbin; sy < minbin + nbins; ++sy) {

            int ry0 = m_sources.verticalBinLayer->getIYForBin(v, sy);
            int ry1 = m_sources.verticalBinLayer->getIYForBin(v, sy + 1);

            if (m_params.invertVertical) {
                ry0 = h - ry0 - 1;
                ry1 = h - ry1 - 1;
            }
                    
            QRect r(rx0, ry1, rw, ry0 - ry1);

            float value = preparedColumn[sy - minbin];
            QColor colour = m_params.colourScale.getColour
                (value, m_params.colourRotation);

            if (rw == 1) {
                paint.setPen(colour);
                paint.setBrush(Qt::NoBrush);
                paint.drawLine(r.x(), r.y(), r.x(), r.y() + r.height() - 1);
                continue;
            }

            QColor brush(colour);

            if (rw > 3 && r.height() > 3) {
                brush.setAlpha(160);
            }

            paint.setPen(Qt::NoPen);
            paint.setBrush(brush);

            if (illuminate) {
                if (r.contains(illuminatePos)) {
                    paint.setPen(v->getForeground());
                }
            }
            
#ifdef DEBUG_COLOUR_PLOT_REPAINT
//            SVDEBUG << "rect " << r.x() << "," << r.y() << " "
//                      << r.width() << "x" << r.height() << endl;
#endif

            paint.drawRect(r);

            if (showLabel) {
                double value = model->getValueAt(sx, sy);
                snprintf(labelbuf, buflen, "%06f", value);
                QString text(labelbuf);
                PaintAssistant::drawVisibleText
                    (v,
                     paint,
                     rx0 + 2,
                     ry0 - h / sh - 1 + 2 + paint.fontMetrics().ascent(),
                     text,
                     PaintAssistant::OutlinedText);
            }
        }
    }

    return magRange;
}

void
Colour3DPlotRenderer::getPreferredPeakCache(const LayerGeometryProvider *v,
                                            int &peakCacheIndex,
                                            int &binsPerPeak) const
{
    peakCacheIndex = -1;
    binsPerPeak = -1;

    auto model = ModelById::getAs<DenseThreeDimensionalModel>(m_sources.source);
    if (!model) return;
    if (m_params.binDisplay == BinDisplay::PeakFrequencies) return;
    if (m_params.colourScale.getScale() == ColourScaleType::Phase) return;
    
    ZoomLevel zoomLevel = v->getRoundedZoomLevel();
    int binResolution;
    double renderBinResolution;
    if (!getBinResolutions(v, binResolution, renderBinResolution)) return;

    for (int ix = 0; in_range_for(m_sources.peakCaches, ix); ++ix) {
        auto peakCache = ModelById::getAs<Dense3DModelPeakCache>
            (m_sources.peakCaches[ix]);
        if (!peakCache) continue;
        int bpp = peakCache->getColumnsPerPeak();
        ZoomLevel equivZoom(ZoomLevel::FramesPerPixel,
                            round(renderBinResolution * bpp));
#ifdef DEBUG_COLOUR_PLOT_CACHE_SELECTION
        SVDEBUG << "render " << m_sources.source
                << ": getPreferredPeakCache: zoomLevel = " << zoomLevel
                << ", cache " << ix << " has bpp = " << bpp
                << " for equivZoom = " << equivZoom << endl;
#endif
        if (zoomLevel >= equivZoom) {
            // this peak cache would work, though it might not be best
            if (bpp > binsPerPeak) {
                // ok, it's better than the best one we've found so far
                peakCacheIndex = ix;
                binsPerPeak = bpp;
            }
        }
    }

#ifdef DEBUG_COLOUR_PLOT_CACHE_SELECTION
    SVDEBUG << "render " << m_sources.source
            << ": getPreferredPeakCache: zoomLevel = " << zoomLevel
            << ", renderBinResolution " << renderBinResolution
            << ", peakCaches " << m_sources.peakCaches.size()
            << ": preferring peakCacheIndex " << peakCacheIndex
            << " for binsPerPeak " << binsPerPeak
            << endl;
#endif
}

void
Colour3DPlotRenderer::renderToCachePixelResolution(const LayerGeometryProvider *v,
                                                   int x0, int repaintWidth,
                                                   bool rightToLeft,
                                                   bool timeConstrained)
{
    Profiler profiler("Colour3DPlotRenderer::renderToCachePixelResolution");
#ifdef DEBUG_COLOUR_PLOT_REPAINT
    SVDEBUG << "render " << m_sources.source
            << ": [PIXEL] renderToCachePixelResolution" << endl;
#endif
    
    // Draw to the draw buffer, and then copy from there. The draw
    // buffer is at the same resolution as the target in the cache, so
    // no extra scaling needed.

    auto model = ModelById::getAs<DenseThreeDimensionalModel>(m_sources.source);
    if (!model) return;

    int h = v->getPaintHeight();

    clearDrawBuffer(repaintWidth, h);

    vector<int> binforx(repaintWidth);
    vector<double> binfory(h);
    
    int binResolution;
    double renderBinResolution;
    if (!getBinResolutions(v, binResolution, renderBinResolution)) return;

#ifdef DEBUG_COLOUR_PLOT_REPAINT
    SVDEBUG << "renderToCachePixelResolution: binResolution = "
            << binResolution << ", renderBinResolution = "
            << renderBinResolution << endl;
#endif
    
    for (int x = 0; x < repaintWidth; ++x) {
        sv_frame_t f0 = v->getFrameForX(x0 + x);
        double s0 = double(f0 - model->getStartFrame()) / renderBinResolution;
        binforx[x] = int(s0 + 0.0001);
#ifdef DEBUG_COLOUR_PLOT_REPAINT
        SVDEBUG << "renderToCachePixelResolution: getFrameForX("
                << x0 << " + " << x << ") yields " << f0
                << " with model start frame " << model->getStartFrame()
                << " giving s0 = " << s0 << ", so binforx[" << x << "] == "
                << binforx[x] << endl;
#endif
    }

    int peakCacheIndex = -1;
    int binsPerPeak = -1;

    getPreferredPeakCache(v, peakCacheIndex, binsPerPeak);
    
    for (int y = 0; y < h; ++y) {
        binfory[y] = m_sources.verticalBinLayer->getBinForY(v, h - y - 1);
    }

    int attainedWidth;

    if (m_params.binDisplay == BinDisplay::PeakFrequencies) {
        attainedWidth = renderDrawBufferPeakFrequencies(v,
                                                        repaintWidth,
                                                        h,
                                                        binforx,
                                                        binfory,
                                                        rightToLeft,
                                                        timeConstrained);

    } else {
        attainedWidth = renderDrawBuffer(repaintWidth,
                                         h,
                                         binforx,
                                         binfory,
                                         peakCacheIndex,
                                         rightToLeft,
                                         timeConstrained);
    }

#ifdef DEBUG_COLOUR_PLOT_REPAINT
    SVDEBUG << "renderToCachePixelResolution: attainedWidth = "
            << attainedWidth << endl;
#endif
    
    if (attainedWidth == 0) return;

    // draw buffer is pixel resolution, no scaling factors or padding involved
    
    int paintedLeft = x0;
    if (rightToLeft) {
        paintedLeft += (repaintWidth - attainedWidth);
    }

    m_cache.drawImage(paintedLeft, attainedWidth,
                      m_drawBuffer,
                      paintedLeft - x0, attainedWidth);

    for (int i = 0; in_range_for(m_magRanges, i); ++i) {
        m_magCache.sampleColumn(i, m_magRanges.at(i));
    }
}

QImage
Colour3DPlotRenderer::scaleDrawBufferImage(QImage image,
                                           int targetWidth,
                                           int targetHeight) const
{
    int sourceWidth = image.width();
    int sourceHeight = image.height();

    // We can only do this if we're making the image larger --
    // otherwise peaks may be lost. So this should be called only when
    // rendering in DrawBufferBinResolution mode. Whenever the bin
    // size is smaller than the pixel size, in either x or y axis, we
    // should be using DrawBufferPixelResolution mode instead
    
    if (targetWidth < sourceWidth || targetHeight < sourceHeight) {
        SVCERR << "ERROR: Colour3DPlotRenderer::scaleDrawBufferImage: "
               << "targetWidth " << targetWidth
               << " < sourceWidth " << sourceWidth
               << " or targetHeight " << targetHeight
               << " < sourceHeight " << sourceHeight << endl;
        throw std::logic_error("Colour3DPlotRenderer::scaleDrawBufferImage: Can only use this function when making the image larger; should be rendering DrawBufferPixelResolution instead");
    }

    if (sourceWidth <= 0 || sourceHeight <= 0) {
        throw std::logic_error("Colour3DPlotRenderer::scaleDrawBufferImage: Source image is empty");
    }

    if (targetWidth <= 0 || targetHeight <= 0) {
        throw std::logic_error("Colour3DPlotRenderer::scaleDrawBufferImage: Target image is empty");
    }        

    // This function exists because of some unpredictable behaviour
    // from Qt when scaling images with FastTransformation mode. We
    // continue to use Qt's scaler for SmoothTransformation but let's
    // bring the non-interpolated version "in-house" so we know what
    // it's really doing.
    
    if (m_params.interpolate) {
        return image.scaled(targetWidth, targetHeight,
                            Qt::IgnoreAspectRatio,
                            Qt::SmoothTransformation);
    }
    
    // Same format as the target cache
    QImage target(targetWidth, targetHeight,
                  QImage::Format_ARGB32);

    for (int y = 0; y < targetHeight; ++y) {

        QRgb *targetLine = reinterpret_cast<QRgb *>
            (target.scanLine(y));
        
        int sy = int((uint64_t(y) * sourceHeight) / targetHeight);
        if (sy == sourceHeight) --sy;

        const QRgb *sourceLine = reinterpret_cast<const QRgb *>
            (image.constScanLine(sy));

        int psx = -1;
        QRgb colour = {};
        
        for (int x = 0; x < targetWidth; ++x) {

            int sx = int((uint64_t(x) * sourceWidth) / targetWidth);
            if (sx == sourceWidth) --sx;

            if (sx > psx) {
                colour = sourceLine[sx];
            }
            
            targetLine[x] = colour;
            psx = sx;
        }
    }

    return target;
}

void
Colour3DPlotRenderer::renderToCacheBinResolution(const LayerGeometryProvider *v,
                                                 int x0, int repaintWidth)
{
    Profiler profiler("Colour3DPlotRenderer::renderToCacheBinResolution");
#ifdef DEBUG_COLOUR_PLOT_REPAINT
    SVDEBUG << "render " << m_sources.source
            << ": [BIN] renderToCacheBinResolution" << endl;
#endif
    
    // Draw to the draw buffer, and then scale-copy from there. Draw
    // buffer is at bin resolution, i.e. buffer x == source column
    // number. We use toolkit smooth scaling for interpolation.

    auto model = ModelById::getAs<DenseThreeDimensionalModel>(m_sources.source);
    if (!model) return;

    // The draw buffer will contain a fragment at bin resolution. We
    // need to ensure that it starts and ends at points where a
    // time-bin boundary occurs at an exact pixel boundary, and with a
    // certain amount of overlap across existing pixels so that we can
    // scale and draw from it without smoothing errors at the edges.

    // If (getFrameForX(x) / increment) * increment ==
    // getFrameForX(x), then x is a time-bin boundary.  We want two
    // such boundaries at either side of the draw buffer -- one which
    // we draw up to, and one which we subsequently crop at.

    sv_frame_t leftBoundaryFrame = -1, leftCropFrame = -1;
    sv_frame_t rightBoundaryFrame = -1, rightCropFrame = -1;

    int binResolution;
    double renderBinResolution;
    if (!getBinResolutions(v, binResolution, renderBinResolution)) return;

    int drawBufferWidth;

    // These loops should eventually terminate provided that
    // getFrameForX always returns a multiple of the zoom level,
    // i.e. there is some x for which getFrameForX(x) == 0 and
    // subsequent return values are equally spaced

    int edgeBinResolution = int(round(renderBinResolution));
    
    for (int x = x0; ; --x) {
        sv_frame_t f = v->getFrameForX(x);
        if (sv_frame_t (f / edgeBinResolution) * edgeBinResolution == f) {
            if (leftCropFrame == -1) leftCropFrame = f;
            else if (x < x0 - 2) {
                leftBoundaryFrame = f;
                break;
            }
        }
    }
    
    for (int x = x0 + repaintWidth; ; ++x) {
        sv_frame_t f = v->getFrameForX(x);
        if (sv_frame_t (f / edgeBinResolution) * edgeBinResolution == f) {
            if (v->getXForFrame(f) < x0 + repaintWidth) {
                continue;
            }
            if (rightCropFrame == -1) rightCropFrame = f;
            else if (x > x0 + repaintWidth + 2) {
                rightBoundaryFrame = f;
                break;
            }
        }
    }

    drawBufferWidth = int
        ((rightBoundaryFrame - leftBoundaryFrame) / renderBinResolution);

//    SVCERR << "rightBoundaryFrame = " << rightBoundaryFrame << ", leftBoundaryFrame = " << leftBoundaryFrame << ", renderBinResolution = " << renderBinResolution << ", drawBufferWidth = " << drawBufferWidth << endl;
    
    int h = v->getPaintHeight();

    // For our purposes here, the draw buffer needs to be exactly our
    // target size (so we recreate always rather than just clear it)
    
    recreateDrawBuffer(drawBufferWidth, h);

    vector<int> binforx(drawBufferWidth);
    vector<double> binfory(h);
    
    for (int x = 0; x < drawBufferWidth; ++x) {
        binforx[x] = int(leftBoundaryFrame / renderBinResolution) + x;
    }

#ifdef DEBUG_COLOUR_PLOT_REPAINT
    SVDEBUG << "render " << m_sources.source
            << ": renderBinResolution " << renderBinResolution << endl;
    SVDEBUG << "zoomLevel = " << v->getRoundedZoomLevel()
            << ", drawBufferWidth = " << drawBufferWidth << endl;
#endif
    
    for (int y = 0; y < h; ++y) {
        binfory[y] = m_sources.verticalBinLayer->getBinForY(v, h - y - 1);
    }

    int fullResolutionCacheIndex = -1;

    // If there is a peak cache with divisor 1, use it in preference
    // to the original source - it's presumably quicker, otherwise our
    // caller wouldn't have provided it. If we don't find one,
    // fullResolutionCacheIndex will remain at -1 which indicates to
    // use the original source direct
    for (int ix = 0; in_range_for(m_sources.peakCaches, ix); ++ix) {
        auto peakCache = ModelById::getAs<Dense3DModelPeakCache>
            (m_sources.peakCaches[ix]);
        if (!peakCache) continue;
        int bpp = peakCache->getColumnsPerPeak();
        if (bpp == 1) {
            fullResolutionCacheIndex = ix;
            break;
        }
    }
    
    int attainedWidth = renderDrawBuffer(drawBufferWidth,
                                         h,
                                         binforx,
                                         binfory,
                                         fullResolutionCacheIndex,
                                         false,
                                         false);

#ifdef DEBUG_COLOUR_PLOT_REPAINT
    SVDEBUG << "renderToCacheBinResolution: attainedWidth = "
            << attainedWidth << endl;
#endif

    if (attainedWidth == 0) return;

    int scaledLeft = v->getXForFrame(leftBoundaryFrame);
    int scaledRight = v->getXForFrame(rightBoundaryFrame);

#ifdef DEBUG_COLOUR_PLOT_REPAINT
    SVDEBUG << "render " << m_sources.source
            << ": scaling draw buffer from width " << m_drawBuffer.width()
            << " to " << (scaledRight - scaledLeft)
            << " (nb drawBufferWidth = "
            << drawBufferWidth << ", attainedWidth = "
            << attainedWidth << ")" << endl;
#endif

    QImage scaled = scaleDrawBufferImage
        (m_drawBuffer, scaledRight - scaledLeft, h);
            
    int scaledLeftCrop = v->getXForFrame(leftCropFrame);
    int scaledRightCrop = v->getXForFrame(rightCropFrame);
    
    int targetLeft = scaledLeftCrop;
    if (targetLeft < 0) {
        targetLeft = 0;
    }
    
    int targetWidth = scaledRightCrop - targetLeft;
    if (targetLeft + targetWidth > m_cache.getSize().width()) {
        targetWidth = m_cache.getSize().width() - targetLeft;
    }
    
    int sourceLeft = targetLeft - scaledLeft;
    if (sourceLeft < 0) {
        sourceLeft = 0;
    }

#ifdef DEBUG_COLOUR_PLOT_REPAINT
    SVDEBUG << "render " << m_sources.source
            << ": leftBoundaryFrame = " << leftBoundaryFrame
            << ", leftCropFrame = " << leftCropFrame
            << ", scaledLeft = " << scaledLeft
            << ", scaledLeftCrop = " << scaledLeftCrop
            << endl;
    SVDEBUG << "render " << m_sources.source
            << ": rightBoundaryFrame = " << rightBoundaryFrame
            << ", rightCropFrame = " << rightCropFrame
            << ", scaledRight = " << scaledRight
            << ", scaledRightCrop = " << scaledRightCrop
            << endl;
#endif
    
#ifdef DEBUG_COLOUR_PLOT_REPAINT
    SVDEBUG << "render " << m_sources.source
            << ": x0 = " << x0
            << ", repaintWidth = " << repaintWidth
            << ", targetLeft = " << targetLeft 
            << ", targetWidth = " << targetWidth << endl;
#endif
    
    if (targetWidth > 0) {
        // we are copying from an image that has already been scaled,
        // hence using the same width in both geometries
        m_cache.drawImage(targetLeft, targetWidth,
                          scaled,
                          sourceLeft, targetWidth);
    }
    
    for (int i = 0; i < targetWidth; ++i) {
        // but the mag range vector has not been scaled
        int sourceIx = int((double(i + sourceLeft) / scaled.width())
                           * int(m_magRanges.size()));
        if (in_range_for(m_magRanges, sourceIx)) {
            m_magCache.sampleColumn(i, m_magRanges.at(sourceIx));
        }
    }
}

int
Colour3DPlotRenderer::renderDrawBuffer(int w, int h,
                                       const vector<int> &binforx,
                                       const vector<double> &binfory,
                                       int peakCacheIndex,
                                       bool rightToLeft,
                                       bool timeConstrained)
{
    // Callers must have checked that the appropriate subset of
    // Sources data members are set for the supplied flags (e.g. that
    // peakCache corresponding to peakCacheIndex exists)

    Profiler profiler("Colour3DPlotRenderer::renderDrawBuffer");
    
    int divisor = 1;

    std::shared_ptr<DenseThreeDimensionalModel> sourceModel;

    if (peakCacheIndex >= 0) {
        auto peakCache = ModelById::getAs<Dense3DModelPeakCache>
            (m_sources.peakCaches[peakCacheIndex]);
        if (peakCache) {
            divisor = peakCache->getColumnsPerPeak();
            sourceModel = peakCache;
        }
    }

    if (!sourceModel) {
        sourceModel = ModelById::getAs<DenseThreeDimensionalModel>
            (m_sources.source);
    }
    
    if (!sourceModel) return 0;

#ifdef DEBUG_COLOUR_PLOT_REPAINT
    SVDEBUG << "render " << m_sources.source
            << ": renderDrawBuffer: w = " << w << ", h = " << h
            << ", peakCacheIndex = " << peakCacheIndex << " (divisor = "
            << divisor << "), rightToLeft = " << rightToLeft
            << ", timeConstrained = " << timeConstrained << endl;
    SVDEBUG << "render " << m_sources.source
            << ": renderDrawBuffer: normalization = " << int(m_params.normalization)
            << ", binDisplay = " << int(m_params.binDisplay)
            << ", frequencyMapping = " << int(m_params.frequencyMapping)
            << ", opaque = " << m_params.opaque
            << ", interpolate = " << m_params.interpolate << endl;
    SVDEBUG << "render " << m_sources.source
            << ": using sourceModel of type " << sourceModel->getTypeName()
            << endl;
#endif
    
    int sh = sourceModel->getHeight();
    
    int minbin = int(binfory[0] + 0.0001);
    if (minbin >= sh) minbin = sh - 1;
    if (minbin < 0) minbin = 0;

    int nbins  = int(binfory[h-1] + 0.0001) - minbin + 1;
    if (minbin + nbins > sh) nbins = sh - minbin;

#ifdef DEBUG_COLOUR_PLOT_REPAINT
    SVDEBUG << "render " << m_sources.source
            << ": minbin = " << minbin << ", nbins = " << nbins
            << ", last binfory = " << binfory[h-1]
            << " (rounds to " << int(binfory[h-1])
            << ") (model height " << sh << ")" << endl;
#endif
    
    int psx = -1;

    int start = 0;
    int finish = w;
    int step = 1;

    if (rightToLeft) {
        start = w-1;
        finish = -1;
        step = -1;
    }

    int xPixelCount = 0;
    
    int modelWidth = sourceModel->getWidth();

    QRgb *target = reinterpret_cast<QRgb *>(m_drawBuffer.bits());
    int targetWidth = m_drawBuffer.width();
    
#ifdef DEBUG_COLOUR_PLOT_REPAINT
    SVDEBUG << "render " << m_sources.source
            << ": modelWidth " << modelWidth << ", divisor " << divisor << endl;
    SVDEBUG << "render " << m_sources.source
            << ": start = " << start << ", finish = " << finish << ", step = " << step << endl;
#endif

    ColumnOp::Column preparedColumn;
    ColumnOp::Column aggregateColumn(nbins, 0.f);
    ColumnOp::Column distributedColumn(h, 0.f);
    
    RenderTimer timer(timeConstrained ?
                      RenderTimer::FastRender :
                      RenderTimer::NoTimeout);

    for (int x = start; x != finish; x += step) {

//        Profiler profiler("Colour3DPlotRenderer::renderDrawBuffer: per-pixel stuff");
    
        // x is the on-canvas pixel coord; sx (later) will be the
        // source column index
        
        ++xPixelCount;
        
        if (binforx[x] < 0) {
#ifdef DEBUG_COLOUR_PLOT_REPAINT
            SVDEBUG << "binforx[" << x << "] == " << binforx[x] << ", skipping"
                    << endl;
#endif
            continue;
        }

        int sx0 = binforx[x] / divisor;
        int sx1 = sx0;
        if (x+1 < w) sx1 = binforx[x+1] / divisor;
        if (sx0 < 0) sx0 = sx1 - 1;
        if (sx0 < 0) continue;
        if (sx1 <= sx0) sx1 = sx0 + 1;

#ifdef DEBUG_COLOUR_PLOT_REPAINT
        SVDEBUG << "x = " << x << ", binforx[x] = " << binforx[x] << ", sx range " << sx0 << " -> " << sx1 << endl;
#endif

        MagnitudeRange &magRange = m_magRanges.at(x);
        bool haveAnything = false;
        
        for (int sx = sx0; sx < sx1; ++sx) {

            // sx is the source column index, and we are stepping
            // through the source columns that contribute to current
            // on-canvas pixel x

            if (sx < 0 || sx >= modelWidth) {
                continue;
            }

            if (sx != psx) { // psx is index of existing preparedColumn, or -1
                
                // order:
                // get column -> scale -> normalise -> record extents ->
                // peak pick -> distribute/interpolate -> apply display gain

                // this does the first three:
                preparedColumn = getColumn(sx, minbin, nbins, false, sourceModel);

                magRange.sample(preparedColumn);

#ifdef DEBUG_COLOUR_PLOT_REPAINT
                SVDEBUG << "at sx = " << sx << ", sampled column giving mag range now = " << magRange.getMin() << " -> " << magRange.getMax() << endl;
#endif
                
                if (m_params.binDisplay == BinDisplay::PeakBins) {
                    preparedColumn = ColumnOp::peakPick(preparedColumn);
                }

                // (Display gain belongs to the colour scale and is
                // applied by the colour scale object when mapping it)
                
                psx = sx;
            }

            if (sx == sx0) { // first source column for this pixel
                haveAnything = true;
                aggregateColumn = preparedColumn;

            } else { // second or subsequent source column for this pixel
                for (int i = 0; i < nbins; ++i) {
                    aggregateColumn[i] = std::max(aggregateColumn[i],
                                                  preparedColumn[i]);
                }
            }
        }

        if (!haveAnything) {
            for (int y = 0; y < h; ++y) {
                target[y * targetWidth + x] = m_colourmap.at(0);
            }
        } else {

            ColumnOp::distribute(distributedColumn,
                                 aggregateColumn,
                                 h,
                                 binfory,
                                 minbin,
                                 m_params.interpolate);

            if (m_params.invertVertical) {
                for (int y = 0; y < h; ++y) {
                    auto value = distributedColumn[y];
                    auto pixel = m_params.colourScale.getPixel(value);
                    target[y * targetWidth + x] = m_colourmap.at(pixel);
                }
            } else {
                for (int y = h-1; y >= 0; --y) {
                    auto value = distributedColumn[y];
                    auto pixel = m_params.colourScale.getPixel(value);
                    int py = h - y - 1;
                    target[py * targetWidth + x] = m_colourmap.at(pixel);
                }
            }
        }            
                
        if (timeConstrained && (xPixelCount % 16 == 0)) {
            double fractionComplete = double(xPixelCount) / double(w);
            if (timer.outOfTime(fractionComplete)) {
#ifdef DEBUG_COLOUR_PLOT_REPAINT
                SVCERR << "render " << m_sources.source
                       << ": out of time with xPixelCount = " << xPixelCount
                       << ", fractionComplete = " << fractionComplete << endl;
#endif
                updateTimings(timer, xPixelCount);
                return xPixelCount;
            }
        }
    }

    updateTimings(timer, xPixelCount);

#ifdef DEBUG_COLOUR_PLOT_REPAINT
    SVDEBUG << "render " << m_sources.source
            << ": completed with xPixelCount = " << xPixelCount << endl;
#endif
    return xPixelCount;
}

int
Colour3DPlotRenderer::renderDrawBufferPeakFrequencies(const LayerGeometryProvider *v,
                                                      int w, int h,
                                                      const vector<int> &binforx,
                                                      const vector<double> &binfory,
                                                      bool rightToLeft,
                                                      bool timeConstrained)
{
#ifdef DEBUG_COLOUR_PLOT_REPAINT
    SVDEBUG << "render " << m_sources.source
            << ": [PEAK] renderDrawBufferPeakFrequencies" << endl;
#endif

    // Callers must have checked that the appropriate subset of
    // Sources data members are set for the supplied flags (e.g. that
    // fft model exists)
    
    RenderTimer timer(timeConstrained ?
                      RenderTimer::SlowRender :
                      RenderTimer::NoTimeout);

    Profiler profiler("Colour3DPlotRenderer::renderDrawBufferPeakFrequencies");
    
    auto fft = ModelById::getAs<FFTModel>(m_sources.fft);
    if (!fft) return 0;

    int sh = fft->getHeight();
    
    int minbin = int(binfory[0] + 0.0001);
    if (minbin >= sh) minbin = sh - 1;
    if (minbin < 0) minbin = 0;

    int nbins  = int(binfory[h-1]) - minbin + 1;
    if (minbin + nbins > sh) nbins = sh - minbin;

    FFTModel::Peaks peakfreqs;

    int psx = -1;
    
    int start = 0;
    int finish = w;
    int step = 1;

    if (rightToLeft) {
        start = w-1;
        finish = -1;
        step = -1;
    }
    
    int xPixelCount = 0;
    
    ColumnOp::Column preparedColumn;

    int modelWidth = fft->getWidth();
#ifdef DEBUG_COLOUR_PLOT_REPAINT
    SVDEBUG << "render " << m_sources.source
            << ": modelWidth " << modelWidth << endl;
#endif
    
    double minFreq =
        (double(minbin) * fft->getSampleRate()) / fft->getFFTSize();
    double maxFreq =
        (double(minbin + nbins - 1) * fft->getSampleRate()) / fft->getFFTSize();

    QRgb *target = reinterpret_cast<QRgb *>(m_drawBuffer.bits());
    int targetWidth = m_drawBuffer.width();
    
#ifdef DEBUG_COLOUR_PLOT_REPAINT
    SVDEBUG << "render " << m_sources.source
            << ": start = " << start << ", finish = " << finish
            << ", step = " << step << endl;
#endif
    
    for (int x = start; x != finish; x += step) {
        
        // x is the on-canvas pixel coord; sx (later) will be the
        // source column index
        
        ++xPixelCount;
        
        if (binforx[x] < 0) continue;

        int sx0 = binforx[x];
        int sx1 = sx0;
        if (x+1 < w) sx1 = binforx[x+1];
        if (sx0 < 0) sx0 = sx1 - 1;
        if (sx0 < 0) continue;
        if (sx1 <= sx0) sx1 = sx0 + 1;

        ColumnOp::Column pixelPeakColumn;
        MagnitudeRange &magRange = m_magRanges.at(x);
        
        for (int sx = sx0; sx < sx1; ++sx) {

            // sx is the source column index, and we are stepping
            // through the source columns that contribute to current
            // on-canvas pixel x

            if (sx < 0 || sx >= modelWidth) {
                continue;
            }

            if (sx != psx) { // psx is index of existing preparedColumn, or -1

                // The model should use its cache (as normal) if we
                // are retrieving a column that will subsequently be
                // used for peak calculations
                bool shouldCache = (sx == sx0 || sx == sx0+1 || sx+1 == sx1);
                bool suppressCache = !shouldCache;
                
                preparedColumn = getColumn(sx, minbin, nbins, suppressCache, fft);
                magRange.sample(preparedColumn);
                psx = sx;
            }

            if (sx == sx0) {
                pixelPeakColumn = preparedColumn;
                peakfreqs = fft->getPeakFrequencies(FFTModel::AllPeaks, sx,
                                                    minbin, minbin + nbins - 1);
            } else {
                for (int i = 0; in_range_for(pixelPeakColumn, i); ++i) {
                    pixelPeakColumn[i] = std::max(pixelPeakColumn[i],
                                                  preparedColumn[i]);
                }
            }
        }

        if (!pixelPeakColumn.empty()) {

#ifdef DEBUG_COLOUR_PLOT_REPAINT
//            SVDEBUG << "found " << peakfreqs.size() << " peak freqs at column "
//                    << sx0 << endl;
#endif

            for (FFTModel::Peaks::const_iterator pi = peakfreqs.begin();
                 pi != peakfreqs.end(); ++pi) {

                int bin = pi->first;
                double freq = pi->second;

                if (bin < minbin) continue;
                if (bin >= minbin + nbins) break;
            
                double value = pixelPeakColumn[bin - minbin];
            
                double y = v->getYForFrequency
                    (freq, minFreq, maxFreq, m_params.frequencyMapping);
            
                int iy = int(y + 0.5);
                if (iy < 0 || iy >= h) continue;

                auto pixel = m_params.colourScale.getPixel(value);

#ifdef DEBUG_COLOUR_PLOT_REPAINT
//                SVDEBUG << "frequency " << freq << " for bin " << bin
//                        << " -> y = " << y << ", iy = " << iy << ", value = "
//                        << value << ", pixel " << pixel << "\n";
#endif

                target[iy * targetWidth + x] = m_colourmap.at(pixel);
            }

        } else {
#ifdef DEBUG_COLOUR_PLOT_REPAINT
            SVDEBUG << "render " << m_sources.source
                    << ": pixel peak column for range " << sx0 << " to " << sx1
                    << " is empty" << endl;
#endif
        }

        if (timeConstrained && x < (w*2)/3 && (xPixelCount % 16 == 0)) {
            double fractionComplete = double(xPixelCount) / double(w);
            if (timer.outOfTime(fractionComplete)) {
#ifdef DEBUG_COLOUR_PLOT_REPAINT
                SVCERR << "render " << m_sources.source
                       << ": out of time with fractionComplete = "
                       << fractionComplete << endl;
#endif
                updateTimings(timer, xPixelCount);
                return xPixelCount;
            }
        }
    }

    updateTimings(timer, xPixelCount);
    return xPixelCount;
}

void
Colour3DPlotRenderer::updateTimings(const RenderTimer &timer, int xPixelCount)
{
    double secondsPerXPixel = timer.secondsPerItem(xPixelCount);

    // valid if we have enough data points, or if the overall time is
    // massively slow anyway (as we definitely need to warn about that)
    bool valid = (xPixelCount > 20 || secondsPerXPixel > 0.01);

    if (valid) {
        m_secondsPerXPixel = secondsPerXPixel;
        m_secondsPerXPixelValid = true;
    
#ifdef DEBUG_COLOUR_PLOT_REPAINT
    SVCERR << "render " << m_sources.source
           << ": across " << xPixelCount
           << " x-pixels, seconds per x-pixel = "
           << m_secondsPerXPixel << " (total = "
           << (xPixelCount * m_secondsPerXPixel) << ")" << endl;
#endif
    }
}

void
Colour3DPlotRenderer::recreateDrawBuffer(int w, int h)
{
    if (m_drawBuffer.width() != w || m_drawBuffer.height() != h) {
        m_drawBuffer = QImage(w, h, QImage::Format_ARGB32);
    }
    m_drawBuffer.fill(Qt::transparent);
    m_magRanges = vector<MagnitudeRange>(w);
}

void
Colour3DPlotRenderer::clearDrawBuffer(int w, int h)
{
    if (m_drawBuffer.width() < w || m_drawBuffer.height() != h) {
        recreateDrawBuffer(w, h);
    } else {
        m_drawBuffer.fill(Qt::transparent);
        m_magRanges = vector<MagnitudeRange>(w);
    }
}

QRect
Colour3DPlotRenderer::findSimilarRegionExtents(QPoint p) const
{
    QImage image = m_cache.getImage();
    ImageRegionFinder finder;
    QRect rect = finder.findRegionExtents(&image, p);
    return rect;
}
} // end namespace sv