当前位置: 首页>>代码示例>>C++>>正文


C++ QMatrix4x4::inverted方法代码示例

本文整理汇总了C++中QMatrix4x4::inverted方法的典型用法代码示例。如果您正苦于以下问题:C++ QMatrix4x4::inverted方法的具体用法?C++ QMatrix4x4::inverted怎么用?C++ QMatrix4x4::inverted使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在QMatrix4x4的用法示例。


在下文中一共展示了QMatrix4x4::inverted方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: mouse_raycast

QVector3D ExtraMath::mouse_raycast(int mx,
                                   int my,
                                   int width,
                                   int height,
                                   float invertedy,
                                   QMatrix4x4 view_matrix,
                                   QMatrix4x4 projection_matrix) {
    // normalize the x-mouse position
    float nx = (2.0f * mx) / width - 1.0f;
    // normalize the y-mouse position
    float ny = invertedy*(1.0f - (2.0f * my) / height);
    // clip the x,y,z values between -1:1
    QVector4D ray_clip = QVector4D(nx, ny, -1, 1.0);
    // invert the projection
    QMatrix4x4 pInverse = projection_matrix.inverted(NULL);
    // invert the view
    QMatrix4x4 vInverse = view_matrix.inverted(NULL);
    // "convert" the normalized ray to the projection values
    QVector4D ray_eye = pInverse*ray_clip;
    // change the w-value of the vector for matrix manipulation purposes
    ray_eye = QVector4D(ray_eye.x(), ray_eye.y(), -1.0, 0);
    // "convert" the new ray to the view values
    QVector4D ray_wor4 = vInverse*ray_eye;
    // take the x,y,z values of the new position
    QVector3D ray_wor = ray_wor4.toVector3D();
    ray_wor.normalize();  // make the ray a unit vector
    // return the raycast of the 2D mouse in the 3D world view projection
    return ray_wor;
}
开发者ID:Baggins800,项目名称:qt-game-template,代码行数:29,代码来源:extramath.cpp

示例2: glhUnProjectf

int GLWidget::glhUnProjectf(float& winx, float& winy, float& winz,
                            QMatrix4x4& modelview, QMatrix4x4& projection,
                            QVector4D& objectCoordinate)
  {
      //Transformation matrices
      QVector4D in,out;
      //Calculation for inverting a matrix, compute projection x modelview
      //and store in A[16]
      QMatrix4x4  A = projection * modelview;
      //Now compute the inverse of matrix A
      QMatrix4x4  m = A.inverted();

      //Transformation of normalized coordinates between -1 and 1
      in[0]=(winx)/(float)width()*2.0-1.0;
      in[1]=(1-(winy)/(float)height())*2.0-1.0;
      in[2]=2.0*winz-1.0;
      in[3]=1.0;
      //Objects coordinates
      out = m * in;

      if(out[3]==0.0)
         return 0;
      out[3]=1.0/out[3];
      objectCoordinate[0]=out[0]*out[3];
      objectCoordinate[1]=out[1]*out[3];
      objectCoordinate[2]=out[2]*out[3];
      return 1;
  }
开发者ID:Chrizzldi,项目名称:AwesomeBump,代码行数:28,代码来源:glwidget.cpp

示例3: fromVariant

QUniformValue *RenderView::inverseProjectionMatrix(const QMatrix4x4 &) const
{
    QMatrix4x4 projection;
    if (m_data->m_renderCamera)
        projection = m_data->m_renderCamera->projection();
    return QUniformValue::fromVariant(projection.inverted(), m_allocator);
}
开发者ID:James-intern,项目名称:Qt,代码行数:7,代码来源:renderview.cpp

示例4: draw

void Scene::draw(const Camera& camera, QOpenGLShaderProgram* program,
                 int uniformsFlags, bool bindProgram) const
{
    if(!_models or !_painter) {
        debugWarning("Null scene or painter not set.");
        return;
    }

    if(bindProgram)
        program->bind();

    if(uniformsFlags & ViewMatrix)
        program->setUniformValue("viewMatrix", camera.viewMatrix());
    if(uniformsFlags & ViewInvMatrix)
        program->setUniformValue("viewInvMatrix", camera.viewMatrix().inverted());
    if(uniformsFlags & ProjMatrix)
        program->setUniformValue("projMatrix", camera.projMatrix());
    if(uniformsFlags & ProjInvMatrix)
        program->setUniformValue("projInvMatrix", camera.projMatrix().inverted());

    QList<QGLSceneNode*> nodes= _models->allChildren();
    nodes << _models;

    foreach(QGLSceneNode* n, nodes) {
        if(!n->count())
            continue;

        const QMatrix4x4 modelMatrix= n->localTransform();

        if(uniformsFlags & ModelMatrix)
            program->setUniformValue("modelMatrix", modelMatrix);
        if(uniformsFlags & ModelInvMatrix)
            program->setUniformValue("modelInvMatrix", modelMatrix.inverted());
        if(uniformsFlags & ModelITMatrix)
            program->setUniformValue("modelITMatrix", modelMatrix.inverted().transposed());
        if(uniformsFlags & MVPMatrix)
            program->setUniformValue("mvpMatrix", camera.projMatrix() * camera.viewMatrix() * modelMatrix);

        n->material()->bind(_painter);
        n->geometry().draw(_painter, n->start(), n->count());
    }

    if(bindProgram)
        program->release();
}
开发者ID:pablo-odorico,项目名称:cldeferred,代码行数:45,代码来源:scene.cpp

