summaryrefslogtreecommitdiffstats
path: root/src/datavis3d/engine/q3dbars.cpp
blob: 89f49dea59ac0ed6423368fa467c4c800688184f (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
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
/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the documentation of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
**   * Redistributions of source code must retain the above copyright
**     notice, this list of conditions and the following disclaimer.
**   * Redistributions in binary form must reproduce the above copyright
**     notice, this list of conditions and the following disclaimer in
**     the documentation and/or other materials provided with the
**     distribution.
**   * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names
**     of its contributors may be used to endorse or promote products derived
**     from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "q3dbars.h"
#include "q3dbars_p.h"
#include "meshloader_p.h"
#include "vertexindexer_p.h"
#include "camerahelper_p.h"

#include <QMatrix4x4>
#include <QOpenGLShaderProgram>
#include <QScreen>
#include <QMouseEvent>

#include <qmath.h>

#include <QDebug>

QTCOMMERCIALDATAVIS3D_BEGIN_NAMESPACE

#define USE_HAX0R_SELECTION // keep this defined until the "real" method works

const float zComp = 3.0f; // Compensation for z position; move all objects to positive z, as shader can't handle negative values correctly

Q3DBars::Q3DBars()
    : d_ptr(new Q3DBarsPrivate(this))
{
}

Q3DBars::~Q3DBars()
{
    glDeleteBuffers(1, &d_ptr->m_vertexbuffer);
    glDeleteBuffers(1, &d_ptr->m_uvbuffer);
    glDeleteBuffers(1, &d_ptr->m_normalbuffer);
    glDeleteBuffers(1, &d_ptr->m_elementbuffer);

#ifndef USE_HAX0R_SELECTION
    glDeleteFramebuffers(1, &d_ptr->m_framebufferSelection);
    glDeleteTextures(1, &d_ptr->m_selectionTexture);
    glDeleteTextures(1, &d_ptr->m_depthTexture);
#endif

    glDeleteBuffers(1, &d_ptr->m_vertexbufferBackground);
    glDeleteBuffers(1, &d_ptr->m_uvbufferBackground);
    glDeleteBuffers(1, &d_ptr->m_normalbufferBackground);
    glDeleteBuffers(1, &d_ptr->m_elementbufferBackground);
}

void Q3DBars::initialize()
{
    // Initialize shaders
    if (!d_ptr->m_uniformColor) {
        d_ptr->initShaders(QStringLiteral(":/shaders/vertex")
                           , QStringLiteral(":/shaders/fragmentColorOnY"));
    }
    else {
        d_ptr->initShaders(QStringLiteral(":/shaders/vertex")
                           , QStringLiteral(":/shaders/fragment"));
    }
    d_ptr->initBackgroundShaders(QStringLiteral(":/shaders/vertex")
                                 , QStringLiteral(":/shaders/fragment"));
    d_ptr->initSelectionShader();

#ifndef USE_HAX0R_SELECTION
    // Init the selection buffer
    d_ptr->initSelectionBuffer();
#endif

    // Load default mesh
    d_ptr->loadBarMesh();

    // Load background mesh
    d_ptr->loadBackgroundMesh();

    // Set clear color
    glClearColor(0.0f, 0.0f, 0.0f, 1.0f);

    // Set OpenGL features
    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LESS);
    glEnable(GL_CULL_FACE);
    glCullFace(GL_BACK);

    // Set initial camera position
    // X must be 0 for rotation to work - we can use "setCameraRotation" for setting it later
    CameraHelper::setDefaultCameraOrientation(QVector3D(0.0f, 0.0f, 6.0f + zComp)
                                              , QVector3D(0.0f, 0.0f, zComp)
                                              , QVector3D(0.0f, 1.0f, 0.0f));

    CameraHelper::setCameraRotation(QPointF(d_ptr->m_horizontalRotation
                                            , d_ptr->m_verticalRotation));

    // Set view port
    glViewport(0, 0, width(), height());

    // Set initialized -flag
    d_ptr->m_isInitialized = true;
}

