"cant add two pointers" error C2110, using a GLfloat array.cannot - pointers

So i think this is the part of my code that has the error. I think im not sending my array correctly or its something different when trying to add my vertex vectors.
void tetrahedron(GLfloat vertice[6][3])
{
glTranslatef(0.3f, 0.0f, 0.0f);
glRotatef(45.0f, 0.0, 1.0, 0.0);
glRotatef(45.0f, 0.0, 0.0, 1.0);
//Cara1
glBegin(GL_QUADS);
glColor3f(0.1, 0.0, 0.9);
GLfloat temp[3];
temp = vertice[2] + vertice[5] + vertice[0];
glVertex3fv(temp);
glVertex3fv(temp);
glVertex3fv(temp);
glEnd();
}
The error is C2110: '+': cannot add two pointers
in: temp = vertice[2] + vertice[5] + vertice[0];
void octahedron(GLfloat vertice[6][3])
{
glTranslatef(0.0f, 0.0f, -5.0f);
glRotatef(45.0f, 0.0, 1.0, 0.0);
glRotatef(45.0f, 0.0, 0.0, 1.0);
}
nothing special there
In the next function is where i create my array that im trying to send to octahedron and tetrahedron:
void display(void) // Creamos la funcion donde se dibuja
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Limiamos pantalla y Depth Buffer
glMatrixMode(GL_MODELVIEW);
glLoadIdentity(); // Reinicializamos la actual matriz Modelview
GLfloat vertice[6][3] = {
{0.0, 0.5, 0.0}, //arriba
{ 0.0,-0.5,0.0 }, //abajo
{ 0.5,0.0,0.0 }, //izq
{ -0.5,0.0,0.0 }, //der
{ 0.0,0.0,0.5 }, //frontal
{ 0.0,0.0,-0.5 }, //trasero
};
octahedron(vertice);
tetrahedron(vertice);
glFlush();
}

Found my problem, it was that i forgot how to add arrays in general. Solved with a for and stuff:
GLfloat temp[3];
int i;
//cara 1
for ( i = 0; i < 3; i++); {
temp[i]= (vertice[2][i]) + (vertice[5][i]) + (vertice[0][i]);
}

Related

QPainter how draw texture with special color