示例5: drawCoords

void ViewportView::drawCoords(QPainter* painter) const
{
    QPointF mouse_pos = mapToScene(mapFromGlobal(QCursor::pos()));
    if (!sceneRect().contains(mouse_pos))
    {
        return;
    }

    // Get rotate-only transform matrix
    QMatrix4x4 M = getMatrix(ROT);
    const float threshold = 0.98;

    const auto a = M.inverted() * QVector3D(0, 0, 1);

    QList<QPair<char, QVector3D>> axes = {
        {'x', QVector3D(1, 0, 0)},
        {'y', QVector3D(0, 1, 0)},
        {'z', QVector3D(0, 0, 1)}};

    char axis = 0;
    float opacity = 0;
    for (const auto v : axes)
    {
        float dot = fabs(QVector3D::dotProduct(a, v.second));
        if (dot > threshold)
        {
            axis = v.first;
            opacity = (dot - threshold) / (1 - threshold);
        }
    }

    auto p = sceneToWorld(mouse_pos);

    int value = opacity * 200;

    painter->setPen(QPen(QColor(255, 255, 255, value)));
    QString txt;
    if (axis == 'z')
    {
        txt = QString("X: %1\nY: %2").arg(p.x()).arg(p.y());
    }
    else if (axis == 'y')
    {
        txt = QString("X: %1\nZ: %2").arg(p.x()).arg(p.z());
    }
    else if (axis == 'x')
    {
        txt = QString("Y: %1\nZ: %2").arg(p.y()).arg(p.z());
    }

    painter->drawText({-width()/2.0 + 10, -height()/2.0 + 10, 300, 200}, txt);
}
开发者ID:pfelecan,项目名称:antimony-debian-packaging,代码行数:52,代码来源:view.cpp

示例6: updateShotLines

/**
  \brief When a station has been selected, this updates the shot lines

  This shows the shot lines from the selected station.  If no station is
  currently selected, this will hide the lines
  */