void Q3DBars::render()
{
    int startBar = 0;
    int stopBar = 0;
    int stepBar = 0;

    int startRow = 0;
    int stopRow = 0;
    int stepRow = 0;

    float backgroundRotation = 0;

    float barPos = 0;
    float rowPos = 0;

    static QVector3D selection = QVector3D(0, 0, 0);

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    QMatrix4x4 projectionMatrix;
    projectionMatrix.perspective(45.0f, (float)width() / (float)height(), 0.1f, 100.0f);

    QMatrix4x4 viewMatrix = CameraHelper::calculateViewMatrix(d_ptr->m_mousePos, d_ptr->m_zoomLevel
                                                              , width(), height());

    // Calculate drawing order
    //qDebug() << "viewMatrix z" << viewMatrix.row(0).z(); // jos negatiivinen, käännä bar -piirtojärjestys
    //qDebug() << "viewMatrix x" << viewMatrix.row(0).x(); // jos negatiivinen, käännä row -piirtojärjestys
    // TODO: Needs more tuning unless we get depth test working correctly
    if (viewMatrix.row(0).x() < 0) {
        startRow = 0;
        stopRow = d_ptr->m_sampleCount.y();
        stepRow = 1;
    }
    else {
        startRow = d_ptr->m_sampleCount.y() - 1;
        stopRow = -1;
        stepRow = -1;
    }
    if (viewMatrix.row(0).z() > 0) {
        startBar = 0;
        stopBar = d_ptr->m_sampleCount.x();
        stepBar = 1;
    }
    else {
        startBar = d_ptr->m_sampleCount.x() - 1;
        stopBar = -1;
        stepBar = -1;
    }

    // calculate background rotation based on view matrix rotation
    if (viewMatrix.row(0).x() >= 0 && viewMatrix.row(0).z() <= 0) {
        backgroundRotation = 270.0f;
    }
    else if (viewMatrix.row(0).x() > 0 && viewMatrix.row(0).z() > 0) {
        backgroundRotation = 180.0f;
    }
    else if (viewMatrix.row(0).x() <= 0 && viewMatrix.row(0).z() >= 0) {
        backgroundRotation = 90.0f;
    }
    else if (viewMatrix.row(0).x() < 0 && viewMatrix.row(0).z() < 0) {
        backgroundRotation = 0.0f;
    }

    // TODO: Rotate light with camera (position light a bit above camera)
    //QVector3D lightPos = QVector3D(0.0f, 2.0f, zComp); // above the center of bar chart
    QVector3D lightPos = QVector3D(0.5f, 3.0f, zComp * 2.5f);
//    QVector3D lightPos = QVector3D(0.0f, 1.5f, (d_ptr->m_sampleCount.y() / 2.0f));
//    QVector3D lightPos = QVector3D(0.0f, 2.0f, (float)qSqrt((float)d_ptr->m_sampleCount.y()/3.0f));
//    QVector3D lightPos = viewMatrix.row(0).toVector3D();
//    lightPos.setY(lightPos.y() + 3.0f);
//    qDebug() << lightPos;

    // Bind selection shader
    d_ptr->m_selectionShader->bind();

    // Draw bars to selection buffer
    glDisable(GL_DITHER); // disable dithering, it may affect colors if enabled
    for (int row = startRow; row != stopRow; row += stepRow) {
        for (int bar = startBar; bar != stopBar; bar += stepBar) {
            float barHeight = d_ptr->m_dataSet.at(row).at(bar);
            QMatrix4x4 modelMatrix;
            QMatrix4x4 MVPMatrix;
            barPos = (bar + 1) * (d_ptr->m_barSpacing.x());
            rowPos = (row + 1) * (d_ptr->m_barSpacing.y());
            modelMatrix.translate((d_ptr->m_rowWidth - barPos) / d_ptr->m_scaleFactorX
                                  , barHeight - 1.0f
                                  , (d_ptr->m_columnDepth - rowPos) / d_ptr->m_scaleFactorZ + zComp);
            modelMatrix.scale(QVector3D(d_ptr->m_scaleX, barHeight, d_ptr->m_scaleZ));

            MVPMatrix = projectionMatrix * viewMatrix * modelMatrix;

            // add +2 to avoid black
            QVector3D barColor = QVector3D((float)(row + 2) / (float)(d_ptr->m_sampleCount.y() + 2)
                                           , (float)(bar + 2) / (float)(d_ptr->m_sampleCount.x() + 2)
                                           , 0.0f);

            d_ptr->m_selectionShader->setUniformValue(d_ptr->m_mvpMatrixUniformSelection
                                                      , MVPMatrix);
            d_ptr->m_selectionShader->setUniformValue(d_ptr->m_colorUniformSelection
                                                      , barColor);

#ifdef USE_HAX0R_SELECTION
            // 1st attribute buffer : vertices
            glBindBuffer(GL_ARRAY_BUFFER, d_ptr->m_vertexbuffer);
            glVertexAttribPointer(d_ptr->m_positionAttrSelection
                                  , 3, GL_FLOAT, GL_FALSE, 0, (void*)0);

            // Index buffer
            glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, d_ptr->m_elementbuffer);

            glEnableVertexAttribArray(0);

            // Draw the triangles
            glDrawElements(GL_TRIANGLES, d_ptr->m_indexCount, GL_UNSIGNED_SHORT, (void*)0);

            glDisableVertexAttribArray(0);
#else // TODO: fix this - doesn't work yet
            glBindFramebuffer(GL_FRAMEBUFFER, d_ptr->m_framebufferSelection);
            //glReadBuffer(GL_COLOR_ATTACHMENT0);

            // 1st attribute buffer : vertices
            glEnableVertexAttribArray(0);
            glBindBuffer(GL_ARRAY_BUFFER, d_ptr->m_vertexbuffer);
            glVertexAttribPointer(d_ptr->m_positionAttrSelection
                                  , 3, GL_FLOAT, GL_FALSE, 0, (void*)0);

            // Index buffer
            glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, d_ptr->m_elementbuffer);

            // Draw the triangles
            GLenum DrawBuffers[1] = {GL_COLOR_ATTACHMENT0};
            glDrawElements(GL_TRIANGLES, d_ptr->m_indexCount, GL_UNSIGNED_SHORT, DrawBuffers);

            glDisableVertexAttribArray(0);

            //glReadBuffer(GL_NONE);
            glBindFramebuffer(GL_FRAMEBUFFER, 0);
#endif
        }
    }
    glEnable(GL_DITHER);

    // Read color under cursor
    // TODO: Move into a separate function?
    if (d_ptr->m_mousePressed) {
#ifndef USE_HAX0R_SELECTION
        glBindFramebuffer(GL_FRAMEBUFFER, d_ptr->m_framebufferSelection);
#endif
        // This is the only one that works with ANGLE (ES 2.0)
        // Item count will be limited to 256*256*256
        GLubyte pixel[4];
        glReadPixels(d_ptr->m_mousePos.x(), height() - d_ptr->m_mousePos.y(), 1, 1,
                     GL_RGBA, GL_UNSIGNED_BYTE, (void *)pixel);

        // These work with desktop OpenGL
        // They offer a lot higher possible object count and a possibility to use object id's
        //GLuint pixel2[3];
        //glReadPixels(d_ptr->m_mousePos.x(), height() - d_ptr->m_mousePos.y(), 1, 1,
        //             GL_RGB, GL_UNSIGNED_INT, (void *)pixel2);

        //GLfloat pixel3[3];
        //glReadPixels(d_ptr->m_mousePos.x(), height() - d_ptr->m_mousePos.y(), 1, 1,
        //             GL_RGB, GL_FLOAT, (void *)pixel3);

        //qDebug() << "rgba" << pixel[0] << pixel[1] << pixel[2];// << pixel[3];
        //qDebug() << "rgba2" << pixel2[0] << pixel2[1] << pixel2[2];
        //qDebug() << "rgba3" << pixel3[0] << pixel3[1] << pixel3[2];
        selection = QVector3D(pixel[0], pixel[1], pixel[2]);
        //qDebug() << selection;
#ifndef USE_HAX0R_SELECTION
        glBindFramebuffer(GL_FRAMEBUFFER, 0);
#endif
    }

    // Release selection shader
    d_ptr->m_selectionShader->release();

