CIwFMat Physics::GetMatrixFromWheelInfo( const btWheelInfo w, const btRigidBody* b )
{
	CIwFMat modelMatrix( CIwMat::g_Identity );

	const btTransform btTrans = w.m_worldTransform;
	const btVector3 pos = btTrans.getOrigin();

	const float posX = pos.getX();
	const float posY = pos.getY();
	const float posZ = pos.getZ();

	const CIwFVec3 position( posX, posY, posZ );

	const btQuaternion q = btTrans.getRotation();
	CIwFVec3 rot;
	QuaternionToEuler( q, rot );

	const btQuaternion qBody = b->getOrientation();
	CIwFVec3 rotBody;
	QuaternionToEuler( qBody, rotBody );
	
	CIwFMat mat = CIwFMat::g_Identity;
	mat.PostRotateX( rot.x );
	mat.PostRotateY( -rotBody.y );		// mat.PostRotateY( rot.y ); fix for rotating wheels by y axis, there are glitches after 360 degrees rotating
	mat.PostRotateZ( -rotBody.z );
	
	modelMatrix.CopyRot( mat );
	modelMatrix.SetTrans( position );

	return modelMatrix;
}
	void calculateBBox() {
		glm::vec3 min, max;
		for (int i = 0; i < 8; ++i) {
			const float* p = buildingVertices[i].pos;
			glm::vec4 ppos = modelMatrix() * glm::vec4(p[0], p[1], p[2], 1.0f);
			glm::vec3 point = glm::swizzle<glm::X, glm::Y, glm::Z>(ppos);
			if (i == 0) {
				min = point;
				max = point;
			} else {
				if (point.x > max.x)
					max.x = point.x;
				if (point.y > max.y)
					max.y = point.y;
				if (point.z > max.z)
					max.z = point.z;

				if (point.x < min.x)
					min.x = point.x;
				if (point.y < min.y)
					min.y = point.y;
				if (point.z < min.z)
					min.z = point.z;
			}
		}

		m_bbox = BoundingBox(min, max);
	}
Esempio n. 3
0
void RenderUtil::drawWireframeBox(class Camera* camera, const glm::vec3& position, const glm::vec3& size, const glm::vec4& color) {
    if(!_mesh) initializeWireframeBox();

    wireframeShader.bind();

    glBindBuffer(GL_ARRAY_BUFFER, _mesh->vboID);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _mesh->iboID);

    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(glm::vec3), (void*)0);

    const glm::vec3 &cameraPosition = camera->getPosition();

    glm::mat4 modelMatrix(1);
    modelMatrix[3][0] = -cameraPosition.x + position.x;
    modelMatrix[3][1] = -cameraPosition.y + position.y;
    modelMatrix[3][2] = -cameraPosition.z + position.z;
    modelMatrix[0][0] = size.x;
    modelMatrix[1][1] = size.y;
    modelMatrix[2][2] = size.z;
    glm::mat4 MVP = camera->getProjectionMatrix() * camera->getViewMatrix() * modelMatrix;

    glUniformMatrix4fv(blockShader.mvpID, 1, GL_FALSE, &MVP[0][0]);
    glUniform4f(wireframeShader.colorID, color.r, color.g, color.b, color.a);

    glLineWidth(2);

    glDrawElements(GL_LINES, _mesh->numIndices, GL_UNSIGNED_INT, (void*)0);

    glBindBuffer(GL_ARRAY_BUFFER, 0);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

    wireframeShader.unBind();
}
Esempio n. 4
0
void Graphic::DrawRectangle( Rectangle& r )
{
	if( !r.used )
		return;

	glm::mat4 modelMatrix( glm::mat4( 1.0f ) );

	// translate
//	modelMatrix[3] = glm::vec4( r.x, r.y, deapth, 1.f );
	modelMatrix[3][0] = r.x;
	modelMatrix[3][1] = r.y;
	modelMatrix[3][2] = deapth;

	// rotate
	if( r.rotation != 0 )
		modelMatrix = glm::rotate( modelMatrix, r.rotation, glm::vec3( 0.f, 0.f, -1.f ) );

	// scale
	modelMatrix = glm::scale( modelMatrix, glm::vec3( r.scale, r.scale_x ? r.scale_x: r.scale, 0.f ) );

	glUniformMatrix4fv( glGetUniformLocation( shaderProgram, "viewMatrix" ), 1, GL_FALSE, &viewMatrix[0][0] );
	glUniformMatrix4fv( glGetUniformLocation( shaderProgram, "modelMatrix" ), 1, GL_FALSE, &modelMatrix[0][0] );

	glDrawArrays( GL_TRIANGLE_STRIP, 0, 4 );
}
Esempio n. 5
0
void RenderUtil::drawLine(Camera *camera, glm::vec3 p1, glm::vec3 p2, GLubyte r, GLubyte g, GLubyte b, int thickness)
{
    GridVertex verts[2];

    gridShader.bind();

    glm::mat4 modelMatrix(1);
   
    const glm::vec3 &position = camera->getPosition();

    modelMatrix[3][0] = -position.x;
    modelMatrix[3][1] = -position.y;
    modelMatrix[3][2] = -position.z;
 

    glm::mat4 MVP = camera->getProjectionMatrix() * camera->getViewMatrix() * modelMatrix;

    glUniformMatrix4fv(gridShader.mvpID, 1, GL_FALSE, &MVP[0][0]);

    static GLuint vboID = 0;

    if (vboID == 0){
        glGenBuffers(1, &vboID);
    }

    verts[0].position = p1;
    verts[0].color[0] = r;
    verts[0].color[1] = g;
    verts[0].color[2] = b;
    verts[0].color[3] = 255;
    verts[1].position = p2;
    verts[1].color[0] = r;
    verts[1].color[1] = g;
    verts[1].color[2] = b;
    verts[1].color[3] = 255;

    glBindBuffer(GL_ARRAY_BUFFER, vboID);
   
    // orphan the buffer for speed
    glBufferData(GL_ARRAY_BUFFER, sizeof(verts), NULL, GL_STREAM_DRAW);

    glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(verts), verts);

    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(GridVertex), (void *)0); //vertexPosition
    glVertexAttribPointer(1, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(GridVertex), (void *)12); //vertexColor

    glLineWidth(thickness);

    //when drawing lines theres no bonus for using indices so we just use draw arrays
    //so we unbind the element array buffer for good measure
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

    glDrawArrays(GL_LINES, 0, 2);

    gridShader.unBind();

    glLineWidth(1);
}
Esempio n. 6
0
Matrix4x4 Primitive::ModelMatrix() const
{
    Matrix4x4 modelMatrix(orientation[0][0], orientation[0][1], orientation[0][2], translation[0], 
                          orientation[1][0], orientation[1][1], orientation[1][2], translation[1], 
                          orientation[2][0], orientation[2][1], orientation[2][2], translation[2],
                          0, 0, 0, 1);

    return modelMatrix;
}
    void OrthogonalizedBumpFinder::GetVegaBumps(std::vector<std::vector<Matrix> >& theBumps) const
    {
        OrthogonalProjections projector(derivativesProducer_.getAllOnePercentBumps(),
                                                            multiplierCutOff_,
                                                             tolerance_  );


        Size numberRestrictedBumps(projector.numberValidVectors());

        boost::shared_ptr<MarketModel> marketmodel(derivativesProducer_.getInputBumps().associatedModel());
        const EvolutionDescription& evolution(marketmodel->evolution());

        Size numberSteps = evolution.numberOfSteps();
        Size numberRates = evolution.numberOfRates();
        Size factors = marketmodel->numberOfFactors();

        theBumps.resize(numberSteps);
       // recall that the bumps: We do the outermost vector by time step and inner one by which vega.

        for (Size i=0; i < theBumps.size(); ++i)
            theBumps[i].resize(numberRestrictedBumps);

        Matrix modelMatrix(numberRates, factors,0.0);

        for (Size i=0;  i< numberSteps; ++i)
            for (Size j=0; j < numberRestrictedBumps; ++j)
                theBumps[i][j] = modelMatrix;

        const std::vector<VegaBumpCluster>& bumpClusters(derivativesProducer_.getInputBumps().allBumps());


        Size bumpIndex =0;

        for (Size instrument=0; instrument < projector.validVectors().size(); ++instrument)
        {
            if (projector.validVectors()[instrument])
            {
                for (Size cluster =0; cluster< bumpClusters.size(); ++cluster)
                {
                    Real magnitude = projector.GetVector(instrument)[cluster];

                    for (Size step = bumpClusters[cluster].stepBegin(); step <  bumpClusters[cluster].stepEnd(); ++step)
                        for (Size rate = bumpClusters[cluster].rateBegin(); rate < bumpClusters[cluster].rateEnd(); ++rate)
                            for (Size factor = bumpClusters[cluster].factorBegin(); factor <  bumpClusters[cluster].factorEnd(); ++factor)
                                theBumps[step][bumpIndex][rate][factor] = magnitude;
                }

                ++bumpIndex;


            }

        }



    }
