Exemplo n.º 1
0
/*!
    Adds to this section a polygonal face made of triangular sub-faces,
    defined by \a face.  The 0'th vertex is used for the center, while
    the subsequent vertices form the perimeter of the face, which must
    at minimum be a triangle.

    If \a face has less than four vertices this function exits without
    doing anything.

    This function provides functionality similar to the OpenGL mode GL_POLYGON,
    except it divides the face into sub-faces around a \b{central point}.
    The center and perimeter vertices must lie in the same plane (unlike
    triangle fan).  If they do not normals will be incorrectly calculated.

    \image triangulated-face.png

    Here the sub-faces are shown divided by green lines.  Note how this
    function handles some re-entrant (non-convex) polygons, whereas
    addTriangleFan will not support such polygons.

    If required, the center point can be calculated using the center() function
    of QGeometryData:

    \code
    QGeometryData face;
    face.appendVertex(perimeter.center()); // perimeter is a QGeometryData
    face.appendVertices(perimeter);
    builder.addTriangulatedFace(face);
    \endcode

    N sub-faces are generated where \c{N == face.count() - 2}.

    Each triangular sub-face consists of the center; followed by the \c{i'th}
    and \c{((i + 1) % N)'th} vertex.  The last face generated then is
    \c{(center, face[N - 1], face[0]}, the closing face.  Note that the closing
    face is automatically created, unlike addTriangleFan().

    If no normals are supplied in the vertices of \a face, normals are
    calculated as per addTriangle().  One normal is calculated, since a
    face's vertices lie in the same plane.

    Degenerate triangles are skipped in the same way as addTriangles().

    \sa addTriangleFan(), addTriangles()
*/
void QGLBuilder::addTriangulatedFace(const QGeometryData &face)
{
    if (face.count() < 4)
        return;
    QGeometryData f;
    f.appendGeometry(face);
    int cnt = f.count();
    bool calcNormal = !f.hasField(QGL::Normal);
    if (calcNormal)
    {
        QVector3DArray nm(cnt);
        f.appendNormalArray(nm);
    }
    bool skip = false;
    QVector3D norm;
    int k = 0;
    for (int i = 1; i < cnt; ++i)
    {
        int n = i + 1;
        if (n == cnt)
            n = 1;
        if (calcNormal)
        {
            skip = qCalculateNormal(0, i, n, f);
            if (norm.isNull() && !skip)
            {
                norm = f.normalAt(0);
                for (int i = 0; i < cnt; ++i)
                    f.normal(i) = norm;
            }
        }
        if (!skip)
            dptr->addTriangle(0, i, n, f, k);
    }
    dptr->currentNode->setCount(dptr->currentNode->count() + k);
}
Exemplo n.º 2
0
QT_BEGIN_NAMESPACE

