コード例 #1
0
ファイル: cubeObj.cpp プロジェクト: Nand-e/2to3d
/*
 *
 * **************************************************/
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) );*/


}
コード例 #2
0
void Quad::rightPress(BrushArea& brush, QMouseEvent* e) {
	brush.texelRange = QVector2D(1,1);
	brush.position = endPoint_- QVector2D(1,1);
	endPoint_ = startPoint_;
	abort_ = true;
}
コード例 #3
0
    Candidate(const QVector2D &f, const QPointF &s, GeometryUtilities::Side t) : first(f), second(s), third(t) { }

    QVector2D first;
    QPointF second;
    GeometryUtilities::Side third = GeometryUtilities::SideUnspecified;
};

}

bool GeometryUtilities::placeRectAtLine(const QRectF &rect, const QLineF &line, double lineOffset, double distance,
                                        const QLineF &intersectionLine, QPointF *placement, Side *horizontalAlignedSide)
{
    QMT_ASSERT(placement, return false);

    QList<Candidate> candidates;
    candidates << Candidate(QVector2D(rect.topRight() - rect.topLeft()), QPointF(0.0, 0.0), SideTop)
               << Candidate(QVector2D(rect.topLeft() - rect.topRight()), rect.topRight() - rect.topLeft(), SideTop)
               << Candidate(QVector2D(rect.bottomLeft() - rect.topLeft()), QPointF(0.0, 0.0), SideLeft)
               << Candidate(QVector2D(rect.topLeft() - rect.bottomLeft()), rect.bottomLeft() - rect.topLeft(), SideLeft)
               << Candidate(QVector2D(rect.bottomRight() - rect.bottomLeft()), rect.bottomLeft() - rect.topLeft(), SideBottom)
               << Candidate(QVector2D(rect.bottomLeft() - rect.bottomRight()), rect.bottomRight() - rect.topLeft(), SideBottom)
               << Candidate(QVector2D(rect.bottomRight() - rect.topRight()), rect.topRight() - rect.topLeft(), SideRight)
               << Candidate(QVector2D(rect.topRight() - rect.bottomRight()), rect.bottomRight() - rect.topLeft(), SideRight);

    QVector<QVector2D> rectEdgeVectors;
    rectEdgeVectors << QVector2D(rect.topLeft() - rect.topLeft())
                    << QVector2D(rect.topRight() - rect.topLeft())
                    << QVector2D(rect.bottomLeft() - rect.topLeft())
                    << QVector2D(rect.bottomRight() -rect.topLeft());

    QVector2D directionVector(line.p2() - line.p1());
コード例 #4
0
ファイル: Object.cpp プロジェクト: artyrian/graphicon
double Cone::F(const QVector3D &p)
{
	QVector3D s = p - position;
	    float q = QVector2D(s.x(), s.z()).length();
	    return QVector2D::dotProduct(c, QVector2D(q, s.y()));
}
コード例 #5
0
ファイル: glwidget.cpp プロジェクト: s0dz/playingWithOpenGL
void GlWidget::initializeGL()
{
    #ifdef WIN32
        glActiveTexture = (PFNGLACTIVETEXTUREPROC) wglGetProcAddress((LPCSTR) "glActiveTexture");
    #endif

    glEnable(GL_DEPTH_TEST);
    glEnable(GL_CULL_FACE);

    qglClearColor(QColor(Qt::black));

    shaderProgram.addShaderFromSourceFile(QGLShader::Vertex, ":/vertexShader.vsh");
    shaderProgram.addShaderFromSourceFile(QGLShader::Fragment, ":/fragmentShader.fsh");
    shaderProgram.link();

    vertices << QVector3D(-0.5, -0.5,  0.5) << QVector3D( 0.5, -0.5,  0.5) << QVector3D( 0.5,  0.5,  0.5) // Front
             << QVector3D( 0.5,  0.5,  0.5) << QVector3D(-0.5,  0.5,  0.5) << QVector3D(-0.5, -0.5,  0.5)
             << QVector3D( 0.5, -0.5, -0.5) << QVector3D(-0.5, -0.5, -0.5) << QVector3D(-0.5,  0.5, -0.5) // Back
             << QVector3D(-0.5,  0.5, -0.5) << QVector3D( 0.5,  0.5, -0.5) << QVector3D( 0.5, -0.5, -0.5)
             << QVector3D(-0.5, -0.5, -0.5) << QVector3D(-0.5, -0.5,  0.5) << QVector3D(-0.5,  0.5,  0.5) // Left
             << QVector3D(-0.5,  0.5,  0.5) << QVector3D(-0.5,  0.5, -0.5) << QVector3D(-0.5, -0.5, -0.5)
             << QVector3D( 0.5, -0.5,  0.5) << QVector3D( 0.5, -0.5, -0.5) << QVector3D( 0.5,  0.5, -0.5) // Right
             << QVector3D( 0.5,  0.5, -0.5) << QVector3D( 0.5,  0.5,  0.5) << QVector3D( 0.5, -0.5,  0.5)
             << QVector3D(-0.5,  0.5,  0.5) << QVector3D( 0.5,  0.5,  0.5) << QVector3D( 0.5,  0.5, -0.5) // Top
             << QVector3D( 0.5,  0.5, -0.5) << QVector3D(-0.5,  0.5, -0.5) << QVector3D(-0.5,  0.5,  0.5)
             << QVector3D(-0.5, -0.5, -0.5) << QVector3D( 0.5, -0.5, -0.5) << QVector3D( 0.5, -0.5,  0.5) // Bottom
             << QVector3D( 0.5, -0.5,  0.5) << QVector3D(-0.5, -0.5,  0.5) << QVector3D(-0.5, -0.5, -0.5);

    textureCoordinates << QVector2D(0, 0) << QVector2D(1, 0) << QVector2D(1, 1) // Front
                       << QVector2D(1, 1) << QVector2D(0, 1) << QVector2D(0, 0)
                       << QVector2D(0, 0) << QVector2D(1, 0) << QVector2D(1, 1) // Back
                       << QVector2D(1, 1) << QVector2D(0, 1) << QVector2D(0, 0)
                       << QVector2D(0, 0) << QVector2D(1, 0) << QVector2D(1, 1) // Left
                       << QVector2D(1, 1) << QVector2D(0, 1) << QVector2D(0, 0)
                       << QVector2D(0, 0) << QVector2D(1, 0) << QVector2D(1, 1) // Right
                       << QVector2D(1, 1) << QVector2D(0, 1) << QVector2D(0, 0)
                       << QVector2D(0, 0) << QVector2D(1, 0) << QVector2D(1, 1) // Top
                       << QVector2D(1, 1) << QVector2D(0, 1) << QVector2D(0, 0)
                       << QVector2D(0, 0) << QVector2D(1, 0) << QVector2D(1, 1) // Bottom
                       << QVector2D(1, 1) << QVector2D(0, 1) << QVector2D(0, 0);

    texture = bindTexture(QPixmap(":/texture.png"));
}
コード例 #6
0
void Fill::neighbourCheck(QVector2D pos) {
	int lw = lvl_->levelDimensions().x();
	int lh = lvl_->levelDimensions().y();
	int sx = startPos_.x()-30;
	if(sx <= 0)
		sx = 0;
	int sy = startPos_.y()-30;
	if(sy <= 0)
		sy = 0;
	int ex = startPos_.x()+30;
	if(ex >= lw)
		ex = lw;
	int ey = startPos_.y()+30;
	if(ey >= lh)
		ey = lh;

	if(!(int(pos.x()) >= sx && int(pos.x()) < ex && int(pos.y()) >= sy && int(pos.y()) < ey)) return;
	if(Util::List::findElement(visited_, pos)) return;

	std::vector<QVector2D> neighbours;

	auto leftPos = QVector2D(int(pos.x())-1, int(pos.y()));
	auto left = lvl_->getTile(leftPos.x(), leftPos.y(), lvl_->currentLayer());

	if(left && int(left->setLocation.x()) == int(fillTile_->setLocation.x()) && int(left->setLocation.y()) == int(fillTile_->setLocation.y()))
		if(!Util::List::findElement(visited_, leftPos))
			neighbours.push_back(leftPos);

	auto topPos = QVector2D(int(pos.x()), int(pos.y())-1);
	auto top = lvl_->getTile(topPos.x(), topPos.y(), lvl_->currentLayer());

	if(top && int(top->setLocation.x()) == int(fillTile_->setLocation.x()) && int(top->setLocation.y()) == int(fillTile_->setLocation.y()))
		if(!Util::List::findElement(visited_, topPos))
			neighbours.push_back(topPos);

	auto rightPos = QVector2D(int(pos.x())+1, int(pos.y()));
	auto right = lvl_->getTile(rightPos.x(), rightPos.y(), lvl_->currentLayer());

	if(right && int(right->setLocation.x()) == int(fillTile_->setLocation.x()) && int(right->setLocation.y()) == int(fillTile_->setLocation.y()))
		if(!Util::List::findElement(visited_, rightPos))
			neighbours.push_back(rightPos);

	auto downPos = QVector2D(int(pos.x()), int(pos.y())+1);
	auto down = lvl_->getTile(downPos.x(), downPos.y(), lvl_->currentLayer());

	if(down && int(down->setLocation.x()) == int(fillTile_->setLocation.x()) && int(down->setLocation.y()) == int(fillTile_->setLocation.y()))
		if(!Util::List::findElement(visited_, downPos))
			neighbours.push_back(downPos);

	std::pair<int,int> pair = std::make_pair(int(pos.x()), int(pos.y()));
	if(!Util::Map::findKey(urTiles_,pair)) {
		auto prevTile = lvl_->getTile(pair.first, pair.second, lvl_->currentLayer());
		URTile prev;
		if(prevTile) {
			prev = {*prevTile, pos, lvl_->currentLayer()};
		} else
			prev = {Tile(), QVector2D(-1,-1), lvl_->currentLayer()};
		std::pair<URTile,URTile> urPair = std::pair<URTile,URTile>(prev,{*selectedTile_,pos, lvl_->currentLayer()});
		urTiles_[pair] = urPair;
	}
	visited_.push_back(pos);

	for(auto &n : neighbours)
		neighbourCheck(n);
}
コード例 #7
0
ファイル: WarpGrid.cpp プロジェクト: emervark/omnidome
 QVector2D WarpGrid::getTexCoord(int _x, int _y) const
 {
     return QVector2D(float(_x) / (horizontal() - 1),
                      float(_y) / (vertical() - 1));
 }
コード例 #8
0
void SurfaceGraph::mousePressEvent(QMouseEvent *e)
{
    // Save mouse press position
    mousePressPosition = QVector2D(e->localPos());
    isDragging = true;
}
コード例 #9
0
ファイル: objloader.cpp プロジェクト: Victer3965/OGL2
RawModel *OBJLoader::Load(QString path)
{
    QVector<QVector3D> tempVertices, outVertices;
    QVector<QVector2D> tempTextures, outTextures;
    QVector<QVector3D> tempNormals, outNormals;

    QVector<int> vertexIndices;
    QVector<int> texIndices;
    QVector<int> normalIndices;

    QFile file(":/res/"+path+".obj");
    if(!file.open(QIODevice::ReadOnly)) {
        QMessageBox::information(0, "error", file.errorString());
        return NULL;
    }

    QTextStream in(&file);
    while(!in.atEnd())
    {
        QString line = in.readLine();
        QStringList fields = line.split(" ", QString::SkipEmptyParts);
        if (line.startsWith("v "))
        {
            tempVertices.append(QVector3D(fields[1].toFloat(), fields[2].toFloat(), fields[3].toFloat()));
        }
        else if (line.startsWith("vt"))
        {
            tempTextures.append(QVector2D(fields[1].toFloat(), fields[2].toFloat()));
        }
        else if (line.startsWith("vn"))
        {
            tempNormals.append(QVector3D(fields[1].toFloat(), fields[2].toFloat(), fields[3].toFloat()));
        }
        else if (line.startsWith("f "))
        {
            for (int i=0; i<3; i++)
            {
                QStringList indeces = fields[i+1].split("/");
                vertexIndices.append(indeces[0].toInt());
                texIndices   .append(indeces[1].toInt());
                normalIndices.append(indeces[2].toInt());
            }
        }
    }
    for(int i=0; i<vertexIndices.size(); i++)
    {
        unsigned int vertexIndex = vertexIndices[i];
        outVertices.append(tempVertices[vertexIndex-1]);
    }
    for(int i=0; i<texIndices.size(); i++)
    {
        unsigned int texIndex = texIndices[i];
        outTextures.append(tempTextures[texIndex-1]);
    }
    for(int i=0; i<normalIndices.size(); i++)
    {
        unsigned int normalIndex = normalIndices[i];
        outNormals.append(tempNormals[normalIndex-1]);
    }
    return new RawModel(outVertices, outTextures, outNormals);
}
コード例 #10
0
/**
* 指定されたtensor filedに基づいて、ptからsegment_length分の道路セグメントを生成する。
* ただし、ターゲットエリア外に出るか、既存セグメントとの交差点が既存交差点の近くなら、途中で終了する。
*
* @param tensor				tensor field
* @param segment_length		segment length
* @param near_threshold		near threshold
* @param srcDesc			src vertex desc
* @param tgtDesc [OUT]		tgt vertex desc
* @param type				1 -- major eigen vector / 2 -- minor eigen vector
* @return					0 -- 正常終了 / 1 -- ターゲットエリア外に出て終了 / 2 -- 既存交差点の近くで交差して終了
*/
int PMRoadGenerator::generateRoadSegmentByTensor(const cv::Mat& tensor, float segment_length, float near_threshold, RoadVertexDesc srcDesc, RoadVertexDesc& tgtDesc, int type) {
	int num_step = 5;
	float step_length = (segment_length + Util::genRand(-1.0, 1.0)) / num_step;

	BBox bbox = targetArea.envelope();

	QVector2D pt = roads.graph[srcDesc]->pt;
	RoadEdgePtr new_edge = RoadEdgePtr(new RoadEdge(RoadEdge::TYPE_AVENUE, 1));
	new_edge->addPoint(pt);

	for (int i = 0; i < num_step; ++i) {
		// ターゲットエリア外ならストップ
		if (!targetArea.contains(pt)) {
			return 1;
		}

		/////////////////////////////////////////////////////////////////////
		// use Runge-Kutta 4 to obtain the next angle
		int c = pt.x() - bbox.minPt.x();
		int r = pt.y() - bbox.minPt.y();
		float angle1 = tensor.at<float>(r, c);
		if (type == 2) angle1 += M_PI / 2;	// minor eigen vectorならPI/2を足す

		// angle2
		QVector2D pt2 = pt + QVector2D(cosf(angle1), sinf(angle1)) * (step_length * 0.5);
		int c2 = pt2.x() - bbox.minPt.x();
		int r2 = pt2.y() - bbox.minPt.y();
		float angle2 = angle1;
		if (c2 >= 0 && c2 < tensor.cols && r2 >= 0 && r2 < tensor.rows) {
			angle2 = tensor.at<float>(r2, c2);
			if (type == 2) angle2 += M_PI / 2;	// minor eigen vectorならPI/2を足す
		}

		// angle3
		QVector2D pt3 = pt + QVector2D(cosf(angle2), sinf(angle2)) * (step_length * 0.5);
		int c3 = pt3.x() - bbox.minPt.x();
		int r3 = pt3.y() - bbox.minPt.y();
		float angle3 = angle2;
		if (c3 >= 0 && c3 < tensor.cols && r3 >= 0 && r3 < tensor.rows) {
			angle3 = tensor.at<float>(r3, c3);
			if (type == 2) angle3 += M_PI / 2;	// minor eigen vectorならPI/2を足す
		}

		// angle4
		QVector2D pt4 = pt + QVector2D(cosf(angle3), sinf(angle3)) * step_length;
		int c4 = pt4.x() - bbox.minPt.x();
		int r4 = pt4.y() - bbox.minPt.y();
		float angle4 = angle3;
		if (c4 >= 0 && c4 < tensor.cols && r4 >= 0 && r4 < tensor.rows) {
			angle4 = tensor.at<float>(r4, c4);
			if (type == 2) angle4 += M_PI / 2;	// minor eigen vectorならPI/2を足す
		}

		// RK4によりangleを計算
		float angle = angle1 / 6.0 + angle2 / 3.0 + angle3 / 3.0 + angle4 / 6.0;

		// 次のステップの座標を求める
		QVector2D next_pt = pt + QVector2D(cosf(angle), sinf(angle)) * step_length;

		// 交差点を求める
		RoadEdgeDesc nearestEdgeDesc;
		QVector2D intPt;
		if (GraphUtil::isIntersect(roads, pt, next_pt, nearestEdgeDesc, intPt)) {
			int edgeEigenType = roads.graph[nearestEdgeDesc]->eigenType;

			// 他のエッジにスナップ
			tgtDesc = GraphUtil::splitEdge(roads, nearestEdgeDesc, intPt);
			intPt = roads.graph[tgtDesc]->pt;
			roads.graph[tgtDesc]->eigenType |= type;
			roads.graph[tgtDesc]->eigenType |= edgeEigenType;
			roads.graph[tgtDesc]->new_vertx = true;

			new_edge->addPoint(intPt);

			// エッジを生成
			new_edge->eigenType = type;
			GraphUtil::addEdge(roads, srcDesc, tgtDesc, new_edge);

			// エッジを交差点から再開させる
			srcDesc = tgtDesc;
			pt = intPt;
			new_edge = RoadEdgePtr(new RoadEdge(RoadEdge::TYPE_AVENUE, 1));
			new_edge->addPoint(pt);

			// 既に近くに頂点がないかチェック
			bool foundNearVertex = false;
			RoadVertexIter vi, vend;
			for (boost::tie(vi, vend) = boost::vertices(roads.graph); vi != vend; ++vi) {
				// 現在生成中の道路セグメントは、チェックしない。
				if (roads.graph[*vi]->new_vertx) continue;

				// major vector と minor vectorで異なる場合は、チェックしない
				if (!(roads.graph[*vi]->eigenType & type)) continue;

				float dist = (roads.graph[*vi]->pt - intPt).length();
				if (dist < near_threshold) {
					foundNearVertex = true;
					break;
				}
			}

			if (foundNearVertex) {
				// 道路セグメントの生成を交差点でストップさせる
				return 2;
			}
		}

		// ターゲットエリア外なら、終了
		if (!targetArea.contains(next_pt)) {
			return 1;
		}

		new_edge->addPoint(next_pt);

		pt = next_pt;
	}

	if (new_edge->getLength() >= 1.0f) {
		RoadVertexPtr v = RoadVertexPtr(new RoadVertex(pt));
		tgtDesc = GraphUtil::addVertex(roads, v);
		roads.graph[tgtDesc]->eigenType = type;
		roads.graph[tgtDesc]->new_vertx = true;

		// add edge
		new_edge->eigenType = type;
		GraphUtil::addEdge(roads, srcDesc, tgtDesc, new_edge);
	}
	else {
		tgtDesc = srcDesc;
	}
	
	return 0;
}
コード例 #11
0
/**
 * 座標pt、角度angleから開始して1本の道路を生成する。
 *
 * @param size						ターゲットエリアの一辺の長さ
 * @param angle						角度 [rad]
 * @param pt						開始位置
 * @param curvature					曲率
 * @param segment_length			segment length
 * @param regular_elements [OUT]	tensor fieldを指定するためのコントロール情報
 * @param seeds [OUT]				生成された頂点をseedリストに追加する
*/
void PMRoadGenerator::growRoads(float angle, RoadVertexDesc srcDesc, float curvature, float segment_length, int type, std::vector<std::pair<QVector2D, float>>& regular_elements, std::list<RoadVertexDesc>& seeds) {
	int num_steps = 5;

	QVector2D pt = roads.graph[srcDesc]->pt;

	bool loop = true;
	while (loop) {
		// 今後5ステップ分の曲率を、平均がcurvatureになるようランダムに決定する。
		std::vector<float> rotates;
		float total = 0.0f;
		for (int i = 0; i < num_steps; ++i) {
			float r = rand() % 100;
			rotates.push_back(r);
			total += r;
		}
		for (int i = 0; i < num_steps; ++i) {
			rotates[i] = rotates[i] / total * curvature * num_steps;
		}

		// 曲がる方向を決定する
		int rotate_dir = rand() % 2 == 0 ? 1 : -1;

		// 5ステップ分の道路セグメントを生成する
		for (int i = 0; i < num_steps; ++i) {
			// ターゲットエリア外なら終了
			if (!targetArea.contains(pt)) return;

			angle += rotates[i] * rotate_dir;
			QVector2D pt2 = pt + QVector2D(cosf(angle), sinf(angle)) * (segment_length + Util::genRand(-1.0, 1.0));

			RoadEdgeDesc closestEdge;
			QVector2D intPt;
			if (GraphUtil::isIntersect(roads, pt, pt2, closestEdge, intPt)) {
				// 他のエッジにスナップ
				RoadVertexDesc tgtDesc = GraphUtil::splitEdge(roads, closestEdge, intPt);
				roads.graph[tgtDesc]->eigenType |= type;

				// エッジを生成
				RoadEdgePtr new_edge = RoadEdgePtr(new RoadEdge(RoadEdge::TYPE_AVENUE, 1));
				new_edge->addPoint(pt);
				new_edge->addPoint(intPt);
				new_edge->eigenType = type;
				GraphUtil::addEdge(roads, srcDesc, tgtDesc, new_edge);

				return;
			}		

			// add a vertex
			RoadVertexPtr v = RoadVertexPtr(new RoadVertex(pt2));
			RoadVertexDesc tgtDesc = GraphUtil::addVertex(roads, v);
			roads.graph[tgtDesc]->eigenType = type;

			// add this vertex to the seeds
			seeds.push_back(tgtDesc);

			// add an edge
			RoadEdgePtr new_edge = RoadEdgePtr(new RoadEdge(RoadEdge::TYPE_AVENUE, 1));
			new_edge->addPoint(pt);
			new_edge->addPoint(pt2);
			GraphUtil::addEdge(roads, srcDesc, tgtDesc, new_edge);

			regular_elements.push_back(std::make_pair(pt2, angle));

			pt = pt2;
			srcDesc = tgtDesc;
		}
	}
}
コード例 #12
0
/**
 * 指定されたpolylineに従って、srcDesc頂点からエッジを伸ばす。
 * エッジの端点が、srcDescとは違うセルに入る場合は、falseを返却する。
 */
bool PatchRoadGenerator::growRoadSegment(int roadType, RoadVertexDesc srcDesc, ExFeature& f, const Polyline2D &polyline, int lanes, float angleTolerance, std::list<RoadVertexDesc> &seeds) {
	float angle = atan2f(polyline[1].y() - polyline[0].y(), polyline[1].x() - polyline[0].x());

	RoadEdgePtr new_edge = RoadEdgePtr(new RoadEdge(roadType, lanes));
	new_edge->polyline.push_back(roads.graph[srcDesc]->pt);

	RoadVertexDesc tgtDesc;
	bool found = false;
	{
		// 指定された方向で、直近の頂点があるかチェックする。
		// まずは、指定された方向に非常に近い頂点があるかチェックする。この際、距離は少し遠くまで許容する。
		// 次に、方向のレンジを少し広げて、その代わり、距離を短くして、改めてチェックする。
		/*if (GraphUtil::getVertex(roads, srcDesc, polyline.length() * 2.0f, angle, 0.1f, tgtDesc)) {
			found = true;
		} else if (GraphUtil::getVertex(roads, srcDesc, polyline.length() * 1.5f, angle, 0.2f, tgtDesc)) {
			found = true;
		} else if (GraphUtil::getVertex(roads, srcDesc, polyline.length(), angle, 0.3f, tgtDesc)) {
			found = true;
		}
		*/
		if (GraphUtil::getVertexExceptDeadend(roads, srcDesc, polyline.length() * 2.0f, angle, 0.3f, tgtDesc)) {
			found = true;
		}

		if (found) {
			// もしスナップ先が、シードじゃないなら、エッジ生成をキャンセル
			if (std::find(seeds.begin(), seeds.end(), tgtDesc) == seeds.end()) {
				//(要検討。80%の確率ぐらいにすべきか?)
				if (Util::genRand(0, 1) < 0.8f) return false;
			}

			// もしスナップ先の頂点が、redundantなエッジを持っているなら、エッジ生成をキャンセル
			Polyline2D snapped_polyline;
			snapped_polyline.push_back(QVector2D(0, 0));
			snapped_polyline.push_back(QVector2D(roads.graph[srcDesc]->pt - roads.graph[tgtDesc]->pt));
			if (RoadGeneratorHelper::isRedundantEdge(roads, tgtDesc, snapped_polyline, 0.3f)) {
				//(とりあえず、ものすごい鋭角の場合は、必ずキャンセル)
				return false;
			}

			// もし他のエッジに交差するなら、エッジ生成をキャンセル
			// (キャンセルせずに、交差させるべき?)
			QVector2D intPoint;
			RoadEdgeDesc closestEdge;
			new_edge->polyline.push_back(roads.graph[tgtDesc]->pt);
			if (GraphUtil::isIntersect(roads, new_edge->polyline, srcDesc, closestEdge, intPoint)) {
				if (Util::genRand(0, 1) < 0.5f) return false;

				new_edge->polyline[1] = intPoint;

				// 他のエッジにスナップ
				tgtDesc = GraphUtil::splitEdge(roads, closestEdge, intPoint);
				roads.graph[tgtDesc]->properties["generation_type"] = "snapped";
				roads.graph[tgtDesc]->properties["group_id"] = roads.graph[closestEdge]->properties["group_id"];
				roads.graph[tgtDesc]->properties["ex_id"] = roads.graph[closestEdge]->properties["ex_id"];
				roads.graph[tgtDesc]->properties.remove("example_desc");
			} else {
				new_edge->polyline.push_back(roads.graph[tgtDesc]->pt);
			}
		}
	}

	if (!found) {
		// snap先がなければ、指定されたpolylineに従ってエッジを生成する。
		new_edge->polyline.push_back(roads.graph[srcDesc]->pt + polyline[1]);

		// もし、新規エッジが、既存グラフと交差するなら、エッジ生成をキャンセル
		QVector2D intPoint;
		RoadEdgeDesc closestEdge;
		if (GraphUtil::isIntersect(roads, new_edge->polyline, srcDesc, closestEdge, intPoint)) {
			// 60%の確率でキャンセル?
			if (Util::genRand(0, 1) < 0.6f) return false;

			// 交差する箇所で中断させる
			new_edge->polyline[1] = intPoint;

			// 他のエッジにスナップ
			tgtDesc = GraphUtil::splitEdge(roads, closestEdge, intPoint);
			roads.graph[tgtDesc]->properties["generation_type"] = "snapped";
			roads.graph[tgtDesc]->properties["group_id"] = roads.graph[closestEdge]->properties["group_id"];
			roads.graph[tgtDesc]->properties["ex_id"] = roads.graph[closestEdge]->properties["ex_id"];
			roads.graph[tgtDesc]->properties.remove("example_desc");

			found = true;
		}
	}

	if (!found) {
		// 頂点を追加
		RoadVertexPtr v = RoadVertexPtr(new RoadVertex(new_edge->polyline.last()));
		tgtDesc = GraphUtil::addVertex(roads, v);

		// エリアの外なら、onBoundaryフラグをセット
		if (!targetArea.contains(roads.graph[tgtDesc]->pt)) {
			roads.graph[tgtDesc]->onBoundary = true;
		}

		// エリア内なら、seedsに追加
		if (!roads.graph[tgtDesc]->onBoundary) {
			seeds.push_back(tgtDesc);
		}
	}
	
	// エッジを追加
	// エッジをstepサイズに分割し、分割点に頂点を追加する。この頂点は、後でlocal street生成の初期シードとして使用する。
	{
		float step = new_edge->polyline.length() / 5.0f;
		angle = atan2f(new_edge->polyline[1].y() - new_edge->polyline[0].y(), new_edge->polyline[1].x() - new_edge->polyline[0].x());

		RoadVertexDesc curDesc = srcDesc;
		QVector2D curPt = roads.graph[srcDesc]->pt;
		for (float len = step; len < new_edge->polyline.length() - step; len += step) {
			QVector2D nextPt = curPt + QVector2D(cosf(angle) * step, sinf(angle) * step);

			// 頂点を作成
			RoadVertexPtr v = RoadVertexPtr(new RoadVertex(nextPt));
			RoadVertexDesc nextDesc = GraphUtil::addVertex(roads, v);

			// エッジを作成
			RoadEdgePtr e = RoadEdgePtr(new RoadEdge(roadType, lanes));
			e->polyline.push_back(curPt);
			e->polyline.push_back(nextPt);
			GraphUtil::addEdge(roads, curDesc, nextDesc, e);

			curPt = nextPt;
			curDesc = nextDesc;
		}

		// 最後のエッジを作成
		RoadEdgePtr e = RoadEdgePtr(new RoadEdge(roadType, lanes));
		e->polyline.push_back(curPt);
		e->polyline.push_back(roads.graph[tgtDesc]->pt);
		GraphUtil::addEdge(roads, curDesc, tgtDesc, e);
	}
	//RoadEdgeDesc e_desc = GraphUtil::addEdge(roads, srcDesc, tgtDesc, new_edge);

	return true;
}
コード例 #13
0
/****************************************************************************
**
** Copyright (C) 2016 - 2017
**
** This file is generated by the Magus toolkit
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
****************************************************************************/

// Include
#include <float.h>
#include <QMessageBox>
#include <QSettings>
#include "constants.h"
#include "hlms_node_samplerblock.h"
#include "hlms_node_porttypes.h"

//****************************************************************************/
HlmsNodeSamplerblock::HlmsNodeSamplerblock(QString title, QGraphicsItem* parent) :
    Magus::QtNode(title, parent),
    mTextureType(0),
    mTextureIndex(0),
    mSamplerblockEnabled(true),
    mTextureAddressingModeU(0),
    mTextureAddressingModeV(0),
    mTextureAddressingModeW(0),
    mMipLodBias(0.0f),
    mMaxAnisotropy(1.0f),
    mCompareFunction(8),
    mMinLod(-FLT_MAX),
    mMaxLod(FLT_MAX),
    mBorderColourRed(255.0f),
    mBorderColourGreen(255.0f),
    mBorderColourBlue(255.0f),
    mUvSet(0),
    mBlendMode(0),
    mMapWeight(1.0f),
    mEmissiveColourRed(0.0f),
    mEmissiveColourGreen(0.0f),
    mEmissiveColourBlue(0.0f),
    mAnimationEnabled(false),
    mSequenceNumber(-1)
{
    mFileNameTexture = QString("");
    mBaseNameTexture = QString("");
    mPathTexture = QString("");
    mOffset = QVector2D(0.0f, 0.0f);
    mScale = QVector2D(1.0f, 1.0f);
    mAnimationScale = QVector2D(1.0f, 1.0f);
    mAnimationTranslate = QVector2D(0.0f, 0.0f);

    // Define the connection policy
    HlmsPbsDatablockSamplerblockPortType hlmsPbsDatablockSamplerblockPortType;
    HlmsSamplerblockDatablockPortType hlmsSamplerblockDatablockPortType;
    hlmsPbsDatablockSamplerblockPortType.addPortTypeToConnectionPolicy(hlmsSamplerblockDatablockPortType);

    // Apply values from settings.cfg
    QSettings settings(FILE_SETTINGS, QSettings::IniFormat);
    mTextureMinFilter = settings.value(SETTINGS_SAMPLERBLOCK_FILTER_INDEX).toInt();
    mTextureMagFilter = settings.value(SETTINGS_SAMPLERBLOCK_FILTER_INDEX).toInt();
    mTextureMipFilter = settings.value(SETTINGS_SAMPLERBLOCK_FILTER_INDEX).toInt();

    // Custome node settings
    setTitleColor(Qt::white);
    setHeaderTitleIcon(ICON_SAMPLERBLOCK);
    setAction1Icon(ICON_MINMAX);
    setAction2Icon(ICON_CLOSE);
    alignTitle(Magus::ALIGNED_LEFT);
    setHeaderColor(QColor("#874E96"));
    mPort = createPort(PORT_ID_SAMPLERBLOCK,
                       PORT_DATABLOCK,
                       hlmsPbsDatablockSamplerblockPortType,
                       QColor("#874E96"),
                       Magus::PORT_SHAPE_CIRCLE,
                       Magus::ALIGNED_LEFT,
                       QColor("#874E96"));

    setPortNameColor(Qt::white);
    setZoom(0.9);
}
コード例 #14
0
ファイル: cubeObj.cpp プロジェクト: Nand-e/2to3d
void CubeObj::makeobject () {
    vertices.append ( QVector3D ( -0.5f , 0.5f , 0.5f ));        // Make face Front
    vertices.append ( QVector3D ( -0.5f ,-0.5f , 0.5f ));
    vertices.append ( QVector3D (  0.5f ,-0.5f , 0.5f ));
    vertices.append ( QVector3D (  0.5f , 0.5f , 0.5f ));

    vertices.append ( QVector3D (  0.5f , 0.5f ,  0.5f ));        // Make face Right side
    vertices.append ( QVector3D (  0.5f ,-0.5f ,  0.5f ));
    vertices.append ( QVector3D (  0.5f ,-0.5f , -0.5f ));
    vertices.append ( QVector3D (  0.5f , 0.5f , -0.5f ));

    vertices.append ( QVector3D ( -0.5f , 0.5f , 0.5f ));        // Make face Left side
    vertices.append ( QVector3D ( -0.5f , 0.5f , -0.5f ));
    vertices.append ( QVector3D ( -0.5f , -0.5f , -0.5f ));
    vertices.append ( QVector3D ( -0.5f , -0.5f , 0.5f ));

    vertices.append ( QVector3D ( -0.5f , 0.5f , -0.5f ));        // Make face up
    vertices.append ( QVector3D ( -0.5f , 0.5f ,  0.5f ));
    vertices.append ( QVector3D (  0.5f , 0.5f , 0.5f ));
    vertices.append ( QVector3D (  0.5f , 0.5f , -0.5f ));

    vertices.append ( QVector3D ( -0.5f , -0.5f , -0.5f ));        // Make face down
    vertices.append ( QVector3D ( -0.5f , -0.5f ,  0.5f ));
    vertices.append ( QVector3D (  0.5f , -0.5f , 0.5f ));
    vertices.append ( QVector3D (  0.5f , -0.5f , -0.5f ));

    vertices.append ( QVector3D ( -0.5f , 0.5f , -0.5f ));        // Make face Back
    vertices.append ( QVector3D (  0.5f , 0.5f , -0.5f ));
    vertices.append ( QVector3D (  0.5f , -0.5f , -0.5f ));
    vertices.append ( QVector3D (  -0.5f , -0.5f , -0.5f ));

    texCoords.clear();
    texCoords.append( QVector2D ( 0,0));                          // Set Texture coordinate
    texCoords.append( QVector2D ( 0,1));
    texCoords.append( QVector2D ( 1,1));
    texCoords.append( QVector2D ( 1,0));
    // Set Texture coordinate
    texCoords.append( QVector2D ( 0,0));
    texCoords.append( QVector2D ( 0,1));
    texCoords.append( QVector2D ( 1,1));
    texCoords.append( QVector2D ( 1,0));
    // Set Texture coordinate
    texCoords.append( QVector2D ( 0,0));
    texCoords.append( QVector2D ( 0,1));
    texCoords.append( QVector2D ( 1,1));
    texCoords.append( QVector2D ( 1,0));

    // Set Texture coordinate
    texCoords.append( QVector2D ( 0,0));
    texCoords.append( QVector2D ( 0,1));
    texCoords.append( QVector2D ( 1,1));
    texCoords.append( QVector2D ( 1,0));
    // Set Texture coordinate
    texCoords.append( QVector2D ( 0,0));
    texCoords.append( QVector2D ( 0,1));
    texCoords.append( QVector2D ( 1,1));
    texCoords.append( QVector2D ( 1,0));

    // Set Texture coordinate
    texCoords.append( QVector2D ( 0,0));
    texCoords.append( QVector2D ( 0,1));
    texCoords.append( QVector2D ( 1,1));
    texCoords.append( QVector2D ( 1,0));
}
コード例 #15
0
ファイル: qvector4d.cpp プロジェクト: husninazer/qt
/*!
    Returns the 2D vector form of this 4D vector, dividing the x and y
    coordinates by the w coordinate and dropping the z coordinate.
    Returns a null vector if w is zero.

    \sa toVector2D(), toVector3DAffine(), toPoint()
*/
QVector2D QVector4D::toVector2DAffine() const
{
    if (qIsNull(wp))
        return QVector2D();
    return QVector2D(xp / wp, yp / wp, 1);
}
コード例 #16
0
ファイル: lineending.cpp プロジェクト: alagoutte/QCustomPlot
/*! \internal
  
  Draws the line ending with the specified \a painter at the position \a pos. The direction of the
  line ending is controlled with \a dir.
*/
void QCPLineEnding::draw(QCPPainter *painter, const QVector2D &pos, const QVector2D &dir) const
{
  if (mStyle == esNone)
    return;
  
  QVector2D lengthVec(dir.normalized());
  if (lengthVec.isNull())
    lengthVec = QVector2D(1, 0);
  QVector2D widthVec(-lengthVec.y(), lengthVec.x());
  lengthVec *= (float)(mLength*(mInverted ? -1 : 1));
  widthVec *= (float)(mWidth*0.5*(mInverted ? -1 : 1));
  
  QPen penBackup = painter->pen();
  QBrush brushBackup = painter->brush();
  QPen miterPen = penBackup;
  miterPen.setJoinStyle(Qt::MiterJoin); // to make arrow heads spikey
  QBrush brush(painter->pen().color(), Qt::SolidPattern);
  switch (mStyle)
  {
    case esNone: break;
    case esFlatArrow:
    {
      QPointF points[3] = {pos.toPointF(),
                           (pos-lengthVec+widthVec).toPointF(),
                           (pos-lengthVec-widthVec).toPointF()
                          };
      painter->setPen(miterPen);
      painter->setBrush(brush);
      painter->drawConvexPolygon(points, 3);
      painter->setBrush(brushBackup);
      painter->setPen(penBackup);
      break;
    }
    case esSpikeArrow:
    {
      QPointF points[4] = {pos.toPointF(),
                           (pos-lengthVec+widthVec).toPointF(),
                           (pos-lengthVec*0.8f).toPointF(),
                           (pos-lengthVec-widthVec).toPointF()
                          };
      painter->setPen(miterPen);
      painter->setBrush(brush);
      painter->drawConvexPolygon(points, 4);
      painter->setBrush(brushBackup);
      painter->setPen(penBackup);
      break;
    }
    case esLineArrow:
    {
      QPointF points[3] = {(pos-lengthVec+widthVec).toPointF(),
                           pos.toPointF(),
                           (pos-lengthVec-widthVec).toPointF()
                          };
      painter->setPen(miterPen);
      painter->drawPolyline(points, 3);
      painter->setPen(penBackup);
      break;
    }
    case esDisc:
    {
      painter->setBrush(brush);
      painter->drawEllipse(pos.toPointF(),  mWidth*0.5, mWidth*0.5);
      painter->setBrush(brushBackup);
      break;
    }
    case esSquare:
    {
      QVector2D widthVecPerp(-widthVec.y(), widthVec.x());
      QPointF points[4] = {(pos-widthVecPerp+widthVec).toPointF(),
                           (pos-widthVecPerp-widthVec).toPointF(),
                           (pos+widthVecPerp-widthVec).toPointF(),
                           (pos+widthVecPerp+widthVec).toPointF()
                          };
      painter->setPen(miterPen);
      painter->setBrush(brush);
      painter->drawConvexPolygon(points, 4);
      painter->setBrush(brushBackup);
      painter->setPen(penBackup);
      break;
    }
    case esDiamond:
    {
      QVector2D widthVecPerp(-widthVec.y(), widthVec.x());
      QPointF points[4] = {(pos-widthVecPerp).toPointF(),
                           (pos-widthVec).toPointF(),
                           (pos+widthVecPerp).toPointF(),
                           (pos+widthVec).toPointF()
                          };
      painter->setPen(miterPen);
      painter->setBrush(brush);
      painter->drawConvexPolygon(points, 4);
      painter->setBrush(brushBackup);
      painter->setPen(penBackup);
      break;
    }
    case esBar:
    {
      painter->drawLine((pos+widthVec).toPointF(), (pos-widthVec).toPointF());
      break;
    }
    case esHalfBar:
    {
      painter->drawLine((pos+widthVec).toPointF(), pos.toPointF());
      break;
    }
    case esSkewedBar:
    {
      if (qFuzzyIsNull(painter->pen().widthF()) && !painter->modes().testFlag(QCPPainter::pmNonCosmetic))
      {
        // if drawing with cosmetic pen (perfectly thin stroke, happens only in vector exports), draw bar exactly on tip of line
        painter->drawLine((pos+widthVec+lengthVec*0.2f*(mInverted?-1:1)).toPointF(),
                          (pos-widthVec-lengthVec*0.2f*(mInverted?-1:1)).toPointF());
      } else
      {
        // if drawing with thick (non-cosmetic) pen, shift bar a little in line direction to prevent line from sticking through bar slightly
        painter->drawLine((pos+widthVec+lengthVec*0.2f*(mInverted?-1:1)+dir.normalized()*qMax(1.0f, (float)painter->pen().widthF())*0.5f).toPointF(),
                          (pos-widthVec-lengthVec*0.2f*(mInverted?-1:1)+dir.normalized()*qMax(1.0f, (float)painter->pen().widthF())*0.5f).toPointF());
      }
      break;
    }
  }
}
コード例 #17
0
bool GeometryUtilities::placeRectAtLine(const QRectF &rect, const QLineF &line, double lineOffset, double distance,
                                        const QLineF &intersectionLine, QPointF *placement, Side *horizontalAlignedSide)
{
    QMT_CHECK(placement);

    QList<Candidate> candidates;
    candidates << Candidate(QVector2D(rect.topRight() - rect.topLeft()), QPointF(0.0, 0.0), SideTop)
               << Candidate(QVector2D(rect.topLeft() - rect.topRight()), rect.topRight() - rect.topLeft(), SideTop)
               << Candidate(QVector2D(rect.bottomLeft() - rect.topLeft()), QPointF(0.0, 0.0), SideLeft)
               << Candidate(QVector2D(rect.topLeft() - rect.bottomLeft()), rect.bottomLeft() - rect.topLeft(), SideLeft)
               << Candidate(QVector2D(rect.bottomRight() - rect.bottomLeft()), rect.bottomLeft() - rect.topLeft(), SideBottom)
               << Candidate(QVector2D(rect.bottomLeft() - rect.bottomRight()), rect.bottomRight() - rect.topLeft(), SideBottom)
               << Candidate(QVector2D(rect.bottomRight() - rect.topRight()), rect.topRight() - rect.topLeft(), SideRight)
               << Candidate(QVector2D(rect.topRight() - rect.bottomRight()), rect.bottomRight() - rect.topLeft(), SideRight);

    QVector<QVector2D> rectEdgeVectors;
    rectEdgeVectors << QVector2D(rect.topLeft() - rect.topLeft())
                    << QVector2D(rect.topRight() - rect.topLeft())
                    << QVector2D(rect.bottomLeft() - rect.topLeft())
                    << QVector2D(rect.bottomRight() -rect.topLeft());

    QVector2D directionVector(line.p2() - line.p1());
    directionVector.normalize();

    QVector2D sideVector(directionVector.y(), -directionVector.x());

    QVector2D intersectionVector(intersectionLine.p2() - intersectionLine.p1());
    intersectionVector.normalize();

    QVector2D outsideVector = QVector2D(intersectionVector.y(), -intersectionVector.x());
    double p = QVector2D::dotProduct(directionVector, outsideVector);
    if (p < 0.0)
        outsideVector = outsideVector * -1.0;

    double smallestA = -1.0;
    QPointF rectTranslation;
    Side side = SideUnspecified;
    int bestSign = 0;

    foreach (const Candidate &candidate, candidates) {
        // solve equation a * directionVector + candidate.first = b * intersectionVector to find smallest a
        double r = directionVector.x() * intersectionVector.y() - directionVector.y() * intersectionVector.x();
        if (r <= -1e-5 || r >= 1e-5) {
            double a = (candidate.first.y() * intersectionVector.x()
                        - candidate.first.x() * intersectionVector.y()) / r;
            if (a >= 0.0 && (smallestA < 0.0 || a < smallestA)) {
                // verify that all rectangle edges lay outside of shape (by checking for positiv projection to intersection)
                bool ok = true;
                int sign = 0;
                QVector2D rectOriginVector = directionVector * a - QVector2D(candidate.second);
                foreach (const QVector2D &rectEdgeVector, rectEdgeVectors) {
                    QVector2D edgeVector = rectOriginVector + rectEdgeVector;
                    double aa = QVector2D::dotProduct(outsideVector, edgeVector);
                    if (aa < 0.0) {
                        ok = false;
                        break;
                    }
                    int s = sgn(QVector2D::dotProduct(sideVector, edgeVector));
                    if (s) {
                        if (sign) {
                            if (s != sign) {
                                ok = false;
                                break;
                            }
                        } else {
                            sign = s;
                        }
                    }
                }
コード例 #18
0
ファイル: lineending.cpp プロジェクト: alagoutte/QCustomPlot
/*! \internal
  \overload
  
  Draws the line ending. The direction is controlled with the \a angle parameter in radians.
*/
void QCPLineEnding::draw(QCPPainter *painter, const QVector2D &pos, double angle) const
{
  draw(painter, pos, QVector2D(qCos(angle), qSin(angle)));
}
コード例 #19
0
ファイル: gridmap.cpp プロジェクト: justwillim/A40
void Gridmap::mousePressEvent(QMouseEvent *e) { mouse = QVector2D(e->pos()); }
コード例 #20
0
ファイル: tilebound.cpp プロジェクト: crafter2d/crafter2d
void TileBound::calculateNormal()
{
    QPointF direction = mRight - mLeft;
    mNormal = QVector2D(-direction.y(), direction.x());
    mNormal.normalize();
}
コード例 #21
0
ファイル: GeometryEngine.cpp プロジェクト: naniBox/kuroBox
//-----------------------------------------------------------------------------
void GeometryEngine::initGeometry()
{
    // For cube we would need only 8 vertices but we have to
    // duplicate vertex for each face because texture coordinate
    // is different.
    VertexData vertices[] = {
        // Vertex data for face 0
		{QVector3D(-1.0f, -1.0f,  1.0f), QVector2D(0.0f,  0.0f)}, // v0
        {QVector3D( 1.0f, -1.0f,  1.0f), QVector2D(0.33f, 0.0f)}, // v1
		{QVector3D(-1.0f,  1.0f,  1.0f), QVector2D(0.0f,  0.5f)}, // v2
        {QVector3D( 1.0f,  1.0f,  1.0f), QVector2D(0.33f, 0.5f)}, // v3

        // Vertex data for face 1
        {QVector3D( 1.0f, -1.0f,  1.0f), QVector2D( 0.0f, 0.5f)}, // v4
        {QVector3D( 1.0f, -1.0f, -1.0f), QVector2D(0.33f, 0.5f)}, // v5
		{QVector3D( 1.0f,  1.0f,  1.0f), QVector2D(0.0f,  1.0f)}, // v6
        {QVector3D( 1.0f,  1.0f, -1.0f), QVector2D(0.33f, 1.0f)}, // v7

        // Vertex data for face 2
        {QVector3D( 1.0f, -1.0f, -1.0f), QVector2D(0.66f, 0.5f)}, // v8
		{QVector3D(-1.0f, -1.0f, -1.0f), QVector2D(1.0f,  0.5f)}, // v9
        {QVector3D( 1.0f,  1.0f, -1.0f), QVector2D(0.66f, 1.0f)}, // v10
		{QVector3D(-1.0f,  1.0f, -1.0f), QVector2D(1.0f,  1.0f)}, // v11

        // Vertex data for face 3
        {QVector3D(-1.0f, -1.0f, -1.0f), QVector2D(0.66f, 0.0f)}, // v12
		{QVector3D(-1.0f, -1.0f,  1.0f), QVector2D(1.0f,  0.0f)}, // v13
        {QVector3D(-1.0f,  1.0f, -1.0f), QVector2D(0.66f, 0.5f)}, // v14
		{QVector3D(-1.0f,  1.0f,  1.0f), QVector2D(1.0f,  0.5f)}, // v15

        // Vertex data for face 4
        {QVector3D(-1.0f, -1.0f, -1.0f), QVector2D(0.33f, 0.0f)}, // v16
        {QVector3D( 1.0f, -1.0f, -1.0f), QVector2D(0.66f, 0.0f)}, // v17
        {QVector3D(-1.0f, -1.0f,  1.0f), QVector2D(0.33f, 0.5f)}, // v18
        {QVector3D( 1.0f, -1.0f,  1.0f), QVector2D(0.66f, 0.5f)}, // v19

        // Vertex data for face 5
        {QVector3D(-1.0f,  1.0f,  1.0f), QVector2D(0.33f, 0.5f)}, // v20
        {QVector3D( 1.0f,  1.0f,  1.0f), QVector2D(0.66f, 0.5f)}, // v21
        {QVector3D(-1.0f,  1.0f, -1.0f), QVector2D(0.33f, 1.0f)}, // v22
        {QVector3D( 1.0f,  1.0f, -1.0f), QVector2D(0.66f, 1.0f)}  // v23
    };

    // Indices for drawing cube faces using triangle strips.
    // Triangle strips can be connected by duplicating indices
    // between the strips. If connecting strips have opposite
    // vertex order then last index of the first strip and first
    // index of the second strip needs to be duplicated. If
    // connecting strips have same vertex order then only last
    // index of the first strip needs to be duplicated.
    GLushort indices[] = {
         0,  1,  2,  3,  3,     // Face 0 - triangle strip ( v0,  v1,  v2,  v3)
         4,  4,  5,  6,  7,  7, // Face 1 - triangle strip ( v4,  v5,  v6,  v7)
         8,  8,  9, 10, 11, 11, // Face 2 - triangle strip ( v8,  v9, v10, v11)
        12, 12, 13, 14, 15, 15, // Face 3 - triangle strip (v12, v13, v14, v15)
        16, 16, 17, 18, 19, 19, // Face 4 - triangle strip (v16, v17, v18, v19)
        20, 20, 21, 22, 23      // Face 5 - triangle strip (v20, v21, v22, v23)
    };

    // Transfer vertex data to VBO 0
    glBindBuffer(GL_ARRAY_BUFFER, vboIds[0]);
    glBufferData(GL_ARRAY_BUFFER, 24 * sizeof(VertexData), vertices, GL_STATIC_DRAW);

    // Transfer index data to VBO 1
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vboIds[1]);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, 34 * sizeof(GLushort), indices, GL_STATIC_DRAW);

	// grid here
	QVector3D gridVertex[10*2];
	GLushort gridIdx[10*2];
	for ( int i = 0 ; i < 10 ; i++ )
	{
		gridVertex[i*2+0] = QVector3D(-10.0f, 1.0f, i);
		gridVertex[i*2+1] = QVector3D( 10.0f,-1.0f, i);
		gridIdx[i*2+0] = i*2+0;
		gridIdx[i*2+1] = i*2+1;
	}
	glBindBuffer(GL_ARRAY_BUFFER, vboIds[2]);
	glBufferData(GL_ARRAY_BUFFER, 10*2 * sizeof(QVector3D), gridVertex, GL_STATIC_DRAW);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vboIds[3]);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, 10*2 * sizeof(GLushort), gridIdx, GL_STATIC_DRAW);
}
コード例 #22
0
ファイル: AddChain.cpp プロジェクト: lemourin/GameEngine
void AddChain::Node::setLastPoint(QPointF p) {
  QVector2D* array = m_geometry.vertexData<QVector2D>();
  array[m_geometry.vertexCount() - 1] = QVector2D(p.x(), p.y());
  m_geometry.updateVertexData();
}
コード例 #23
0
ファイル: Tapis.cpp プロジェクト: padenot/usdp
/**
 * Compare les coordonnées du bagage aux coordonnées du tronçon suivant.
 */
bool Tapis::bagageEstSorti(Bagage *bagage)
{
    return QVector2D(bagage->position() - _tronconSupport->position()).length()
            < RAYON_PROXIMITE_TRONCON;
}
コード例 #24
0
inline QVector2D CFruchtermanReingold::CoulombForce(const int firstVertexIndex, const int secondVertexIndex) const {
       QVector2D direction = QVector2D(vgc_vertices[firstVertexIndex].v_coordinates - vgc_vertices[secondVertexIndex].v_coordinates);
       return vgc_coeff * vgc_coeff  / Distance(vgc_vertices[firstVertexIndex].v_coordinates,
                                                vgc_vertices[secondVertexIndex].v_coordinates) * direction.normalized();
}
コード例 #25
0
ファイル: geometryengine.cpp プロジェクト: alesegdia/qnod3d
void GeometryEngine::initNodeGeometry(QOpenGLShaderProgram *program)
{
    float width = 0.125f;

    VertexData vertices[] = {
        // Vertex data for face 0
        {QVector3D(-1.0f, -1.0f,  width), QVector2D(0.0f, 0.0f)},  // v0
        {QVector3D( 1.0f, -1.0f,  width), QVector2D(0.33f, 0.0f)}, // v1
        {QVector3D(-1.0f,  1.0f,  width), QVector2D(0.0f, 0.5f)},  // v2
        {QVector3D( 1.0f,  1.0f,  width), QVector2D(0.33f, 0.5f)}, // v3

        // Vertex data for face 1
        {QVector3D( 1.0f, -1.0f,  width), QVector2D( 0.0f, 0.5f)}, // v4
        {QVector3D( 1.0f, -1.0f, -width), QVector2D(0.33f, 0.5f)}, // v5
        {QVector3D( 1.0f,  1.0f,  width), QVector2D(0.0f, 1.0f)},  // v6
        {QVector3D( 1.0f,  1.0f, -width), QVector2D(0.33f, 1.0f)}, // v7

        // Vertex data for face 2
        {QVector3D( 1.0f, -1.0f, -width), QVector2D(0.66f, 0.5f)}, // v8
        {QVector3D(-1.0f, -1.0f, -width), QVector2D(1.0f, 0.5f)},  // v9
        {QVector3D( 1.0f,  1.0f, -width), QVector2D(0.66f, 1.0f)}, // v10
        {QVector3D(-1.0f,  1.0f, -width), QVector2D(1.0f, 1.0f)},  // v11

        // Vertex data for face 3
        {QVector3D(-1.0f, -1.0f, -width), QVector2D(0.66f, 0.0f)}, // v12
        {QVector3D(-1.0f, -1.0f,  width), QVector2D(1.0f, 0.0f)},  // v13
        {QVector3D(-1.0f,  1.0f, -width), QVector2D(0.66f, 0.5f)}, // v14
        {QVector3D(-1.0f,  1.0f,  width), QVector2D(1.0f, 0.5f)},  // v15

        // Vertex data for face 4
        {QVector3D(-1.0f, -1.0f, -width), QVector2D(0.33f, 0.0f)}, // v16
        {QVector3D( 1.0f, -1.0f, -width), QVector2D(0.66f, 0.0f)}, // v17
        {QVector3D(-1.0f, -1.0f,  width), QVector2D(0.33f, 0.5f)}, // v18
        {QVector3D( 1.0f, -1.0f,  width), QVector2D(0.66f, 0.5f)}, // v19

        // Vertex data for face 5
        {QVector3D(-1.0f,  1.0f,  width), QVector2D(0.33f, 0.5f)}, // v20
        {QVector3D( 1.0f,  1.0f,  width), QVector2D(0.66f, 0.5f)}, // v21
        {QVector3D(-1.0f,  1.0f, -width), QVector2D(0.33f, 1.0f)}, // v22
        {QVector3D( 1.0f,  1.0f, -width), QVector2D(0.66f, 1.0f)}  // v23
    };

    GLushort indices[] = {
        0,  1,  2,  3,  3,     // Face 0 - triangle strip ( v0,  v1,  v2,  v3)
        4,  4,  5,  6,  7,  7, // Face 1 - triangle strip ( v4,  v5,  v6,  v7)
        8,  8,  9, 10, 11, 11, // Face 2 - triangle strip ( v8,  v9, v10, v11)
        12, 12, 13, 14, 15, 15, // Face 3 - triangle strip (v12, v13, v14, v15)
        16, 16, 17, 18, 19, 19, // Face 4 - triangle strip (v16, v17, v18, v19)
        20, 20, 21, 22, 23      // Face 5 - triangle strip (v20, v21, v22, v23)
    };

    m_vao = new QOpenGLVertexArrayObject(0);
    m_vao->create();
    m_vao->bind();

    m_arrayBuf.bind();
    m_arrayBuf.allocate(vertices, 24 * sizeof(VertexData));

    m_indexBuf.bind();
    m_indexBuf.allocate(indices, 34 * sizeof(GLushort));

    quintptr offset = 0;

    int vertexLocation = program->attributeLocation("a_position");
    int texcoordLocation = program->attributeLocation("a_texcoord");

    program->enableAttributeArray(vertexLocation);
    program->enableAttributeArray(texcoordLocation);

    program->setAttributeBuffer(vertexLocation, GL_FLOAT, offset, 3, sizeof(VertexData));
    offset += sizeof(QVector3D);
    program->setAttributeBuffer(texcoordLocation, GL_FLOAT, offset, 2, sizeof(VertexData));

    m_gpuModelsBuffer.bind();

    int modelLocation = program->attributeLocation("a_modelMatrix");

    for( int i = 0; i < 4; i++ ) {
        program->enableAttributeArray( modelLocation + i );
        program->setAttributeBuffer( modelLocation + i, GL_FLOAT, i * sizeof(QVector4D), 4, 4 * sizeof(QVector4D) );
        m_gl330->glVertexAttribDivisor( modelLocation + i, 1 );
    }

    m_gpuModelsBuffer.release();
    m_vao->release();
    program->release();
}
コード例 #26
0
inline QVector2D CFruchtermanReingold::HookeForce(const int firstVertexIndex, const int secondVertexIndex) const {
       QVector2D direction = QVector2D(vgc_vertices[secondVertexIndex].v_coordinates - vgc_vertices[firstVertexIndex].v_coordinates);
       return  (SPRING_CONSTANT / vgc_coeff) * (Distance(vgc_vertices[firstVertexIndex].v_coordinates,
                                 vgc_vertices[secondVertexIndex].v_coordinates) / SPRING_LENGTH) * direction.normalized();
}
コード例 #27
0
void LanczosFilter::performPaint(EffectWindowImpl* w, int mask, QRegion region, WindowPaintData& data)
{
    if (effects->compositingType() == KWin::OpenGLCompositing && (data.xScale() < 0.9 || data.yScale() < 0.9) &&
            KGlobalSettings::graphicEffectsLevel() & KGlobalSettings::SimpleAnimationEffects) {
        if (!m_inited)
            init();
        const QRect screenRect = Workspace::self()->clientArea(ScreenArea, w->screen(), w->desktop());
        // window geometry may not be bigger than screen geometry to fit into the FBO
        if (m_shader && w->width() <= screenRect.width() && w->height() <= screenRect.height()) {
            double left = 0;
            double top = 0;
            double right = w->width();
            double bottom = w->height();
            foreach (const WindowQuad & quad, data.quads) {
                // we need this loop to include the decoration padding
                left   = qMin(left, quad.left());
                top    = qMin(top, quad.top());
                right  = qMax(right, quad.right());
                bottom = qMax(bottom, quad.bottom());
            }
            double width = right - left;
            double height = bottom - top;
            if (width > screenRect.width() || height > screenRect.height()) {
                // window with padding does not fit into the framebuffer
                // so cut of the shadow
                left = 0;
                top = 0;
                width = w->width();
                height = w->height();
            }
            int tx = data.xTranslation() + w->x() + left * data.xScale();
            int ty = data.yTranslation() + w->y() + top * data.yScale();
            int tw = width * data.xScale();
            int th = height * data.yScale();
            const QRect textureRect(tx, ty, tw, th);
            const bool hardwareClipping = !(QRegion(textureRect)-region).isEmpty();

            int sw = width;
            int sh = height;

            GLTexture *cachedTexture = static_cast< GLTexture*>(w->data(LanczosCacheRole).value<void*>());
            if (cachedTexture) {
                if (cachedTexture->width() == tw && cachedTexture->height() == th) {
                    cachedTexture->bind();
                    if (hardwareClipping) {
                        glEnable(GL_SCISSOR_TEST);
                    }
                    if (ShaderManager::instance()->isValid()) {
                        glEnable(GL_BLEND);
                        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

                        const qreal rgb = data.brightness() * data.opacity();
                        const qreal a = data.opacity();

                        GLShader *shader = ShaderManager::instance()->pushShader(ShaderManager::SimpleShader);
                        shader->setUniform(GLShader::Offset, QVector2D(0, 0));
                        shader->setUniform(GLShader::ModulationConstant, QVector4D(rgb, rgb, rgb, a));
                        shader->setUniform(GLShader::Saturation, data.saturation());
                        shader->setUniform(GLShader::AlphaToOne, 0);

                        cachedTexture->render(region, textureRect, hardwareClipping);

                        ShaderManager::instance()->popShader();
                        glDisable(GL_BLEND);
                    } else {
                        prepareRenderStates(cachedTexture, data.opacity(), data.brightness(), data.saturation());
                        cachedTexture->render(region, textureRect, hardwareClipping);
                        restoreRenderStates(cachedTexture, data.opacity(), data.brightness(), data.saturation());
                    }
                    if (hardwareClipping) {
                        glDisable(GL_SCISSOR_TEST);
                    }
                    cachedTexture->unbind();
                    m_timer.start(5000, this);
                    return;
                } else {
                    // offscreen texture not matching - delete
                    delete cachedTexture;
                    cachedTexture = 0;
                    w->setData(LanczosCacheRole, QVariant());
                }
            }

            WindowPaintData thumbData = data;
            thumbData.setXScale(1.0);
            thumbData.setYScale(1.0);
            thumbData.setXTranslation(-w->x() - left);
            thumbData.setYTranslation(-w->y() - top);
            thumbData.setBrightness(1.0);
            thumbData.setOpacity(1.0);
            thumbData.setSaturation(1.0);

            // Bind the offscreen FBO and draw the window on it unscaled
            updateOffscreenSurfaces();
            GLRenderTarget::pushRenderTarget(m_offscreenTarget);

            glClearColor(0.0, 0.0, 0.0, 0.0);
            glClear(GL_COLOR_BUFFER_BIT);
            w->sceneWindow()->performPaint(mask, infiniteRegion(), thumbData);

            // Create a scratch texture and copy the rendered window into it
            GLTexture tex(sw, sh);
            tex.setFilter(GL_LINEAR);
            tex.setWrapMode(GL_CLAMP_TO_EDGE);
            tex.bind();

            glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, m_offscreenTex->height() - sh, sw, sh);

            // Set up the shader for horizontal scaling
            float dx = sw / float(tw);
            int kernelSize;
            m_shader->createKernel(dx, &kernelSize);
            m_shader->createOffsets(kernelSize, sw, Qt::Horizontal);

            m_shader->bind();
            m_shader->setUniforms();

            // Draw the window back into the FBO, this time scaled horizontally
            glClear(GL_COLOR_BUFFER_BIT);
            QVector<float> verts;
            QVector<float> texCoords;
            verts.reserve(12);
            texCoords.reserve(12);

            texCoords << 1.0 << 0.0; verts << tw  << 0.0; // Top right
            texCoords << 0.0 << 0.0; verts << 0.0 << 0.0; // Top left
            texCoords << 0.0 << 1.0; verts << 0.0 << sh;  // Bottom left
            texCoords << 0.0 << 1.0; verts << 0.0 << sh;  // Bottom left
            texCoords << 1.0 << 1.0; verts << tw  << sh;  // Bottom right
            texCoords << 1.0 << 0.0; verts << tw  << 0.0; // Top right
            GLVertexBuffer *vbo = GLVertexBuffer::streamingBuffer();
            vbo->reset();
            vbo->setData(6, 2, verts.constData(), texCoords.constData());
            vbo->render(GL_TRIANGLES);

            // At this point we don't need the scratch texture anymore
            tex.unbind();
            tex.discard();

            // create scratch texture for second rendering pass
            GLTexture tex2(tw, sh);
            tex2.setFilter(GL_LINEAR);
            tex2.setWrapMode(GL_CLAMP_TO_EDGE);
            tex2.bind();

            glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, m_offscreenTex->height() - sh, tw, sh);

            // Set up the shader for vertical scaling
            float dy = sh / float(th);
            m_shader->createKernel(dy, &kernelSize);
            m_shader->createOffsets(kernelSize, m_offscreenTex->height(), Qt::Vertical);
            m_shader->setUniforms();

            // Now draw the horizontally scaled window in the FBO at the right
            // coordinates on the screen, while scaling it vertically and blending it.
            glClear(GL_COLOR_BUFFER_BIT);

            verts.clear();

            verts << tw  << 0.0; // Top right
            verts << 0.0 << 0.0; // Top left
            verts << 0.0 << th;  // Bottom left
            verts << 0.0 << th;  // Bottom left
            verts << tw  << th;  // Bottom right
            verts << tw  << 0.0; // Top right
            vbo->setData(6, 2, verts.constData(), texCoords.constData());
            vbo->render(GL_TRIANGLES);

            tex2.unbind();
            tex2.discard();
            m_shader->unbind();

            // create cache texture
            GLTexture *cache = new GLTexture(tw, th);

            cache->setFilter(GL_LINEAR);
            cache->setWrapMode(GL_CLAMP_TO_EDGE);
            cache->bind();
            glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, m_offscreenTex->height() - th, tw, th);
            GLRenderTarget::popRenderTarget();

            if (hardwareClipping) {
                glEnable(GL_SCISSOR_TEST);
            }
            if (ShaderManager::instance()->isValid()) {
                glEnable(GL_BLEND);
                glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

                const qreal rgb = data.brightness() * data.opacity();
                const qreal a = data.opacity();

                GLShader *shader = ShaderManager::instance()->pushShader(ShaderManager::SimpleShader);
                shader->setUniform(GLShader::Offset, QVector2D(0, 0));
                shader->setUniform(GLShader::ModulationConstant, QVector4D(rgb, rgb, rgb, a));
                shader->setUniform(GLShader::Saturation, data.saturation());
                shader->setUniform(GLShader::AlphaToOne, 0);

                cache->render(region, textureRect, hardwareClipping);

                ShaderManager::instance()->popShader();
                glDisable(GL_BLEND);
            } else {
                prepareRenderStates(cache, data.opacity(), data.brightness(), data.saturation());
                cache->render(region, textureRect, hardwareClipping);
                restoreRenderStates(cache, data.opacity(), data.brightness(), data.saturation());
            }
            if (hardwareClipping) {
                glDisable(GL_SCISSOR_TEST);
            }

            cache->unbind();
            w->setData(LanczosCacheRole, QVariant::fromValue(static_cast<void*>(cache)));

            // Delete the offscreen surface after 5 seconds
            m_timer.start(5000, this);
            return;
        }
    } // if ( effects->compositingType() == KWin::OpenGLCompositing )