#if 1
    // Clear after selection
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    // Bind background shader
    d_ptr->m_backgroundShader->bind();

    // Draw background
    if (d_ptr->m_background) {
        QMatrix4x4 modelMatrix;
        QMatrix4x4 MVPMatrix;
        if (zComp != 0)
            modelMatrix.translate(0.0f, 0.0f, zComp);
        modelMatrix.scale(QVector3D(d_ptr->m_rowWidth * d_ptr->m_sceneScale
                                    , 1.0f
                                    , d_ptr->m_columnDepth * d_ptr->m_sceneScale));
        modelMatrix.rotate(backgroundRotation, 0.0f, 1.0f, 0.0f);

        MVPMatrix = projectionMatrix * viewMatrix * modelMatrix;

        QVector3D backgroundColor = QVector3D(0.75, 0.75, 0.75);

        d_ptr->m_backgroundShader->setUniformValue(d_ptr->m_lightPositionUniformBackground
                                                   , lightPos);
        d_ptr->m_backgroundShader->setUniformValue(d_ptr->m_viewMatrixUniformBackground
                                                   , viewMatrix);
        d_ptr->m_backgroundShader->setUniformValue(d_ptr->m_modelMatrixUniformBackground
                                                   , modelMatrix);
        d_ptr->m_backgroundShader->setUniformValue(d_ptr->m_invTransModelMatrixUniformBackground
                                                   , modelMatrix.inverted().transposed());
        d_ptr->m_backgroundShader->setUniformValue(d_ptr->m_mvpMatrixUniformBackground
                                                   , MVPMatrix);
        d_ptr->m_backgroundShader->setUniformValue(d_ptr->m_colorUniformBackground
                                                   , backgroundColor);
        d_ptr->m_backgroundShader->setUniformValue(d_ptr->m_lightStrengthUniformBackground
                                                   , 4.0f);

        // 1st attribute buffer : vertices
        glEnableVertexAttribArray(0);
        glBindBuffer(GL_ARRAY_BUFFER, d_ptr->m_vertexbufferBackground);
        glVertexAttribPointer(d_ptr->m_positionAttrBackground, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);

        // 2nd attribute buffer : normals
        glEnableVertexAttribArray(1); // this causes trouble with desktop opengl, but ANGLE requires it
        glBindBuffer(GL_ARRAY_BUFFER, d_ptr->m_normalbufferBackground);
        glVertexAttribPointer(d_ptr->m_normalAttrBackground, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);

        // 3rd attribute buffer : UVs
        //glEnableVertexAttribArray(2);
        //glBindBuffer(GL_ARRAY_BUFFER, d_ptr->m_uvbufferBackground);
        //glVertexAttribPointer(d_ptr->m_uvAttrBackground, 2, GL_FLOAT, GL_FALSE, 0, (void*)0);

        // Index buffer
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, d_ptr->m_elementbufferBackground);

        // Draw the triangles
        glDrawElements(GL_TRIANGLES, d_ptr->m_indexCountBackground, GL_UNSIGNED_SHORT, (void*)0);

        //glDisableVertexAttribArray(2);
        glDisableVertexAttribArray(1); // this causes trouble with desktop opengl, but ANGLE requires it
        glDisableVertexAttribArray(0);
    }

    // Release background shader
    d_ptr->m_backgroundShader->release();

    // Bind bar shader
    d_ptr->m_barShader->bind();

    // Draw bars
    int barIndex = 1; // TODO: Remove when done debugging
    for (int row = startRow; row != stopRow; row += stepRow) {
        for (int bar = startBar; bar != stopBar; bar += stepBar) {
            float barHeight = d_ptr->m_dataSet.at(row).at(bar);
            //qDebug() << "barHeight" << barHeight;
            QMatrix4x4 modelMatrix;
            QMatrix4x4 MVPMatrix;
            barPos = (bar + 1) * (d_ptr->m_barSpacing.x());
            //qDebug() << "x" << d_ptr->m_rowWidth << "-" << barPos << "=" << d_ptr->m_rowWidth - barPos;
            rowPos = (row + 1) * (d_ptr->m_barSpacing.y());
            //qDebug() << "z" << rowPos << "-" << d_ptr->m_columnDepth << "=" << rowPos - d_ptr->m_columnDepth;
            modelMatrix.translate((d_ptr->m_rowWidth - barPos) / d_ptr->m_scaleFactorX
                                  , barHeight - 1.0f
                                  , (d_ptr->m_columnDepth - rowPos) / d_ptr->m_scaleFactorZ + zComp);
            modelMatrix.scale(QVector3D(d_ptr->m_scaleX, barHeight, d_ptr->m_scaleZ));

            MVPMatrix = projectionMatrix * viewMatrix * modelMatrix;

            //qDebug() << "modelMatrix" << modelMatrix;
            //qDebug() << "MVPMatrix" << MVPMatrix;

            QVector3D baseColor = QVector3D(d_ptr->m_baseColor.redF()
                                            , d_ptr->m_baseColor.greenF()
                                            , d_ptr->m_baseColor.blueF());
            QVector3D heightColor = QVector3D(d_ptr->m_heightColor.redF()
                                              , d_ptr->m_heightColor.greenF()
                                              , d_ptr->m_heightColor.blueF())
                    * barHeight;
            QVector3D depthColor = QVector3D(d_ptr->m_depthColor.redF()
                                             , d_ptr->m_depthColor.greenF()
                                             , d_ptr->m_depthColor.blueF())
                    * (float(row) / float(d_ptr->m_sampleCount.y()));

            QVector3D barColor = baseColor + heightColor + depthColor;

            float lightStrength = 5.0f;
            // TODO: Make highlightings modifiable via API (highlight row & column, or just bar)
            Q3DBarsPrivate::SelectionType selectionType = d_ptr->isSelected(row, bar, selection);
            switch (selectionType) {
            case Q3DBarsPrivate::Bar:
            {
                // highlight bar by inverting the color of the bar
                barColor = QVector3D(1.0f, 1.0f, 1.0f) - barColor;
                lightStrength = 10.0f;
                if (d_ptr->m_mousePressed) {
                    qDebug() << "selected object:" << barIndex << "( row:" << row + 1 << ", column:" << bar + 1 << ")";
                    qDebug() << barIndex << "object position:" << modelMatrix.column(3).toVector3D();
                    //qDebug() << "light position:" << lightPos;
                }
                break;
            }
            case Q3DBarsPrivate::Row:
            {
                // Current bar is on the same row as the selected bar
                barColor = QVector3D(1.0f, 1.0f, 1.0f) - barColor;
                lightStrength = 0.1f;
                break;
            }
            case Q3DBarsPrivate::Column:
            {
                // Current bar is on the same column as the selected bar
                barColor = QVector3D(1.0f, 1.0f, 1.0f) - barColor;
                lightStrength = 0.1f;
                break;
            }
            }

            if (d_ptr->m_mousePressed) {
                //qDebug() << "baseColor:" << baseColor;
                //qDebug() << "heightColor:" << heightColor;
                //qDebug() << "depthColor:" << depthColor;
                //qDebug() << "barColor:" << barColor;
                //qDebug() << barIndex << "object position:" << modelMatrix.column(3).toVector3D();
            }
            barIndex++; // TODO: Remove when done debugging

            d_ptr->m_barShader->setUniformValue(d_ptr->m_lightPositionUniform, lightPos);
            d_ptr->m_barShader->setUniformValue(d_ptr->m_viewMatrixUniform, viewMatrix);
            d_ptr->m_barShader->setUniformValue(d_ptr->m_modelMatrixUniform, modelMatrix);
            d_ptr->m_barShader->setUniformValue(d_ptr->m_invTransModelMatrixUniform
                                                , modelMatrix.inverted().transposed());
            d_ptr->m_barShader->setUniformValue(d_ptr->m_mvpMatrixUniform, MVPMatrix);
            d_ptr->m_barShader->setUniformValue(d_ptr->m_colorUniform, barColor);
            d_ptr->m_barShader->setUniformValue(d_ptr->m_lightStrengthUniform, lightStrength);
            //qDebug() << "height:" << barHeight;

            // 1st attribute buffer : vertices
            glEnableVertexAttribArray(0);
            glBindBuffer(GL_ARRAY_BUFFER, d_ptr->m_vertexbuffer);
            glVertexAttribPointer(d_ptr->m_positionAttr, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);

            // 2nd attribute buffer : normals
            glEnableVertexAttribArray(1); // this causes trouble with desktop opengl, but ANGLE requires it
            glBindBuffer(GL_ARRAY_BUFFER, d_ptr->m_normalbuffer);
            glVertexAttribPointer(d_ptr->m_normalAttr, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);

            // 3rd attribute buffer : UVs
            //glEnableVertexAttribArray(2);
            //glBindBuffer(GL_ARRAY_BUFFER, d_ptr->m_uvbuffer);
            //glVertexAttribPointer(d_ptr->m_uvAttr, 2, GL_FLOAT, GL_FALSE, 0, (void*)0);

            // Index buffer
            glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, d_ptr->m_elementbuffer);

            // Draw the triangles
            glDrawElements(GL_TRIANGLES, d_ptr->m_indexCount, GL_UNSIGNED_SHORT, (void*)0);

            //glDisableVertexAttribArray(2);
            glDisableVertexAttribArray(1); // this causes trouble with desktop opengl, but ANGLE requires it
            glDisableVertexAttribArray(0);
        }
    }

    // Release bar shader
    d_ptr->m_barShader->release();
