Пример #1
0
 void Camera::setUp(QVector3D const& _up)
 {
   up_ = _up.normalized();
 }
  QList<QVariant> QTAIMLocateNuclearCriticalPoint( QList<QVariant> input  )
  {
    const QString fileName=input.at(0).toString();
    const qint64 nucleus=input.at(1).toInt();
    const QVector3D x0y0z0(
        input.at(2).toReal(),
        input.at(3).toReal(),
        input.at(4).toReal()
        );

    QTAIMWavefunction wfn;
    wfn.loadFromBinaryFile(fileName);

    QTAIMWavefunctionEvaluator eval(wfn);

    QVector3D result;

    if( wfn.nuclearCharge(nucleus) < 4 )
    {
      //      QTAIMODEIntegrator ode(eval,QTAIMODEIntegrator::CMBPMinusThreeGradientInElectronDensity);
      QTAIMLSODAIntegrator ode(eval,QTAIMLSODAIntegrator::CMBPMinusThreeGradientInElectronDensity);
      result=ode.integrate(x0y0z0);
    }
    else
    {
      result=x0y0z0;
    }

    bool correctSignature;
    Matrix<qreal,3,1> xyz; xyz << result.x(), result.y(), result.z();

    if(
        QTAIMMathUtilities::signatureOfASymmetricThreeByThreeMatrix(
            eval.hessianOfElectronDensity(xyz)
            ) == -3
        )
    {
      correctSignature=true;
    }
    else
    {
      correctSignature=false;
    }

    QList<QVariant> value;

    if( correctSignature )
    {
      value.append(correctSignature);
      value.append(result.x());
      value.append(result.y());
      value.append(result.z());
    }
    else
    {
      value.append(false);
    }

    return value;

  }
Пример #3
0
void RotateYHandle::drag(QVector3D center, QVector3D delta)
{
    Q_UNUSED(delta);
    QVector3D d = center - position();
    setValue("a", atan2(d.z(), d.x()) * 180 / M_PI);
}
Пример #4
0
void GdvCanvas2D::clearBuffer(const QVector3D &clearColor)
{
    buffer2D.fill(QColor(clearColor.x()*255,
                         clearColor.y()*255,
                         clearColor.z()*255));
}
  QList<QVariant> QTAIMLocateBondCriticalPoint( QList<QVariant> input  )
  {

    QList<QVariant> value;
    value.clear();

    const QString wfnFileName=input.at(0).toString();
    const QString nuclearCriticalPointsFileName=input.at(1).toString();
    const qint64 nucleusA=input.at(2).toInt();
    const qint64 nucleusB=input.at(3).toInt();
    const QVector3D x0y0z0(
        input.at(4).toReal(),
        input.at(5).toReal(),
        input.at(6).toReal()
        );

    QTAIMWavefunction wfn;
    wfn.loadFromBinaryFile(wfnFileName);

    QList<QVector3D> nuclearCriticalPoints;
    QFile nuclearCriticalPointsFile(nuclearCriticalPointsFileName);
    nuclearCriticalPointsFile.open(QIODevice::ReadOnly);
    QDataStream nuclearCriticalPointsFileIn(&nuclearCriticalPointsFile);
    nuclearCriticalPointsFileIn >> nuclearCriticalPoints ;
    nuclearCriticalPointsFile.close();

    QList<QPair<QVector3D,qreal> > betaSpheres;
    for( qint64 i=0 ; i < nuclearCriticalPoints.length() ; ++i )
    {
      QPair<QVector3D,qreal> thisBetaSphere;
      thisBetaSphere.first=nuclearCriticalPoints.at(i);
      thisBetaSphere.second=0.1;
      betaSpheres.append(thisBetaSphere);
    }

    QTAIMWavefunctionEvaluator eval(wfn);

    QList<QVector3D> ncpList;

    QVector3D result;
    //    QTAIMODEIntegrator ode(eval,QTAIMODEIntegrator::CMBPMinusOneGradientInElectronDensity);
    QTAIMLSODAIntegrator ode(eval,QTAIMLSODAIntegrator::CMBPMinusOneGradientInElectronDensity);
    result=ode.integrate(x0y0z0);
    Matrix<qreal,3,1> xyz; xyz << result.x(), result.y(), result.z();

    if(
        !( QTAIMMathUtilities::signatureOfASymmetricThreeByThreeMatrix(
            eval.hessianOfElectronDensity(xyz)
            ) == -1 )
        || (eval.gradientOfElectronDensity(xyz)).norm() > SMALL_GRADIENT_NORM
        )
    {
      value.append(false);
      value.append(result.x());
      value.append(result.y());
      value.append(result.z());
      return value;
    }

    Matrix<qreal,3,3> eigenvectorsOfHessian;
    eigenvectorsOfHessian=QTAIMMathUtilities::eigenvectorsOfASymmetricThreeByThreeMatrix(
        eval.hessianOfElectronDensity(xyz)
        );
    Matrix<qreal,3,1> highestEigenvectorOfHessian;
    highestEigenvectorOfHessian <<
        eigenvectorsOfHessian(0,2),
        eigenvectorsOfHessian(1,2),
        eigenvectorsOfHessian(2,2);

    const qreal smallStep=0.01;

    QVector3D forwardStartingPoint( result.x() + smallStep*highestEigenvectorOfHessian(0),
                                    result.y() + smallStep*highestEigenvectorOfHessian(1),
                                    result.z() + smallStep*highestEigenvectorOfHessian(2) );

    QVector3D backwardStartingPoint( result.x() - smallStep*highestEigenvectorOfHessian(0),
                                     result.y() - smallStep*highestEigenvectorOfHessian(1),
                                     result.z() - smallStep*highestEigenvectorOfHessian(2) );

    //    QTAIMODEIntegrator forwardODE(eval,QTAIMODEIntegrator::SteepestAscentPathInElectronDensity);
    QTAIMLSODAIntegrator forwardODE(eval,QTAIMLSODAIntegrator::SteepestAscentPathInElectronDensity);
    forwardODE.setBetaSpheres( betaSpheres );
    QVector3D forwardEndpoint=forwardODE.integrate(forwardStartingPoint);
    QList<QVector3D> forwardPath=forwardODE.path();

    //    QTAIMODEIntegrator backwardODE(eval,QTAIMODEIntegrator::SteepestAscentPathInElectronDensity);
    QTAIMLSODAIntegrator backwardODE(eval,QTAIMLSODAIntegrator::SteepestAscentPathInElectronDensity);
    backwardODE.setBetaSpheres( betaSpheres );
    QVector3D backwardEndpoint=backwardODE.integrate(backwardStartingPoint);
    QList<QVector3D> backwardPath=backwardODE.path();

    qreal smallestDistance=HUGE_REAL_NUMBER;
    qint64 smallestDistanceIndex=0;

    for( qint64 n=0 ; n < wfn.numberOfNuclei()  ; ++n )
    {
      Matrix<qreal,3,1> a(forwardEndpoint.x(),forwardEndpoint.y(),forwardEndpoint.z());
      Matrix<qreal,3,1> b(wfn.xNuclearCoordinate(n), wfn.yNuclearCoordinate(n), wfn.zNuclearCoordinate(n));

      qreal distance=QTAIMMathUtilities::distance(a,b);

      if( distance < smallestDistance )
      {
        smallestDistance = distance;
        smallestDistanceIndex=n;
      }
    }
    qint64 forwardNucleusIndex=smallestDistanceIndex;

    smallestDistance=HUGE_REAL_NUMBER;
    smallestDistanceIndex=0;

    for( qint64 n=0 ; n < wfn.numberOfNuclei()  ; ++n )
    {
      Matrix<qreal,3,1> a(backwardEndpoint.x(),backwardEndpoint.y(),backwardEndpoint.z());
      Matrix<qreal,3,1> b(wfn.xNuclearCoordinate(n), wfn.yNuclearCoordinate(n), wfn.zNuclearCoordinate(n));

      qreal distance=QTAIMMathUtilities::distance(a,b);

      if( distance < smallestDistance )
      {
        smallestDistance = distance;
        smallestDistanceIndex=n;
      }
    }
    qint64 backwardNucleusIndex=smallestDistanceIndex;

    bool bondPathConnectsPair;
    if( (forwardNucleusIndex == nucleusA && backwardNucleusIndex == nucleusB) ||
        (forwardNucleusIndex == nucleusB && backwardNucleusIndex == nucleusA) )
    {
      bondPathConnectsPair=true;
    }
    else
    {
      bondPathConnectsPair=false;
    }

    if( bondPathConnectsPair )
    {
      value.append(true);
      value.append(nucleusA);
      value.append(nucleusB);
      value.append(result.x());
      value.append(result.y());
      value.append(result.z());
      Matrix<qreal,3,1> xyz ; xyz << result.x(),result.y(),result.z();
      value.append( eval.laplacianOfElectronDensity(xyz) );
      value.append( QTAIMMathUtilities::ellipticityOfASymmetricThreeByThreeMatrix(
          eval.hessianOfElectronDensity(xyz)
          )
                    );
      value.append( 1 + forwardPath.length() + 1 + backwardPath.length() + 1);
      value.append( forwardEndpoint.x() );
      for(qint64 i=forwardPath.length() - 1 ; i >= 0 ; --i)
      {
        value.append( forwardPath.at(i).x() );
      }
      value.append(result.x());
      for(qint64 i=0; i < backwardPath.length() ; ++i)
      {
        value.append( backwardPath.at(i).x() );
      }
      value.append( backwardEndpoint.x() );
      value.append( forwardEndpoint.y() );
      for(qint64 i=forwardPath.length() - 1 ; i >= 0 ; --i)
      {
        value.append( forwardPath.at(i).y() );
      }
      value.append(result.y());
      for(qint64 i=0; i < backwardPath.length() ; ++i)
      {
        value.append( backwardPath.at(i).y() );
      }
      value.append( backwardEndpoint.y() );
      value.append( forwardEndpoint.z() );
      for(qint64 i=forwardPath.length() - 1 ; i >= 0 ; --i)
      {
        value.append( forwardPath.at(i).z() );
      }
      value.append(result.z());
      for(qint64 i=0; i < backwardPath.length() ; ++i)
      {
        value.append( backwardPath.at(i).z() );
      }
      value.append( backwardEndpoint.z() );

    }
    else
    {
      value.append(false);
      // for debugging
      value.append(result.x());
      value.append(result.y());
      value.append(result.z());
    }

    return value;
  }