コード例 #28
0
ファイル: qvector4d.cpp プロジェクト: husninazer/qt
/*!
    Returns the 2D vector form of this 4D vector, dropping the z and w coordinates.

    \sa toVector2DAffine(), toVector3D(), toPoint()
*/
QVector2D QVector4D::toVector2D() const
{
    return QVector2D(xp, yp, 1);
}
コード例 #29
0
ファイル: quadObj.cpp プロジェクト: Nand-e/2to3d
/*
 *
 * **************************************************/
void QuadObj::takeTexture() {
    // Calculate Matrix using the parent matrixes too
    std::stack<QMatrix4x4> mats;
    QMatrix4x4 cmat;

    // Store previous matrixes in stack
    QuadObj *po = this;
    bool notroot = true;
    while ( notroot ) {

        if ( po != pro.objectRoot ) {
            mats.push( po->getMatrix() );
           // qDebug() << po->m_itemData;
            po = (QuadObj * ) po->parentItem();
        } else {
            mats.push( po->getMatrix() );
            //qDebug() << po->m_itemData;
            notroot = false;
        }
    }

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

    QVector3D vect;
    qDebug() << "verticies " << vertices.size();
    qDebug() << "TexCoords " << texCoords.size();
    for ( int i = 0; i < vertices.size(); i++) {    // verticies.size
        vect =  cmat * vertices[i];
        texCoords[i] = 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 textpoint[4];
  //  UvtoCvCoordinate(manager->mainproject->actualBackground, textpoint);

  /*  for ( int i = 0; i < 4; i++) {
        qDebug() << textpoint[i].x << " : " << textpoint[i].y;
        cv::circle( manager->mainproject->actualBackground, textpoint[i],5, cv::Scalar(1,255,1), 3 );
    }*/

 //   sortCorners(textpoint);
  //  manager->mainwindow->glWidget->UploadTexture(manager->mainproject->actualBackground.cols ,
   //               manager->mainproject->actualBackground.rows,
    //             manager->mainproject->actualBackground.data );


    cv::Mat ptransform = getPerspectiveTransform ( textpoint, ocoords);
  //  cv::Mat transmtx = cv::getPerspectiveTransform(corners, quad_pts);
 //   cv::warpPerspective( *manager->mainproject->actualBackground, *textureMat, ptransform,  textureMat->size() );


    GLWidget & gl = pro.getManger().getMainGLW();
    if ( textureID == 0 ) {
        gl.glGenBuffers( 1, &textureID);
    }
    gl.glBindTexture ( GL_TEXTURE_2D , textureID);
    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);
    //qDebug() << "Background ID:" << manager->mainproject->backtextID;
    qDebug() << "TextureId:" << textureID;
    //texCoords.clear();
    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) );


}
コード例 #30
0
ファイル: bezierwidget.cpp プロジェクト: radrad350/QtOpenCL
void BezierWidget::computeVerticesNative()
{
    computeMatrices();
    allocVertices();

    QVector4D *posns;
    QVector2D *texcs;

#ifdef USE_VBOS
    if (vertexBuffer) {
        vertexBuffer->bind();
        void *mapped = vertexBuffer->map(QGLBuffer::WriteOnly);
        posns = (QVector4D *)mapped;
    } else {
        posns = positions;
    }
#else
    posns = positions;
#endif

    // Compute the positions.
    for (int sint = 0; sint < subdivisionSize; ++sint) {
        qreal s = qreal(sint) / (subdivisionSize - 1);
        QVector4D svec = QVector4D(s * s * s, s * s, s, 1);
        for (int tint = 0; tint < subdivisionSize; ++tint) {
            qreal t = qreal(tint) / (subdivisionSize - 1);
            QVector4D tvec = QVector4D(t * t * t, t * t, t, 1);
            qreal x = QVector4D::dotProduct(svec * matrixX, tvec);
            qreal y = QVector4D::dotProduct(svec * matrixY, tvec);
            qreal z = QVector4D::dotProduct(svec * matrixZ, tvec);
            int offset = sint + tint * subdivisionSize;
            posns[offset] = QVector4D(x, y, z, 1);
        }
    }

#ifdef USE_VBOS
    if (vertexBuffer) {
        vertexBuffer->unmap();
        vertexBuffer->release();
        texBuffer->bind();
        void *mapped = texBuffer->map(QGLBuffer::WriteOnly);
        texcs = (QVector2D *)mapped;
    } else {
        texcs = texCoords;
    }
#else
    texcs = texCoords;
#endif

    // Compute the texture co-ordinates.
    for (int sint = 0; sint < subdivisionSize; ++sint) {
        qreal s = qreal(sint) / (subdivisionSize - 1);
        for (int tint = 0; tint < subdivisionSize; ++tint) {
            qreal t = qreal(tint) / (subdivisionSize - 1);
            int offset = sint + tint * subdivisionSize;
            texcs[offset] = QVector2D(s, t);
        }
    }

#ifdef USE_VBOS
    if (texBuffer) {
        texBuffer->unmap();
        texBuffer->release();
    }
#endif
}