#endif
}

void Q3DBars::mousePressEvent(QMouseEvent *event)
{
    // TODO: for testing shaders
    static int shaderNo = 1;
    //qDebug() << "mouse button pressed" << event->button();
    if (Qt::LeftButton == event->button()) {
        d_ptr->m_mousePressed = true;
        // update mouse positions to prevent jumping when releasing or repressing a button
        d_ptr->m_mousePos = event->pos();
    }
    else if (Qt::RightButton == event->button()) {
        // reset rotations
        d_ptr->m_mousePos = QPoint(0, 0);
    }
    else if (Qt::MiddleButton == event->button()) {
        // TODO: testing shaders
        if (++shaderNo > 3)
            shaderNo = 1;
        switch (shaderNo) {
        case 1:
            d_ptr->initShaders(QStringLiteral(":/shaders/vertex")
                               , QStringLiteral(":/shaders/fragment"));
            break;
        case 2:
            d_ptr->initShaders(QStringLiteral(":/shaders/vertex")
                               , QStringLiteral(":/shaders/fragmentColorOnY"));
            break;
        case 3:
            d_ptr->initShaders(QStringLiteral(":/shaders/vertex")
                               , QStringLiteral(":/shaders/fragmentAmbient"));
            break;
        }
    }
    CameraHelper::updateMousePos(d_ptr->m_mousePos);
}