Пример #6
0
void Node::setPos3D(const QVector3D &vector)
{
	setPos(vector.toPoint());
	setZValue(vector.z());
}
Пример #7
0
void Data3DTreeDelegate::setModelData(QWidget* editor, QAbstractItemModel* model, const QModelIndex& index) const
{
    const Data3DTreeModel* pData3DTreeModel = static_cast<const Data3DTreeModel*>(index.model());
    const AbstractTreeItem* pAbstractItem = static_cast<const AbstractTreeItem*>(pData3DTreeModel->itemFromIndex(index));

    //Set data manually here so we can use our own item roles.
    switch(pAbstractItem->type()) {
        case MetaTreeItemTypes::SurfaceColorGyri: {
            QColorDialog* pColorDialog = static_cast<QColorDialog*>(editor);
            QColor color = pColorDialog->currentColor();
            QVariant data;
            data.setValue(color);

            model->setData(index, data, MetaTreeItemRoles::SurfaceColorGyri);
            model->setData(index, data, Qt::DecorationRole);
            break;
        }

        case MetaTreeItemTypes::SurfaceColorSulci: {
            QColorDialog* pColorDialog = static_cast<QColorDialog*>(editor);
            QColor color = pColorDialog->currentColor();
            QVariant data;
            data.setValue(color);

            model->setData(index, data, MetaTreeItemRoles::SurfaceColorSulci);
            model->setData(index, data, Qt::DecorationRole);
            break;
        }

        case MetaTreeItemTypes::ColormapType: {
            QComboBox* pColorMapType = static_cast<QComboBox*>(editor);
            QVariant data;
            data.setValue(pColorMapType->currentText());

            model->setData(index, data, MetaTreeItemRoles::ColormapType);
            model->setData(index, data, Qt::DisplayRole);
            break;
        }

        case MetaTreeItemTypes::DataThreshold: {
            if(Spline* pSpline = dynamic_cast<Spline*>(editor)) {
                QVector3D returnVector;
                returnVector = pSpline->getThreshold();

                QString displayThreshold;
                displayThreshold = QString("%1,%2,%3").arg(returnVector.x()).arg(returnVector.y()).arg(returnVector.z());
                QVariant data;
                data.setValue(displayThreshold);
                model->setData(index, data, Qt::DisplayRole);
                data.setValue(returnVector);
                model->setData(index, data, MetaTreeItemRoles::DataThreshold);
            }
            break;
        }

        case MetaTreeItemTypes::StreamingTimeInterval: {
            QSpinBox* pSpinBox = static_cast<QSpinBox*>(editor);

            QVariant data;
            data.setValue(pSpinBox->value());

            model->setData(index, data, MetaTreeItemRoles::StreamingTimeInterval);
            model->setData(index, data, Qt::DisplayRole);
            break;
        }

        case MetaTreeItemTypes::VisualizationType: {
            QComboBox* pVisType = static_cast<QComboBox*>(editor);
            QVariant data;
            data.setValue(pVisType->currentText());

            model->setData(index, data, MetaTreeItemRoles::VisualizationType);
            model->setData(index, data, Qt::DisplayRole);
            break;
        }

        case MetaTreeItemTypes::Color: {
            QColorDialog* pColorDialog = static_cast<QColorDialog*>(editor);
            QColor color = pColorDialog->currentColor();
            QVariant data;
            data.setValue(color);

            model->setData(index, data, MetaTreeItemRoles::Color);
            model->setData(index, data, Qt::DecorationRole);
            break;
        }

        case MetaTreeItemTypes::NumberAverages: {
            QSpinBox* pSpinBox = static_cast<QSpinBox*>(editor);

            QVariant data;
            data.setValue(pSpinBox->value());

            model->setData(index, data, MetaTreeItemRoles::NumberAverages);
            model->setData(index, data, Qt::DisplayRole);
            break;
        }

        case MetaTreeItemTypes::AlphaValue: {
            QDoubleSpinBox* pDoubleSpinBox = static_cast<QDoubleSpinBox*>(editor);
            QVariant data;
            data.setValue(pDoubleSpinBox->value());

            model->setData(index, data, MetaTreeItemRoles::AlphaValue);
            model->setData(index, data, Qt::DisplayRole);
            break;
        }

        case MetaTreeItemTypes::SurfaceTessInner: {
            QDoubleSpinBox* pDoubleSpinBox = static_cast<QDoubleSpinBox*>(editor);
            QVariant data;
            data.setValue(pDoubleSpinBox->value());

            model->setData(index, data, MetaTreeItemRoles::SurfaceTessInner);
            model->setData(index, data, Qt::DisplayRole);
            break;
        }

        case MetaTreeItemTypes::SurfaceTessOuter: {
            QDoubleSpinBox* pDoubleSpinBox = static_cast<QDoubleSpinBox*>(editor);
            QVariant data;
            data.setValue(pDoubleSpinBox->value());

            model->setData(index, data, MetaTreeItemRoles::SurfaceTessOuter);
            model->setData(index, data, Qt::DisplayRole);
            break;
        }

        case MetaTreeItemTypes::SurfaceTriangleScale: {
            QDoubleSpinBox* pDoubleSpinBox = static_cast<QDoubleSpinBox*>(editor);
            QVariant data;
            data.setValue(pDoubleSpinBox->value());

            model->setData(index, data, MetaTreeItemRoles::SurfaceTriangleScale);
            model->setData(index, data, Qt::DisplayRole);
            break;
        }

        case MetaTreeItemTypes::TranslateX: {
            QDoubleSpinBox* pDoubleSpinBox = static_cast<QDoubleSpinBox*>(editor);
            QVariant data;
            data.setValue(pDoubleSpinBox->value());

            model->setData(index, data, MetaTreeItemRoles::TranslateX);
            model->setData(index, data, Qt::DisplayRole);
            break;
        }

        case MetaTreeItemTypes::TranslateY: {
            QDoubleSpinBox* pDoubleSpinBox = static_cast<QDoubleSpinBox*>(editor);
            QVariant data;
            data.setValue(pDoubleSpinBox->value());

            model->setData(index, data, MetaTreeItemRoles::TranslateY);
            model->setData(index, data, Qt::DisplayRole);
            break;
        }

        case MetaTreeItemTypes::TranslateZ: {
            QDoubleSpinBox* pDoubleSpinBox = static_cast<QDoubleSpinBox*>(editor);
            QVariant data;
            data.setValue(pDoubleSpinBox->value());

            model->setData(index, data, MetaTreeItemRoles::TranslateZ);
            model->setData(index, data, Qt::DisplayRole);
            break;
        }

        case MetaTreeItemTypes::Scale: {
            QDoubleSpinBox* pDoubleSpinBox = static_cast<QDoubleSpinBox*>(editor);
            QVariant data;
            data.setValue(pDoubleSpinBox->value());

            model->setData(index, data, MetaTreeItemRoles::Scale);
            model->setData(index, data, Qt::DisplayRole);
            break;
        }

        case MetaTreeItemTypes::MaterialType: {
            QComboBox* pComboBox = static_cast<QComboBox*>(editor);
            QVariant data;
            data.setValue(pComboBox->currentText());

            model->setData(index, data, MetaTreeItemRoles::SurfaceMaterial);
            model->setData(index, data, Qt::DisplayRole);
            break;
        }

        case MetaTreeItemTypes::CancelDistance: {
            QDoubleSpinBox* pDoubleSpinBox = static_cast<QDoubleSpinBox*>(editor);
            QVariant data;
            data.setValue(pDoubleSpinBox->value());

            model->setData(index, data, MetaTreeItemRoles::CancelDistance);
            model->setData(index, data, Qt::DisplayRole);
            break;
        }

        case MetaTreeItemTypes::InterpolationFunction: {
            QComboBox* pColorMapType = static_cast<QComboBox*>(editor);
            QVariant data;
            data.setValue(pColorMapType->currentText());

            model->setData(index, data, MetaTreeItemRoles::InterpolationFunction);
            model->setData(index, data, Qt::DisplayRole);
            break;
        }

        // Handle all other item types via QItemDelegate::setModelData handling
        default: {
            QItemDelegate::setModelData(editor, model, index);
            break;
        }
    }
}
Пример #8
0
bool Tools::isInRange(QVector3D x, QVector3D y, float dist)
{
    if (x.distanceToPoint(y) < dist)  return true ;
}
Пример #9
0
/*
 *
 * **************************************************/