I have some patterns which are black with alpha and have some points that I want to draw line with patterns.
I find QBrush can be constructed by texture, but I don't know how to draw it with difference colors.
This answer show a way here in C# code, but I don't know how to change patterns color with ColorMatrix.
The modification of RGBA values of an image using a 5×5 color matrix reminds me to the transformation of homogeneous coordinates how it is often used in computer graphics. If you imagine the RGBA values as 4-dimensional color/alpha space the transformation of colors using transformation matrices doesn't sound that revolutionary. (Not that you got me wrong – this impressed me much, and I couldn't resist to try this out immediately.) Hence, I didn't wonder why a 5×5 matrix is needed though there are only 4 color components. (E.g. if a translation of color values is intended the 5th dimension cames into play.)
I must admit that I first applied my knowledge from Computer Animation to this problem and compared my approach to the one described on MSDN Using a Color Matrix to Transform a Single Color afterwards. Then I realized that the original paper uses transposed vectors and matrices compared to mine. This is just mathematics as
(vT MT)T = v' = M v
if I remember right.
Practically, it means I have to use matrix rows as columns when I try to reproduce the samples of e.g. the ColorMatrix Guide. (This feels somehow right to me as it is exactly as we describe transformations in 3d space i.e. translation is the last column of the transformation matrix.)
The sample code:
colorMatrix.h:
#ifndef COLOR_MATRIX_H
#define COLOR_MATRIX_H
#include <algorithm>
struct ColorMatrix {
float values[5][5];
ColorMatrix() { }
ColorMatrix(const float(&values)[25])
{
std::copy(std::begin(values), std::end(values), (float*)this->values);
}
float (&operator[](unsigned i))[5] { return values[i]; }
const float(&operator[](unsigned i) const)[5] { return values[i]; }
};
struct ColorVector {
float values[5];
ColorVector(const float(&values)[5])
{
std::copy(std::begin(values), std::end(values), (float*)this->values);
}
float& operator[](size_t i) { return values[i]; }
const float& operator[](size_t i) const { return values[i]; }
};
#endif // COLOR_MATRIX_H
colorMatrix.cc:
#include <algorithm>
#include <QtWidgets>
#include "colorMatrix.h"
#include "QColorMatrixView.h"
ColorVector operator*(const ColorMatrix &m, const ColorVector &v)
{
return ColorVector({
m[0][0] * v[0] + m[0][1] * v[1] + m[0][2] * v[2] + m[0][3] * v[3] + m[0][4] * v[4],
m[1][0] * v[0] + m[1][1] * v[1] + m[1][2] * v[2] + m[1][3] * v[3] + m[1][4] * v[4],
m[2][0] * v[0] + m[2][1] * v[1] + m[2][2] * v[2] + m[2][3] * v[3] + m[2][4] * v[4],
m[3][0] * v[0] + m[3][1] * v[1] + m[3][2] * v[2] + m[3][3] * v[3] + m[3][4] * v[4],
m[4][0] * v[0] + m[4][1] * v[1] + m[4][2] * v[2] + m[4][3] * v[3] + m[4][4] * v[4]
});
}
const ColorMatrix Identity({
1.0f, 0.0f, 0.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 0.0f, 0.0f, 1.0f
});
template <typename T>
T clamp(T value, T min, T max)
{
return value < min ? min
: value > max ? max
: value;
}
QRgb transform(const ColorMatrix &mat, const QRgb &color)
{
ColorVector vec({
qRed(color) / 255.0f, qGreen(color) / 255.0f, qBlue(color) / 255.0f, qAlpha(color) / 255.0f, 1.0f });
vec = mat * vec;
if (vec[4] != 0.0f) {
vec[0] /= vec[4]; vec[1] /= vec[4]; vec[2] /= vec[4]; vec[3] /= vec[4]; // vec[4] = 1.0f;
}
return qRgba(
clamp<int>(255 * vec[0], 0, 255),
clamp<int>(255 * vec[1], 0, 255),
clamp<int>(255 * vec[2], 0, 255),
clamp<int>(255 * vec[3], 0, 255));
}
QImage transform(const ColorMatrix &mat, const QImage &qImg)
{
const int w = qImg.width(), h = qImg.height();
QImage qImgDst(w, h, qImg.format());
for (int y = 0; y < h; ++y) for (int x = 0; x < w; ++x) {
qImgDst.setPixel(x, y, transform(mat, qImg.pixel(x, y)));
}
return qImgDst;
}
QImage open(QWidget *pQParent)
{
return QImage(
QFileDialog::getOpenFileName(pQParent,
QString::fromUtf8("Open Image File"),
QString()));
}
void update(
QLabel &qLblViewResult,
const QColorMatrixView &qEditColMat, const QLabel &qLblViewOrig)
{
ColorMatrix colMat = qEditColMat.values();
const QPixmap *pQPixmap = qLblViewOrig.pixmap();
const QImage qImg = pQPixmap ? pQPixmap->toImage() : QImage();
qLblViewResult.setPixmap(
QPixmap::fromImage(transform(colMat, qImg)));
}
int main(int argc, char **argv)
{
QApplication app(argc, argv);
// setup GUI
QWidget qWin;
qWin.setWindowTitle(QString::fromUtf8("Qt Color Matrix Demo"));
QGridLayout qGrid;
QVBoxLayout qVBoxColMat;
QLabel qLblColMat(QString::fromUtf8("Color Matrix:"));
qVBoxColMat.addWidget(&qLblColMat, 0);
QColorMatrixView qEditColMat;
qEditColMat.setValues(Identity);
qVBoxColMat.addWidget(&qEditColMat);
QPushButton qBtnReset(QString::fromUtf8("Identity"));
qVBoxColMat.addWidget(&qBtnReset);
QPushButton qBtnGray(QString::fromUtf8("Grayscale"));
qVBoxColMat.addWidget(&qBtnGray);
qVBoxColMat.addStretch(1);
qGrid.addLayout(&qVBoxColMat, 0, 0, 2, 1);
QLabel qLblX(QString::fromUtf8(" \xc3\x97 "));
qGrid.addWidget(&qLblX, 0, 1);
QLabel qLblViewOrig;
qGrid.addWidget(&qLblViewOrig, 0, 2);
QPushButton qBtnLoad(QString::fromUtf8("Open..."));
qGrid.addWidget(&qBtnLoad, 1, 2);
QLabel qLblEq(QString::fromUtf8(" = "));
qGrid.addWidget(&qLblEq, 0, 3);
QLabel qLblViewResult;
qGrid.addWidget(&qLblViewResult, 0, 4);
qWin.setLayout(&qGrid);
qWin.show();
// install signal handlers
QObject::connect(&qEditColMat, &QColorMatrixView::editingFinished,
[&]() { update(qLblViewResult, qEditColMat, qLblViewOrig); });
QObject::connect(&qBtnReset, &QPushButton::clicked,
[&]() {
qEditColMat.setValues(Identity);
update(qLblViewResult, qEditColMat, qLblViewOrig);
});
QObject::connect(&qBtnGray, &QPushButton::clicked,
[&]() {
qEditColMat.setValues(ColorMatrix({
0.33f, 0.59f, 0.11f, 0.0f, 0.0f,
0.33f, 0.59f, 0.11f, 0.0f, 0.0f,
0.33f, 0.59f, 0.11f, 0.0f, 0.0f,
0.00f, 0.00f, 0.00f, 1.0f, 0.0f,
0.00f, 0.00f, 0.00f, 0.0f, 1.0f
}));
update(qLblViewResult, qEditColMat, qLblViewOrig);
});
QObject::connect(&qBtnLoad, &QPushButton::clicked,
[&]() {
qLblViewOrig.setPixmap(QPixmap::fromImage(open(&qBtnLoad)));
update(qLblViewResult, qEditColMat, qLblViewOrig);
});
// initial contents
{
QImage qImg("colorMatrixDefault.jpg");
qLblViewOrig.setPixmap(QPixmap::fromImage(qImg));
update(qLblViewResult, qEditColMat, qLblViewOrig);
}
// runtime loop
return app.exec();
}
QColorMatrixView.h:
#ifndef Q_COLOR_MATRIX_VIEW_H
#define Q_COLOR_MATRIX_VIEW_H
#include <QLineEdit>
#include <QGridLayout>
#include <QWidget>
#include "colorMatrix.h"
class QColorMatrixView: public QWidget {
Q_OBJECT
private:
QGridLayout _qGrid;
QLineEdit _qEdit[5][5];
signals:
void editingFinished();
public:
QColorMatrixView(QWidget *pQParent = nullptr);
virtual ~QColorMatrixView() = default;
QColorMatrixView(const QColorMatrixView&) = delete;
QColorMatrixView& operator=(const QColorMatrixView&) = delete;
ColorMatrix values() const;
void setValues(const ColorMatrix &mat);
};
#endif // Q_COLOR_MATRIX_VIEW_H
QColorMatrixView.cc:
#include "QColorMatrixView.h"
QColorMatrixView::QColorMatrixView(QWidget *pQParent):
QWidget(pQParent)
{
QFontMetrics qFontMetrics(font());
const int w = qFontMetrics.boundingRect(QString("-000.000")).width() + 10;
for (int r = 0; r < 5; ++r) {
for (int c = 0; c < 5; ++c) {
QLineEdit &qEdit = _qEdit[r][c];
_qGrid.addWidget(&qEdit, r, c);
qEdit.setFixedWidth(w);
QObject::connect(&qEdit, &QLineEdit::editingFinished,
[this, r, c]() {
_qEdit[r][c].setText(
QString::number(_qEdit[r][c].text().toFloat(), 'f', 3));
editingFinished();
});
}
}
setLayout(&_qGrid);
}
ColorMatrix QColorMatrixView::values() const
{
ColorMatrix mat;
for (int r = 0; r < 5; ++r) for (int c = 0; c < 5; ++c) {
mat[r][c] = _qEdit[r][c].text().toFloat();
}
return mat;
}
void QColorMatrixView::setValues(const ColorMatrix &mat)
{
for (int r = 0; r < 5; ++r) for (int c = 0; c < 5; ++c) {
_qEdit[r][c].setText(QString::number(mat[r][c], 'f', 3));
}
}
moc_colorMatrix.cc (to consider moc generated sources):
#include "moc_QColorMatrixView.cpp"
colorMatrix.pro (the qmake project file):
SOURCES = colorMatrix.cc QColorMatrixView.cc
HEADERS = colorMatrix.h QColorMatrixView.h
SOURCES += moc_colorMatrix.cc
MOC_DIR = .
QT += widgets
and the default sample image colorMatrixDefault.jpg if no (cat) photo file is at hand:
Although, I've developed and tested the application in VS2013, I built and tested also on cygwin to ensure that the qmake project is complete and self-standing:
$ qmake-qt5 colorMatrix.pro
$ make
$ ./colorMatrix
An enhanced version of this sample code can be found on github Qt Color Matrix Demo.