void GameObject::draw(){
	shaderProgram->Activate();
	if (needRebuffer)
		rebuffer();

	shaderProgram->SetVariable(MODEL_SHADER_VARIABLE_NAME, modelMatrix());
	shaderProgram->Activate();

	glBindVertexArray(vaoObject1);
	//ARRAY_COUNT(indexData)
	glDrawElements(GL_TRIANGLES, indexData.size(), GL_UNSIGNED_SHORT, 0);
	glBindVertexArray(0);
}
Esempio n. 9
0
Transform::Transform(GameObject* parent) : Component(parent)
{
  setObjectName("core/Transform");
  m_position.setX(0);
  m_position.setY(0);
  m_position.setZ(0);
  m_scaling.setX(1);
  m_scaling.setY(1);
  m_scaling.setZ(1);
  m_forward = QVector3D(0,0,1);
  m_up = QVector3D(0,1,0);
  m_right = QVector3D(1,0,0);
  modelMatrix();
}
Esempio n. 10
0
void CObject::draw(const CMVP* p_camera, QList<CLight*>* p_lights, QVector2D p_biasVP){
	float mvp[16];
	float mv[16];
	float mvi[9];
	const QMatrix4x4 camView = p_camera->viewMatrix();
	const QMatrix4x4 camProj = p_camera->projMatrix();
	const QMatrix4x4 modelView = camView * modelMatrix();
	const QMatrix4x4 modelViewProj = camProj * modelView;
	const CLight* light;

	p_camera->setViewPort(p_biasVP);

    this->convertMatrix(modelView, mv);
    this->convertMatrix(modelView.normalMatrix(), mvi);
    this->convertMatrix(modelViewProj, mvp);

	glVertexAttribPointer( 0, 3, GL_FLOAT, GL_FALSE, 0, CVA::vertices() );
	glVertexAttribPointer( 1, 2, GL_FLOAT, GL_FALSE, 0, CVA::textures() );
	glVertexAttribPointer( 2, 3, GL_FLOAT, GL_FALSE, 0, CVA::normals() );

	CShaderInterface::sendUniformMatrix4fv("mvp", 1, GL_TRUE, mvp);
	CShaderInterface::sendUniformMatrix4fv("mv", 1, GL_TRUE, mv);
	CShaderInterface::sendUniformMatrix3fv("mvi", 1, GL_TRUE, mvi);

	order(modelViewProj);

	CVA::enable();

	if(m_mat != NULL)
		m_mat->sendToProgram();

	if(p_lights == NULL)
		drawSub();
	else{
		for(int a = 0; a < p_lights->size(); a++){
			light = p_lights->at(a);
			if(p_lights->at(a)->enabled()){
				light->sendToProgram(p_camera, m_modelMatrix);

				drawSub();
			}
		}
	}

	CVA::disable();
}
Esempio n. 11
0
void Graphic::DrawText( glm::mat4& projectionMatrix )
{
	glUseProgram( shaderText );

	glUniformMatrix4fv( glGetUniformLocation(shaderText, "projectionMatrix"), 1, GL_FALSE, &projectionMatrix[0][0] );

	for( int i(0); i < texts.size(); i++ )
	{
		Text& t( texts[i] );
		if( t.used == false )
			continue;
		std::string& s(t.s);
		glm::mat4 modelMatrix( glm::mat4( 1.0f ) );
		modelMatrix[3][2] = 0.05;
		for( int i(0), next_char(0), new_line(0); i < t.s.size(); i++ )
		{
			if( s[i] == ' ' )
			{
				next_char++;
				continue;
			}
			else if( s[i] == '\n' )
			{
				next_char = 0;
				new_line++;
				continue;
			}
			glBindTexture( GL_TEXTURE_2D, glTexture[ char_textures[ s[i] ] ] );

			modelMatrix[3][0] = t.x + next_char * t.size + t.size / 2;
			modelMatrix[3][1] = t.y - new_line * t.size - t.size / 2;
			next_char++;

			modelMatrix[0][0] = modelMatrix[1][1] = modelMatrix[2][2] = t.size;

			glm::mat4 modelViewMatrix = viewMatrix * modelMatrix;
			glUniformMatrix4fv( glGetUniformLocation( shaderText, "modelViewMatrix" ), 1, GL_FALSE, &modelViewMatrix[0][0] );

			glDrawArrays( GL_TRIANGLE_STRIP, 0, 4 );
		}
	}

	glUseProgram( 0 );
}
Esempio n. 12
0
void MeshRenderer :: computeDepthBuffer()
{
    ntk::TimeCount tc_depth("computeDepthBuffer", 1);
    glReadPixels(0, 0, m_depth_buffer.cols, m_depth_buffer.rows, GL_DEPTH_COMPONENT, GL_FLOAT, m_depth_buffer.data);
    tc_depth.elapsedMsecs("-- glReadPixels: ");
    cv::Mat1f flipped;
    flip(m_depth_buffer, flipped, 0);
    m_depth_buffer = flipped;

    // FIXME: this is very slow !!!
    // gluUnproject is not necessary, or at least one
    // could invert the projection Matrix only once.

    cv::Mat_<GLdouble> modelMatrix(4,4);
    setIdentity(modelMatrix);

    cv::Mat_<GLdouble> projMatrix(4,4);
    glGetDoublev(GL_PROJECTION_MATRIX,projMatrix[0]);
    // projMatrix = projMatrix.inv();

    int viewport[4];
    glGetIntegerv(GL_VIEWPORT,viewport);

    GLdouble objx, objy, objz;

    for (int r = 0; r < m_depth_buffer.rows; ++r)
        for (int c = 0; c < m_depth_buffer.cols; ++c)
        {
            double depth = m_depth_buffer(r,c);
            if (ntk::flt_eq(depth,1) || ntk::flt_eq(depth,0))
            {
                m_depth_buffer(r,c) = 0;
                continue;
            }
            gluUnProject(c, r, depth, modelMatrix[0], projMatrix[0], viewport,&objx, &objy, &objz);
            // double winz = (2.0*depth)-1;
            // double objz = (projMatrix(2,3)) / (winz * projMatrix(3,2) + projMatrix(3,3));
            // double objz = ;
            m_depth_buffer(r,c) = -objz;
        }
    tc_depth.elapsedMsecs(" -- after unprojecting points: ");
}
Esempio n. 13
0
	//-------------------------------------------------------------------------------
	void GameApp::renderDebugHUD()
	{
		if( m_renderDebugHUD )
		{
			m_renderer->pushCamera( m_debugCamera );
			m_mainFontParams.set( "text", std::string( "FPS: " ) + floatToString( m_currentFPS, 0 ) );
			mat4f modelMatrix( mat4f::IDENTITY );
			modelMatrix.translate( vec3f( (float)m_screenWidth, (float) m_screenHeight - 30.0f, 0.0f ) );
			m_mainFontParams.set( "modelMatrix", modelMatrix );
			m_mainFontParams.set( "posRel", std::string( "TOPRIGHT" ) );
			fireEvent( "renderText", m_mainFontParams );
			
			//m_mainFontParams.set( "posRel", std::string( "TOPLEFT" ) );
			//modelMatrix.loadIdentity();
			//modelMatrix.translate( vec3f( 0.0f, (float)m_screenHeight ) );
			//m_mainFontParams.set( "modelMatrix", modelMatrix );
			ProfileSystem::getInstance()->renderData( vec3f( 50.0f, (float)m_screenHeight - 30.0f, 0.0f ), m_debugCamera );
			m_renderer->popCamera();
		}
	}