void CubeObj::takeTexture() {
    // Calculate Matrix using the parent matrixes too
    std::stack<QMatrix4x4> mats;
    QMatrix4x4 cmat;

    // Store previous matrixes in stack
    CubeObj *po = this;
    bool notroot = true;
    while ( notroot ) {
        if ( po != pro.objectRoot ) {
            mats.push( po->getMatrix() );
           // qDebug() << po->m_itemData;
            po = (CubeObj * ) po->parentItem();
        } else {
            mats.push( po->getMatrix() );
            //qDebug() << po->m_itemData;
            notroot = false;
        }
    }

    // camera mat * parent mat * parent mat ..... * parent mat * this mat * this scale
//    cmat = pro.getManger().fixCamera->getMatrix();          // TODO
    for ( int i=0 , e = mats.size(); i < e ; i ++ ) {
        cmat *= mats.top();
        mats.pop();
       // qDebug() << "mat";
    }
    cmat.scale(scale);

    // Project points to screen
    QVector3D vect;
    qDebug() << "verticies " << vertices.size();
    qDebug() << "TexCoords " << texCoords.size();

    QVector<QVector2D> projectedPoints;
    for ( int i = 0; i < vertices.size(); i++) {    // verticies.size
        vect =  cmat * vertices[i];
        projectedPoints.append(  QVector2D ( ( vect.x()   + 1 ) / 2   , ( 1 - vect.y() )  / 2 ) );
    }

    // The output texture image coordinate and size
    int w,h;
    w = textureMat->cols;
    h = textureMat->rows;

    cv::Point2f ocoords[ 4 ];
    ocoords[0] = cv::Point2f (0, 0);
    ocoords[1] = cv::Point2f (0, h);
    ocoords[2] = cv::Point2f (w, h);
    ocoords[3] = cv::Point2f (w, 0);

    cv::Point2f textpoints[24];      // TODO
 //   UvtoCvCoordinate( *pro.actualBackground, projectedPoints, textpoints ); TODO
/*
    // for test
    for ( int i = 0; i < 24 ; i++) {
        //qDebug() << textpoints[i].x << " : " << textpoints[i].y;
        cv::circle( pro.actualBackground, textpoints[i],3, cv::Scalar(1,255,1), 2 );
        pro.reLoadback();
    }
    // -------------------*/

    GLWidget & gl = pro.getManger().getMainGLW();
    for ( int i =0; i < 6; i++) {
        cv::Mat ptransform = getPerspectiveTransform ( &textpoints[i*4], ocoords);
//        cv::warpPerspective( *pro.actualBackground, *textureMat, ptransform,  textureMat->size() );
        if ( textureIDs[i] == 0 ) {
            gl.glGenBuffers( 1, &textureIDs[i]);
            qDebug() << "TextureId:" << textureIDs[i];
        }
        gl.glBindTexture ( GL_TEXTURE_2D , textureIDs[i]);
        gl.glTexImage2D(  GL_TEXTURE_2D, 0, GL_RGB, textureMat->cols, textureMat->rows, 0, GL_RGB,
                          GL_UNSIGNED_BYTE, ( GLvoid * ) textureMat->data );
        gl.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
        gl.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
        gl.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
        gl.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    }



  /*  texCoords[0] =  QVector2D ( 0,0);                      // Set Texture coordinate
    texCoords[1] =  QVector2D ( 0,1);
    texCoords[2] =  QVector2D ( 1,1);
    texCoords[3] =  QVector2D ( 1,0);*/
 /*  textPixmap   =  QPixmap::fromImage( this->cvMatToQImage( *textureMat) );*/


}
Пример #10
0
int Slice::GenerateSegments(B9ModelInstance* inputInstance)
{
    unsigned int t;
	int v1;
	int v2;
	int cmpcount = 0;//0 or 1 for knowing what point your trying to find.;

	QVector3D* thisvert = NULL;//local pointer to make quick access to vertices
	QVector3D* thatvert = NULL;

    std::vector<Triangle3D*>* rangedTriangles;

	double xdisp;
	double ydisp;
	double zdisp;
	double planefraction;

	int intersections = 0;


	//Triangle Splitting here:
    //Get the right container of triangles and use that as the list
    //(we used to use the triList which was O(n^2))
    rangedTriangles = inputInstance->GetTrianglesAroundZ(realAltitude);


    for(t = 0; t < rangedTriangles->size(); t++)//for each triangle in the model
	{
		//we want to create a temporary pointer to the currenct triangle
        Triangle3D* pTransTri = rangedTriangles->at(t);

		//test if the triangle intersects the XY plane of this slice!
		if(!pTransTri->IntersectsXYPlane(realAltitude))
		{
            continue;
		}
			
		intersections++;
		cmpcount = 0;
		
		//create 1 new segment object for the end result 
		Segment* seg1 = new Segment;
		QVector2D points[2];
		for(v1=0;v1<3;v1++)//for 1 or 2 triangle verts ABOVE the plane:
		{
			thisvert = &pTransTri->vertex[v1];
			if(thisvert->z() <= realAltitude)//we only want to compare FROM above the plane by convention (yes this means flush triangles below the plane)
			{
				continue;
			}
			for(v2=0; v2<3; v2++)//to every other triangle vert
			{
				if(v2 == v1)
				{continue;}

				thatvert = &pTransTri->vertex[v2];

				//are both points on the same side of plane?
				//if so we dont want to compare
				if((thatvert->z() > realAltitude))
				{
					continue;
				}
					
				cmpcount++;
				//common
				//displacments (final - initial)
				xdisp = thatvert->x() - thisvert->x();
				ydisp = thatvert->y() - thisvert->y();
				zdisp = thatvert->z() - thisvert->z();

                planefraction = (thisvert->z() - realAltitude)/fabs(zdisp);//0-1 fraction of where the plane is in relation to the z distance between the 2 verts.
				//(0 would be the plane is at the hieght of thisvert)

				points[cmpcount-1].setX(thisvert->x() + xdisp*planefraction);
				points[cmpcount-1].setY(thisvert->y() + ydisp*planefraction);
			}
		}
	
		//initiallize the segment.
		seg1->normal.setX(pTransTri->normal.x());
		seg1->normal.setY(pTransTri->normal.y());

		seg1->p1.setX(points[0].x());
		seg1->p1.setY(points[0].y());

		seg1->p2.setX(points[1].x());
		seg1->p2.setY(points[1].y());

		seg1->normal.normalize();

		seg1->CorrectPointOrder();//to match the normal convention!
			
		AddSegment(seg1);
	}
	return segmentList.size();
}
Пример #11
0
QVector3D EnvRoomTemplate::ClipPlayerTrajectory(const QVector3D & pos, const QVector3D & vel) const
{

    QVector3D new_vel;

    bool x_collide = false;
    bool z_collide = false;

    QPointF move(pos.x() + vel.x(), pos.z() + vel.z());
    QPointF move_x(pos.x() + vel.x(), pos.z());
    QPointF move_z(pos.x(), pos.z() + vel.z());

    for (int i=0; i<colliders.size(); ++i) {

        if (colliders[i].contains(move)) {

            if (colliders[i].contains(move_x)) {
                x_collide = true;
            }

            if (colliders[i].contains(move_z)) {
                z_collide = true;
            }

        }

    }

    if (!x_collide && z_collide) {
        new_vel = QVector3D(vel.x(), 0, 0);
    }
    else if (!z_collide && x_collide) {
        new_vel = QVector3D(0, 0, vel.z());
    }
    else if (x_collide && z_collide) {
        new_vel = QVector3D(0, 0, 0);
    }
    else {
        new_vel = vel;
    }

    move = QPointF(pos.x() + new_vel.x(), pos.z() + new_vel.z());
    for (int i=0; i<circ_colliders.size(); ++i) {

        QVector3D cent_dir = QVector3D(circ_colliders[i].pos.x() - move.x(), 0, circ_colliders[i].pos.y() - move.y());
        const float cent_dist = cent_dir.length();

        if ((circ_colliders[i].stay_inside && cent_dist > circ_colliders[i].rad) ||
             (!circ_colliders[i].stay_inside && cent_dist < circ_colliders[i].rad)) {
            new_vel += cent_dir.normalized() * (cent_dist - circ_colliders[i].rad);
        }

    }

    /*
    qDebug() << "the mountpoints:";
    for (int angle=0; angle<=360; angle+=18) {

        if (angle % 36 == 0) {
            qDebug() << sinf(float(angle)* MathUtil::_PI_OVER_180) * 20.0f << "0" << cosf(float(angle)* MathUtil::_PI_OVER_180) * 20.0f
                     << -sinf(float(angle)* MathUtil::_PI_OVER_180) << "0" << -cosf(float(angle)* MathUtil::_PI_OVER_180);
        }
        else {
            qDebug() << sinf(float(angle)* MathUtil::_PI_OVER_180) * 12.1f << "0" << cosf(float(angle)* MathUtil::_PI_OVER_180) * 12.1f
                        << sinf(float(angle)* MathUtil::_PI_OVER_180) << "0" << cosf(float(angle)* MathUtil::_PI_OVER_180);
        }
    }
    */

    return new_vel;

}
Пример #12
0
void TrackBall::move(const QPointF& p, const QQuaternion &transformation, bool bFromRelease)
{
    if (!m_pressed)
        return;

    QTime currentTime = QTime::currentTime();
    int msecs = m_lastTime.msecsTo(currentTime);
    if (msecs <= 20)
        return;

    switch (m_mode) {
    case Plane: // rotate the camera
    {
        QLineF delta(m_lastPos, p);
        m_angularVelocity = 180*delta.length() / (PI*msecs);
        m_axis = QVector3D(-delta.dy(), delta.dx(), 0.0f).normalized(); // normal direction
        m_axis = transformation.rotatedVector(m_axis);
        m_rotation = QQuaternion::fromAxisAndAngle(m_axis, 180 / PI * delta.length()) * m_rotation;
    }
    break;
    case Sphere: // rotate the model
    {
        // lastPos3D lies on a unit sphere
        QVector3D lastPos3D = QVector3D(m_lastPos.x(), m_lastPos.y(), 0.0f);
        float sqrZ = 1 - QVector3D::dotProduct(lastPos3D, lastPos3D);
        if (sqrZ > 0)
            lastPos3D.setZ(sqrt(sqrZ));
        else
            lastPos3D.normalize();

        // currentPos3D lies on a unit sphere
        QVector3D currentPos3D = QVector3D(p.x(), p.y(), 0.0f);
        sqrZ = 1 - QVector3D::dotProduct(currentPos3D, currentPos3D);
        if (sqrZ > 0)
            currentPos3D.setZ(sqrt(sqrZ));
        else
            currentPos3D.normalize();

        m_axis = QVector3D::crossProduct(lastPos3D, currentPos3D);
        // a x b = |a|.|b|.sin(angle).n
        float angle = 180 / PI * asin(sqrt(QVector3D::dotProduct(m_axis, m_axis)));

        m_angularVelocity = angle / msecs;
        m_axis.normalize();
        m_axis = transformation.rotatedVector(m_axis);
        m_rotation = QQuaternion::fromAxisAndAngle(m_axis, angle) * m_rotation;
    }
    break;
    case Drag:
    {
        if (!bFromRelease)
        {
            QVector3D currentPos = QVector3D(p.x(), p.y(), 0.0f);

            QVector3D direction = currentPos - m_DragPos;

            if (direction.length() > 0.5) // avoid teleporting
            {
                m_DragPos = m_DragPos + 0.1*direction;
            }
            else
            {
                m_DragPos = QVector3D(p.x(), p.y(), 0.0f);
            }
        }
    }
    break;
    }

    m_lastPos = p;
    m_lastTime = currentTime;
}
Пример #13
0
/*!
    \internal
*/
void SphereMesh::createGeometry()
{
    // We cache a maximum of 10 levels of detail for lod animations.
    // Create a new geometry node for this level of detail if necessary.
    QGLSceneNode *geometry = d->lodGeometry.value(d->lod, 0);
    if (!geometry) {
        QGLBuilder builder;
        builder.newSection(QGL::Faceted);
        builder << QGLSphere(2.0f, d->lod);
        geometry = builder.finalizedSceneNode();
        geometry->setParent(this);
        d->lodGeometry.insert(d->lod, geometry);
    }
    Q_ASSERT_X(geometry != 0, Q_FUNC_INFO, "Could not create/find geometry!");
    if (d->currentSphere != geometry)
    {
        if (d->currentSphere)
            d->topNode->removeNode(d->currentSphere);
        d->topNode->addNode(geometry);
        d->currentSphere = geometry;
    }

    // Set the radius as a scale on the modelview transformation.
    // This way, we don't have to regenerate the geometry every
    // frame if the radius is being animated.
    if (d->radius != 1.0f)
    {
        if (!d->scale)
        {
            d->scale = new QGraphicsScale3D(d->topNode);
            d->topNode->addTransform(d->scale);
        }
        if (d->scale->scale().x() != d->radius)
        {
            d->scale->setScale(QVector3D(d->radius, d->radius, d->radius));
        }
    }
    else
    {
        // If there is already a scale set it to be the identity scale.
        // This case is optimised for in QGraphicsScale.  Removing it from
        // the transform list is too expensive, especially if the size is
        // being animated, and the next frame will recreate it.
        if (d->scale)
            d->scale->setScale(QVector3D(1, 1, 1));
    }

    // Also rotate the geometry into the correct axis orientation.
    const QVector3D Y_AXIS = QVector3D(0, 1, 0);  // for Qt::XAxis we rotate around Y
    const QVector3D X_AXIS = QVector3D(1, 0, 0);  // for Qt::YAxis we rotate around X
    if (d->axis != Qt::ZAxis && !d->rot)
    {
        d->rot = new QGraphicsRotation3D(d->topNode);
        d->topNode->addTransform(d->rot);
    }
    if (d->axis == Qt::XAxis && d->rot->axis().y() != Y_AXIS.y())
    {
        d->rot->setAxis(Y_AXIS);
        d->rot->setAngle(90.0f);
    }
    else if (d->axis == Qt::YAxis && d->rot->axis().x() != X_AXIS.x())
    {
        d->rot->setAxis(X_AXIS);
        d->rot->setAngle(-90.0f);
    }
    else if (d->axis == Qt::ZAxis && d->rot && d->rot->angle() != 0.0f)
    {
        d->rot->setAngle(0.0f);
        d->rot->setAxis(QVector3D(0, 0, 0));
    }

    if (!d->sceneSet)
    {
        setScene(new SphereScene(d->topNode));
        d->sceneSet = true;
    }
}
Пример #14
0
bool DigitizerTreeItem::addData(const QList<FIFFLIB::FiffDigPoint>& tDigitizer, Qt3DCore::QEntity* parent)
{
    //Clear all data
    m_lSpheres.clear();

//    if(!m_pRenderable3DEntity.isNull()) {
//        m_pRenderable3DEntity->deleteLater();
//    }

    m_pRenderable3DEntity = new Renderable3DEntity(parent);

    //Create digitizers as small 3D spheres
    QVector3D pos;
    QColor colDefault(100,100,100);

    for(int i = 0; i < tDigitizer.size(); ++i) {
        Renderable3DEntity* pSourceSphereEntity = new Renderable3DEntity(m_pRenderable3DEntity);

        pos.setX(tDigitizer[i].r[0]);
        pos.setY(tDigitizer[i].r[1]);
        pos.setZ(tDigitizer[i].r[2]);

        Qt3DExtras::QSphereMesh* sourceSphere = new Qt3DExtras::QSphereMesh();

        if (tDigitizer[i].kind == FIFFV_POINT_CARDINAL) {
            sourceSphere->setRadius(0.002f);
        } else {
            sourceSphere->setRadius(0.001f);
        }
        pSourceSphereEntity->addComponent(sourceSphere);
        pSourceSphereEntity->setPosition(pos);

        Qt3DExtras::QPhongMaterial* material = new Qt3DExtras::QPhongMaterial();

        switch (tDigitizer[i].kind) {
        case FIFFV_POINT_CARDINAL:
            colDefault = Qt::yellow;
            material->setAmbient(colDefault);
            break;
        case FIFFV_POINT_HPI:
            colDefault = Qt::red;
            material->setAmbient(colDefault);
            break;
        case FIFFV_POINT_EEG:
            colDefault = Qt::green;
            material->setAmbient(colDefault);
            break;
        case FIFFV_POINT_EXTRA:
            colDefault = Qt::blue;
            material->setAmbient(colDefault);
            break;
        default:
            colDefault = Qt::white;
            material->setAmbient(colDefault);
            break;
        }

        pSourceSphereEntity->addComponent(material);

        pSourceSphereEntity->setParent(m_pRenderable3DEntity);

        m_lSpheres.append(pSourceSphereEntity);
    }

    QList<QStandardItem*> items = this->findChildren(MetaTreeItemTypes::PointColor);

    for(int i = 0; i < items.size(); ++i) {
        if(MetaTreeItem* item = dynamic_cast<MetaTreeItem*>(items.at(i))) {
            QVariant data;
            data.setValue(colDefault);
            item->setData(data, MetaTreeItemRoles::PointColor);
        }
    }

    return true;
}
Пример #15
0
void BookPage::update( const float timeStep ) {
    bool moving = isMoving();

    if (pulling==false) {
        if (!incing && expulling==true) {
            if (pageTurn>0.2) currentPageDir *= -1.0f;
        }

        if (!incing) {
            secondVector += QVector3D( currentPageDir, 0, 0)* timeStep*12.0f;
            secondVector.normalize();
            mainVector += secondVector*timeStep*4.0f;
            mainVector.normalize();

        } else {
            pullDirX += pullDirInc[0] * timeStep;
            pullDirY += pullDirInc[1] * timeStep;
            pullDirInc[0] -= pullDirInc[0] * timeStep*2.0f;
            pullDirInc[1] -= pullDirInc[1] * timeStep*2.0f;
            pullDirInc[0] -= pullDirX * timeStep*5.0f;
            pullDirInc[1] -= pullDirY * timeStep*5.0f;



            if ((pullDir2DLength-exPullDir2DLength)<0.007f || pageTurn>0.95f) {
                // check turn here.
                if ((pullFromCenter==false && pageTurn>0.1f) || (pullFromCenter==true && pageTurn>0.8f)) {
                    currentPageDir *= -1.0f;
                    incing = false;
                }

                if (pullDir2DLength<0.02f) {
                    incing = false;
                    pulling = false;
                    pullDirX = 0;
                    pullDirY = 0;
                    secondVector = QVector3D( currentPageDir, 0, 0);
                    mainVector = secondVector;
                }
            }
        }
    }

    if (pulling || incing) {

        if (pullFromCenter == false && pullDirX<0) {

            dividerPosX = pullSourceX + pullDirX;
            dividerPosY = pullSourceY + pullDirY;

            QVector3D todiv = QVector3D( dividerPosX, dividerPosY - 0.5f, 0);
            QVector3D tosource = QVector3D( pullSourceX, pullSourceY - 0.5f, 0);
            if (todiv.length()>tosource.length()) {
                //todiv.
                todiv.normalize();
                todiv *= tosource.length();
                dividerPosX = todiv.x();
                dividerPosY = todiv.y();
            }



            pullDirX = dividerPosX - pullSourceX;
            pullDirY = dividerPosY - pullSourceY;


            //pullDirX

            //float pulllength = sqrtf( pullDirX * pullDirX + pullDirY * pullDirY );

            // dividerpos limitations -> dividerdir can be different from pulldir's normal



            float pullnorm[2];
            pullnorm[0] = -pullDirY;
            pullnorm[1] = pullDirX;


            float divpos1[2];
            float divpos2[2];
            pageTurn = 1.0f;

            float steps = dividerPosY / -pullnorm[1];
            divpos1[0] = dividerPosX + steps * pullnorm[0];
            divpos1[1] = dividerPosY + steps * pullnorm[1];
            if (-(divpos1[0]-0.3f)*3.0f<pageTurn) pageTurn = -(divpos1[0]-0.3f)*3.0f;


            if (divpos1[0] < 0.0f) { divpos1[0] = 0.0f; divpos1[1] = 0.0f; }
            if (divpos1[0]>1.0f) {
                steps = (divpos1[0]-1.0f) / pullnorm[0];
                divpos1[1] -= steps * pullnorm[1];
                divpos1[0] -= steps * pullnorm[0];
            }




            steps = (1.0f-dividerPosY) / pullnorm[1];
            divpos2[0] = dividerPosX + steps * pullnorm[0];
            divpos2[1] = dividerPosY + steps * pullnorm[1];
            if (-(divpos2[0]-0.3f)*3.0f<pageTurn) pageTurn = -(divpos2[0]-0.3f)*3.0f;


            if (divpos2[0] < 0.0f) { divpos2[1] = 1.0f; divpos2[0] = 0.0f; }
            if (divpos2[0]>1.0f) {
                steps = (divpos2[0]-1.0f) / -pullnorm[0];
                divpos2[1] -= steps * -pullnorm[1];
                divpos2[0] -= steps * -pullnorm[0];
            }
            if (pageTurn<0) pageTurn = 0;


                // correct,.. new dir is still required.
            dividerPosX = (divpos1[0] + divpos2[0])/2.0f;
            dividerPosY = (divpos1[1] + divpos2[1])/2.0f;

            pullDirNormY = -(divpos1[0] - divpos2[0]);
            pullDirNormX = (divpos1[1] - divpos2[1]);
            float nlength = sqrtf( pullDirNormX*pullDirNormX + pullDirNormY * pullDirNormY );
            if (nlength==0.0f) nlength = 1.0f;
            pullDirNormX /= nlength;
            pullDirNormY /= nlength;
        } else {
            dividerPosX = pullSourceX;
            dividerPosY = pullSourceY;

            pullDirNormX = pullDirX;
            pullDirNormY = -pullDirY;
        }



        pullDir2DLength = fabsf( pullDirX );
        if (pullDirX>0) pullDir2DLength = 0;
        exPullDir2DLength = pullDir2DLength;

        if (pullFromCenter) {
            pageTurn = pullDir2DLength;
            if (pageTurn<0) pageTurn = 0;
        } else {
        }
        if (pageTurn<0) pageTurn = 0;
        if (pageTurn>=0.99f) pageTurn = 0.99f;



        float pageAngle = pageTurn * 3.14159f;

        mainVector = QVector3D( currentPageDir*cosf( pageAngle), 0, sinf( pageAngle ));
        if (pullFromCenter==false) {
            secondVector = QVector3D( currentPageDir*pullDirNormX*(1-pageTurn),pullDirNormY*(1-pageTurn),(1-pageTurn)*0.1f );
            secondVector.normalize();
        } else {
            float negpower = (pageTurn * 1.8f) * (1.0f - pageTurn*pageTurn);
            if (negpower>1.0f) negpower = 1.0f;
            secondVector = QVector3D( currentPageDir*cosf( pageAngle - negpower * 3.14159f*0.9f), 0, sinf( pageAngle - negpower * 3.14159f * 0.9f ));
        }
    }


    expulling = pulling;

        // Does the geometry need refreshing
    if (moving) refreshGeometry = true;

    if (wasMoving==true && moving==false) {
            // Reset position
        setDirection( currentPageDir );
        refreshGeometry = true;
    }
    wasMoving = moving;
}
Пример #16
0
RVector RVector::rotate3D(const QQuaternion& quaternion) {
    QVector3D qv = quaternion.rotatedVector(QVector3D(x, y, z));
    *this = RVector(qv.x(), qv.y(), qv.z());
    return *this;
}
Пример #17
0
QT_BEGIN_NAMESPACE