void cwScrapStationView::updateShotLines() {
    if(scrap() == nullptr) { return; }
    if(scrap()->parentNote() == nullptr) { return; }
    if(scrap()->parentNote()->parentTrip() == nullptr) { return; }
    if(transformUpdater() == nullptr) { return; }

    cwNoteStation noteStation = scrap()->station(selectedItemIndex());
    //Get the current trip
    cwNote* note = scrap()->parentNote();
    cwTrip* trip = note->parentTrip();
    cwCave* cave = trip->parentCave();
    cwStationPositionLookup stationPositionLookup = cave->stationPositionLookup();

    //Clear all the lines
    ShotLines.clear();

    if(noteStation.isValid() && stationPositionLookup.hasPosition(noteStation.name())) {
        QString stationName = noteStation.name();
        QSet<cwStation> neighboringStations = trip->neighboringStations(stationName);

        //The position of the selected station
        QVector3D selectedStationPos = stationPositionLookup.position(noteStation.name());

        //Create the matrix to covert global position into note position
        QMatrix4x4 noteTransformMatrix = scrap()->noteTransformation()->matrix(); //Matrix from page coordinates to cave coordinates
        noteTransformMatrix = noteTransformMatrix.inverted(); //From cave coordinates to page coordinates

        QMatrix4x4 notePageAspect = note->scaleMatrix().inverted(); //The note's aspect ratio

        QMatrix4x4 offsetMatrix;
        offsetMatrix.translate(-selectedStationPos);

        QMatrix4x4 dotPerMeter;
        dotPerMeter.scale(note->dotPerMeter(), note->dotPerMeter(), 1.0);

        QMatrix4x4 noteStationOffset;
        noteStationOffset.translate(QVector3D(noteStation.positionOnNote()));

        QMatrix4x4 toNormalizedNote = noteStationOffset *
                dotPerMeter *
                notePageAspect *
                noteTransformMatrix *
                offsetMatrix;

        //Go through all the neighboring stations and add the position to the line
        foreach(cwStation station, neighboringStations) {

            QVector3D currentPos = stationPositionLookup.position(station.name());
            QVector3D normalizeNotePos = toNormalizedNote.map(currentPos);

            ShotLines.append(QLineF(noteStation.positionOnNote(), normalizeNotePos.toPointF()));
        }
开发者ID:jlillest,项目名称:cavewhere,代码行数:58,代码来源:cwScrapStationView.cpp

示例7: qSwap

/*!
    Maps \a point from viewport co-ordinates to eye co-ordinates.
    The size of the viewport is given by \a viewportSize, and its
    aspect ratio by \a aspectRatio.

    The returned vector will have its x and y components set to the
    position of the point on the near plane, and the z component
    set to -nearPlane().

    This function is used for converting a mouse event's position
    into eye co-ordinates within the current camera view.
*/
QVector3D QGLCamera::mapPoint
    (const QPoint& point, float aspectRatio, const QSize& viewportSize) const
{
    Q_D(const QGLCamera);

    // Rotate the co-ordinate system to account for the screen rotation.
    int x = point.x();
    int y = point.y();
    int width = viewportSize.width();
    int height = viewportSize.height();
    if (!d->adjustForAspectRatio)
        aspectRatio = 1.0f;
    if (d->screenRotation == 90) {
        if (aspectRatio != 0.0f)
            aspectRatio = 1.0f / aspectRatio;
        qSwap(x, y);
        qSwap(width, height);
        y = height - 1 - y;
    } else if (d->screenRotation == 180) {
        x = width - 1 - x;
        y = height - 1 - y;
    } else if (d->screenRotation == 270) {
        if (aspectRatio != 0.0f)
            aspectRatio = 1.0f / aspectRatio;
        qSwap(x, y);
        qSwap(width, height);
    }

    // Determine the relative distance from the middle of the screen.
    // After this xrel and yrel are typically between -1.0 and +1.0
    // (unless the point was outside the viewport).  The yrel is
    // flipped upside down to account for the incoming co-ordinate
    // being left-handed, but the world being right-handed.
    float xrel, yrel;
    if (width)
        xrel = ((float(x * 2)) - float(width)) / float(width);
    else
        xrel = 0.0f;
    if (height)
        yrel = -((float(y * 2)) - float(height)) / float(height);
    else
        yrel = 0.0f;

    // Reverse the projection and return the point in world co-ordinates.
    QMatrix4x4 m = projectionMatrix(aspectRatio);
    QMatrix4x4 invm = m.inverted();
    return invm.map(QVector3D(xrel, yrel, -1.0f));
}
开发者ID:Distrotech,项目名称:qt3d,代码行数:60,代码来源:qglcamera.cpp

示例8: draw

void BinghamRenderer::draw( QMatrix4x4 p_matrix, QMatrix4x4 mv_matrix, int width, int height, int renderMode, PropertyGroup& props )
{
    if ( renderMode != 1 ) // we are drawing opaque objects
    {
        // obviously not opaque
        return;
    }

    setRenderParams( props );

    if ( m_orient == 0 )
    {
        return;
    }

    m_pMatrix = p_matrix;
    m_mvMatrix = mv_matrix;


    initGeometry( props );

    QGLShaderProgram* program = GLFunctions::getShader( "qball" );
    program->bind();

    program->setUniformValue( "u_alpha", 1.0f );
    program->setUniformValue( "u_renderMode", renderMode );
    program->setUniformValue( "u_canvasSize", width, height );
    program->setUniformValue( "D0", 9 );
    program->setUniformValue( "D1", 10 );
    program->setUniformValue( "D2", 11 );
    program->setUniformValue( "P0", 12 );

    // Set modelview-projection matrix
    program->setUniformValue( "mvp_matrix", p_matrix * mv_matrix );
    program->setUniformValue( "mv_matrixInvert", mv_matrix.inverted() );
    program->setUniformValue( "u_hideNegativeLobes", m_minMaxScaling );
    program->setUniformValue( "u_scaling", m_scaling );

    glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, vboIds[ 0 ] );
    glBindBuffer( GL_ARRAY_BUFFER, vboIds[ 1 ] );
    setShaderVars( props );
    glDrawElements( GL_TRIANGLES, m_tris1, GL_UNSIGNED_INT, 0 );

    glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 );
    glBindBuffer( GL_ARRAY_BUFFER, 0 );
}
开发者ID:dmastrovito,项目名称:braingl,代码行数:46,代码来源:binghamrenderer.cpp

示例9: draw