/*!
    \class QGLCylinder
    \brief The QGLCylinder class represents the geometry of a simple cylinder/cone in 3D space.
    \since 4.8
    \ingroup qt3d
    \ingroup qt3d::geometry

    The following example creates a cone with a top diameter of 1 unit,
    a bottom diameter of 2 units in diameter and height of 3 units.

    It then draws it at (10, 25, 0) in a QGLPainter:

    \code
    QGLBuilder builder;
    builder << QGLCylinder(1.0,2.0,3.0);
    QGLSceneNode *node = builder.finalizedSceneNode();

    painter.translate(10, 25, 0);
    node->draw(&painter);
    \endcode

    Note that the bottom circle of the cylinder will always be centred at (0,0,0)
    unless otherwise transformed after cylinder creation.

    The QGLCylinder class specifies positions, normals and 2D texture
    co-ordinates for all of the vertices that make up the cylinder.

    The texture co-ordinates are fixed at construction time.  This
    is because constructing the cylinder can involve generating additional
    vertices which need to interpolate the texture co-ordinates of their
    neighboring vertices.

    The QGLCylinder is divided into slices and layers.  The slices value
    indicate number of triangular sections into which the top and bottom
    circles of the cylinder are broken into.  Consequently it also sets the
    number of facets which run the length of the cylinder.  More slices
    results in a smoother circumference.

    The layers value indicates the number of longitudinal sections the
    cylinder is broken into.  Fewer layers means that the side facets of the
    cylinder will be made up of fewer, very long, triangles, while a higher
    number of layers will produce many and smaller triangles.  Often it is
    desirable to avoid large triangles as they may cause inefficiencies in
    texturing/lighting on certain platforms.

    The end-caps and sides of the cylinder are independent sections of the
    scene-graph, and so may be textured separately.

    Textures are wrapped around the sides of thecylinder in such a way that
    the texture may distort across the x axis if the top and bottom diameters
    of the cylinder differ (ie. the cylinder forms a truncated cone).  Textures
    begin and end at the centre points of the top and bottom end-caps of the
    cylinder.  This wrapping means that textures on either end-cap may be
    distorted.

    Texture coordinates are assigned as shown below.

    \image cylinder-texture-coords.png

    It is worth noting that the cylinder class can, in fact, be used to generate
    any regular solid polygonal prism.  A rectangular prism can be created, for
    example, by creating a 4 sided cylinder.  Likewise a hexagonal prism is
    simply a 6 sided cylinder.

    With this knowledge, and an understanding of the texture coordinate mapping,
    it is possible to make custom textures which will be usable with these
    three dimensional objects.

    \sa QGLBuilder
*/


/*!
    \fn QGLCylinder::QGLCylinder(float diameterTop, float diameterBase , float height, int slices, int layers, bool top, bool base)

    Constructs the geometry for a cylinder with top of diameter \a diameterTop,
    a base of diameter \a diameterBase, and a height of \a height.

    The resultant mesh will be divided around the vertical axis of the cylinder
    into \a slices individual wedges, and shall be formed of \a layers stacked
    to form the cylinder.

    If the values for \a top or \a base are true, then the cylinder will be
    created with solid endcaps.  Otherwise, it shall form a hollow pipe.

    units on a side.
*/


/*!
    \fn float QGLCylinder::diameterTop() const

    Returns the diameter of the top of the cylinder.

    The default value is 1.

    \sa setDiameterTop()
*/

/*!
    \fn void QGLCylinder::setDiameterTop(float diameter)

    Sets the diameter of the top of this cylinder to \a diameter.

    \sa diameterTop()
*/

/*!
    \fn float QGLCylinder::diameterBottom() const

    Returns the diameter of the bottom of the cylinder.

    The default value is 1.

    \sa setDiameterBottom()
*/

/*!
    \fn void QGLCylinder::setDiameterBottom(float diameter)

    Sets the diameter of the bottom of this cylinder to \a diameter.

    \sa diameterBottom()
*/

/*!
    \fn float QGLCylinder::height() const

    Returns the height of the cylinder.

    The default value is 1.0

    \sa setDiameterBottom()
*/

/*!
    \fn void QGLCylinder::setHeight(float height)

    Sets the height of this cylinder to \a height.

    \sa diameterBottom()
*/


/*!
    \fn int QGLCylinder::slices() const

    Returns the number of triangular slices the cylinder is divided into
    around its polar axis.

    The default is 6.

    \sa setSlices()
*/

/*!
    \fn int QGLCylinder::setSlices(int slices)

    Sets the number of triangular \a slices the cylinder is divided into
    around its polar axis.

    \sa slices()
*/

/*!
    \fn int QGLCylinder::layers() const

    Returns the number of cylindrical layers the cylinder is divided into
    along its height.

    The default is 3.

    \sa setLayers()
*/

/*!
    \fn int QGLCylinder::setLayers(int layers)

    Sets the number of stacked \a layers the cylinder is divided into
    along its height.

    \sa layers()
*/

/*!
    \fn  bool QGLCylinder::topEnabled() const

    Returns true if the top of the cyclinder will be created when
    building the mesh.

    The default is true.

    \sa setTopEnabled()
*/