/*!
    \class QSphere3D
    \brief The QSphere3D class represents a mathematical sphere in 3D space.
    \since 4.8
    \ingroup qt3d
    \ingroup qt3d::math

    QSphere3D can be used to represent the bounding regions of objects
    in a 3D scene so that they can be easily culled if they are out of view.
    It can also be used to assist with collision testing.

    \sa QBox3D
*/

/*!
    \fn QSphere3D::QSphere3D()

    Constructs a default sphere with a center() of (0, 0, 0)
    and radius() of 1.
*/

/*!
    \fn QSphere3D::QSphere3D(const QVector3D &center, qreal radius)

    Constructs a sphere with the specified \a center and \a radius.
*/

/*!
    \fn QVector3D QSphere3D::center() const

    Returns the center of this sphere.

    \sa setCenter(), radius()
*/

/*!
    \fn void QSphere3D::setCenter(const QVector3D &center)

    Sets the \a center of this sphere.

    \sa center(), setRadius()
*/

/*!
    \fn qreal QSphere3D::radius() const

    Returns the radius of this sphere.

    \sa setRadius(), center()
*/

/*!
    \fn void QSphere3D::setRadius(qreal radius)

    Sets the \a radius of this sphere.

    \sa radius(), setCenter()
*/

/*!
    \fn bool QSphere3D::contains(const QVector3D &point) const

    Returns true if \a point is contained within the bounds of
    this sphere; false otherwise.
*/