Nothing gets drawn as soon as GL_DEPTH_TEST is enabled

As soon as I set glEnable(GL_DEPTH_TEST) in the following code, nothing except for the clear color gets drawn on screen.
window.cpp
void Window::initializeGL() {
makeCurrent();
initializeOpenGLFunctions();
glClearColor(0.0f, 0.03f, 0.2f, 1.0f);
Shaders::initShaders();
glEnable(GL_DEPTH_TEST);
currentLevel.addTiles();
viewMatrix.setToIdentity();
viewMatrix.translate(0.0f, 0.0f, -8.0f);
viewMatrix.rotate(45.0f, -1.0f, 0.0f, 0.0f);
}
void Window::resizeGL(int width, int height) {
const float fov = 45.0f,
zNear = 0.0f,
zFar = 1000.0f;
projectionMatrix.setToIdentity();
projectionMatrix.perspective(fov, width / float(height), zNear, zFar);
}
void Window::paintGL() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
currentLevel.setProjectionMatrix(projectionMatrix);
currentLevel.setViewMatrix(viewMatrix);
currentLevel.draw();
}
tile.cpp:
// Constructor with custom shader
Tile::Tile(QVector3D v1, QVector3D v2, QVector3D v3, QVector3D v4, QOpenGLShaderProgram* shaderProgram) :
vbo(QOpenGLBuffer::VertexBuffer),
cbo(QOpenGLBuffer::VertexBuffer),
ibo(QOpenGLBuffer::IndexBuffer) {
// Calculate surface normal & second set of vertices
QVector3D surfaceNormal = QVector3D::normal(v1, v2, v3);
QVector3D v1_n = v1 - surfaceNormal;
QVector3D v2_n = v2 - surfaceNormal;
QVector3D v3_n = v3 - surfaceNormal;
QVector3D v4_n = v4 - surfaceNormal;
// Set up rectangular mesh from given corner vectors
vertices = {
v1, v2, v3, v4,
v1_n, v2_n, v3_n, v4_n
};
colors = {
color1, color1, color2, color2,
color1, color1, color2, color2
};
indices = {
// Face 1
0, 1, 2,
2, 3, 0,
// Face 2
0, 4, 5,
5, 1, 0,
// Face 3
4, 5, 6,
6, 7, 4
};
this->shaderProgram = shaderProgram;
cacheShaderLocations();
createBuffers();
}
Tile::~Tile() {
vbo.destroy();
vao.destroy();
ibo.destroy();
}
// Cache Uniform Locations for shaders
void Tile::cacheShaderLocations() {
positionLocation = shaderProgram->attributeLocation("position");
colorLocation = shaderProgram->attributeLocation("color");
modelLocation = shaderProgram->uniformLocation("model");
viewLocation = shaderProgram->uniformLocation("view");
projectionLocation = shaderProgram->uniformLocation("projection");
}
// Create buffers
void Tile::createBuffers() {
// Vertex Buffer Object
vbo.create();
vbo.bind();
vbo.setUsagePattern(QOpenGLBuffer::StaticDraw);
vbo.allocate(vertices.constData(), vertices.size() * sizeof(QVector3D));
vbo.release();
// Color Buffer Object
cbo.create();
cbo.bind();
cbo.setUsagePattern(QOpenGLBuffer::StaticDraw);
cbo.allocate(colors.constData(), colors.size() * sizeof(QVector3D));
cbo.release();
// Index Buffer Object
ibo.create();
ibo.bind();
ibo.setUsagePattern(QOpenGLBuffer::StaticDraw);
ibo.allocate(indices.constData(), indices.size() * sizeof(GLushort));
ibo.release();
// Vertex Array Object
vao.create();
// Setup buffer attributes
shaderProgram->bind();
vao.bind();
vbo.bind();
shaderProgram->enableAttributeArray(positionLocation);
shaderProgram->setAttributeBuffer(positionLocation, GL_FLOAT, 0, 3, 0);
cbo.bind();
shaderProgram->enableAttributeArray(colorLocation);
shaderProgram->setAttributeBuffer(colorLocation, GL_FLOAT, 0, 3, 0);
ibo.bind();
vao.release();
// Release buffers & shader program
vbo.release();
cbo.release();
ibo.release();
shaderProgram->release();
}
void Tile::draw() {
shaderProgram->bind();
// Send uniforms to shader
shaderProgram->setUniformValue(projectionLocation, projectionMatrix);
shaderProgram->setUniformValue(viewLocation, viewMatrix);
shaderProgram->setUniformValue(modelLocation, modelMatrix);
// Draw vertices
vao.bind();
glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_SHORT, 0);
vao.release();
shaderProgram->release();
}
As for the depth buffer itself, according to the Qt documentation it's enabled by default. In the main.cpp I set the surface format/context like this:
// Set OpenGL Version information
QSurfaceFormat format;
format.setDepthBufferSize(24);
format.setRenderableType(QSurfaceFormat::OpenGL);
format.setProfile(QSurfaceFormat::CoreProfile);
format.setVersion(3,3);
I really have no clue why nothing gets drawn when I try to use depth testing so I would greatly appreciate any help.