void Q3DBars::mouseReleaseEvent(QMouseEvent *event)
{
    //qDebug() << "mouse button released" << event->button();
    d_ptr->m_mousePressed = false;
    // update mouse positions to prevent jumping when releasing or repressing a button
    d_ptr->m_mousePos = event->pos();
    CameraHelper::updateMousePos(event->pos());
}

void Q3DBars::mouseMoveEvent(QMouseEvent *event)
{
    if (d_ptr->m_mousePressed) {
        //qDebug() << "mouse moved while pressed" << event->pos();
        d_ptr->m_mousePos = event->pos();
    }
#if 0
    // TODO: Testi - laske kursorin sijainti scenessä
    QPointF mouse3D((2.0f * event->pos().x() - width()) / height()
                    , 1.0f - (2.0f * event->pos().y()) / height());
    //qDebug() << "mouse position in scene" << mouse3D;

    // TODO: Testi laske focal point
    float focalPoint = tan(45.0f / 2.0f);

    // TODO: Testi - laske viewmatriisin kerroin
    QVector3D worldRay = QVector3D(0.0f, 0.0f, 0.0f)
            - QVector3D(mouse3D.x(), mouse3D.y(), -focalPoint);
    //qDebug() << "worldRay" << worldRay;
    // multiply viewmatrix with this to get something?
#endif
}

void Q3DBars::wheelEvent(QWheelEvent *event)
{
    if (d_ptr->m_zoomLevel > 100) {
        d_ptr->m_zoomLevel += event->angleDelta().y() / 12;
    }
    else if (d_ptr->m_zoomLevel > 50) {
        d_ptr->m_zoomLevel += event->angleDelta().y() / 60;
    }
    else {
        d_ptr->m_zoomLevel += event->angleDelta().y() / 120;
    }
    if (d_ptr->m_zoomLevel > 500) {
        d_ptr->m_zoomLevel = 500;
    }
    else if (d_ptr->m_zoomLevel < 10) {
        d_ptr->m_zoomLevel = 10;
    }
}

void Q3DBars::resizeEvent(QResizeEvent *event)
{
    Q_UNUSED(event);

    // Set view port
    glViewport(0, 0, width(), height());

    // If orientation changes, we need to scale again
    // TODO: Handle it
}

void Q3DBars::setBarSpecs(QPointF thickness, QPointF spacing, bool relative)
{
    d_ptr->m_barThickness = thickness;
    if (relative) {
        d_ptr->m_barSpacing.setX((thickness.x() * 2) * (spacing.x() + 1.0f));
        d_ptr->m_barSpacing.setY((thickness.y() * 2) * (spacing.y() + 1.0f));
    }
    else {
        d_ptr->m_barSpacing = thickness * 2 + spacing * 2;
    }
    // Calculate here and at setting sample space
    d_ptr->calculateSceneScalingFactors();
}

void Q3DBars::setBarType(BarStyle style, bool smooth)
{
    if (style == Bars) {
        if (smooth) {
            d_ptr->m_objFile = QStringLiteral(":/defaultMeshes/barSmooth");
        }
        else {
            d_ptr->m_objFile = QStringLiteral(":/defaultMeshes/bar");
        }
    }
    else if (style == Pyramids) {
        if (smooth) {
            d_ptr->m_objFile = QStringLiteral(":/defaultMeshes/pyramidSmooth");
        }
        else {
            d_ptr->m_objFile = QStringLiteral(":/defaultMeshes/pyramid");
        }
    }
    else if (style == Cones) {
        if (smooth) {
            d_ptr->m_objFile = QStringLiteral(":/defaultMeshes/coneSmooth");
        }
        else {
            d_ptr->m_objFile = QStringLiteral(":/defaultMeshes/cone");
        }
    }
    else if (style == Cylinders) {
        if (smooth) {
            d_ptr->m_objFile = QStringLiteral(":/defaultMeshes/cylinderSmooth");
        }
        else {
            d_ptr->m_objFile = QStringLiteral(":/defaultMeshes/cylinder");
        }
    }
    if (d_ptr->m_isInitialized) {
        // Reload mesh data
        d_ptr->loadBarMesh();
    }
}

void Q3DBars::setMeshFileName(const QString &objFileName)
{
    d_ptr->m_objFile = objFileName;
}

void Q3DBars::setupSampleSpace(QPoint sampleCount)
{
    d_ptr->m_sampleCount = sampleCount;
    // Initialize data set
    QVector<float> row;
    for (int columns = 0; columns < sampleCount.x(); columns ++) {
        row.append(0.0f);
    }
    for (int rows = 0; rows < sampleCount.y(); rows++) {
        d_ptr->m_dataSet.append(row);
    }
    // TODO: Invent "idiotproof" max scene size formula..
    // This seems to work ok if spacing is not negative
    d_ptr->m_maxSceneSize = 2 * qSqrt(sampleCount.x() * sampleCount.y());
    //qDebug() << "maxSceneSize" << d_ptr->m_maxSceneSize;
    // Calculate here and at setting bar specs
    d_ptr->calculateSceneScalingFactors();
}