/*!
    Returns true if this sphere intersects \a ray; false otherwise.

    \sa intersection()
*/
bool QSphere3D::intersects(const QRay3D &ray) const
{
    QVector3D centerToOrigin = ray.origin() - m_center;
    qreal term1 = ray.direction().lengthSquared();
    qreal term2 = 2.0f * QVector3D::dotProduct(centerToOrigin, ray.direction());
    qreal term3 = centerToOrigin.lengthSquared() - m_radius * m_radius;
    qreal det = term2 * term2 - (4.0f * term1 * term3);
    return term1 != 0.0f && det >= 0.0f;
}
Пример #18
0
QDebug operator<<(QDebug dbg, const QVector3D &vector)
{
    dbg.nospace() << "QVector3D("
        << vector.x() << ", " << vector.y() << ", " << vector.z() << ')';
    return dbg.space();
}
Пример #19
0
	void parseVertex() 
	{
		QVector3D v;
		bool indexFlag = false, vertexFlag = false;
		int index1 = 0, index2 = 0, index3 = 0, index4 = 0;
		GROUP_BEGIN();
		switch(group.code)
		{
		case 0:
			{
				finished = true; 
				m_groupStack.push_back(group);
				if(indexFlag){
					if(index4){
						m_rootNode->back()->geometry().appendIndices(index1 - 1, index2 - 1,index3 - 1);
						m_rootNode->back()->geometry().appendIndices(index3 - 1, index4 - 1, index1 - 1);
					}else
						m_rootNode->back()->geometry().appendIndices( index1 - 1, index2 - 1,index3 - 1);
				}
				if(vertexFlag)
					m_rootNode->back()->geometry().appendVertex(v);
			}
			break;
		case(10):
			{
				v.setX(atof(group.type.c_str()));
			}
			break;
		case(20):
			{
				v.setY(atof(group.type.c_str()));
			}
			break;
		case(30):
			{
				v.setZ(atof(group.type.c_str()));
			}
			break;
		case(70):
			{
				int flag = atoi(group.type.c_str());
				if(flag&128){
					if(flag&64)
						vertexFlag = true;
					else
						indexFlag = true;
				}
			}
			break;
		case(71):
			{
				index1 = abs(atoi(group.type.c_str()));
			}
			break;
		case(72):
			{
				index2 = abs(atoi(group.type.c_str()));
			}
			break;
		case(73):
			{
				index3 = abs(atoi(group.type.c_str()));
			}
			break;
		case(74):
			{
				index4 = abs(atoi(group.type.c_str()));
			}
			break;
		}
		GROUP_END();
	}