Esempio n. 14
0
void Terrain::draw()
{
	mat4 mvp=mat4(0.0f);
	//rendering terrain
	//add modelmatrix if needed(should not be needed)
	mvp=this->projMatrix*this->viewMatrix;
	//terrain doesnt support any scaling etc
	mat4 modelMatrix(1.0f);
	this->TerrainShader.use();
	this->TerrainShader.setUniform("modelMatrix",modelMatrix);
	this->TerrainShader.setUniform("MVP",mvp);
	
	//draws ground plane
	glBindVertexArray(this->vaoh);
	glDrawArrays(GL_TRIANGLES,0,6);
	
	
	this->surfaceTexShader.use();
	this->surfaceTexShader.setUniform("outAlpha",1.0f);
	glActiveTexture(GL_TEXTURE0);
	glEnable (GL_BLEND);
	glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	glDisable(GL_DEPTH_TEST);
	for(unsigned int j=0;j<this->surfacesTextures.size();j++)
	{
		glBindVertexArray(this->surfacesTextures[j].getVaoH());
		for(unsigned int i=0; i<this->surfacesTextures[j].getModelMatrices()->size();i++)
		{			
			mvp=this->projMatrix*this->viewMatrix*this->surfacesTextures[j].getModelMatrices()->at(i);
			this->surfaceTexShader.setUniform("normalMatrix",mat3(this->surfacesTextures[j].getModelMatrices()->at(i)));
			this->surfaceTexShader.setUniform("MVP",mvp);
			glBindTexture(GL_TEXTURE_2D,this->surfacesTextures[j].getTexHandle());
			glDrawArrays(GL_TRIANGLES,0,6);
		}
	}
	
	this->surfaceBboxShader.use();
	this->surfaceBboxShader.setUniform("ro",0.0f);
	this->surfaceBboxShader.setUniform("go",1.0f);
	this->surfaceBboxShader.setUniform("bo",0.0f);
	glLineWidth(2);
	for(unsigned int j=0;j<this->surfacesTextures.size();j++)
	{		
		for(unsigned int i=0; i<this->surfacesTextures[j].getModelMatrices()->size();i++)
		{
			if(this->surfacesTextures[j].getDrawBbox()->at(i))
			{
				mvp=this->projMatrix*this->viewMatrix*this->surfacesTextures[j].getModelMatrices()->at(i);
				this->surfaceTexShader.setUniform("MVP",mvp);
				glDrawArrays(GL_LINE_STRIP,0,5);
			}
		}
	}
	
	glLineWidth(4);
	if(worldClickX>0)
	{
		this->surfaceBboxShader.setUniform("ro",0.1f);
		this->surfaceBboxShader.setUniform("go",0.6f);
		this->surfaceBboxShader.setUniform("bo",0.8f);
		if(this->drawCircle)
		{
			this->radiusMarker.setPos(vec3(this->worldClickX,0,-this->worldClickZ));
			mat4 mvp = this->projMatrix*this->viewMatrix*translate(vec3(this->worldClickX,0,-this->worldClickZ))*scale(mat4(1.0f),vec3(this->radiusMarker.getScale()));
			this->surfaceTexShader.setUniform("MVP",mvp);
			glBindVertexArray(this->radiusMarker.getVaoh());
			glDrawArrays(GL_LINE_STRIP,0,this->radiusMarker.getNrOfLines());
		}
	}
	
	glDisable(GL_BLEND);
	glEnable(GL_DEPTH_TEST);
	glUseProgram(0);
	glBindVertexArray(0);
}
Esempio n. 15
0
void KisOpenGLCanvas2::drawImage()
{
    if (!d->displayShader) {
        return;
    }

    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    KisCoordinatesConverter *converter = coordinatesConverter();

    d->displayShader->bind();

    QMatrix4x4 projectionMatrix;
    projectionMatrix.setToIdentity();
    projectionMatrix.ortho(0, width(), height(), 0, NEAR_VAL, FAR_VAL);

    // Set view/projection matrices
    QMatrix4x4 modelMatrix(coordinatesConverter()->imageToWidgetTransform());
    modelMatrix.optimize();
    modelMatrix = projectionMatrix * modelMatrix;
    d->displayShader->setUniformValue(d->displayShader->location(Uniform::ModelViewProjection), modelMatrix);

    QMatrix4x4 textureMatrix;
    textureMatrix.setToIdentity();
    d->displayShader->setUniformValue(d->displayShader->location(Uniform::TextureMatrix), textureMatrix);

    QRectF widgetRect(0,0, width(), height());
    QRectF widgetRectInImagePixels = converter->documentToImage(converter->widgetToDocument(widgetRect));

    qreal scaleX, scaleY;
    converter->imageScale(&scaleX, &scaleY);
    d->displayShader->setUniformValue(d->displayShader->location(Uniform::ViewportScale), (GLfloat) scaleX);
    d->displayShader->setUniformValue(d->displayShader->location(Uniform::TexelSize), (GLfloat) d->openGLImageTextures->texelSize());

    QRect ir = d->openGLImageTextures->storedImageBounds();
    QRect wr = widgetRectInImagePixels.toAlignedRect();

    if (!d->wrapAroundMode) {
        // if we don't want to paint wrapping images, just limit the
        // processing area, and the code will handle all the rest
        wr &= ir;
    }

    int firstColumn = d->xToColWithWrapCompensation(wr.left(), ir);
    int lastColumn = d->xToColWithWrapCompensation(wr.right(), ir);
    int firstRow = d->yToRowWithWrapCompensation(wr.top(), ir);
    int lastRow = d->yToRowWithWrapCompensation(wr.bottom(), ir);

    int minColumn = d->openGLImageTextures->xToCol(ir.left());
    int maxColumn = d->openGLImageTextures->xToCol(ir.right());
    int minRow = d->openGLImageTextures->yToRow(ir.top());
    int maxRow = d->openGLImageTextures->yToRow(ir.bottom());

    int imageColumns = maxColumn - minColumn + 1;
    int imageRows = maxRow - minRow + 1;

    for (int col = firstColumn; col <= lastColumn; col++) {
        for (int row = firstRow; row <= lastRow; row++) {

            int effectiveCol = col;
            int effectiveRow = row;
            QPointF tileWrappingTranslation;

            if (effectiveCol > maxColumn || effectiveCol < minColumn) {
                int translationStep = floor(qreal(col) / imageColumns);
                int originCol = translationStep * imageColumns;
                effectiveCol = col - originCol;
                tileWrappingTranslation.rx() = translationStep * ir.width();
            }

            if (effectiveRow > maxRow || effectiveRow < minRow) {
                int translationStep = floor(qreal(row) / imageRows);
                int originRow = translationStep * imageRows;
                effectiveRow = row - originRow;
                tileWrappingTranslation.ry() = translationStep * ir.height();
            }

            KisTextureTile *tile =
                    d->openGLImageTextures->getTextureTileCR(effectiveCol, effectiveRow);

            if (!tile) {
                warnUI << "OpenGL: Trying to paint texture tile but it has not been created yet.";
                continue;
            }

            /*
             * We create a float rect here to workaround Qt's
             * "history reasons" in calculation of right()
             * and bottom() coordinates of integer rects.
             */
            QRectF textureRect(tile->tileRectInTexturePixels());
            QRectF modelRect(tile->tileRectInImagePixels().translated(tileWrappingTranslation.x(), tileWrappingTranslation.y()));

            //Setup the geometry for rendering
            if (KisOpenGL::hasOpenGL3()) {
                rectToVertices(d->vertices, modelRect);

                d->quadBuffers[0].bind();
                d->quadBuffers[0].write(0, d->vertices, 3 * 6 * sizeof(float));

                rectToTexCoords(d->texCoords, textureRect);
                d->quadBuffers[1].bind();
                d->quadBuffers[1].write(0, d->texCoords, 2 * 6 * sizeof(float));
            }
            else {
                rectToVertices(d->vertices, modelRect);
                d->displayShader->enableAttributeArray(PROGRAM_VERTEX_ATTRIBUTE);
                d->displayShader->setAttributeArray(PROGRAM_VERTEX_ATTRIBUTE, d->vertices);

                rectToTexCoords(d->texCoords, textureRect);
                d->displayShader->enableAttributeArray(PROGRAM_TEXCOORD_ATTRIBUTE);
                d->displayShader->setAttributeArray(PROGRAM_TEXCOORD_ATTRIBUTE, d->texCoords);
            }

            if (d->displayFilter) {
                glActiveTexture(GL_TEXTURE0 + 1);
                glBindTexture(GL_TEXTURE_3D, d->displayFilter->lutTexture());
                d->displayShader->setUniformValue(d->displayShader->location(Uniform::Texture1), 1);
            }

            int currentLodPlane = tile->currentLodPlane();
            if (d->displayShader->location(Uniform::FixedLodLevel) >= 0) {
                d->displayShader->setUniformValue(d->displayShader->location(Uniform::FixedLodLevel),
                                                  (GLfloat) currentLodPlane);
            }

            glActiveTexture(GL_TEXTURE0);
            tile->bindToActiveTexture();

            if (currentLodPlane > 0) {
                glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
            } else if (SCALE_MORE_OR_EQUAL_TO(scaleX, scaleY, 2.0)) {
                glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
                glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
            } else {
                glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

                switch(d->filterMode) {
                case KisOpenGL::NearestFilterMode:
                    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
                    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
                    break;
                case KisOpenGL::BilinearFilterMode:
                    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
                    break;
                case KisOpenGL::TrilinearFilterMode:
                    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
                    break;
                case KisOpenGL::HighQualityFiltering:
                    if (SCALE_LESS_THAN(scaleX, scaleY, 0.5)) {
                        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
                    } else {
                        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
                    }
                    break;
                }
            }

            glDrawArrays(GL_TRIANGLES, 0, 6);
        }
    }

    glBindTexture(GL_TEXTURE_2D, 0);
    d->displayShader->release();
    glBindBuffer(GL_ARRAY_BUFFER, 0);
}
Esempio n. 16
0
void RenderUtil::drawReferenceVoxel(class Camera* camera, const glm::vec3 position, vector <glm::vec3> &brushCoords){
	if (!_referenceCubeMesh) initializeReferenceVoxel();

	blockShader.bind();


	const glm::vec3 &pos = camera->getPosition();

	glm::mat4 modelMatrix(1);
	modelMatrix[3][0] = -pos.x;
	modelMatrix[3][1] = -pos.y;
	modelMatrix[3][2] = -pos.z;

	glm::mat4 MVP = camera->getProjectionMatrix() * camera->getViewMatrix() * modelMatrix;

	//send our uniform data, the matrix, the light position, and the texture data
	glUniformMatrix4fv(blockShader.mvpID, 1, GL_FALSE, &MVP[0][0]);

	glm::vec3 lightPos = position;
	lightPos = glm::normalize(lightPos);
	glUniform3f(blockShader.lightPosID, lightPos.x, lightPos.y, lightPos.z);

	GLuint *indices;

	if ((int)position.x != (int)_lastPosition.x || (int)position.y != (int)_lastPosition.y || (int)position.z != (int)_lastPosition.z){
		if (brushCoords.size() < 1){
			indices = new GLuint[36];
			for (int i = 0; i < 24; i++){
				_voxVerts.verts[i] = _voxBaseVerts.verts[i];
				_voxVerts.verts[i].position.x += position.x;
				_voxVerts.verts[i].position.y += position.y;
				_voxVerts.verts[i].position.z += position.z;
			}
			RenderUtil::uploadMesh(&_referenceCubeMesh->vboID, &_referenceCubeMesh->iboID, &_voxVerts.verts[0], 24, _referenceCubeIndices, 36);
		}
		else{
			_brushVerts.resize(0);
			for (int i = 0; i < brushCoords.size(); i++){
				BlockVertex tv;
				for (int j = 0; j < 24; j++){
					tv = _voxBaseVerts.verts[j];
					/*tv.position.x = brushCoords[i].x;
					tv.position.y = brushCoords[i].y;
					tv.position.z = brushCoords[i].z;*/
					tv.position.x += position.x + brushCoords[i].x;
					tv.position.y += position.y + brushCoords[i].y;
					tv.position.z += position.z + brushCoords[i].z;
					_brushVerts.push_back(tv);
				}
			}
			indices = new GLuint[36 * brushCoords.size()];
			for (int i = 0, j = 0; i < 36 * brushCoords.size(); i += 6, j += 4){
				indices[i] = j;
				indices[i + 1] = j + 1;
				indices[i + 2] = j + 2;
				indices[i + 3] = j + 2;
				indices[i + 4] = j + 3;
				indices[i + 5] = j;
			}
			RenderUtil::uploadMesh(&_referenceCubeMesh->vboID, &_referenceCubeMesh->iboID, &_brushVerts[0], _brushVerts.size(), indices, 36 * brushCoords.size());
		}
		_lastPosition = position;
	}
	else{
		glBindBuffer(GL_ARRAY_BUFFER, _referenceCubeMesh->vboID);
		glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _referenceCubeMesh->iboID);
	}

	//initialize the buffer, only happens once
	
	//set our attribute pointers using our interleaved vertex data. Last parameter is offset into the vertex
	glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(BlockVertex), (void *)0); //vertexPosition
	glVertexAttribPointer(1, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(BlockVertex), (void *)12); //vertexColor
	glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, sizeof(BlockVertex), (void *)16); //vertexNormal

	//Finally, draw our data. The last parameter is the offset into the bound buffer
	if (brushCoords.size() > 0){
		glDrawElements(GL_TRIANGLES, (6 * _brushVerts.size()) / 4, GL_UNSIGNED_INT, NULL);
		//glDrawElements(GL_TRIANGLES, 36 * brushCoords.size(), GL_UNSIGNED_INT, NULL);
	}
	else{
		glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_INT, NULL);
	}

	blockShader.unBind();
}
Esempio n. 17
0
void Model::render() {
    glUniformMatrix4fv(glGetUniformLocation(shader, "model"), 1, GL_FALSE, glm::value_ptr(modelMatrix()));
    for(vector<Mesh *>::iterator it = meshes->begin(); it != meshes->end(); ++it) {
        (*it)->render(shader);
    }
}
Esempio n. 18
0
// this is able to handle multiple weapon graphics now
// removed mountRotation,they get such stuff from psObj directly now
static bool displayCompObj(DROID *psDroid, bool bButton, const glm::mat4 &viewMatrix)
{
	iIMDShape *psMoveAnim, *psStillAnim;
	SDWORD				iConnector;
	PROPULSION_STATS	*psPropStats;
	SDWORD				pieFlag, iPieData;
	PIELIGHT			brightness;
	UDWORD				colour;
	UBYTE	i;
	bool				didDrawSomething = false;

	glm::mat4 modelMatrix(1.f);

	if (graphicsTime - psDroid->timeLastHit < GAME_TICKS_PER_SEC / 4 && psDroid->lastHitWeapon == WSC_ELECTRONIC && !gamePaused())
	{
		colour = getPlayerColour(rand() % MAX_PLAYERS);
	}
	else
	{
		colour = getPlayerColour(psDroid->player);
	}

	/* get propulsion stats */
	psPropStats = asPropulsionStats + psDroid->asBits[COMP_PROPULSION];
	ASSERT_OR_RETURN(didDrawSomething, psPropStats != nullptr, "invalid propulsion stats pointer");

	//set pieflag for button object or ingame object
	if (bButton)
	{
		pieFlag = pie_BUTTON;
		brightness = WZCOL_WHITE;
	}
	else
	{
		pieFlag = pie_SHADOW;
		brightness = pal_SetBrightness(psDroid->illumination);
		// NOTE: Beware of transporters that are offscreen, on a mission!  We should *not* be checking tiles at this point in time!
		if (!isTransporter(psDroid) && !missionIsOffworld())
		{
			MAPTILE *psTile = worldTile(psDroid->pos.x, psDroid->pos.y);
			if (psTile->jammerBits & alliancebits[psDroid->player])
			{
				pieFlag |= pie_ECM;
			}
		}
	}

	/* set default components transparent */
	if (psDroid->asBits[COMP_PROPULSION] == 0)
	{
		pieFlag  |= pie_TRANSLUCENT;
		iPieData  = DEFAULT_COMPONENT_TRANSLUCENCY;
	}
	else
	{
		iPieData = 0;
	}

	if (!bButton && psPropStats->propulsionType == PROPULSION_TYPE_PROPELLOR)
	{
		// FIXME: change when adding submarines to the game
		modelMatrix *= glm::translate(glm::vec3(0.f, -world_coord(1) / 2.3f, 0.f));
	}

	iIMDShape *psShapeProp = (leftFirst ? getLeftPropulsionIMD(psDroid) : getRightPropulsionIMD(psDroid));
	if (psShapeProp)
	{
		if (pie_Draw3DShape(psShapeProp, 0, colour, brightness, pieFlag, iPieData, viewMatrix * modelMatrix))
		{
			didDrawSomething = true;
		}
	}

	/* set default components transparent */
	if (psDroid->asBits[COMP_BODY] == 0)
	{
		pieFlag  |= pie_TRANSLUCENT;
		iPieData  = DEFAULT_COMPONENT_TRANSLUCENCY;
	}
	else
	{
		pieFlag  &= ~pie_TRANSLUCENT;
		iPieData = 0;
	}

	/* Get the body graphic now*/
	iIMDShape *psShapeBody = BODY_IMD(psDroid, psDroid->player);
	if (psShapeBody)
	{
		iIMDShape *strImd = psShapeBody;
		if (psDroid->droidType == DROID_PERSON)
		{
			modelMatrix *= glm::scale(glm::vec3(.75f)); // FIXME - hideous....!!!!
		}
		if (strImd->objanimpie[psDroid->animationEvent])
		{
			strImd = psShapeBody->objanimpie[psDroid->animationEvent];
		}
		glm::mat4 viewModelMatrix = viewMatrix * modelMatrix;
		while (strImd)
		{
			if (drawShape(psDroid, strImd, colour, brightness, pieFlag, iPieData, viewModelMatrix))
			{
				didDrawSomething = true;
			}
			strImd = strImd->next;
		}
	}

	/* Render animation effects based on movement or lack thereof, if any */
	psMoveAnim = asBodyStats[psDroid->asBits[COMP_BODY]].ppMoveIMDList[psDroid->asBits[COMP_PROPULSION]];
	psStillAnim = asBodyStats[psDroid->asBits[COMP_BODY]].ppStillIMDList[psDroid->asBits[COMP_PROPULSION]];
	glm::mat4 viewModelMatrix = viewMatrix * modelMatrix;
	if (!bButton && psMoveAnim && psDroid->sMove.Status != MOVEINACTIVE)
	{
		if (pie_Draw3DShape(psMoveAnim, getModularScaledGraphicsTime(psMoveAnim->animInterval, psMoveAnim->numFrames), colour, brightness, pie_ADDITIVE, 200, viewModelMatrix))
		{
			didDrawSomething = true;
		}
	}
	else if (!bButton && psStillAnim) // standing still
	{
		if (pie_Draw3DShape(psStillAnim, getModularScaledGraphicsTime(psStillAnim->animInterval, psStillAnim->numFrames), colour, brightness, 0, 0, viewModelMatrix))
		{
			didDrawSomething = true;
		}
	}

	//don't change the screen coords of an object if drawing it in a button
	if (!bButton)
	{
		/* set up all the screen coords stuff - need to REMOVE FROM THIS LOOP */
		calcScreenCoords(psDroid, viewModelMatrix);
	}

	/* set default components transparent */
	if (psDroid->asWeaps[0].nStat        == 0 &&
	    psDroid->asBits[COMP_SENSOR]     == 0 &&
	    psDroid->asBits[COMP_ECM]        == 0 &&
	    psDroid->asBits[COMP_BRAIN]      == 0 &&
	    psDroid->asBits[COMP_REPAIRUNIT] == 0 &&
	    psDroid->asBits[COMP_CONSTRUCT]  == 0)
	{
		pieFlag  |= pie_TRANSLUCENT;
		iPieData  = DEFAULT_COMPONENT_TRANSLUCENCY;
	}
	else
	{
		pieFlag  &= ~pie_TRANSLUCENT;
		iPieData = 0;
	}

	if (psShapeBody && psShapeBody->nconnectors)
	{
		/* vtol weapons attach to connector 2 (underneath);
		 * all others to connector 1 */
		/* VTOL's now skip the first 5 connectors(0 to 4),
		VTOL's use 5,6,7,8 etc now */
		if (psPropStats->propulsionType == PROPULSION_TYPE_LIFT && psDroid->droidType == DROID_WEAPON)
		{
			iConnector = VTOL_CONNECTOR_START;
		}
		else
		{
			iConnector = 0;
		}

		switch (psDroid->droidType)
		{
		case DROID_DEFAULT:
		case DROID_TRANSPORTER:
		case DROID_SUPERTRANSPORTER:
		case DROID_CYBORG:
		case DROID_CYBORG_SUPER:
		case DROID_WEAPON:
		case DROID_COMMAND:		// command droids have a weapon to store all the graphics
			/*	Get the mounting graphic - we've already moved to the right position
			Allegedly - all droids will have a mount graphic so this shouldn't
			fall on it's arse......*/
			/* Double check that the weapon droid actually has any */
			for (i = 0; i < psDroid->numWeaps; i++)
			{
				if ((psDroid->asWeaps[i].nStat > 0 || psDroid->droidType == DROID_DEFAULT)
				    && psShapeBody->connectors)
				{
					Rotation rot = getInterpolatedWeaponRotation(psDroid, i, graphicsTime);

					glm::mat4 localModelMatrix = modelMatrix;

					//to skip number of VTOL_CONNECTOR_START ground unit connectors
					if (iConnector < VTOL_CONNECTOR_START)
					{
						localModelMatrix *= glm::translate(glm::vec3(psShapeBody->connectors[i].xzy()));
					}
					else
					{
						localModelMatrix *= glm::translate(glm::vec3(psShapeBody->connectors[iConnector + i].xzy()));
					}
					localModelMatrix *= glm::rotate(UNDEG(-rot.direction), glm::vec3(0.f, 1.f, 0.f));

					/* vtol weapons inverted */
					if (iConnector >= VTOL_CONNECTOR_START)
					{
						//this might affect gun rotation
						localModelMatrix *= glm::rotate(UNDEG(65536 / 2), glm::vec3(0.f, 0.f, 1.f));
					}

					/* Get the mount graphic */
					iIMDShape *psShape = WEAPON_MOUNT_IMD(psDroid, i);

					int recoilValue = getRecoil(psDroid->asWeaps[i]);
					localModelMatrix *= glm::translate(glm::vec3(0.f, 0.f, recoilValue / 3.f));

					/* Draw it */
					if (psShape)
					{
						if (pie_Draw3DShape(psShape, 0, colour, brightness, pieFlag, iPieData, viewMatrix * localModelMatrix))
						{
							didDrawSomething = true;
						}
					}
					localModelMatrix *= glm::translate(glm::vec3(0, 0, recoilValue));

					/* translate for weapon mount point */
					if (psShape && psShape->nconnectors)
					{
						localModelMatrix *= glm::translate(glm::vec3(psShape->connectors->xzy()));
					}

					/* vtol weapons inverted */
					if (iConnector >= VTOL_CONNECTOR_START)
					{
						//pitch the barrel down
						localModelMatrix *= glm::rotate(UNDEG(-rot.pitch), glm::vec3(1.f, 0.f, 0.f));
					}
					else
					{
						//pitch the barrel up
						localModelMatrix *= glm::rotate(UNDEG(rot.pitch), glm::vec3(1.f, 0.f, 0.f));
					}

					/* Get the weapon (gun?) graphic */
					psShape = WEAPON_IMD(psDroid, i);

					// We have a weapon so we draw it and a muzzle flash from weapon connector
					if (psShape)
					{
						glm::mat4 localViewModelMatrix = viewMatrix * localModelMatrix;
						if (pie_Draw3DShape(psShape, 0, colour, brightness, pieFlag, iPieData, localViewModelMatrix))
						{
							didDrawSomething = true;
						}
						drawMuzzleFlash(psDroid->asWeaps[i], psShape, MUZZLE_FLASH_PIE(psDroid, i), brightness, pieFlag, iPieData, localViewModelMatrix);
					}
				}
			}
			break;

		case DROID_SENSOR:
		case DROID_CONSTRUCT:
		case DROID_CYBORG_CONSTRUCT:
		case DROID_ECM:
		case DROID_REPAIR:
		case DROID_CYBORG_REPAIR:
			{
				Rotation rot = getInterpolatedWeaponRotation(psDroid, 0, graphicsTime);
				iIMDShape *psShape = nullptr;
				iIMDShape *psMountShape = nullptr;

				switch (psDroid->droidType)
				{
				default:
					ASSERT(false, "Bad component type");
					break;
				case DROID_SENSOR:
					psMountShape = SENSOR_MOUNT_IMD(psDroid, psDroid->player);
					/* Get the sensor graphic, assuming it's there */
					psShape = SENSOR_IMD(psDroid, psDroid->player);
					break;
				case DROID_CONSTRUCT:
				case DROID_CYBORG_CONSTRUCT:
					psMountShape = CONSTRUCT_MOUNT_IMD(psDroid, psDroid->player);
					/* Get the construct graphic assuming it's there */
					psShape = CONSTRUCT_IMD(psDroid, psDroid->player);
					break;
				case DROID_ECM:
					psMountShape = ECM_MOUNT_IMD(psDroid, psDroid->player);
					/* Get the ECM graphic assuming it's there.... */
					psShape = ECM_IMD(psDroid, psDroid->player);
					break;
				case DROID_REPAIR:
				case DROID_CYBORG_REPAIR:
					psMountShape = REPAIR_MOUNT_IMD(psDroid, psDroid->player);
					/* Get the Repair graphic assuming it's there.... */
					psShape = REPAIR_IMD(psDroid, psDroid->player);
					break;
				}
				/*	Get the mounting graphic - we've already moved to the right position
				Allegedly - all droids will have a mount graphic so this shouldn't
				fall on it's arse......*/
				//sensor and cyborg and ecm uses connectors[0]

				glm::mat4 localModelMatrix = modelMatrix;
				/* vtol weapons inverted */
				if (iConnector >= VTOL_CONNECTOR_START)
				{
					//this might affect gun rotation
					localModelMatrix *= glm::rotate(UNDEG(65536 / 2), glm::vec3(0.f, 0.f, 1.f));
				}

				localModelMatrix *= glm::translate(glm::vec3(psShapeBody->connectors[0].xzy()));

				localModelMatrix *= glm::rotate(UNDEG(-rot.direction), glm::vec3(0.f, 1.f, 0.f));
				/* Draw it */
				if (psMountShape)
				{
					if (pie_Draw3DShape(psMountShape, 0, colour, brightness, pieFlag, iPieData, viewMatrix * localModelMatrix))
					{
						didDrawSomething = true;
					}
				}

				/* translate for construct mount point if cyborg */
				if (cyborgDroid(psDroid) && psMountShape && psMountShape->nconnectors)
				{
					localModelMatrix *= glm::translate(glm::vec3(psMountShape->connectors[0].xzy()));
				}

				/* Draw it */
				if (psShape)
				{
					if (pie_Draw3DShape(psShape, 0, colour, brightness, pieFlag, iPieData, viewMatrix * localModelMatrix))
					{
						didDrawSomething = true;
					}

					// In repair droid case only:
					if ((psDroid->droidType == DROID_REPAIR || psDroid->droidType == DROID_CYBORG_REPAIR) &&
					    psShape->nconnectors && psDroid->action == DACTION_DROIDREPAIR)
					{
						Spacetime st = interpolateObjectSpacetime(psDroid, graphicsTime);
						localModelMatrix *= glm::translate(glm::vec3(psShape->connectors[0].xzy()));
						localModelMatrix *= glm::translate(glm::vec3(0.f, -20.f, 0.f));

						psShape = getImdFromIndex(MI_FLAME);

						/* Rotate for droid */
						localModelMatrix *= glm::rotate(UNDEG(st.rot.direction), glm::vec3(0.f, 1.f, 0.f));
						localModelMatrix *= glm::rotate(UNDEG(-st.rot.pitch), glm::vec3(1.f, 0.f, 0.f));
						localModelMatrix *= glm::rotate(UNDEG(-st.rot.roll), glm::vec3(0.f, 0.f, 1.f));
						//rotate Y
						localModelMatrix *= glm::rotate(UNDEG(rot.direction), glm::vec3(0.f, 1.f, 0.f));

						localModelMatrix *= glm::rotate(UNDEG(-player.r.y), glm::vec3(0.f, 1.f, 0.f));
						localModelMatrix *= glm::rotate(UNDEG(-player.r.x), glm::vec3(1.f, 0.f, 0.f));

						if (pie_Draw3DShape(psShape, getModularScaledGraphicsTime(psShape->animInterval, psShape->numFrames), 0, brightness, pie_ADDITIVE, 140, viewMatrix * localModelMatrix))
						{
							didDrawSomething = true;
						}

//						localModelMatrix *= glm::rotate(UNDEG(player.r.x), glm::vec3(1.f, 0.f, 0.f)); // Not used?
//						localModelMatrix *= glm::rotate(UNDEG(player.r.y), glm::vec3(0.f, 1.f, 0.f)); // Not used?
					}
				}
				break;
			}
		case DROID_PERSON:
			// no extra mounts for people
			break;
		default:
			ASSERT(!"invalid droid type", "Whoa! Weirdy type of droid found in drawComponentObject!!!");
			break;
		}
	}

	/* set default components transparent */
	if (psDroid->asBits[COMP_PROPULSION] == 0)
	{
		pieFlag  |= pie_TRANSLUCENT;
		iPieData  = DEFAULT_COMPONENT_TRANSLUCENCY;
	}
	else
	{
		pieFlag  &= ~pie_TRANSLUCENT;
		iPieData = 0;
	}

	// now render the other propulsion side
	psShapeProp = (leftFirst ? getRightPropulsionIMD(psDroid) : getLeftPropulsionIMD(psDroid));
	if (psShapeProp)
	{
		if (pie_Draw3DShape(psShapeProp, 0, colour, brightness, pieFlag, iPieData, viewModelMatrix)) // Safe to use viewModelMatrix because modelView has not been changed since it was calculated
		{
			didDrawSomething = true;
		}
	}

	return didDrawSomething;
}
Esempio n. 19
0
void Player::renderReflection() {
    glUniformMatrix4fv(glGetUniformLocation(shader, "model"), 1, GL_FALSE, glm::value_ptr(glm::scale(modelMatrix(), glm::vec3(2,2,2))));
    m->render(shader);
}
Esempio n. 20
0
void Graphic::Update( unsigned int diffTime )
{
	Messages();

	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	glLoadIdentity();

	glUseProgram( shaderProgram );

	float angle = 90; // degres
	glm::mat4 modelMatrix( glm::mat4( 1.0f ) );
	modelMatrix = glm::rotate( modelMatrix, angle, glm::vec3( 0.0f, 1.0f, 0.0f ) );

	glm::mat4 modelViewMatrix = viewMatrix * modelMatrix;
	glUniformMatrix4fv( glGetUniformLocation( shaderProgram, "modelViewMatrix" ), 1, GL_FALSE, &modelViewMatrix[0][0] );

	glm::mat3 tempMatrix = glm::inverseTranspose( (glm::mat3)modelViewMatrix );
	glUniformMatrix3fv( glGetUniformLocation( shaderProgram, "normalInverseTranspose"), 1, GL_FALSE, &tempMatrix[0][0] );

	/// handle the light position
	glm::vec4 lightPosition( -1.0f, 1.0f, 0.0f, 1.0f );
	lightPosition = viewMatrix * lightPosition;
	glUniform1fv( glGetUniformLocation( shaderProgram, "lightPosition"), 1, &lightPosition[0] );

	// TEXTURE
	GLuint texture;
	glGenTextures( 1, &texture );
	glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
	glBindTexture( GL_TEXTURE_2D, texture );

	glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );
	glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );
	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );

	glTexImage2D( GL_TEXTURE_2D, 0, 3, textures[0].width, textures[0].height, 0, GL_BGR_EXT, GL_UNSIGNED_BYTE, textures[0].t );

	glBindTexture( GL_TEXTURE_2D, texture );
	// END TEXTURE

	// MODEL
	GLuint Vbo[2];
	glGenBuffers(2, Vbo);

	int size = models[0].num * sizeof( float );

	// Vertex, normal, texture
	glBindBuffer(GL_ARRAY_BUFFER, Vbo[0]); 
	glBufferData(GL_ARRAY_BUFFER, size * 3, models[0].vertexs, GL_STATIC_DRAW);

	glBindBuffer(GL_ARRAY_BUFFER, Vbo[1]);
	glBufferData(GL_ARRAY_BUFFER, size * 3, models[0].normals, GL_STATIC_DRAW);
	
	glBindBuffer(GL_ARRAY_BUFFER, Vbo[2]);
	glBufferData(GL_ARRAY_BUFFER, size * 2, models[0].textureCoordinates, GL_STATIC_DRAW);

	// create 1 VAO
	GLuint Vao;
	glGenVertexArrays(1, &Vao);
	glBindVertexArray(Vao);

	// Vertex, normal, texture
	glEnableVertexAttribArray(0);
	glEnableVertexAttribArray(1);
	glEnableVertexAttribArray(2);

	GLubyte* null = 0;

	glBindBuffer(GL_ARRAY_BUFFER, Vbo[0]);
	glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, null);

	glBindBuffer(GL_ARRAY_BUFFER, Vbo[1]);
	glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, null);

	glBindBuffer(GL_ARRAY_BUFFER, Vbo[2]);
	glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 0, null);

	glBindVertexArray(Vao);
	glDrawArrays( GL_TRIANGLES, 0, models[0].num );
	// END MODEL

	glUseProgram(0);
	glBindVertexArray(0);

	SDL_GL_SwapBuffers();
}
Esempio n. 21
0
void KisOpenGLCanvas2::paintToolOutline(const QPainterPath &path)
{
    d->cursorShader->bind();

    // setup the mvp transformation
    KisCoordinatesConverter *converter = coordinatesConverter();

    QMatrix4x4 projectionMatrix;
    projectionMatrix.setToIdentity();
    projectionMatrix.ortho(0, width(), height(), 0, NEAR_VAL, FAR_VAL);

    // Set view/projection matrices
    QMatrix4x4 modelMatrix(converter->flakeToWidgetTransform());
    modelMatrix.optimize();
    modelMatrix = projectionMatrix * modelMatrix;
    d->cursorShader->setUniformValue(d->cursorShader->location(Uniform::ModelViewProjection), modelMatrix);

    glHint(GL_LINE_SMOOTH_HINT, GL_NICEST);

    // XXX: glLogicOp not in ES 2.0 -- it would be better to use another method.
    // It is defined in 3.1 core profile onward.
    // Actually, https://www.opengl.org/sdk/docs/man/html/glLogicOp.xhtml says it's in 2.0 onwards,
    // only not in ES, but we don't care about ES, so we could use the function directly.
    glEnable(GL_COLOR_LOGIC_OP);
    if (ptr_glLogicOp) {
        ptr_glLogicOp(GL_XOR);
    }

    // Paint the tool outline
    if (KisOpenGL::hasOpenGL3()) {
        d->outlineVAO.bind();
        d->lineBuffer.bind();
    }

    // Convert every disjointed subpath to a polygon and draw that polygon
    QList<QPolygonF> subPathPolygons = path.toSubpathPolygons();
    for (int i = 0; i < subPathPolygons.size(); i++) {
        const QPolygonF& polygon = subPathPolygons.at(i);

        QVector<QVector3D> vertices;
        vertices.resize(polygon.count());
        for (int j = 0; j < polygon.count(); j++) {
            QPointF p = polygon.at(j);
            vertices[j].setX(p.x());
            vertices[j].setY(p.y());
        }
        if (KisOpenGL::hasOpenGL3()) {
            d->lineBuffer.allocate(vertices.constData(), 3 * vertices.size() * sizeof(float));
        }
        else {
            d->cursorShader->enableAttributeArray(PROGRAM_VERTEX_ATTRIBUTE);
            d->cursorShader->setAttributeArray(PROGRAM_VERTEX_ATTRIBUTE, vertices.constData());
        }

        glDrawArrays(GL_LINE_STRIP, 0, vertices.size());
    }

    if (KisOpenGL::hasOpenGL3()) {
        d->lineBuffer.release();
        d->outlineVAO.release();
    }

    glDisable(GL_COLOR_LOGIC_OP);

    d->cursorShader->release();
}
Esempio n. 22
0
int main(void)
{
	//Set the error callback
	glfwSetErrorCallback(error_callback);

	//Initialize GLFW
	if (!glfwInit())
	{
		exit(EXIT_FAILURE);
	}

	//Set the GLFW window creation hints - these are optional
	//glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); //Request a specific OpenGL version
	//glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); //Request a specific OpenGL version
	//glfwWindowHint(GLFW_SAMPLES, 4); //Request 4x antialiasing
	//glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);


	//Create a window and create its OpenGL context
	window = glfwCreateWindow(960, 720, "Test Window", NULL, NULL);

	//If the window couldn't be created
	if (!window)
	{
		fprintf(stderr, "Failed to open GLFW window.\n");
		glfwTerminate();
		//exit(EXIT_FAILURE);
	}

	//This function makes the context of the specified window current on the calling thread. 
	glfwMakeContextCurrent(window);

	//Sets the key callback
	glfwSetKeyCallback(window, key_callback);

	//Initialize GLEW
	GLenum err = glewInit();

	//If GLEW hasn't initialized
	if (err != GLEW_OK)
	{
		fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
		return -1;
	}

	//Set a background color
	glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
	glfwSetCursorPos(window, 1024 / 2, 768 / 2);

	GLuint VertexArrayID;
	glGenVertexArrays(1, &VertexArrayID);
	glBindVertexArray(VertexArrayID);

	// Create and compile our GLSL program from the shaders
	GLuint red = LoadShaders("SimpleTransform.vertexshader", "SingleColorRed.fragmentshader");
	GLuint grid = LoadShaders("SimpleTransform.vertexshader", "SingleColorGrid.fragmentshader");
	glBindFragDataLocation(red, 0, "red");
	glBindFragDataLocation(grid, 1, "grid");
	// Get a handle for our "MVP" uniform
	GLuint MatrixID = glGetUniformLocation(red, "MVP");

	// Projection matrix : 45° Field of View, 4:3 ratio, display range : 0.1 unit <-> 100 units
	glm::mat4 Projection = glm::perspective(45.0f, 4.0f / 3.0f, 0.1f, 1000.0f);
	// Or, for an ortho camera :
	//glm::mat4 Projection = glm::ortho(-10.0f,10.0f,-10.0f,10.0f,0.0f,100.0f); // In world coordinates

	// Camera matrix
	glm::mat4 View = glm::lookAt(
		glm::vec3(4, 3, 3), // Camera is at (4,3,3), in World Space
		glm::vec3(0, 0, 0), // and looks at the origin
		glm::vec3(0, 1, 0)  // Head is up (set to 0,-1,0 to look upside-down)
		);


	static const GLfloat g_vertex_buffer_data[] = {
		-1.0f, -1.0f, 0.0f,
		1.0f, -1.0f, 0.0f,
		0.0f, 1.0f, 0.0f,
	};

	static const GLushort g_element_buffer_data[] = { 0, 1, 2 };

	GLuint vertexbuffer;
	glGenBuffers(1, &vertexbuffer);
	glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
	glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data), g_vertex_buffer_data, GL_STATIC_DRAW);

	static const GLfloat g_triangle_buffer_data[] = {
		-1.0f, -1.0f, -1.0f,
		1.0f, -1.0f, -1.0f,
		0.0f, 1.0f, -1.0f,
	};

	GLuint triangle;
	glGenBuffers(1, &triangle);
	glBindBuffer(GL_ARRAY_BUFFER, triangle);
	glBufferData(GL_ARRAY_BUFFER, sizeof(g_triangle_buffer_data), g_triangle_buffer_data, GL_STATIC_DRAW);

	// Enable depth test
	glEnable(GL_DEPTH_TEST);
	// Accept fragment if it closer to the camera than the former one
	glDepthFunc(GL_LESS);
	glEnable(GL_CULL_FACE);
	glEnable(GL_LIGHTING);
	glEnable(GL_SMOOTH);//OPENGL INSTANTIATION
	HRESULT hr;
	NUI_IMAGE_FRAME depthFrame;
	HANDLE hDepth;
	INuiSensor* pNuiSensor = NULL;
	int iSensorCount = 0;
	hr = NuiGetSensorCount(&iSensorCount);

	if (FAILED(hr))
		return hr;

	for (int i = 0; i < iSensorCount; i++)
	{
		INuiSensor* tempSensor;
		hr = NuiCreateSensorByIndex(i, &tempSensor);

		if (FAILED(hr))
			continue;

		hr = tempSensor->NuiStatus();
		if (S_OK == hr)
		{
			pNuiSensor = tempSensor;
			break;
		}

		tempSensor->Release();
	}

	for (int i = 0; i < 2048; i++) {
		depthLookUp[i] = rawDepthToMeters(i);
	}

	rotation = getRotationMatrix(theta, psi, fi);

	pNuiSensor->NuiInitialize(NUI_INITIALIZE_FLAG_USES_DEPTH);
	pNuiSensor->NuiImageStreamOpen(
		NUI_IMAGE_TYPE_DEPTH,
		NUI_IMAGE_RESOLUTION_320x240,
		0,
		2,
		NULL,
		&hDepth);//KINECT INSTANTIATION

	cout << "Starting Main Loop";

	static double lastTime = glfwGetTime();
	//Main Loop
	do
	{
		double currentTime = glfwGetTime();
		float deltaTime = float(currentTime - lastTime);
		//Clear color buffer
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

		glUseProgram(grid);
		modelMatrix(MatrixID);


		hr = pNuiSensor->NuiImageStreamGetNextFrame(hDepth, 0, &depthFrame);
		if (!FAILED(hr))
		{

			INuiFrameTexture* pTexture;
			NUI_LOCKED_RECT LockedRect;

			hr = pNuiSensor->NuiImageFrameGetDepthImagePixelFrameTexture(
				hDepth, &depthFrame, false, &pTexture);

			if (FAILED(hr))
			{
				pNuiSensor->NuiImageStreamReleaseFrame(hDepth, &depthFrame);
				continue;
			}

			pTexture->LockRect(0, &LockedRect, NULL, 0);//Kinect Image Grab
			int skipX = 1;
			int skipY = 1;
			float scalar = 4.0f;

			if (LockedRect.Pitch != 0)
			{
				for (int x = 0; x < width; x += skipX)
				{
					for (int y = 0; y < height; y += skipY)
					{
						const NUI_DEPTH_IMAGE_PIXEL * pBufferRun = reinterpret_cast<const NUI_DEPTH_IMAGE_PIXEL *>(LockedRect.pBits) + x + y * width;
						
						//float depth = (float)(pBufferRun->depth);
						//glm::vec3 location = realWorld(depth, height - y, x, 500.0f, 1000.0f);
						//createCube(0.006f, location);
						Vector4 locationDepth = NuiTransformDepthImageToSkeleton(x, y, (short)(pBufferRun->depth << 3));
						glm::vec3 locationDepthxyz = glm::vec3(locationDepth.x * scalar, locationDepth.y * scalar, locationDepth.z * scalar);
						createCube(0.009f, locationDepthxyz);
					}
				}
			}

			pTexture->UnlockRect(0);
			pTexture->Release();

			pNuiSensor->NuiImageStreamReleaseFrame(hDepth, &depthFrame);
		}

		createGrid();

		//Test drawings
		/*
		glUseProgram(red);
		modelMatrix(MatrixID);
		//createCube(0.05f, glm::vec3(1.0f,1.0f,1.0f));
		// 1rst attribute buffer : vertices
		glEnableVertexAttribArray(0);
		//createObject(vertexbuffer, GL_TRIANGLES, 3);
		//createObject(triangle, GL_TRIANGLES, 3);
		glDisableVertexAttribArray(0);
		*/

		//Swap buffers
		glfwSwapBuffers(window);
		//Get and organize events, like keyboard and mouse input, window resizing, etc...
		glfwPollEvents();

		std::string title = "Title | DELTA TIME " + std::to_string(1.0f/deltaTime);
		const char* pszConstString = title.c_str();
		glfwSetWindowTitle(window, pszConstString);

		lastTime = currentTime;
	} //Check if the ESC key had been pressed or if the window had been closed
	while (!glfwWindowShouldClose(window));


	//Close OpenGL window and terminate GLFW
	glfwDestroyWindow(window);
	//Finalize and clean up GLFW
	glfwTerminate();

	exit(EXIT_SUCCESS);
}
PMatrix3x3 PRenderTransform::normalMatrix() const
{
    PMatrix3x3 ret;
    pMatrix3x3InverseTransposeMatrix4x4(modelMatrix().m_m, ret.m_m);
    return ret;
}
Esempio n. 24
0
void KisOpenGLCanvas2::drawCheckers()
{
    if (!d->checkerShader) {
        return;
    }

    KisCoordinatesConverter *converter = coordinatesConverter();
    QTransform textureTransform;
    QTransform modelTransform;
    QRectF textureRect;
    QRectF modelRect;

    QRectF viewportRect = !d->wrapAroundMode ?
                converter->imageRectInViewportPixels() :
                converter->widgetToViewport(this->rect());

    converter->getOpenGLCheckersInfo(viewportRect,
                                     &textureTransform, &modelTransform, &textureRect, &modelRect, d->scrollCheckers);

    textureTransform *= QTransform::fromScale(d->checkSizeScale / KisOpenGLImageTextures::BACKGROUND_TEXTURE_SIZE,
                                              d->checkSizeScale / KisOpenGLImageTextures::BACKGROUND_TEXTURE_SIZE);

    if (!d->checkerShader->bind()) {
        qWarning() << "Could not bind checker shader";
        return;
    }

    QMatrix4x4 projectionMatrix;
    projectionMatrix.setToIdentity();
    projectionMatrix.ortho(0, width(), height(), 0, NEAR_VAL, FAR_VAL);

    // Set view/projection matrices
    QMatrix4x4 modelMatrix(modelTransform);
    modelMatrix.optimize();
    modelMatrix = projectionMatrix * modelMatrix;
    d->checkerShader->setUniformValue(d->checkerShader->location(Uniform::ModelViewProjection), modelMatrix);

    QMatrix4x4 textureMatrix(textureTransform);
    d->checkerShader->setUniformValue(d->checkerShader->location(Uniform::TextureMatrix), textureMatrix);

    //Setup the geometry for rendering
    if (KisOpenGL::hasOpenGL3()) {
        rectToVertices(d->vertices, modelRect);

        d->quadBuffers[0].bind();
        d->quadBuffers[0].write(0, d->vertices, 3 * 6 * sizeof(float));

        rectToTexCoords(d->texCoords, textureRect);
        d->quadBuffers[1].bind();
        d->quadBuffers[1].write(0, d->texCoords, 2 * 6 * sizeof(float));
    }
    else {
        rectToVertices(d->vertices, modelRect);
        d->checkerShader->enableAttributeArray(PROGRAM_VERTEX_ATTRIBUTE);
        d->checkerShader->setAttributeArray(PROGRAM_VERTEX_ATTRIBUTE, d->vertices);

        rectToTexCoords(d->texCoords, textureRect);
        d->checkerShader->enableAttributeArray(PROGRAM_TEXCOORD_ATTRIBUTE);
        d->checkerShader->setAttributeArray(PROGRAM_TEXCOORD_ATTRIBUTE, d->texCoords);
    }

    // render checkers
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, d->openGLImageTextures->checkerTexture());

    glDrawArrays(GL_TRIANGLES, 0, 6);

    glBindTexture(GL_TEXTURE_2D, 0);
    d->checkerShader->release();
    glBindBuffer(GL_ARRAY_BUFFER, 0);
}