qt opengl shader texture coordinates

I use OpenGL shader for apply median filter to image. Input image I copy to in_fbo buffer. All work fine.
QGLFramebufferObject *in_fbo, *out_fbo;
painter.begin(in_fbo); //Copy QImage to QGLFramebufferObject
painter.drawImage(0,0,image_in,0,0,width,height);
painter.end();
out_fbo->bind();
glViewport( 0, 0, nWidth, nHeight );
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
glOrtho( 0.0, nWidth, 0.0, nHeight, -1.0, 1.0 );
glMatrixMode( GL_MODELVIEW );
glLoadIdentity( );
glEnable( GL_TEXTURE_2D );
out_fbo->drawTexture( QPointF(0.0,0.0), in_fbo->texture( ), GL_TEXTURE_2D );
But in shader code I need divide position of vertex by width and height of image, because texture coordinates are normalized to a range between 0 and 1.
How correctly calculate texture coordinates?
//vertex shader
varying vec2 pos;
void main( void )
{
pos = gl_Vertex.xy;
gl_Position = ftransform( );
}
//fragment shader
#extension GL_ARB_texture_rectangle : enable
uniform sampler2D texture0;
uniform int imgWidth;
uniform int imgHeight;
uniform int len;
varying vec2 pos;
#define MAX_LEN (100)
void main(){
float v[ MAX_LEN ];
for (int i = 0; i < len; i++) {
vec2 posi = pos + float(i);
posi.x = posi.x / float( imgWidth );
posi.y = posi.y / float( imgHeight );
v[i] = texture2D(texture0, posi).r;
}
//
//.... Calculating new value
//
gl_FragColor = vec4( m, m, m, 1.0 );
}
Before I did it in OpenFrameworks. But shader for texture in OF does not work for texture in Qt. I suppose because OF create textures with textureTarget = GL_TEXTURE_RECTANGLE_ARB. Now the result of applying shader above isn't correct. It isn't identical with result of the old shader (there are few pixels with different colors). I don't know how modify shader above :(.
Old shaders:
//vertex
#version 120
#extension GL_ARB_texture_rectangle : enable
void main() {
gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
gl_TexCoord[0] = gl_MultiTexCoord0;
gl_FrontColor = gl_Color;
}
//fragment
#version 120
#extension GL_ARB_texture_rectangle : enable
uniform sampler2D texture0;
uniform int len;
void main(){
vec2 pos = gl_TexCoord[0].xy;
pos.x = int( pos.x );
pos.y = int( pos.y );
float v[ MAX_LEN ];
for (int i=0; i<len; i++) {
vec2 posi = pos + i;
posi.x = int( posi.x + 0.5 ) + 0.5;
posi.y = int( posi.y + 0.5 ) + 0.5;
v[i] = texture2D(texture0, posi).r;
}
//
//.... Calculating new value
//
gl_FragColor = vec4( m, m, m, 1.0 );
}
OpenGL code from OpenFrameworks lib
texData.width = w;
texData.height = h;
texData.tex_w = w;
texData.tex_h = h;
texData.textureTarget = GL_TEXTURE_RECTANGLE_ARB;
texData.bFlipTexture = true;
texData.glType = GL_RGBA;
// create & setup FBO
glGenFramebuffersEXT(1, &fbo);
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo);
// Create the render buffer for depth
glGenRenderbuffersEXT(1, &depthBuffer);
glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, depthBuffer);
glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT, texData.tex_w, texData.tex_h);
// create & setup texture
glGenTextures(1, (GLuint *)(&texData.textureID)); // could be more then one, but for now, just one
glBindTexture(texData.textureTarget, (GLuint)(texData.textureID));
glTexParameterf(texData.textureTarget, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(texData.textureTarget, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameterf(texData.textureTarget, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameterf(texData.textureTarget, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexImage2D(texData.textureTarget, 0, texData.glType, texData.tex_w, texData.tex_h, 0, texData.glType, GL_UNSIGNED_BYTE, 0);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
// attach it to the FBO so we can render to it
glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, texData.textureTarget, (GLuint)texData.textureID, 0);
I do not think you actually want to use the texture's dimensions to do this. From the sounds of things this is a simple fullscreen image filter and you really just want fragment coordinates mapped into the range [0.0,1.0]. If this is the case, then gl_FragCoord.xy / viewport.xy, where viewport is a 2D uniform that defines the width and height of your viewport ought to work for your texture coordinates (in the fragment shader).
vec2 texCoord = vec2 (transformed_pos.x, transformed_pos.y) / transformed_pos.w * vec2 (0.5, 0.5) + vec2 (1.0, 1.0) may also work using the same principle -- clip-space coordinates transformed into NDC and then mapped to texture-space. This approach will not properly account for texel centers ((0.5, 0.5) rather than (0.0, 0.0)), however and can present problems when texture filtering is enabled and the wrap mode is not GL_CLAMP_TO_EDGE.

How to fix QTGLWidget using QTimer to decrease rendering time?

I am currently using QtOpenGL for my program. My program plots dots in the 3D space. These dots could be any number between one to several thousand. I am using the function, 'glusphere', for drawing the sphere to represent each dot.
With this, each frame is created and I need to display each frames as an animation using QTimer. This animation should be controlled by fps.For example, if fps=30, I would put t=1000/30 for QTimer's setInterval(t).Whether fps=10 or 30, I found that fps does not change my program much.
I looked for a problem by setting fps to 0 and observed how much the rendering time takes by using setInterval(0). The following is the results:
n = number of spheres
when n=10: 28ms => about 30ms
when n=100: 87ms => about 90ms
when n=150: 137ms => about 140ms
when n=1000: 598ms => about 600ms => 0.6sec
From the results above, the rendering time of each frame linearly increases with the number of spheres. The following is a part of my code:
GLWidget::GLWidget(QWidget *parent) : QGLWidget(parent)
{
setFormat(QGLFormat(QGL::DoubleBuffer | QGL::DepthBuffer));
scale=1.0;
rot_x=0;
rot_y=0;
rot_z=0;
trans_x=0;
trans_y=0;
trans_z=0;
isloaded=false;
isplayed=false;
currentFrame=1;
sphereNum=1;
myTimer=new QTimer(this);
//fps=60;
myTimer->setInterval(0);
//myTimer->setInterval();
connect(myTimer, SIGNAL(timeout()), this, SLOT(timerEvent()));
}
void GLWidget::initializeGL()
{
qglClearColor(QColor(Qt::black));
glEnable(GL_DEPTH_TEST);
srand((unsigned)time(NULL));
//QGLFormat::setDoubleBuffer(true);
//qDebug() << "initGL context: " << this->context();
}
void GLWidget::timerEvent()
{
static QTime current_time, last_time;
int elapsed_time;
last_time=current_time;
current_time=QTime::currentTime();
elapsed_time=(current_time.second()*1000 + current_time.msec())-(last_time.second()*1000 + last_time.msec());
//qDebug() << "Timer elapsed time: " << elapsed_time;
if(isloaded && isplayed) {
if(currentFrame<markerData.frameSize) currentFrame++;
makeCurrent();
updateGL();
}
if(currentFrame==markerData.frameSize) {
isplayed=false;
myTimer->stop();
currentFrame=1;
}
}
void GLWidget::drawSphere(GLfloat x, GLfloat y, GLfloat z, GLfloat radius)
{
qglColor(Qt::yellow);
glPushMatrix();
glTranslatef(x, y, z);
gluSphere(p, radius, 10, 10);
//gluCylinder(p, 10, 10, 10, 4, 4);
glPopMatrix();
}
void GLWidget::drawMarkers() {
int markerIndex;
glPushMatrix();
/*for(int i=0; i<markerData.rowSize; i++) {
markerIndex=(currentFrame-1)*markerData.rowSize+i;
//qDebug() << markerIndex;
drawSphere(markerData.markerSet[markerIndex].x, markerData.markerSet[markerIndex].y, markerData.markerSet[markerIndex].z, 10);
}*/
for(int i=0; i<sphereNum; i++) {
markerIndex=rand()%1000;
drawSphere(markerIndex, markerIndex, markerIndex, 10);
}
glPopMatrix();
}
void GLWidget::drawText(double x, double y, double z, QString txt)
{
glDisable(GL_DEPTH_TEST);
qglColor(Qt::white);
renderText(x, y, z, txt, QFont("Arial", 12, QFont::Bold, false) );
glEnable(GL_DEPTH_TEST);
}
void GLWidget::paintGL()
{
static QTime current_time, last_time;
int elapsed_time;
float paint_fps;
//if file data is loaded
if(isloaded)
{
//calculate elapsed time drown 1 frame per second
//elapsed time is millisecond
last_time=current_time;
current_time=QTime::currentTime();
elapsed_time=(current_time.second()*1000 + current_time.msec())-(last_time.second()*1000 + last_time.msec());
paint_fps=1000/elapsed_time;
//qDebug() << "elapsed time: " << elapsed_time << " fps: " << paint_fps;
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0.0f,0.0f,-20.0f);
glRotatef(30.0, 0.0, 1.0, 0.0);
glRotatef(15.0, 1.0, 0.0, 0.0);
glRotatef(rot_x, 1.0, 0.0, 0.0);
glRotatef(rot_y, 0.0, 1.0, 0.0);
glRotatef(rot_z, 0.0, 0.0, 1.0);
glScalef(scale, scale, scale);
glTranslatef(trans_x, trans_y, trans_z);
//draw elapsed time(ms)
glPushMatrix();
drawText(100, -300, 100, QString::number(elapsed_time) + "ms");
glPopMatrix();
//draw 3-axis
glBegin(GL_LINES);
qglColor(Qt::red);
glVertex3f(0, 0, 0);
glVertex3f(3000, 0, 0);
glEnd();
glBegin(GL_LINES);
qglColor(Qt::green);
glVertex3f(0, 0, 0);
glVertex3f(0, 3000, 0);
glEnd();
glBegin(GL_LINES);
qglColor(Qt::blue);
glVertex3f(0, 0, 0);
glVertex3f(0, 0, 3000);
glEnd();
//draw spheres
p=gluNewQuadric();
drawMarkers();
gluDeleteQuadric(p);
//swapBuffers
if(doubleBuffer()) {
swapBuffers();
makeCurrent();
}
}
}
To clarify:
Rendering time for each frame changes depending on the number of spheres.
The number of spheres should not change the rendering time
Even though it draw 1000 spheres, it spends half second
Do you think the problem is using glusphere?
If there is another way to draw the sphere, could it be possible to do it more than 100 fps?
Could someone please explain where the bottleneck is that is creating this slow rendering?

Apply texture to grid

I would like to apply a texture to a grid in 3d space using Processing, I've tried declaring a PImage and setting the .jpg file with loadimage with no results..
PImage tex;
void setup() {
size(800, 600, P3D);
tex=loadImage("ground104");
noCursor();
}
void draw()
{
directionalLight(255, 255, 255, 0, 0, -1);
background(180);
drawPlane();
}
void drawPlane()
{ //lights();
int s = 10000;
int ss = 500;
fill(0, 200, 20); stroke(200); for(int i = 0; i < s; i += ss) {
stroke(0,100,0);
strokeWeight(3);
beginShape(QUAD_STRIP);
for(int j = 0; j <= s; j += ss)
{
texture(tex);
vertex(j, i, 0);
vertex(j, i + ss, 0);
}
endShape(); } noStroke(); }
Do you have any advice?
Thanks!
looks like you need a file extension like .jpg. You can troubleshoot by running the code from the reference page:
http://www.processing.org/reference/texture_
size(100, 100, P3D);
noStroke();
PImage img = loadImage("laDefense.jpg");
beginShape();
texture(img);
vertex(10, 20, 0, 0);
vertex(80, 5, 100, 0);
vertex(95, 90, 100, 100);
vertex(40, 95, 0, 100);
endShape();
and replace laDefense.jpg with your image name. Also, it needs to be placed in the data directory in the sketch directory. If it works, then your problem is elsewhere. I am not sure what your plan is in the sketch, but you might find peasycam useful for troubleshooting in 3d.
http://mrfeinberg.com/peasycam/
another technique is to increment a float by 0.01 per frame and call a RotateX(), Y or Z or all of the above at the beginning of your draw() method / loop.
Thank you for your reply!
I've changed my code to this and now you can run it and see what I get (first download the grass.jpg from https://www.dropbox.com/s/fsda0tih67q8tll/grass.jpg?m). I'm close but I wonder why the grid is green when it was supposed to be a grass land...
PImage tex;
void setup()
{
size(800, 600, P3D);
tex=loadImage("grass.jpg");
noCursor();
}
void draw()
{
translate(width/2 , height/2 , 0); // center of screen
rotateX(QUARTER_PI * 1.0); // move camera up
rotateZ(QUARTER_PI * 1.8);
//rotateZ(camZ.val + offset); // rotate around turret
rotateZ(map(mouseX, mouseY, width, 2.5, -2.5));
translate(-1000, 0, -1000);
directionalLight(255, 255, 255, 0, 0, -1);
background(180);
drawPlane();
}
void drawPlane()
{ //lights();
int s = 10000;
int ss = 500;
fill(0, 200, 20); stroke(200); for(int i = 0; i < s; i += ss) {
stroke(0,100,0);
strokeWeight(3);
beginShape(QUAD_STRIP);
for(int j = 0; j <= s; j += ss)
{
texture(tex);
vertex(j, i, 0);
vertex(j, i + ss, 0);
}
endShape();
}
noStroke();
}

Resources