graphics::Model *TerrainGenerator::simplexTerrain2(float xRange, float zRange, float vertexDensity, float octaves[], float yScales[], int nOctaves)
{
    graphics::Model* model = new graphics::Model;
    graphics::ModelGroup group;
    cv::Mat heightMap(xRange*vertexDensity, zRange*vertexDensity, CV_32FC1);
    cv::Mat heightMapThresh(xRange*vertexDensity, zRange*vertexDensity, CV_32FC1);
    int step = heightMap.cols;

    qDebug() << "Number of octaves: " << nOctaves;

    float y = 0;

    // find max scale to scale correctly when saved to cv::Mat
    float maxScale = 0;
    for (int i = 0; i < nOctaves; i++){
        if (yScales[i] > maxScale){
            maxScale = yScales[i];
        }
    }

    qDebug() << "MaxScale: " << maxScale;

    // Generate height map and texture coordinates
    for (int x = 0; x < xRange*vertexDensity; x++){
        for (int z = 0; z < zRange*vertexDensity; z++){

            y = 0;
            for(int i = 0; i < nOctaves; i++){
                y += SimplexNoise1234::noise(x/octaves[i], z/octaves[i]) * yScales[i];
            }

            group.vertices.push_back(QVector3D((float)x/vertexDensity, y, (float)z/vertexDensity));

            group.texCoords.push_back(QVector3D((float)x/(xRange*vertexDensity),(float)z/(zRange*vertexDensity), 0));

            heightMap.at<float>(x,z) = (y + maxScale) / (2*maxScale);
        }
    }

    //cv::imshow("heightMap", heightMap);
    cv::threshold(heightMap, heightMapThresh, 0.5, 1, 1);
    //cv::imshow("heightMapThresh", heightMapThresh);

    qDebug() << "step: " << step;

    // Tie vertices together. openGL indexing starts at 0 tydligen..
    for (int x = 1; x < xRange*vertexDensity; x++){
        for (int z = 1; z < zRange*vertexDensity; z++){

            // First triangle
            group.indices.push_back( (x-1)*step + z-1);  // 0
            group.indices.push_back( x*step     + z  );  // 3
            group.indices.push_back( x*step     + z-1);  // 2

            // Second triangle
            group.indices.push_back( (x-1)*step + z-1);  // 0
            group.indices.push_back( (x-1)*step + z  );  // 1
            group.indices.push_back( x*step     + z  );  // 3
        }
    }

    float y00, y01, y10;
    QVector3D tangent1, tangent2;
    QVector3D normal;

    // Calculate normals
    for (int z = 0; z < zRange*vertexDensity; z++){
        group.normals.push_back(QVector3D(0,1,0));
    }

    for (int x = 1; x < xRange*vertexDensity; x++){
        group.normals.push_back(QVector3D(0,1,0));
        for (int z = 1; z < zRange*vertexDensity; z++){

            y00 = heightMap.at<float>(x-1,z-1);
            y01 = heightMap.at<float>(x-1,z);
            y10 = heightMap.at<float>(x,z-1);

            tangent1 = QVector3D(1, y10-y00, 0);
            tangent2 = QVector3D(0, y01-y00, 1);

            normal = normal.crossProduct(tangent2, tangent1);
            normal.normalize();

            group.normals.push_back(normal);
        }
    }

    model->groups.push_back(group);
    model->uploadToGPU();

    return model;
}
Пример #21
0
void PaintData::setScale(const QVector3D &scale)
{
    d->scale.setXScale(scale.x());
    d->scale.setYScale(scale.y());
    d->scale.setZScale(scale.z());
}
void SpringMesh::updateCurrentPos()
{
	QVector3D curForce;
	for (auto force : forces)
	{
		curForce += *force;
	}
	
	// Apply external force
	for (auto vertex : mesh->vertSet)
	{
		if (fixedPoint.find(vertex->index) != fixedPoint.end())
		{
			continue;
		}
		vertex->in_force = QVector3D();// Initialize internal force
		//cout << vertex->in_force.length() << endl;
		//cout << "Y: " << vertex->pos.y();
		vertex->pre_pos = vertex->pos;
		vertex->pre_vel = vertex->vel;
		vertex->vel += (curForce - vertex->vel * airFriction) * timestep;
		vertex->pos += 0.5 * (vertex->pre_vel + vertex->vel) * timestep;
		

		
	}
	
	
	// Calculate new face normals
	for (auto face : mesh->faceSet)
	{
		face->computeNormal();
	}

	// update internal force
	for (auto spring : springEdges)
	{
		auto& vi = mesh->vertMap[spring.first.first];
		auto& vj = mesh->vertMap[spring.first.second];
		QVector3D uij = vj->pos - vi->pos;
		if (uij.length() < 0.01)
		{
			cout << "hehehehe\n";
		}
		float len = uij.length() - spring.second;// delta L
		uij.normalize();

		auto fi_spr = ks * uij * len;
		auto fi_damp = damper * ((vj->pre_vel - vi->pre_vel) * uij) * uij;

		vi->in_force += fi_spr + fi_damp;
		vj->in_force -= fi_spr + fi_damp;
	}
	//calcTorque();
	
	// Integrate
	integrate();

	// Clean up for next integration
	for (auto face : mesh->faceSet)
	{
		face->pre_n = face->computeNormal();
	}
}
Пример #23
0
void AxisRenderer::drawGrid(int gridSize, QGLShaderProgram &program,const AxisCamera &camera)
{
    qDebug()<< "[AxisRender] Drawing Grid";

    int gridNumber = camera.getGridFactor() * 2; //double size of grid to ensure it covers entire view
    float lineLimit = gridNumber * gridSize; //bounds of grid for this size and number

    qDebug()<< "[AxisRender] lineLimit = " << lineLimit;

    //general xline for grid
    float lineX[] = {lineLimit, 0.0f, 0.0f, 1.0f,
                     -lineLimit, 0.0f, 0.0f, 1.0f};

    //general yline for grid
    float lineY[] = { 0.0f, lineLimit, 0.0f, 1.0f,
                    0.0f, -lineLimit, 0.0f, 1.0f};

    //general zline for grid
    float lineZ[] = {0.0f, 0.0f, lineLimit, 1.0f,
                    0.0f, 0.0f, -lineLimit, 1.0f};

    //bind and fill xline buffer
    program.bind();
    QGLBuffer bufferX(QGLBuffer::VertexBuffer);
    bufferX.setUsagePattern(QGLBuffer::StaticDraw);
    bufferX.create();
    bufferX.bind();
    bufferX.allocate(lineX,sizeof(lineX));

    //bind and fill yline buffer
    QGLBuffer bufferY(QGLBuffer::VertexBuffer);
    bufferY.setUsagePattern(QGLBuffer::StaticDraw);
    bufferY.create();
    bufferY.bind();
    bufferY.allocate(lineY, sizeof(lineY));

    //bind and fill zline buffer
    QGLBuffer bufferZ(QGLBuffer::VertexBuffer);
    bufferZ.setUsagePattern(QGLBuffer::StaticDraw);
    bufferZ.create();
    bufferZ.bind();
    bufferZ.allocate(lineZ, sizeof(lineZ));

    QMatrix4x4 mvp;
    QMatrix4x4 vp = camera.getProjMatrix();
    QMatrix4x4 m;

    //find the offest based on camera position
    QVector3D pos = camera.getPosistion();
    int xoff = pos.x() / gridSize;
    int yoff = pos.y() / gridSize;
    int zoff = pos.z() / gridSize;

    //set color uniform to grey
    QVector4D color(0.3f, 0.3f, 0.3f, 1.0f);
    program.setUniformValueArray("color", &color, 1);

    //draw each line
    program.enableAttributeArray("vertex");
    for(int i = -gridNumber; i <= gridNumber; ++i){
        //x lines only for XY and XZ Axis
        if(camera.getLock() == XY || camera.getLock() == XZ)
        {
            bufferX.bind();
            program.setAttributeBuffer("vertex", GL_FLOAT, 0, 4);

            //use model matrix to translate each line with offset
            m.setToIdentity();
            m.translate(0.0f + (xoff * gridSize), (i + yoff) * gridSize, (i + zoff) * gridSize);

            mvp = vp * m ;//set mvp up

            //set mvp uniform then draw
            program.setUniformValueArray("modelToCamera", &mvp, 1);
            glDrawArrays(GL_LINES, 0, 2);
        }

        //y lines for XY and YZ axis only
        if(camera.getLock() == XY || camera.getLock() == YZ)
        {
            bufferY.bind();
            program.setAttributeBuffer("vertex", GL_FLOAT, 0, 4);

            //use model matrix to translate each line with offset
            m.setToIdentity();
            m.translate((i + xoff) * gridSize, 0.0f + (yoff * gridSize) ,(i + zoff) * gridSize);
            mvp = vp * m;

            //set mvp uniform and draw
            program.setUniformValueArray("modelToCamera", &mvp, 1);
            glDrawArrays(GL_LINES, 0, 2);
        }

        //z lines
        if(camera.getLock() == XZ || camera.getLock() == YZ)
        {
            bufferZ.bind();
            program.setAttributeBuffer("vertex", GL_FLOAT, 0, 4);

            //use model matrix to translate each line with offset
            m.setToIdentity();
            m.translate((i + xoff) * gridSize, (i + yoff) * gridSize ,0.0f + (zoff * gridSize));
            mvp = vp * m;

            //set mvp uniform then draw
            program.setUniformValueArray("modelToCamera", &mvp, 1);
            glDrawArrays(GL_LINES, 0, 2);
        }
    }
}
Пример #24
0
/**
 * Fixe les coordonnées d'un vertex et met à   jour l'array openGL.
 *
 * @param i
 * @param nouveau
 */