void Q3DBars::setCameraPosition(float horizontal, float vertical, int distance)
{
    d_ptr->m_horizontalRotation = qBound(-180.0f, horizontal, 180.0f);
    d_ptr->m_verticalRotation = qBound(0.0f, vertical, 90.0f);
    d_ptr->m_zoomLevel = qBound(10, distance, 500);
    CameraHelper::setCameraRotation(QPointF(d_ptr->m_horizontalRotation
                                            , d_ptr->m_verticalRotation));
    qDebug() << "camera rotation set to" << d_ptr->m_horizontalRotation << d_ptr->m_verticalRotation;
}

void Q3DBars::setBarColor(QColor baseColor, QColor heightColor, QColor depthColor, bool uniform)
{
    d_ptr->m_baseColor = baseColor;
    d_ptr->m_heightColor = heightColor;
    d_ptr->m_depthColor = depthColor;
    //qDebug() << "colors:" << d_ptr->m_baseColor << d_ptr->m_heightColor << d_ptr->m_depthColor;
    d_ptr->m_uniformColor = uniform;
}

void Q3DBars::addDataRow(const QVector<float> &dataRow)
{
    QVector<float> row = dataRow;
    // Check that the input data fits into sample space, and resize if it doesn't
    if (row.size() > d_ptr->m_sampleCount.x()) {
        row.resize(d_ptr->m_sampleCount.x());
        qWarning("Data set too large for sample space");
    }
    // The vector contains data (=height) for each bar, a row at a time
    // With each new row, the previous data set (=row) must be moved back
    // ie. we need as many vectors as we have rows in the sample space
    d_ptr->m_dataSet.prepend(row);
    // if the added data pushed us over sample space, remove the oldest data set
    if (d_ptr->m_dataSet.size() > d_ptr->m_sampleCount.y())
        d_ptr->m_dataSet.resize(d_ptr->m_sampleCount.y());
}

void Q3DBars::addDataSet(const QVector< QVector<float> > &data)
{
    d_ptr->m_dataSet.clear();
    // Check sizes
    if (data.at(0).size() > d_ptr->m_sampleCount.x()) {
        qCritical("Too much data per row, aborting");
        return;
    }
    d_ptr->m_dataSet = data;
    if (d_ptr->m_dataSet.size() > d_ptr->m_sampleCount.y()) {
        qWarning("Data set too large for sample space. Cropping it to fit.");
        d_ptr->m_dataSet.resize(d_ptr->m_sampleCount.y());
    }
}

Q3DBarsPrivate::Q3DBarsPrivate(Q3DBars *q)
    : q_ptr(q)
    , m_barShader(0)
    , m_selectionShader(0)
    , m_backgroundShader(0)
    , m_sampleCount(QPoint(0, 0))
    , m_objFile(QStringLiteral(":/defaultMeshes/bar"))
    , m_vertexCount(0)
    , m_indexCount(0)
    , m_indexCountBackground(0)
    , m_mousePressed(false)
    , m_mousePos(QPoint(0, 0))
    , m_zoomLevel(100)
    , m_horizontalRotation(-45.0f)
    , m_verticalRotation(15.0f)
    , m_barThickness(QPointF(0.75f, 0.75f))
    , m_barSpacing(m_barThickness * 3.0f)
    , m_meshDataLoaded(false)
    , m_background(false)
    , m_dataSet(0)
    , m_rowWidth(0)
    , m_columnDepth(0)
    , m_maxDimension(0)
    , m_scaleX(0)
    , m_scaleZ(0)
    , m_scaleFactorX(0)
    , m_scaleFactorZ(0)
    , m_sceneScale(0)
    , m_maxSceneSize(40.0)
    , m_baseColor(QColor(Qt::gray))
    , m_heightColor(QColor(Qt::white))
    , m_depthColor(QColor(Qt::darkGray))
    , m_uniformColor(true)
    , m_isInitialized(false)
{
}

Q3DBarsPrivate::~Q3DBarsPrivate()
{
}

void Q3DBarsPrivate::loadBarMesh()
{
    if (m_meshDataLoaded) {
        // Delete old data
        q_ptr->glDeleteBuffers(1, &m_vertexbuffer);
        q_ptr->glDeleteBuffers(1, &m_uvbuffer);
        q_ptr->glDeleteBuffers(1, &m_normalbuffer);
        q_ptr->glDeleteBuffers(1, &m_elementbuffer);
    }
    QVector<QVector3D> vertices;
    QVector<QVector2D> uvs;
    QVector<QVector3D> normals;
    bool loadOk = MeshLoader::loadOBJ(m_objFile, vertices, uvs, normals);
    if (!loadOk)
        qFatal("loading failed");

    m_vertexCount = vertices.size();
    qDebug() << "vertex count" << m_vertexCount;

    // Index vertices
    QVector<unsigned short> indices;
    QVector<QVector3D> indexed_vertices;
    QVector<QVector2D> indexed_uvs;
    QVector<QVector3D> indexed_normals;
    VertexIndexer::indexVBO(vertices, uvs, normals, indices, indexed_vertices, indexed_uvs
                            , indexed_normals);

    m_indexCount = indices.size();
    //qDebug() << "index count" << m_indexCount;

    q_ptr->glGenBuffers(1, &m_vertexbuffer);
    q_ptr->glBindBuffer(GL_ARRAY_BUFFER, m_vertexbuffer);
    q_ptr->glBufferData(GL_ARRAY_BUFFER, indexed_vertices.size() * sizeof(QVector3D)
                        , &indexed_vertices.at(0)
                        , GL_STATIC_DRAW);

    q_ptr->glGenBuffers(1, &m_normalbuffer);
    q_ptr->glBindBuffer(GL_ARRAY_BUFFER, m_normalbuffer);
    q_ptr->glBufferData(GL_ARRAY_BUFFER, indexed_normals.size() * sizeof(QVector3D)
                        , &indexed_normals.at(0)
                        , GL_STATIC_DRAW);

    //q_ptr->glGenBuffers(1, &m_uvbuffer);
    //q_ptr->glBindBuffer(GL_ARRAY_BUFFER, m_uvbuffer);
    //q_ptr->glBufferData(GL_ARRAY_BUFFER, indexed_uvs.size() * sizeof(QVector2D), &indexed_uvs.at(0)
    //        , GL_STATIC_DRAW);

    q_ptr->glGenBuffers(1, &m_elementbuffer);
    q_ptr->glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_elementbuffer);
    q_ptr->glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned short), &indices.at(0)
                        , GL_STATIC_DRAW);

    m_meshDataLoaded = true;
}