/*!
    \fn void QGLCylinder::setTopEnabled(bool top)

    Set whether the top end-cap of the cylinder will be created when
    building the mesh.  If \a top is true, the end-cap will be created.

    \sa topEnabled()
*/

/*!
    \fn  bool QGLCylinder::baseEnabled() const

    Returns true if the base of the cyclinder will be created when
    building the mesh.

    The default is true.

    \sa setBaseEnabled()
*/

/*!
    \fn void QGLCylinder::setBaseEnabled(bool base)

    Set whether the base end-cap of the cylinder will be created when
    building the mesh.  If \a base is true, the end-cap will be created.

    \sa baseEnabled()
*/

/*!
    \relates QGLCylinder

    Builds the geometry for \a cylinder within the specified
    geometry \a builder.
*/

QGLBuilder& operator<<(QGLBuilder& builder, const QGLCylinder& cylinder)
{
    int nCaps = (cylinder.topEnabled()?1:0) + (cylinder.baseEnabled()?1:0);
    Q_ASSERT(cylinder.layers() >= 1 + nCaps);

    float numSlices = float(cylinder.slices());
    float numLayers = float(cylinder.layers() - nCaps); // minus top and base caps
    float topRadius = cylinder.diameterTop() / 2.0f;
    float bottomRadius = cylinder.diameterBottom() / 2.0f;

    float angle = 0.0f;
    float angleIncrement = (2.0f * M_PI) / numSlices;
    float radius = topRadius;
    float radiusIncrement = float(bottomRadius-topRadius) / numLayers;
    float height = float(cylinder.height());
    float heightDecrement = height / numLayers;
    height *= 0.5f;

    float textureHeight = 1.0f;
    float textureDecrement = 1.0f / numLayers;

    QGeometryData oldLayer;

    // layer 0: Top cap
    {
        QGeometryData newLayer;
        //Generate a circle of vertices for this layer.
        for (int i=0; i<cylinder.slices(); i++) {
            newLayer.appendVertex(QVector3D(radius * cosf(angle), radius * sinf(angle), height));
            angle+=angleIncrement;
        }
        angle = 0.0f;
        QVector3D center = newLayer.center();
        // Generate texture coordinates (including an extra seam vertex for textures).
        newLayer.appendVertex(newLayer.vertex(0));
        newLayer.generateTextureCoordinates();
        for (int i = 0; i < newLayer.count(); ++i)
            newLayer.texCoord(i).setY(textureHeight);
        if (cylinder.topEnabled()) {
            QGeometryData top;
            builder.newSection();
            builder.currentNode()->setObjectName(QStringLiteral("Cylinder Top"));
            top.appendVertex(center);
            top.appendVertexArray(newLayer.vertices());
            //Generate a circle of texture vertices for this layer.
            top.appendTexCoord(QVector2D(0.5f, 0.5f));
            for (int i=1; i<top.count(); i++) {
                top.appendTexCoord(QVector2D(0.5f * cosf(angle) + 0.5f, 0.5f * sinf(angle) + 0.5f));
                angle+=angleIncrement;
            }
            angle = 0;
            builder.addTriangulatedFace(top);
        }
        oldLayer.clear();
        oldLayer.appendGeometry(newLayer);
    }

    // intermediate layers
    for (int layerCount=0; layerCount<(cylinder.layers()-nCaps); ++layerCount) {
        radius+=radiusIncrement;
        height-=heightDecrement;
        textureHeight-=textureDecrement;
        QGeometryData newLayer;
        //Generate a circle of vertices for this layer.
        for (int i=0; i<cylinder.slices(); ++i) {
            newLayer.appendVertex(QVector3D(radius * cosf(angle), radius * sinf(angle), height));
            angle+=angleIncrement;
        }
        angle = 0.0f;
        // Generate texture coordinates (including an extra seam vertex for textures).
        newLayer.appendVertex(newLayer.vertex(0));
        newLayer.generateTextureCoordinates();
        for (int i = 0; i < newLayer.count(); ++i)
            newLayer.texCoord(i).setY(textureHeight);

        if (layerCount==0) {
            builder.newSection();
            builder.currentNode()->setObjectName(QStringLiteral("Cylinder Sides"));
        }
        builder.addQuadsInterleaved(oldLayer, newLayer);

        oldLayer.clear();
        oldLayer.appendGeometry(newLayer);
    }

    // last layer: Base cap
    if (cylinder.baseEnabled()) {
        builder.newSection();
        builder.currentNode()->setObjectName(QStringLiteral("Cylinder Base"));
        QGeometryData base;
        {
            QVector3DArray vvv = oldLayer.vertices();
            for (int i=0; i<vvv.size()-1; ++i)
                base.appendVertex(vvv.at(i));
            QVector3D center = base.center();
            base.appendVertex(vvv.at(0));
            base.appendVertex(center);
        }
        //Generate a circle of texture vertices for this layer.
        for (int i=1; i<base.count(); i++) {
            base.appendTexCoord(QVector2D(0.5f * cosf(angle) + 0.5f, 0.5f * sinf(angle) + 0.5f));
            angle+=angleIncrement;
        }
        base.appendTexCoord(QVector2D(0.5f, 0.5f));
        angle = 0.0f;
        //we need to reverse the above to draw it properly - windings!
        builder.addTriangulatedFace(base.reversed());
    }

    return builder;
}
Exemplo n.º 3
0
QGeometryData MgGeometriesData::sphere(qreal radius,int divisions)
{
	QGeometryData geometry;

	// Determine the number of slices and stacks to generate.
	static int const slicesAndStacks[] = {
			4, 4,
			8, 4,
			8, 8,
			16, 8,
			16, 16,
			32, 16,
			32, 32,
			64, 32,
			64, 64,
			128, 64,
			128, 128
	};
	if (divisions < 1)
		divisions = 1;
	else if (divisions > 10)
		divisions = 10;
	int stacks = slicesAndStacks[divisions * 2 - 1];
	int slices = slicesAndStacks[divisions * 2 - 2];

	// Precompute sin/cos values for the slices and stacks.
	const int maxSlices = 128 + 1;
	const int maxStacks = 128 + 1;
	qreal sliceSin[maxSlices];
	qreal sliceCos[maxSlices];
	qreal stackSin[maxStacks];
	qreal stackCos[maxStacks];
	for (int slice = 0; slice < slices; ++slice)
	{
		qreal angle = 2 * M_PI * slice / slices;
		sliceSin[slice] = qFastSin(angle);
		sliceCos[slice] = qFastCos(angle);
	}
	sliceSin[slices] = sliceSin[0]; // Join first and last slice.
	sliceCos[slices] = sliceCos[0];

	for (int stack = 0; stack <= stacks; ++stack)
	{
		qreal angle = M_PI * stack / stacks;
		stackSin[stack] = qFastSin(angle);
		stackCos[stack] = qFastCos(angle);
	}
	stackSin[0] = 0.0f;             // Come to a point at the poles.
	stackSin[stacks] = 0.0f;

	// Create the stacks.
	for (int stack = 0; stack < stacks; ++stack)
	{
		QGeometryData prim;
		qreal z = radius * stackCos[stack];
		qreal nextz = radius * stackCos[stack + 1];
		qreal s = stackSin[stack];
		qreal nexts = stackSin[stack + 1];
		qreal c = stackCos[stack];
		qreal nextc = stackCos[stack + 1];
		qreal r = radius * s;
		qreal nextr = radius * nexts;
		for (int slice = 0; slice <= slices; ++slice)
		{
			prim.appendVertex
			(QVector3D(nextr * sliceSin[slice],
					nextr * sliceCos[slice], nextz));
			prim.appendNormal
			(QVector3D(sliceSin[slice] * nexts,
					sliceCos[slice] * nexts, nextc));

			prim.appendVertex
			(QVector3D(r * sliceSin[slice],
					r * sliceCos[slice], z));
			prim.appendNormal
			(QVector3D(sliceSin[slice] * s,
					sliceCos[slice] * s, c));
		}
		geometry.appendGeometry(prim);
	}
	return geometry;
}