void Mesh::setXYZ(int i, const QVector3D &nouveau)
{
    setXYZ(i, nouveau.x(), nouveau.y(), nouveau.z());
}
  QList<QVariant> QTAIMLocateElectronDensitySource( QList<QVariant> input  )
  {
    qint64 counter=0;
    const QString fileName=input.at(counter).toString(); counter++;
    //    const qint64 nucleus=input.at(counter).toInt(); counter++
    qreal x0=input.at(counter).toReal(); counter++;
    qreal y0=input.at(counter).toReal(); counter++;
    qreal z0=input.at(counter).toReal(); counter++;

    const QVector3D x0y0z0(x0,y0,z0);

    QTAIMWavefunction wfn;
    wfn.loadFromBinaryFile(fileName);

    QTAIMWavefunctionEvaluator eval(wfn);

    bool correctSignature;
    QVector3D result;

    Matrix<qreal,3,1> xyz; xyz << x0, y0, z0;
    if( eval.electronDensity( xyz ) < 1.e-1 )
    {
      correctSignature=false;
    }
    else
    {
      //      QTAIMODEIntegrator ode(eval,QTAIMODEIntegrator::CMBPPlusThreeGradientInElectronDensityLaplacian);
      QTAIMLSODAIntegrator ode(eval,QTAIMLSODAIntegrator::CMBPPlusThreeGradientInElectronDensityLaplacian);
      result=ode.integrate(x0y0z0);

      Matrix<qreal,3,1> xyz; xyz << result.x(), result.y(), result.z();

      if( eval.electronDensity(xyz) > 1.e-1 &&
          eval.gradientOfElectronDensityLaplacian(xyz).norm() < 1.e-3 )
      {
        if(
            QTAIMMathUtilities::signatureOfASymmetricThreeByThreeMatrix(
                eval.hessianOfElectronDensityLaplacian(xyz)
                ) == 3
            )
        {
          correctSignature=true;
        }
        else
        {
          correctSignature=false;
        }
      }
      else
      {
        correctSignature=false;
      }
    }

    QList<QVariant> value;
    if( correctSignature )
    {
      value.append(correctSignature);
      value.append(result.x());
      value.append(result.y());
      value.append(result.z());
    }
    else
    {
      value.append(false);
    }

    return value;

  }