void SeaNode::draw(std::stack<QMatrix4x4> &MVStack, QMatrix4x4 cameraMatrix, QMatrix4x4 projectionMatrix, QOpenGLShaderProgram *shader) {
	QOpenGLShaderProgram *sh = Shaders::waterGeometryProgram;
	MVStack.push(MVStack.top());

	MVStack.top().translate(this->translation);

	//Convert the quat to a matrix, may be a performance leak.
	QMatrix4x4 tempRot;
	tempRot.rotate(this->rotation.normalized());
	MVStack.top() *= tempRot;

	//If the node is a leaf, draw its contents
	if(leaf) {
		Shaders::bind(sh);
		glUniformMatrix4fv(sh->uniformLocation("modelViewMatrix"), 1, GL_FALSE, MVStack.top().constData());
		glUniformMatrix4fv(sh->uniformLocation("cameraInverseMatrix"), 1, GL_FALSE, cameraMatrix.inverted().constData());
		glUniformMatrix4fv(sh->uniformLocation("perspectiveMatrix"), 1, GL_FALSE, projectionMatrix.constData());
		glUniformMatrix4fv(sh->uniformLocation("normalMatrix"), 1, GL_FALSE, MVStack.top().inverted().transposed().constData());
		int r = (id & 0x000000FF) >>  0;
		int g = (id & 0x0000FF00) >>  8;
		int b = (id & 0x00FF0000) >> 16;
		glUniform4f(sh->uniformLocation("id"), r/255.0f, g/255.0f, b/255.0f, 1.0f);

		glUniform4fv(sh->uniformLocation("color"), 1, color);

		struct timeval start;
		gettimeofday(&start, NULL);
		float seconds = ((start.tv_sec % (int) periodicity) + start.tv_usec / 1000000.0) / (periodicity / 4);

		glActiveTexture(GL_TEXTURE5);
		glBindTexture(GL_TEXTURE_3D, noiseTexture);
		//glUniform1i(sh->uniformLocation("noiseTexture"), 5);

		glUniform1i(sh->uniformLocation("seaWidth"), seaWidth);
		glUniform1i(sh->uniformLocation("seaHeight"), seaHeight);
		glUniform1f(sh->uniformLocation("time"), seconds);

		this->primitive->draw();
		Shaders::release(sh);
	} else {
开发者ID:TheSlothExperience,项目名称:SheepBattleBoats,代码行数:40,代码来源:seanode.cpp

示例10: updateCUDALights

void VolRenRaycastCuda::updateCUDALights(const QMatrix4x4& matView)
{
    CudaLight cudaLights[10];
    for (unsigned int i = 0; i < lights.size(); ++i)
    {
        QVector3D lightDir(matView.inverted() * QVector4D(lights[i].direction, 0.f));
        lightDir.normalize();
        cudaLights[i].direction.x = lightDir.x();
        cudaLights[i].direction.y = lightDir.y();
        cudaLights[i].direction.z = lightDir.z();
        cudaLights[i].ambient.x = lights[i].color.x() * lights[i].ambient;
        cudaLights[i].ambient.y = lights[i].color.y() * lights[i].ambient;
        cudaLights[i].ambient.z = lights[i].color.z() * lights[i].ambient;
        cudaLights[i].diffuse.x = lights[i].color.x() * lights[i].diffuse;
        cudaLights[i].diffuse.y = lights[i].color.y() * lights[i].diffuse;
        cudaLights[i].diffuse.z = lights[i].color.z() * lights[i].diffuse;
        cudaLights[i].specular.x = lights[i].color.x() * lights[i].specular;
        cudaLights[i].specular.y = lights[i].color.y() * lights[i].specular;
        cudaLights[i].specular.z = lights[i].color.z() * lights[i].specular;
        cudaLights[i].shininess = lights[i].shininess;
    }
    cudaSetLights(lights.size(), cudaLights);
}
开发者ID:marwan-abdellah,项目名称:VolRen,代码行数:23,代码来源:volrenraycastcuda.cpp

示例11: compute

    // TODO: optimize for other color spaces
    void compute() const {
        recompute = false;
        //http://docs.rainmeter.net/tips/colormatrix-guide
        //http://www.graficaobscura.com/matrix/index.html
        //http://beesbuzz.biz/code/hsv_color_transforms.php
        // ??
        const float b = brightness;
        // brightness R,G,B
        QMatrix4x4 B(1, 0, 0, b,
                     0, 1, 0, b,
                     0, 0, 1, b,
                     0, 0, 0, 1);
        // Contrast (offset) R,G,B
        const float c = contrast+1.0;
        const float t = (1.0 - c) / 2.0;
        QMatrix4x4 C(c, 0, 0, t,
                     0, c, 0, t,
                     0, 0, c, t,
                     0, 0, 0, 1);
        // Saturation
        const float wr = 0.3086f;
        const float wg = 0.6094f;
        const float wb = 0.0820f;
        float s = saturation + 1.0f;
        QMatrix4x4 S(
            (1.0f - s)*wr + s, (1.0f - s)*wg    , (1.0f - s)*wb    , 0.0f,
            (1.0f - s)*wr    , (1.0f - s)*wg + s, (1.0f - s)*wb    , 0.0f,
            (1.0f - s)*wr    , (1.0f - s)*wg    , (1.0f - s)*wb + s, 0.0f,
                         0.0f,              0.0f,              0.0f, 1.0f
        );
        // Hue
        const float n = 1.0f / sqrtf(3.0f);       // normalized hue rotation axis: sqrt(3)*(1 1 1)
        const float h = hue*M_PI;               // hue rotation angle
        const float hc = cosf(h);
        const float hs = sinf(h);
        QMatrix4x4 H(     // conversion of angle/axis representation to matrix representation
            n*n*(1.0f - hc) + hc  , n*n*(1.0f - hc) - n*hs, n*n*(1.0f - hc) + n*hs, 0.0f,
            n*n*(1.0f - hc) + n*hs, n*n*(1.0f - hc) + hc  , n*n*(1.0f - hc) - n*hs, 0.0f,
            n*n*(1.0f - hc) - n*hs, n*n*(1.0f - hc) + n*hs, n*n*(1.0f - hc) + hc  , 0.0f,
                              0.0f,                   0.0f,                   0.0f, 1.0f
        );

        // B*C*S*H*rgb_range_mat(*yuv2rgb*yuv_range_mat)*bpc_scale
        M = B*C*S*H;
        // M *= rgb_range_translate*rgb_range_scale
        // TODO: transform to output color space other than RGB
        switch (cs_out) {
        case ColorSpace_XYZ:
            M = kXYZ2sRGB.inverted() * M;
            break;
        case ColorSpace_RGB:
            M *= ColorRangeRGB(ColorRange_Full, range_out);
            break;
        case ColorSpace_GBR:
            M *= ColorRangeRGB(ColorRange_Full, range_out);
            M = kGBR2RGB.inverted() * M;
            break;
        default:
            M = YUV2RGB(cs_out).inverted() * M;
            break;
        }

        switch (cs_in) {
        case ColorSpace_XYZ:
            M *= kXYZ2sRGB;
            break;
        case ColorSpace_RGB:
            break;
        case ColorSpace_GBR:
            M *= kGBR2RGB;
            break;
        default:
            M *= YUV2RGB(cs_in)*ColorRangeYUV(range_in, ColorRange_Full);
            break;
        }
        if (bpc_scale != 1.0 && cs_in != ColorSpace_XYZ) { // why no range correction for xyz?
            //qDebug("bpc scale: %f", bpc_scale);
            M *= QMatrix4x4(bpc_scale, 0, 0, 0,
                            0, bpc_scale, 0, 0,
                            0, 0, bpc_scale, 0,
                            0, 0, 0, a_bpc_scale ? bpc_scale : 1); // scale alpha channel too
        }
        //qDebug() << "color mat: " << M;
    }
开发者ID:SvetZari,项目名称:QtAV,代码行数:85,代码来源:ColorTransform.cpp

示例12: QPoint

QPoint CubeItem::cubeIntersection
    (QWidget *widget, const QPoint &point, int *actualFace) const
{
    // Bail out if no scene.
    if (!mScene) {
        *actualFace = -1;
        return QPoint();
    }

    // Get the combined matrix for the projection.
    int dpiX = widget->logicalDpiX();
    int dpiY = widget->logicalDpiY();
    QRectF bounds = boundingRect();
    qreal aspectRatio = (bounds.width() * dpiY) / (bounds.height() * dpiX);
    QMatrix4x4 mv = camera()->modelViewMatrix();
    QMatrix4x4 proj = camera()->projectionMatrix(aspectRatio);
    QMatrix4x4 combined = proj * mv;

    // Find the relative position of the point within (-1, -1) to (1, 1).
    QPointF relativePoint =
        QPointF((point.x() - bounds.center().x()) * 2 / bounds.width(),
                -(point.y() - bounds.center().y()) * 2 / bounds.height());

    // Determine which face of the cube contains the point.
    QVector3D pt1, pt2, pt3, pt4;
    bool singleFace = (pressedFace != -1);
    for (int face = 0; face < 6; ++face) {
        if (singleFace && face != pressedFace)
            continue;

        // Create a polygon from the projected version of the face
        // so that we can test for point membership.
        pt1 = QVector3D(vertexData[face * 4 * 3],
                        vertexData[face * 4 * 3 + 1],
                        vertexData[face * 4 * 3 + 2]);
        pt2 = QVector3D(vertexData[face * 4 * 3 + 3],
                        vertexData[face * 4 * 3 + 4],
                        vertexData[face * 4 * 3 + 5]);
        pt3 = QVector3D(vertexData[face * 4 * 3 + 6],
                        vertexData[face * 4 * 3 + 7],
                        vertexData[face * 4 * 3 + 8]);
        pt4 = QVector3D(vertexData[face * 4 * 3 + 9],
                        vertexData[face * 4 * 3 + 10],
                        vertexData[face * 4 * 3 + 11]);
        QVector<QPointF> points2d;
        points2d.append((combined * pt1).toPointF());
        points2d.append((combined * pt2).toPointF());
        points2d.append((combined * pt3).toPointF());
        points2d.append((combined * pt4).toPointF());
        QPolygonF polygon(points2d);
        if (!singleFace) {
            if (!polygon.containsPoint(relativePoint, Qt::OddEvenFill))
                continue;
        }

        // We want the face that is pointing towards the user.
        QVector3D v = mv.mapVector
            (QVector3D::crossProduct(pt2 - pt1, pt3 - pt1));
        if (!singleFace && v.z() <= 0.0f)
            continue;

        // Determine the intersection between the cube face and
        // the ray coming from the eye position.
        QVector3D eyept = proj.inverted().map
            (QVector3D(relativePoint.x(), relativePoint.y(), -1.0f));
        QLine3D ray(QVector3D(0, 0, 0), eyept);
        QPlane3D plane(mv * pt1, v);
        QResult<QVector3D> intersection = plane.intersection(ray);
        if (!intersection.isValid())
            continue;
        QVector3D worldpt = mv.inverted().map(intersection.value());

        // Map the world point to the range 0..1.
        worldpt = (worldpt / CubeSize) + QVector3D(0.5f, 0.5f, 0.5f);

        // Figure out the texture co-ordinates on the face that
        // correspond to the point.
        qreal xtex, ytex;
        switch (face) {
        case 0:
            xtex = 1.0f - worldpt.y();
            ytex = 1.0f - worldpt.z();
            break;
        case 1:
            xtex = 1.0f - worldpt.x();
            ytex = 1.0f - worldpt.z();
            break;
        case 2:
            xtex = worldpt.y();
            ytex = 1.0f - worldpt.z();
            break;
        case 3:
            xtex = worldpt.x();
            ytex = 1.0f - worldpt.z();
            break;
        case 4:
            xtex = worldpt.x();
            ytex = 1.0f - worldpt.y();
            break;
        case 5: default:
//.........这里部分代码省略.........
开发者ID:slavablind91,项目名称:code,代码行数:101,代码来源:cubeitem.cpp

示例13: paintGL

void Scene::paintGL(){
    setStates();                    // включаем буфер глубины, свет и прочее (возможно можно вынести в initGL)

    //glClear(GL_COLOR_BUFFER_BIT); // если включен буфер глубины, то без его очистки мы ничего не увидим
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    //glMatrixMode(GL_PROJECTION);
    //qgluPerspective(60.0, width / height, 0.01, 15.0);

    //glMatrixMode(GL_MODELVIEW);

    //пишем матрицы преобразований
    QMatrix4x4 LMM; // Local Model matrix (делает преобразования в локальных координатах объекта, для одного объекта их может быть несколько для разных частей объекта)
    QMatrix4x4 MM; // Model matrix (выносит координаты объекта в координаты пространства сцены,
                  //выполняется в следующем порядке - масштабирование, поворот, перенос)
                  // TranslationMatrix * RotationMatrix * ScaleMatrix * OriginalVector; (в коде это выглядит в обратном порядке)
    QMatrix4x4 MVM; // ModelView matrix (View matrix)("масштабирует крутит и перемещает весь мир")
    QMatrix4x4 CameraView; // тоже самое что и MVM, но для использования функции LookAt
    QMatrix4x4 PM; // Projection matrix // проекционная матрица
    QMatrix4x4 MVPM; // ModelViewProjection matrix (projection * view * model)
    if (perspective) {
        // устанавливаем трёхмерную канву (в перспективной проекции) для рисования (плоскости отсечения)
        // угол перспективы, отношение сторон, расстояние до ближней отсекающей плоскости и дальней
        PM.perspective(cameraFocusAngle,ratio,0.1f,100.0f);  // glFrustum( xmin, xmax, ymin, ymax, near, far)  // gluPerspective(fovy, aspect, near, far)
    }
    else {
        // устанавливаем трёхмерную канву (в ортогональной проекции) для рисования (плоскости отсечения)
        PM.ortho(-2.0f,2.0f,-2.0f,2.0f,-8.0f,8.0f); // glOrtho(left,right,bottom,top,near,far) // увеличение значений уменьшает фигуры на сцене (по Z задаём больше, чтобы не видеть отсечение фигур)
        // переносим по z дальше, обязательное условие для перспективной проекции // по оси z 0 это "глаз", - движение камеры назад, + вперёд.
    }
    ///MVM.translate(0.0f,0.0f,-6.0f); // переносим по z от "глаз", сдвигаем камеру на минус, т.е. в сторону затылка.
    // не работает в ортогональной проекции если перенести слишком далеко, за пределы куба отсечения
    // оппа, мы видим передние границы пирамиды отсечения, где всё отсекается (тут-то шейдерным сферам и конец)
    // изменяем масштаб фигуры (увеличиваем)
    ///MVM.scale(10.0f);  // отрицательное число переворачивает проекцию // влияет только на ортогональную проекцию // убивает Шферы
    // указываем угол поворота и ось поворота смотрящую из центра координат к точке x,y,z,
    MVM.rotate(m_angle,0.0f,1.0f,0.0f);  // поворот вокруг оси центра координат
    CameraView.lookAt(cameraEye,cameraCenter,cameraUp); // установка камеры (матрицы трансфрмации)
    MVM=CameraView*MVM;  // получаем матрицу трансформации итогового вида

    // находим проекционную инверсную мтрицу
    bool inverted;
    QMatrix4x4 PMi=PM.inverted(&inverted);
    if (!inverted)
        qDebug() << "PMi не конвертится";
    MVPM=PM*MVM;
    QMatrix4x4 MVPMi=MVPM.inverted(&inverted);
    if (!inverted)
        qDebug() << "MVPMi не конвертится";

    // РИСУЕМ ТРЕУГОЛЬНИК
    // инициализируем данные программы матрицы и атрибуты
    m_triangle->init();
    // зaпихиваем в его программу матрицу ориентации
    m_triangle->m_program.setUniformValue(m_triangle->m_matrixUniform, MVPM);
    // вызываем функцию рисования объекта (или объектов в for)
    m_triangle->draw();
    // проводим сброс инициализации параметров
    m_triangle->drop();//*/

    //РИСУЕМ СФЕРЫ
    m_shphere->init();
    m_shphere->m_program->setUniformValue(m_shphere->m_matrixUniform, MVPM);
    m_shphere->m_program->setUniformValue("PMi", PMi);
    m_shphere->m_program->setUniformValue("MVM", MVM);
    m_shphere->m_program->setUniformValue("MVPMi", MVPMi);
    m_shphere->m_program->setUniformValue("viewport",viewport);
    m_shphere->draw();
    m_shphere->drop();//*/

}
开发者ID:paraschenkodn,项目名称:karta,代码行数:70,代码来源:scene.cpp

示例14: draw

void FiberRenderer::draw( QMatrix4x4 p_matrix, QMatrix4x4 mv_matrix, int width, int height, int renderMode, PropertyGroup* props )
{
    float alpha = props->get( Fn::Property::ALPHA ).toFloat();
    if ( renderMode != 1 ) // we are not picking
    {
        if ( renderMode == 4 || renderMode == 5 ) // we are drawing opaque objects
        {
            if ( alpha < 1.0 )
            {
                // obviously not opaque
                return;
            }
        }
        else // we are drawing tranparent objects
        {
            if ( !(alpha < 1.0 ) )
            {
                // not transparent
                return;
            }
        }
    }

    QGLShaderProgram* program = GLFunctions::getShader( "fiber" );
    program->bind();

    GLFunctions::setupTextures();
    GLFunctions::setTextureUniforms( GLFunctions::getShader( "fiber" ) );

    // Set modelview-projection matrix
    program->setUniformValue( "mvp_matrix", p_matrix * mv_matrix );
    program->setUniformValue( "mv_matrixInvert", mv_matrix.inverted() );

    initGeometry();

    glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, vboIds[ 0 ] );
    glBindBuffer( GL_ARRAY_BUFFER, vboIds[ 1 ] );
    setShaderVars( props );

    program->setUniformValue( "u_alpha", alpha );
    program->setUniformValue( "u_renderMode", renderMode );
    program->setUniformValue( "u_canvasSize", width, height );
    program->setUniformValue( "D0", 9 );
    program->setUniformValue( "D1", 10 );
    program->setUniformValue( "D2", 11 );

    glLineWidth( props->get( Fn::Property::FIBER_THICKNESS ).toFloat() );

    QVector<bool>*selected = m_selector->getSelection();

    if ( props->get( Fn::Property::COLORMODE ).toInt() != 2 )
    {
        for ( int i = 0; i < m_data.size(); ++i )
        {
            if ( selected->at( i ) )
            {
                glDrawArrays( GL_LINE_STRIP, m_startIndexes[i], m_pointsPerLine[i] );
            }
        }
    }
    else
    {
        for ( int i = 0; i < m_data.size(); ++i )
        {
            if ( selected->at( i ) )
            {
                program->setUniformValue( "u_color", m_colorField[i].redF(),
                                                                                 m_colorField[i].greenF(),
                                                                                 m_colorField[i].blueF(), 1.0 );
                glDrawArrays( GL_LINE_STRIP, m_startIndexes[i], m_pointsPerLine[i] );
            }
        }
    }

    glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 );
    glBindBuffer( GL_ARRAY_BUFFER, 0 );
}
开发者ID:yangguang-ecnu,项目名称:fibernavigator2,代码行数:77,代码来源:fiberrenderer.cpp

示例15: draw

void FiberRenderer::draw( QMatrix4x4 p_matrix, QMatrix4x4 mv_matrix, int width, int height, int renderMode, PropertyGroup& props )
{
    float alpha = props.get( Fn::Property::D_ALPHA ).toFloat();
    if ( renderMode == 0 ) // picking
    {
        return;
    }
    else if ( renderMode == 1 ) // we are drawing opaque objects
    {
        if ( alpha < 1.0 )
        {
            // obviously not opaque
            return;
        }
    }
    else // we are drawing tranparent objects
    {
        if ( !(alpha < 1.0 ) )
        {
            // not transparent
            return;
        }
    }

    if ( m_updateExtraData )
    {
    	updateExtraData( m_selectedExtraData );
    }

    QGLShaderProgram* program = GLFunctions::getShader( "fiber" );
    program->bind();

    GLFunctions::setupTextures();
    GLFunctions::setTextureUniforms( GLFunctions::getShader( "fiber" ), "maingl" );

    // Set modelview-projection matrix
    program->setUniformValue( "mvp_matrix", p_matrix * mv_matrix );
    program->setUniformValue( "mv_matrixInvert", mv_matrix.inverted() );
    program->setUniformValue( "mv_matrixTI", mv_matrix.transposed().inverted() );
    program->setUniformValue( "userTransformMatrix", props.get( Fn::Property::D_TRANSFORM ).value<QMatrix4x4>() );

    initGeometry();

    glBindBuffer( GL_ARRAY_BUFFER, vbo );
    setShaderVars( props );

    glBindBuffer( GL_ARRAY_BUFFER, dataVbo );
    int extraLocation = program->attributeLocation( "a_extra" );
    program->enableAttributeArray( extraLocation );
    glVertexAttribPointer( extraLocation, 1, GL_FLOAT, GL_FALSE, sizeof(float), 0 );

    glBindBuffer( GL_ARRAY_BUFFER, indexVbo );
    int indexLocation = program->attributeLocation( "a_indexes" );
    program->enableAttributeArray( indexLocation );
    glVertexAttribPointer( indexLocation, 1, GL_FLOAT, GL_FALSE, sizeof(float), 0 );

    program->setUniformValue( "u_alpha", alpha );
    program->setUniformValue( "u_renderMode", renderMode );
    program->setUniformValue( "u_canvasSize", width, height );
    program->setUniformValue( "D0", 9 );
    program->setUniformValue( "D1", 10 );
    program->setUniformValue( "D2", 11 );
    program->setUniformValue( "P0", 12 );
    program->setUniformValue( "C5", 13 );
    program->setUniformValue( "u_fibGrowth", props.get( Fn::Property::D_FIBER_GROW_LENGTH).toFloat() );

    program->setUniformValue( "u_lighting", props.get( Fn::Property::D_LIGHT_SWITCH ).toBool() );
    program->setUniformValue( "u_lightAmbient", props.get( Fn::Property::D_LIGHT_AMBIENT ).toFloat() );
    program->setUniformValue( "u_lightDiffuse", props.get( Fn::Property::D_LIGHT_DIFFUSE ).toFloat() );
    program->setUniformValue( "u_materialAmbient", props.get( Fn::Property::D_MATERIAL_AMBIENT ).toFloat() );
    program->setUniformValue( "u_materialDiffuse", props.get( Fn::Property::D_MATERIAL_DIFFUSE ).toFloat() );
    program->setUniformValue( "u_materialSpecular", props.get( Fn::Property::D_MATERIAL_SPECULAR ).toFloat() );
    program->setUniformValue( "u_materialShininess", props.get( Fn::Property::D_MATERIAL_SHININESS ).toFloat() );

    glLineWidth( props.get( Fn::Property::D_FIBER_THICKNESS ).toFloat() );

    std::vector<bool>*selected = m_selector->getSelection();

    int percent = props.get( Fn::Property::D_FIBER_THIN_OUT ).toFloat() * 10;

    for ( unsigned int i = 0; i < m_fibs->size(); ++i )
    {
        if ( ( i % 1000 ) > percent )
        {
            continue;
        }

        if ( selected->at( i ) )
        {
            QColor c = m_fibs->at( i ).customColor();
            program->setUniformValue( "u_color", c.redF(), c.greenF(), c.blueF(), 1.0 );
            c = m_fibs->at( i ).globalColor();
            program->setUniformValue( "u_globalColor", c.redF(), c.greenF(), c.blueF(), 1.0 );
            glDrawArrays( GL_LINE_STRIP, m_startIndexes[i], m_pointsPerLine[i] );
        }
        else
        {
            if ( Models::getGlobal( Fn::Property::G_UNSELECTED_FIBERS_GREY ).toBool() )
            {
                program->setUniformValue( "u_color", .4f, .4f, .4f, 1.0 );
//.........这里部分代码省略.........
开发者ID:dmastrovito,项目名称:braingl,代码行数:101,代码来源:fiberrenderer.cpp


注:本文中的QMatrix4x4::inverted方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。