void Q3DBarsPrivate::loadBackgroundMesh()
{
    QVector<QVector3D> vertices;
    QVector<QVector2D> uvs;
    QVector<QVector3D> normals;
    bool loadOk = MeshLoader::loadOBJ(QStringLiteral(":/defaultMeshes/background")
                                      , vertices, uvs, normals);
    if (!loadOk)
        qFatal("loading failed");

    // Index vertices
    QVector<unsigned short> indices;
    QVector<QVector3D> indexed_vertices;
    QVector<QVector2D> indexed_uvs;
    QVector<QVector3D> indexed_normals;
    VertexIndexer::indexVBO(vertices, uvs, normals, indices, indexed_vertices, indexed_uvs
                            , indexed_normals);

    m_indexCountBackground = indices.size();

    q_ptr->glGenBuffers(1, &m_vertexbufferBackground);
    q_ptr->glBindBuffer(GL_ARRAY_BUFFER, m_vertexbufferBackground);
    q_ptr->glBufferData(GL_ARRAY_BUFFER, indexed_vertices.size() * sizeof(QVector3D)
                        , &indexed_vertices.at(0)
                        , GL_STATIC_DRAW);

    q_ptr->glGenBuffers(1, &m_normalbufferBackground);
    q_ptr->glBindBuffer(GL_ARRAY_BUFFER, m_normalbufferBackground);
    q_ptr->glBufferData(GL_ARRAY_BUFFER, indexed_normals.size() * sizeof(QVector3D)
                        , &indexed_normals.at(0)
                        , GL_STATIC_DRAW);

    //q_ptr->glGenBuffers(1, &m_uvbufferBackground);
    //q_ptr->glBindBuffer(GL_ARRAY_BUFFER, m_uvbufferBackground);
    //q_ptr->glBufferData(GL_ARRAY_BUFFER, indexed_uvs.size() * sizeof(QVector2D), &indexed_uvs.at(0)
    //        , GL_STATIC_DRAW);

    q_ptr->glGenBuffers(1, &m_elementbufferBackground);
    q_ptr->glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_elementbufferBackground);
    q_ptr->glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned short), &indices.at(0)
                        , GL_STATIC_DRAW);

    m_background = true;
}

void Q3DBarsPrivate::initShaders(const QString &vertexShader, const QString &fragmentShader)
{
    if (m_barShader)
        delete m_barShader;
    m_barShader = new QOpenGLShaderProgram(q_ptr);
    if (!m_barShader->addShaderFromSourceFile(QOpenGLShader::Vertex, vertexShader))
        qFatal("Compiling Vertex shader failed");
    if (!m_barShader->addShaderFromSourceFile(QOpenGLShader::Fragment, fragmentShader))
        qFatal("Compiling Fragment shader failed");
    m_barShader->link();
    m_mvpMatrixUniform = m_barShader->uniformLocation("MVP");
    m_viewMatrixUniform = m_barShader->uniformLocation("V");
    m_modelMatrixUniform = m_barShader->uniformLocation("M");
    m_invTransModelMatrixUniform = m_barShader->uniformLocation("itM");
    m_positionAttr = m_barShader->attributeLocation("vertexPosition_mdl");
    m_uvAttr = m_barShader->attributeLocation("vertexUV");
    m_normalAttr = m_barShader->attributeLocation("vertexNormal_mdl");
    m_lightPositionUniform = m_barShader->uniformLocation("lightPosition_wrld");
    m_colorUniform = m_barShader->uniformLocation("color_mdl");
    m_lightStrengthUniform = m_barShader->uniformLocation("lightStrength");
}

void Q3DBarsPrivate::initSelectionShader()
{
    m_selectionShader = new QOpenGLShaderProgram(q_ptr);
    if (!m_selectionShader->addShaderFromSourceFile(QOpenGLShader::Vertex
                                                    , QStringLiteral(":/shaders/vertexSelection")))
        qFatal("Compiling Vertex shader failed");
    if (!m_selectionShader->addShaderFromSourceFile(QOpenGLShader::Fragment
                                                    , QStringLiteral(":/shaders/fragmentSelection")))
        qFatal("Compiling Fragment shader failed");
    m_selectionShader->link();
    m_mvpMatrixUniformSelection = m_selectionShader->uniformLocation("MVP");
    m_colorUniformSelection = m_selectionShader->uniformLocation("color_mdl");
    m_positionAttrSelection = m_selectionShader->attributeLocation("vertexPosition_mdl");
}