double Distance3D(QVector3D point1, QVector3D point2)
{
	return sqrt( pow((point2.x()-point1.x()),2) + pow((point2.y()-point1.y()),2) + pow((point2.z()-point1.z()),2));
}
Пример #27
0
void Voxel::set(QVector3D _position, float _length){
    position = QVector3D(_position.x(),_position.y(),_position.z());
    length = _length;
}
Пример #28
0
void BookPage::recalculateGeometry() {

    int x,y;
    float bx,by;
    float ftemp;


    float xitem_length = 1.0f/(renderer->getGridWidth()-1) * xscale;
    float turn_mul = xitem_length;


    GLfloat *t = vertices;
    for (y=0; y<renderer->getGridHeight(); y++) {
        by = (float)y / (float)(renderer->getGridHeight()-1);
        QVector3D curDir = QVector3D(0,0,1);
        QVector3D curPos = QVector3D(  0, -0.5*yscale + by * yscale, zbase );

        for (x=0; x<renderer->getGridWidth(); x++) {
            bx = (float)x / (float)(renderer->getGridWidth()-1);

            // Uv
            t[3] = bx;
            t[4] = 1.0f-by;

            ftemp = (bx - dividerPosX)*pullDirNormX + (by - dividerPosY)*pullDirNormY;

            t[0] = curPos.x();
            t[1] = curPos.y();
            t[2] = curPos.z();

            if (pullFromCenter) {
                ftemp =  0.4f-ftemp*3.0f;
                //ftemp =  1.0f-fabsf(ftemp)*4.0f;
                if (ftemp<0.0f) ftemp = 0.0f;
                if (ftemp>1.0f) ftemp = 1.0f;
            } else {
                ftemp =  -ftemp*4.0f;
                if (ftemp<0.0f) ftemp = 0.0f;
                if (ftemp>1.0f) ftemp = 1.0f;
            }

            curDir+=secondVector*ftemp*turn_mul + mainVector*(1-ftemp)*turn_mul;
            curDir.normalize();
            curDir *= xitem_length;
            curPos += curDir;

                // Normal
            t[5] = 0;
            t[6] = 0;
            t[7] = 0;
            t+=8;
        }
    }



    // Calculate the normals
    QVector3D tv1,tv2;
    int i1,i2,i3,i4;

    for (y=0; y<renderer->getGridHeight()-1; y++)
        for (x=0; x<renderer->getGridWidth()-1; x++) {
            i1 = (y*renderer->getGridWidth()+x);
            i2 = (i1+1);
            i3 = (i1+renderer->getGridWidth());
            i4 = (i2+renderer->getGridWidth());

            i1 *= 8;
            i2 *= 8;
            i3 *= 8;
            i4 *= 8;

            tv1 = QVector3D( vertices[i2] - vertices[i1],
                             vertices[i2+1] - vertices[i1+1],
                             vertices[i2+2] - vertices[i1+2] );
            tv1.normalize();

            tv2 = QVector3D( vertices[i3] - vertices[i1],
                             vertices[i3+1] - vertices[i1+1],
                             vertices[i3+2] - vertices[i1+2] );
            tv2.normalize();

            tv1 = QVector3D::crossProduct( tv1, tv2 );
          // NOTE, check the normalizations.


            // distribute
            vertices[i1+5] += tv1.x();
            vertices[i2+5] += tv1.x();
            vertices[i3+5] += tv1.x();
            vertices[i4+5] += tv1.x();

            vertices[i1+6] += tv1.y();
            vertices[i2+6] += tv1.y();
            vertices[i3+6] += tv1.y();
            vertices[i4+6] += tv1.y();

            vertices[i1+7] += tv1.z();
            vertices[i2+7] += tv1.z();
            vertices[i3+7] += tv1.z();
            vertices[i4+7] += tv1.z();
        }

    // Normalize the vertex normals
    float len;
    t=vertices;
    for (int i=0; i<renderer->getGridWidth() * renderer->getGridHeight(); i++) {
        len = sqrtf( t[5]*5[t]+t[6]*t[6]+t[7]*t[7] );
        if (len==0.0f) len = 0.0f; else len = 1.0f/len;
        t[5] *= -len;
        t[6] *= -len;
        t[7] *= -len;
        t+=8;
    }

}
Пример #29
0
bool QFrustum::boxInFrustum(const QVector3D& position, const QVector3D& halSize) const
{
    // Тут работы немного больше, но тоже не слишком много.
    // Нам передаётся центр куба и половина его длинны. Думайте о длинне так же,
    // как о радиусе для сферы. Мы проверяем каждую точку куба на нахождение внутри
    // пирамиды. Если точка находится перед стороной, переходим к следующей сторону.

    for(int i = 0; i < 6; i++ )
    {
        if (m_frustum[i][A] * (position.x() - halSize.x()) + m_frustum[i][B] * (position.y() - halSize.y()) +
            m_frustum[i][C] * (position.z() - halSize.z()) + m_frustum[i][D] > 0.0f)
           continue;
        if (m_frustum[i][A] * (position.x() + halSize.x()) + m_frustum[i][B] * (position.y() - halSize.y()) +
            m_frustum[i][C] * (position.z() - halSize.z()) + m_frustum[i][D] > 0.0f)
           continue;
        if (m_frustum[i][A] * (position.x() - halSize.x()) + m_frustum[i][B] * (position.y() + halSize.y()) +
            m_frustum[i][C] * (position.z() - halSize.z()) + m_frustum[i][D] > 0.0f)
           continue;
        if (m_frustum[i][A] * (position.x() + halSize.x()) + m_frustum[i][B] * (position.y() + halSize.y()) +
            m_frustum[i][C] * (position.z() - halSize.z()) + m_frustum[i][D] > 0.0f)
           continue;
        if (m_frustum[i][A] * (position.x() - halSize.x()) + m_frustum[i][B] * (position.y() - halSize.y()) +
            m_frustum[i][C] * (position.z() + halSize.z()) + m_frustum[i][D] > 0.0f)
           continue;
        if (m_frustum[i][A] * (position.x() + halSize.x()) + m_frustum[i][B] * (position.y() - halSize.y()) +
            m_frustum[i][C] * (position.z() + halSize.z()) + m_frustum[i][D] > 0.0f)
           continue;
        if (m_frustum[i][A] * (position.x() - halSize.x()) + m_frustum[i][B] * (position.y() + halSize.y()) +
            m_frustum[i][C] * (position.z() + halSize.z()) + m_frustum[i][D] > 0.0f)
           continue;
        if (m_frustum[i][A] * (position.x() + halSize.x()) + m_frustum[i][B] * (position.y() + halSize.y()) +
            m_frustum[i][C] * (position.z() + halSize.z()) + m_frustum[i][D] > 0.0f)
           continue;

        // Если мы дошли досюда, куб не внутри пирамиды.
        return false;
    }

    return true;
}
Пример #30
0
QVector3D cube::getReflVector(QVector3D& v, QVector3D& n)
{
    float d = (v.x()*n.x() + v.y()*n.y() + v.z()*n.z())/
            sqrtf(n.x()*n.x() + n.y()*n.y() + n.z()*n.z());
    return QVector3D(-v.x()+2*d*n.x(), -v.y()+2*d*n.y(), -v.z()+2*d*n.z());
}