void Q3DBarsPrivate::initSelectionBuffer()
{
#if 0
    // Create frame buffer object
    q_ptr->glGenFramebuffers(1, &m_framebufferSelection);
    q_ptr->glBindFramebuffer(GL_FRAMEBUFFER, m_framebufferSelection);

    // Create texture object for the primitive information buffer
    q_ptr->glGenTextures(1, &m_selectionTexture);
    q_ptr->glBindTexture(GL_TEXTURE_2D, m_selectionTexture);
    q_ptr->glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, q_ptr->width(), q_ptr->height(),
                        0, GL_RGB, GL_UNSIGNED_BYTE, NULL);
    q_ptr->glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
                                  m_selectionTexture, 0);

    // Create texture object for the depth buffer
    q_ptr->glGenTextures(1, &m_depthTexture);
    q_ptr->glBindTexture(GL_TEXTURE_2D, m_depthTexture);
    q_ptr->glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, q_ptr->width(), q_ptr->height(),
                        0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL);
    q_ptr->glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D,
                                  m_depthTexture, 0);

    // Verify that the frame buffer is complete
    GLenum status = q_ptr->glCheckFramebufferStatus(GL_FRAMEBUFFER);

    if (status != GL_FRAMEBUFFER_COMPLETE) {
        qCritical() << "Frame buffer creation failed" << status;
        return;
    }

    // Restore the default framebuffer
    q_ptr->glBindTexture(GL_TEXTURE_2D, 0);
    q_ptr->glBindFramebuffer(GL_FRAMEBUFFER, 0);
#endif
}

void Q3DBarsPrivate::initBackgroundShaders(const QString &vertexShader
                                           , const QString &fragmentShader)
{
    if (m_backgroundShader)
        delete m_backgroundShader;
    m_backgroundShader = new QOpenGLShaderProgram(q_ptr);
    if (!m_backgroundShader->addShaderFromSourceFile(QOpenGLShader::Vertex, vertexShader))
        qFatal("Compiling Vertex shader failed");
    if (!m_backgroundShader->addShaderFromSourceFile(QOpenGLShader::Fragment, fragmentShader))
        qFatal("Compiling Fragment shader failed");
    m_backgroundShader->link();
    m_mvpMatrixUniformBackground = m_backgroundShader->uniformLocation("MVP");
    m_viewMatrixUniformBackground = m_backgroundShader->uniformLocation("V");
    m_modelMatrixUniformBackground = m_backgroundShader->uniformLocation("M");
    m_invTransModelMatrixUniformBackground = m_backgroundShader->uniformLocation("itM");
    m_positionAttrBackground = m_backgroundShader->attributeLocation("vertexPosition_mdl");
    m_uvAttrBackground = m_backgroundShader->attributeLocation("vertexUV");
    m_normalAttrBackground = m_backgroundShader->attributeLocation("vertexNormal_mdl");
    m_lightPositionUniformBackground = m_backgroundShader->uniformLocation("lightPosition_wrld");
    m_colorUniformBackground = m_backgroundShader->uniformLocation("color_mdl");
    m_lightStrengthUniformBackground = m_backgroundShader->uniformLocation("lightStrength");
}

void Q3DBarsPrivate::calculateSceneScalingFactors()
{
    // Calculate scene scaling and translation factors
    m_rowWidth = ((m_sampleCount.x() + 1) * m_barSpacing.x()) / 2.0f;
    m_columnDepth = ((m_sampleCount.y() + 1) * m_barSpacing.y()) / 2.0f;
    m_maxDimension = qMax(m_rowWidth, m_columnDepth);//(m_rowWidth > m_columnDepth) ? m_rowWidth : m_columnDepth;
    m_scaleX = m_barThickness.x() / m_sampleCount.x() * (m_maxSceneSize / m_maxDimension);
    m_scaleZ = m_barThickness.y() / m_sampleCount.x() * (m_maxSceneSize / m_maxDimension);
    m_sceneScale = qMin(m_scaleX, m_scaleZ);//(m_scaleX < m_scaleZ) ? m_scaleX : m_scaleZ;
    float minThickness = qMin(m_barThickness.x(), m_barThickness.y());//(m_barThickness.x() < m_barThickness.y()) ? m_barThickness.x() : m_barThickness.y();
    m_sceneScale = m_sceneScale / minThickness;
    m_scaleFactorX = m_sampleCount.x() * (m_maxDimension / m_maxSceneSize);
    m_scaleFactorZ = m_sampleCount.x() * (m_maxDimension / m_maxSceneSize);
    qDebug() << "m_scaleX" << m_scaleX << "m_scaleFactorX" << m_scaleFactorX;
    qDebug() << "m_scaleZ" << m_scaleZ << "m_scaleFactorZ" << m_scaleFactorZ;
    qDebug() << "m_rowWidth:" << m_rowWidth << "m_columnDepth:" << m_columnDepth << "m_maxDimension:" << m_maxDimension;
    qDebug() << m_rowWidth * m_sceneScale << m_columnDepth * m_sceneScale;
}

Q3DBarsPrivate::SelectionType Q3DBarsPrivate::isSelected(int row, int bar, const QVector3D &selection)
{
    SelectionType isSelectedType = None;
    if (selection == QVector3D(0, 0, 0))
        return isSelectedType; // skip background (= black)
    QVector3D current = QVector3D((GLubyte)(((float)(row + 2) / (float)(m_sampleCount.y() + 2))
                                            * 255 + 0.49) // add 0.49 to fix rounding
                                  , (GLubyte)(((float)(bar + 2) / (float)(m_sampleCount.x() + 2))
                                              * 255 + 0.49) // add 0.49 to fix rounding
                                  , 0);
    //if (m_mousePressed)
    //    qDebug() << "selected:" << selection << "current:" << current;
    if (current == selection) {
        isSelectedType = Bar;
    }
    else if (current.x() == selection.x()) {
        isSelectedType = Column;
    }
    else if (current.y() == selection.y()) {
        isSelectedType = Row;
    }
    return isSelectedType;
}

QTCOMMERCIALDATAVIS3D_END_NAMESPACE