Exemplo n.º 1
0
bool ScaleDiv::buildLinDiv(int maxMajSteps, int maxMinSteps, double step)
{

   int nMaj, nMin, minSize, i0,i,k;
   double val, mval;
   double firstTick, lastTick;
   double minStep;
   QVector<double> buffer;
   bool rv = true;

   // parameter range check
   maxMajSteps = MusECore::qwtMax(1, maxMajSteps);
   maxMinSteps = MusECore::qwtMax(0, maxMinSteps);
   step = MusECore::qwtAbs(step);

   // reset vectors
   d_minMarks.resize(0);
   d_majMarks.resize(0);

   if (d_lBound == d_hBound) return true;

   //
   // Set up major divisions
   //
   if (step == 0.0)
      d_majStep = MusECore::qwtCeil125(MusECore::qwtAbs(d_hBound - d_lBound) * 0.999999
                                       / double(maxMajSteps));
   else
      d_majStep = step;

   if (d_majStep == 0.0) return true;

   firstTick = ceil( (d_lBound - step_eps * d_majStep) / d_majStep) * d_majStep;
   lastTick = floor( (d_hBound + step_eps * d_majStep) / d_majStep) * d_majStep;

   nMaj = MusECore::qwtMin(10000, int(rint((lastTick - firstTick) / d_majStep)) + 1);

   d_majMarks.resize(nMaj);
   MusECore::qwtLinSpace(d_majMarks.data(), d_majMarks.size(), firstTick, lastTick);

   //
   // Set up minor divisions
   //
   if (maxMinSteps < 1) // no minor divs
      return true;

   minStep = MusECore::qwtCeil125( d_majStep  /  double(maxMinSteps) );

   if (minStep == 0.0) return true;

   nMin = MusECore::qwtAbs(int(rint(d_majStep / minStep))) - 1; // # minor steps per interval

   // Do the minor steps fit into the interval?
   if ( MusECore::qwtAbs(double(nMin +  1) * minStep - d_majStep) >  step_eps * d_majStep)
   {
      nMin = 1;
      minStep = d_majStep * 0.5;
   }

   // Are there minor ticks below the first major tick?
   if (d_majMarks[0] > d_lBound )
      i0 = -1;
   else
      i0 = 0;

   // resize buffer to the maximum possible number of minor ticks
   buffer.resize(nMin * (nMaj + 1));

   // calculate minor ticks
   if (rv)
   {
      minSize = 0;
      for (i = i0; i < (int)d_majMarks.size(); i++)
      {
         if (i >= 0)
            val = d_majMarks[i];
         else
            val = d_majMarks[0] - d_majStep;

         for (k=0; k< nMin; k++)
         {
            mval = (val += minStep);
            if (limRange(mval, d_lBound, d_hBound, border_eps))
            {
               buffer[minSize] = mval;
               minSize++;
            }
         }
      }
      //d_minMarks.duplicate(buffer.data(), minSize);
      d_minMarks.resize(minSize);
      qCopy(buffer.data(), buffer.data() + minSize, d_minMarks.begin());
   }

   return rv;
}
Exemplo n.º 2
0
Mesh* ModelInterface::loadMesh(aiMesh* ai_mesh, aiMaterial* ai_material, const int index)
{
    Q_UNUSED(index)

    Mesh* mesh = new Mesh();

    QVector3D* vertices  = new QVector3D[ai_mesh->mNumVertices];
    QVector3D* normals   = new QVector3D[ai_mesh->mNumVertices];
    QVector3D* tangent   = new QVector3D[ai_mesh->mNumVertices];
    QVector2D* texCoords = new QVector2D[ai_mesh->mNumVertices];
    QVector4D* boneIDs   = new QVector4D[ai_mesh->mNumVertices];
    QVector4D* weight    = new QVector4D[ai_mesh->mNumVertices];

    QVector<uint> indices;

    if(ai_mesh->HasBones() && bones)
    {
        for(uint i = 0; i < ai_mesh->mNumBones; ++i)
        {
            for(uint j = 0; j < ai_mesh->mBones[i]->mNumWeights; ++j)
            {
                QString boneName(ai_mesh->mBones[i]->mName.data);

                aiVertexWeight w  = ai_mesh->mBones[i]->mWeights[j];
                int vertexId      = w.mVertexId;
                float weightValue = w.mWeight;

                int boneID = bones->getBone(boneName)->getId();

                addWeightData(&boneIDs[vertexId], &weight[vertexId], boneID, weightValue);
            }
        }
    }

    for(uint i = 0; i < ai_mesh->mNumVertices; ++i)
    {
        vertices[i] = QVector3D(ai_mesh->mVertices[i].x, ai_mesh->mVertices[i].y, ai_mesh->mVertices[i].z);
        normals[i]  = QVector3D(ai_mesh->mNormals[i].x,  ai_mesh->mNormals[i].y,  ai_mesh->mNormals[i].z);

        if(ai_mesh->mTangents)
            tangent[i] = QVector3D(ai_mesh->mTangents[i].x, ai_mesh->mTangents[i].y, ai_mesh->mTangents[i].z);
        else
            tangent[i] = QVector3D(1.0f, 0.0f, 0.0f);

        if(ai_mesh->mTextureCoords[0])
            texCoords[i] = QVector2D(ai_mesh->mTextureCoords[0][i].x, ai_mesh->mTextureCoords[0][i].y);
        else
            texCoords[i] = QVector2D(0.0f, 0.0f);
    }

    for(uint i = 0; i < ai_mesh->mNumFaces; ++i)
    {
        aiFace face = ai_mesh->mFaces[i];

        for(uint j = 0; j < face.mNumIndices; ++j)
            indices.push_back(face.mIndices[j]);
    }

    loadMaterial(ai_material, mesh);

    mesh->createVertexArrayObject();
    mesh->createBuffer(Mesh::Vertices,  vertices, sizeof(QVector3D)  * ai_mesh->mNumVertices);
    mesh->createBuffer(Mesh::Normals,   normals, sizeof(QVector3D)   * ai_mesh->mNumVertices);
    mesh->createBuffer(Mesh::TexCoords, texCoords, sizeof(QVector2D) * ai_mesh->mNumVertices);
    mesh->createBuffer(Mesh::Tangent,   tangent, sizeof(QVector3D)   * ai_mesh->mNumVertices);
    mesh->createBuffer(Mesh::Bones,     boneIDs, sizeof(QVector4D)   * ai_mesh->mNumVertices);
    mesh->createBuffer(Mesh::Weight,    weight, sizeof(QVector4D)    * ai_mesh->mNumVertices);
    mesh->createBuffer(Mesh::Index,     indices.data(), sizeof(int)  * indices.size());
    mesh->setNumFaces(indices.size());

    delete[] vertices;
    delete[] normals;
    delete[] tangent;
    delete[] texCoords;
    delete[] weight;
    delete[] boneIDs;

    return mesh;
}
Exemplo n.º 3
0
bool GLWidgetRendererPrivate::initTextures(const VideoFormat &fmt)
{
    // isSupported(pixfmt)
    if (!fmt.isValid())
        return false;
    video_format.setPixelFormatFFmpeg(fmt.pixelFormatFFmpeg());

    //http://www.berkelium.com/OpenGL/GDC99/internalformat.html
    //NV12: UV is 1 plane. 16 bits as a unit. GL_LUMINANCE4, 8, 16, ... 32?
    //GL_LUMINANCE, GL_LUMINANCE_ALPHA are deprecated in GL3, removed in GL3.1
    //replaced by GL_RED, GL_RG, GL_RGB, GL_RGBA? for 1, 2, 3, 4 channel image
    //http://www.gamedev.net/topic/634850-do-luminance-textures-still-exist-to-opengl/
    //https://github.com/kivy/kivy/issues/1738: GL_LUMINANCE does work on a Galaxy Tab 2. LUMINANCE_ALPHA very slow on Linux
     //ALPHA: vec4(1,1,1,A), LUMINANCE: (L,L,L,1), LUMINANCE_ALPHA: (L,L,L,A)
    /*
     * To support both planar and packed use GL_ALPHA and in shader use r,g,a like xbmc does.
     * or use Swizzle_mask to layout the channels: http://www.opengl.org/wiki/Texture#Swizzle_mask
     * GL ES2 support: GL_RGB, GL_RGBA, GL_LUMINANCE, GL_LUMINANCE_ALPHA, GL_ALPHA
     * http://stackoverflow.com/questions/18688057/which-opengl-es-2-0-texture-formats-are-color-depth-or-stencil-renderable
     */
    if (!fmt.isPlanar()) {
        GLint internal_fmt;
        GLenum data_fmt;
        GLenum data_t;
        if (!OpenGLHelper::videoFormatToGL(fmt, &internal_fmt, &data_fmt, &data_t)) {
            qWarning("no opengl format found");
            return false;
        }
        internal_format = QVector<GLint>(fmt.planeCount(), internal_fmt);
        data_format = QVector<GLenum>(fmt.planeCount(), data_fmt);
        data_type = QVector<GLenum>(fmt.planeCount(), data_t);
    } else {
        internal_format.resize(fmt.planeCount());
        data_format.resize(fmt.planeCount());
        data_type = QVector<GLenum>(fmt.planeCount(), GL_UNSIGNED_BYTE);
        if (fmt.isPlanar()) {
        /*!
         * GLES internal_format == data_format, GL_LUMINANCE_ALPHA is 2 bytes
         * so if NV12 use GL_LUMINANCE_ALPHA, YV12 use GL_ALPHA
         */
            qDebug("///////////bpp %d", fmt.bytesPerPixel());
            internal_format[0] = data_format[0] = GL_LUMINANCE; //or GL_RED for GL
            if (fmt.planeCount() == 2) {
                internal_format[1] = data_format[1] = GL_LUMINANCE_ALPHA;
            } else {
                if (fmt.bytesPerPixel(1) == 2) {
                    // read 16 bits and compute the real luminance in shader
                    internal_format.fill(GL_LUMINANCE_ALPHA); //vec4(L,L,L,A)
                    data_format.fill(GL_LUMINANCE_ALPHA);
                } else {
                    internal_format[1] = data_format[1] = GL_LUMINANCE; //vec4(L,L,L,1)
                    internal_format[2] = data_format[2] = GL_ALPHA;//GL_ALPHA;
                }
            }
            for (int i = 0; i < internal_format.size(); ++i) {
                // xbmc use bpp not bpp(plane)
                //internal_format[i] = GetGLInternalFormat(data_format[i], fmt.bytesPerPixel(i));
                //data_format[i] = internal_format[i];
            }
        } else {
            //glPixelStorei(GL_UNPACK_ALIGNMENT, fmt.bytesPerPixel());
            // TODO: if no alpha, data_fmt is not GL_BGRA. align at every upload?
        }
    }
    for (int i = 0; i < fmt.planeCount(); ++i) {
        //qDebug("format: %#x GL_LUMINANCE_ALPHA=%#x", data_format[i], GL_LUMINANCE_ALPHA);
        if (fmt.bytesPerPixel(i) == 2 && fmt.planeCount() == 3) {
            //data_type[i] = GL_UNSIGNED_SHORT;
        }
        int bpp_gl = OpenGLHelper::bytesOfGLFormat(data_format[i], data_type[i]);
        int pad = qCeil((qreal)(texture_size[i].width() - effective_tex_width[i])/(qreal)bpp_gl);
        texture_size[i].setWidth(qCeil((qreal)texture_size[i].width()/(qreal)bpp_gl));
        texture_upload_size[i].setWidth(qCeil((qreal)texture_upload_size[i].width()/(qreal)bpp_gl));
        effective_tex_width[i] /= bpp_gl; //fmt.bytesPerPixel(i);
        //effective_tex_width_ratio =
        qDebug("texture width: %d - %d = pad: %d. bpp(gl): %d", texture_size[i].width(), effective_tex_width[i], pad, bpp_gl);
    }

    /*
     * there are 2 fragment shaders: rgb and yuv.
     * only 1 texture for packed rgb. planar rgb likes yuv
     * To support both planar and packed yuv, and mixed yuv(NV12), we give a texture sample
     * for each channel. For packed, each (channel) texture sample is the same. For planar,
     * packed channels has the same texture sample.
     * But the number of actural textures we upload is plane count.
     * Which means the number of texture id equals to plane count
     */
    if (textures.size() != fmt.planeCount()) {
        glDeleteTextures(textures.size(), textures.data());
        qDebug("delete %d textures", textures.size());
        textures.clear();
        textures.resize(fmt.planeCount());
        glGenTextures(textures.size(), textures.data());
    }

    if (!hasGLSL) {
        initTexture(textures[0], internal_format[0], data_format[0], data_type[0], texture_size[0].width(), texture_size[0].height());
        // more than 1?
        qWarning("Does not support GLSL!");
        return false;
    }
    qDebug("init textures...");
    for (int i = 0; i < textures.size(); ++i) {
        initTexture(textures[i], internal_format[i], data_format[i], data_type[i], texture_size[i].width(), texture_size[i].height());
    }
    return true;
}
Exemplo n.º 4
0
void SpeedPlotView::paintEvent(QPaintEvent *)
{
    QPainter painter(viewport());

    QRect fullRect = viewport()->rect();
    QRect rect = viewport()->rect();
    QFontMetrics fontMetrics = painter.fontMetrics();

    rect.adjust(4, 4, 0, -4); // Add padding

    int maxY = maxYValue();

    rect.adjust(0, fontMetrics.height(), 0, 0); // Add top padding for top speed text

    // draw Y axis speed labels
    QVector<QString> speedLabels = {
        Utils::Misc::friendlyUnit(maxY, true),
        Utils::Misc::friendlyUnit(0.75 * maxY, true),
        Utils::Misc::friendlyUnit(0.5 * maxY, true),
        Utils::Misc::friendlyUnit(0.25 * maxY, true),
        Utils::Misc::friendlyUnit(0, true)
    };

    int yAxeWidth = 0;
    for (const QString &label : speedLabels)
        if (fontMetrics.width(label) > yAxeWidth)
            yAxeWidth = fontMetrics.width(label);

    int i = 0;
    for (const QString &label : speedLabels) {
        QRectF labelRect(rect.topLeft() + QPointF(-yAxeWidth, (i++) * 0.25 * rect.height() - fontMetrics.height()),
                         QSizeF(2 * yAxeWidth, fontMetrics.height()));
        painter.drawText(labelRect, label, Qt::AlignRight | Qt::AlignTop);
    }

    // draw grid lines
    rect.adjust(yAxeWidth + 4, 0, 0, 0);

    QPen gridPen;
    gridPen.setStyle(Qt::DashLine);
    gridPen.setWidthF(1);
    gridPen.setColor(QColor(128, 128, 128, 128));
    painter.setPen(gridPen);

    painter.drawLine(fullRect.left(), rect.top(), rect.right(), rect.top());
    painter.drawLine(fullRect.left(), rect.top() + 0.25 * rect.height(), rect.right(), rect.top() + 0.25 * rect.height());
    painter.drawLine(fullRect.left(), rect.top() + 0.50 * rect.height(), rect.right(), rect.top() + 0.50 * rect.height());
    painter.drawLine(fullRect.left(), rect.top() + 0.75 * rect.height(), rect.right(), rect.top() + 0.75 * rect.height());
    painter.drawLine(fullRect.left(), rect.bottom(), rect.right(), rect.bottom());

    painter.drawLine(rect.left(), fullRect.top(), rect.left(), fullRect.bottom());
    painter.drawLine(rect.left() + 0.2 * rect.width(), fullRect.top(), rect.left() + 0.2 * rect.width(), fullRect.bottom());
    painter.drawLine(rect.left() + 0.4 * rect.width(), fullRect.top(), rect.left() + 0.4 * rect.width(), fullRect.bottom());
    painter.drawLine(rect.left() + 0.6 * rect.width(), fullRect.top(), rect.left() + 0.6 * rect.width(), fullRect.bottom());
    painter.drawLine(rect.left() + 0.8 * rect.width(), fullRect.top(), rect.left() + 0.8 * rect.width(), fullRect.bottom());

    // Set antialiasing for graphs
    painter.setRenderHints(QPainter::Antialiasing | QPainter::HighQualityAntialiasing);

    // draw graphs
    rect.adjust(3, 0, 0, 0); // Need, else graphs cross left gridline

    double yMultiplier = (maxY == 0) ? 0.0 : static_cast<double>(rect.height()) / maxY;
    double xTickSize = static_cast<double>(rect.width()) / m_viewablePointsCount;

    boost::circular_buffer<PointData> &queue = getCurrentData();

    for (int id = UP; id < NB_GRAPHS; ++id) {

        if (!m_properties[static_cast<GraphID>(id)].enable)
            continue;

        QVector<QPoint> points;

        for (int i = int(queue.size()) - 1, j = 0; i >= 0 && j <= m_viewablePointsCount; --i, ++j) {

            int new_x = rect.right() - j * xTickSize;
            int new_y = rect.bottom() - queue[i].y[id] * yMultiplier;

            points.push_back(QPoint(new_x, new_y));
        }

        painter.setPen(m_properties[static_cast<GraphID>(id)].pen);
        painter.drawPolyline(points.data(), points.size());
    }

    // draw legend
    QPoint legendTopLeft(rect.left() + 4, fullRect.top() + 4);

    double legendHeight = 0;
    int legendWidth = 0;
    for (const auto &property : m_properties) {

        if (!property.enable)
            continue;

        if (fontMetrics.width(property.name) > legendWidth)
            legendWidth =  fontMetrics.width(property.name);
        legendHeight += 1.5 * fontMetrics.height();
    }

    QRectF legendBackgroundRect(QPoint(legendTopLeft.x() - 4, legendTopLeft.y() - 4), QSizeF(legendWidth + 8, legendHeight + 8));
    QColor legendBackgroundColor = QWidget::palette().color(QWidget::backgroundRole());
    legendBackgroundColor.setAlpha(128);  // 50% transparent
    painter.fillRect(legendBackgroundRect, legendBackgroundColor);

    i = 0;
    for (const auto &property : m_properties) {

        if (!property.enable)
            continue;

        int nameSize = fontMetrics.width(property.name);
        double indent = 1.5 * (i++) * fontMetrics.height();

        painter.setPen(property.pen);
        painter.drawLine(legendTopLeft + QPointF(0, indent + fontMetrics.height()),
                         legendTopLeft + QPointF(nameSize, indent + fontMetrics.height()));
        painter.drawText(QRectF(legendTopLeft + QPointF(0, indent), QSizeF(2 * nameSize, fontMetrics.height())),
                         property.name, QTextOption(Qt::AlignVCenter));
    }
}
Exemplo n.º 5
0
//! Create 3DRep from a Lib3dsNode
GLC_3DRep GLC_3dsToWorld::create3DRep(Lib3dsMesh* p3dsMesh)
{
	QString meshName(p3dsMesh->name);
	if (m_LoadedMeshes.contains(meshName))
	{
		// This mesh as been already loaded
		QList<GLC_3DViewInstance*> instancesList(m_pWorld->collection()->instancesHandle());
		GLC_3DViewInstance* pCurrentInstance= NULL;
		int currentIndex= -1;
		do
		{
			pCurrentInstance= instancesList[++currentIndex];
		} while (pCurrentInstance->name() != meshName);
		// return an instance.
		//qDebug() << "instance";
		return pCurrentInstance->representation();
	}
	GLC_Mesh * pMesh= new GLC_Mesh();
	pMesh->setName(p3dsMesh->name);
	// The mesh normals
	const int normalsNumber= p3dsMesh->faces * 3;

	Lib3dsVector *normalL= new Lib3dsVector[normalsNumber];
	lib3ds_mesh_calculate_normals(p3dsMesh, normalL);

	// Position vector
	QVector<float> position(normalsNumber * 3);

	// Normal Vector
	QVector<float> normal(normalsNumber * 3);
	memcpy((void*)normal.data(), normalL, normalsNumber * 3 * sizeof(float));

	// Texel Vector
	QVector<float> texel;
	if (p3dsMesh->texels > 0)
	{
		texel.resize(normalsNumber * 2);
	}

	int normalIndex= 0;
	for (unsigned int i= 0; i < p3dsMesh->faces; ++i)
	{
		IndexList triangleIndex;
		Lib3dsFace *p3dsFace=&p3dsMesh->faceL[i];
		for (int i=0; i < 3; ++i)
		{
			triangleIndex.append(normalIndex);
			// Add vertex coordinate
			memcpy((void*)&(position.data()[normalIndex * 3]), &p3dsMesh->pointL[p3dsFace->points[i]], 3 * sizeof(float));

			// Add texel
			if (p3dsMesh->texels > 0)
			{
				memcpy((void*)&(texel.data()[normalIndex * 2]), &p3dsMesh->texelL[p3dsFace->points[i]], 2 * sizeof(float));
			}
			++normalIndex;
		}

		// Load the material
		// The material current face index
		GLC_Material* pCurMaterial= NULL;
		if (p3dsFace->material[0])
		{
			Lib3dsMaterial* p3dsMat=lib3ds_file_material_by_name(m_pLib3dsFile, p3dsFace->material);
			if (NULL != p3dsMat)
			{
				// Check it this material as already been loaded
				const QString materialName(p3dsFace->material);

				if (!m_Materials.contains(materialName))
				{ // Material not already loaded, load it
					loadMaterial(p3dsMat);
				}
				pCurMaterial= m_Materials.value(materialName);
			}
		}
		pMesh->addTriangles(pCurMaterial, triangleIndex);
	}
	pMesh->addVertice(position);
	pMesh->addNormals(normal);
	if (p3dsMesh->texels > 0)
	{
		pMesh->addTexels(texel);
	}

	// free normal memmory
	delete[] normalL;
	// Compute loading progress
	++m_CurrentMeshNumber;
	m_CurrentQuantumValue = static_cast<int>((static_cast<double>(m_CurrentMeshNumber) / m_NumberOfMeshes) * (100 - m_InitQuantumValue)) + m_InitQuantumValue;
	if (m_CurrentQuantumValue > m_PreviousQuantumValue)
	{
		emit currentQuantum(m_CurrentQuantumValue);
	}
	m_PreviousQuantumValue= m_CurrentQuantumValue;

	pMesh->finish();
	return GLC_3DRep(pMesh);
}
Exemplo n.º 6
0
void UwMath::toConformalInverted(QVector<QPointF> &object) {
    QPointF * data = object.data();

    for(int i = 0; i < object.size(); i++)
        data[i] = UwMath::toConformalInverted(object.at(i));
}
Exemplo n.º 7
0
bool QmcUnit::loadUnitData(QDataStream &stream)
{
    char *qmlUnitPtr = new char[header->sizeQmlUnit];
    qmlUnit = reinterpret_cast<QV4::CompiledData::QmlUnit*>(qmlUnitPtr);
    if (!qmlUnit)
        return false;
    compilationUnit->data = unit = &(qmlUnit->header);

    if (!readData(qmlUnitPtr, header->sizeQmlUnit, stream))
        return false;

    // load imports
    for (int i = 0; i < (int)header->imports; i++) {
        QV4::CompiledData::Import import;
        if (!readData((char *)&import, sizeof(QV4::CompiledData::Import), stream))
            return false;
        if (import.uriIndex >= header->strings || import.qualifierIndex >= header->strings)
            return false;
        imports.append(import);
    }

    for (int i = 0; i < (int)header->strings; i++) {
        QString string;
        if (!readString(string, stream))
            return false;
        strings.append(string);
    }

    for (int i = 0; i < (int)header->namespaces; i++) {
        QString ns;
        if (!readString(ns, stream))
            return false;
        namespaces.append(ns);
    }

    for (int i = 0; i < (int)header->typeReferences; i++) {
        QmcUnitTypeReference typeRef;
        if (!readData((char *)&typeRef, sizeof (QmcUnitTypeReference), stream))
            return false;
        typeReferences.append(typeRef);
    }

    for (int i = 0; i < (int)header->scriptReferences; i++) {
        QString string;
        if (!readString(string, stream))
            return false;
        scriptReferences.append(string);
    }

    // coderefs
    codeRefSizes.resize(header->codeRefs);
    for (int i = 0; i < (int)header->codeRefs; i++) {

        if (!readData((char *)&exceptionReturnLabel, sizeof(QmcUnitExceptionReturnLabel), stream))
            return false;

        exceptionPropagationJumps.clear();
        quint32 exceptionPropagationJumpsCount = 0;
        if (!readData((char *)&exceptionPropagationJumpsCount, sizeof(quint32), stream))
            return false;

        for (uint j = 0; j < exceptionPropagationJumpsCount; j++) {
            QmcUnitExceptionPropagationJump jump;
            if (!readData((char *)&jump, sizeof (QmcUnitExceptionPropagationJump), stream))
                return false;
            exceptionPropagationJumps.append(jump);
        }

#if CPU(ARM_THUMB2)
        linkRecords.clear();
        quint32 linkRecordsCount = 0;
        if (!readData((char *)&linkRecordsCount, sizeof(quint32), stream))
            return false;
        if (linkRecordsCount > QMC_UNIT_MAX_LINK_RECORDS)
            return false;

        for (uint j = 0; j < linkRecordsCount; j++) {
            QmcUnitLinkRecord record;
            if (!readData((char *)&record, sizeof (QmcUnitLinkRecord), stream))
                return false;
            linkRecords.append(record);
        }
#endif

        quint32 codeRefLen = 0;
        if (!readData((char *)&codeRefLen, sizeof(quint32), stream))
            return false;
        if (codeRefLen > QMC_UNIT_MAX_CODE_REF_SIZE)
            return false;
        //qDebug() << "Codereflen" << QString("%1").arg(codeRefLen, 0, 16);
        if (codeRefLen == 0) {
            JSC::MacroAssemblerCodeRef codeRef;
            compilationUnit->codeRefs.append(codeRef);
            QVector<QmcUnitCodeRefLinkCall> linkData;
            linkCalls.append(linkData);
            QVector<QV4::Primitive> constData;
            constantVectors.append(constData);
            continue;
        }

        // read code to temporary variable, there will be executable code if it
        QVector<char> code;
        code.resize(codeRefLen);
        if (!readData(code.data(), codeRefLen, stream)) {
            return false;
        }
        codeRefData.append(code);

        quint32 linkCallsCount = 0;
        if (!readData((char *)&linkCallsCount, sizeof(quint32), stream))
            return false;
        if (linkCallsCount > QMC_UNIT_MAX_CODE_REF_LINK_CALLS)
            return false;
        QVector<QmcUnitCodeRefLinkCall> linkData;
        if (linkCallsCount > 0) {
            linkData.resize(linkCallsCount);
            if (!readData((char *)linkData.data(), sizeof (QmcUnitCodeRefLinkCall) * linkCallsCount, stream))
                return false;
        }
        linkCalls.append(linkData);

        quint32 constantVectorLen = 0;
        if (!readData((char *)&constantVectorLen, sizeof(quint32), stream))
            return false;
        if (constantVectorLen > QMC_UNIT_MAX_CONSTANT_VECTOR_SIZE)
            return false;
        QVector<QV4::Primitive > constantVector;
        if (constantVectorLen > 0) {
            constantVector.resize(constantVectorLen);
            if (constantVectorLen == 0)
                continue;
            if (!readData((char *)constantVector.data(), constantVectorLen, stream))
                return false;
        }
        constantVectors.append(constantVector);

#if 0
        QV4::ExecutableAllocator::Allocation *executableMemory =
                QQmlEnginePrivate::get(engine)->v4engine()->executableAllocator->allocate(codeRefLen);
        if (!executableMemory)
            return false;
        allocations.append(executableMemory);
        char *codeExec = (char *) executableMemory->start();
        //ASSERT(code);
        JSC::ExecutableAllocator::makeWritable(codeExec, codeRefLen);
        memcpy(codeExec, code.data(), codeRefLen);

        JSC::MacroAssemblerCodePtr codePtr = JSC::MacroAssemblerCodePtr::createFromExecutableAddress(codeExec);
        JSC::MacroAssemblerCodeRef codeRef = JSC::MacroAssemblerCodeRef::createSelfManagedCodeRef(codePtr);
        compilationUnit->constantValues.append(constantVectors);
#else
        QV4::ExecutableAllocator* executableAllocator = QQmlEnginePrivate::get(engine)->v4engine()->executableAllocator;
        QmcBackedInstructionSelection *isel = new QmcBackedInstructionSelection(compilationUnit);
        QV4::IR::Function nullFunction(0, 0);
        QV4::JIT::Assembler* as = new QV4::JIT::Assembler(isel, &nullFunction, executableAllocator, 6); // 6 == max argc for calls to built-ins with an argument array

#if CPU(ARM_THUMB2)
        foreach (const QmcUnitLinkRecord &record, linkRecords) {
            as->addJump(JSC::AssemblerLabel(record.from), JSC::AssemblerLabel(record.to),
                    record.type, record.condition);
        }
#endif

        QList<QV4::JIT::Assembler::CallToLink>& callsToLink = as->callsToLink();
        foreach (const QmcUnitCodeRefLinkCall &call, linkData) {
            // resolve function pointer
            if (call.index > sizeof (QMC_LINK_TABLE) / sizeof (QmcLinkEntry))
                return false;
            void *functionPtr = QMC_LINK_TABLE[call.index].addr;
            QV4::JIT::Assembler::CallToLink c;
            JSC::AssemblerLabel label(call.offset);
            c.call = QV4::JIT::Assembler::Call(label, QV4::JIT::Assembler::Call::Linkable);
            c.externalFunction = JSC::FunctionPtr((quint64(*)(void))functionPtr);
#if QT_VERSION > QT_VERSION_CHECK(5,3,0)
            c.label.m_label = label;
#endif
            callsToLink.append(c);
        }

        QV4::JIT::Assembler::ConstantTable& constTable = as->constantTable();
        int iii = 0;
        foreach (const QV4::Primitive &p, constantVector) {
            int idx = constTable.add(p);
            Q_ASSERT(idx == iii++);
        }
void QSGTextMaskMaterial::populate(const QPointF &p,
                                   const QVector<quint32> &glyphIndexes,
                                   const QVector<QPointF> &glyphPositions,
                                   QSGGeometry *geometry,
                                   QRectF *boundingRect,
                                   QPointF *baseLine,
                                   const QMargins &margins)
{
    Q_ASSERT(m_font.isValid());
    QVector<QFixedPoint> fixedPointPositions;
    for (int i=0; i<glyphPositions.size(); ++i)
        fixedPointPositions.append(QFixedPoint::fromPointF(glyphPositions.at(i)));

    QTextureGlyphCache *cache = glyphCache();

    QRawFontPrivate *fontD = QRawFontPrivate::get(m_font);
    cache->populate(fontD->fontEngine, glyphIndexes.size(), glyphIndexes.constData(),
                    fixedPointPositions.data());
    cache->fillInPendingGlyphs();

    int margin = fontD->fontEngine->glyphMargin(cache->cacheType());

    Q_ASSERT(geometry->indexType() == GL_UNSIGNED_SHORT);
    geometry->allocate(glyphIndexes.size() * 4, glyphIndexes.size() * 6);
    QVector4D *vp = (QVector4D *)geometry->vertexDataAsTexturedPoint2D();
    Q_ASSERT(geometry->sizeOfVertex() == sizeof(QVector4D));
    ushort *ip = geometry->indexDataAsUShort();

    QPointF position(p.x(), p.y() - m_font.ascent());
    bool supportsSubPixelPositions = fontD->fontEngine->supportsSubPixelPositions();
    for (int i=0; i<glyphIndexes.size(); ++i) {
         QFixed subPixelPosition;
         if (supportsSubPixelPositions)
             subPixelPosition = fontD->fontEngine->subPixelPositionForX(QFixed::fromReal(glyphPositions.at(i).x()));

         QTextureGlyphCache::GlyphAndSubPixelPosition glyph(glyphIndexes.at(i), subPixelPosition);
         const QTextureGlyphCache::Coord &c = cache->coords.value(glyph);

         QPointF glyphPosition = glyphPositions.at(i) + position;
         int x = qFloor(glyphPosition.x()) + c.baseLineX - margin;
         int y = qFloor(glyphPosition.y()) - c.baseLineY - margin;

         *boundingRect |= QRectF(x + margin, y + margin, c.w, c.h);

         float cx1 = x - margins.left();
         float cx2 = x + c.w + margins.right();
         float cy1 = y - margins.top();
         float cy2 = y + c.h + margins.bottom();

         float tx1 = c.x - margins.left();
         float tx2 = c.x + c.w + margins.right();
         float ty1 = c.y - margins.top();
         float ty2 = c.y + c.h + margins.bottom();

         if (baseLine->isNull())
             *baseLine = glyphPosition;

         vp[4 * i + 0] = QVector4D(cx1, cy1, tx1, ty1);
         vp[4 * i + 1] = QVector4D(cx2, cy1, tx2, ty1);
         vp[4 * i + 2] = QVector4D(cx1, cy2, tx1, ty2);
         vp[4 * i + 3] = QVector4D(cx2, cy2, tx2, ty2);

         int o = i * 4;
         ip[6 * i + 0] = o + 0;
         ip[6 * i + 1] = o + 2;
         ip[6 * i + 2] = o + 3;
         ip[6 * i + 3] = o + 3;
         ip[6 * i + 4] = o + 1;
         ip[6 * i + 5] = o + 0;
    }
}
void QSGTextMaskMaterial::populate(const QPointF &p,
                                   const QVector<quint32> &glyphIndexes,
                                   const QVector<QPointF> &glyphPositions,
                                   QSGGeometry *geometry,
                                   QRectF *boundingRect,
                                   QPointF *baseLine,
                                   const QMargins &margins)
{
    Q_ASSERT(m_font.isValid());
    QVector<QFixedPoint> fixedPointPositions;
    for (int i=0; i<glyphPositions.size(); ++i)
        fixedPointPositions.append(QFixedPoint::fromPointF(glyphPositions.at(i)));

    QTextureGlyphCache *cache = glyphCache();

    QRawFontPrivate *fontD = QRawFontPrivate::get(m_font);
    cache->populate(fontD->fontEngine, glyphIndexes.size(), glyphIndexes.constData(),
                    fixedPointPositions.data());
    cache->fillInPendingGlyphs();

    int margin = fontD->fontEngine->glyphMargin(cache->glyphFormat());

    qreal glyphCacheScaleX = cache->transform().m11();
    qreal glyphCacheScaleY = cache->transform().m22();
    qreal glyphCacheInverseScaleX = 1.0 / glyphCacheScaleX;
    qreal glyphCacheInverseScaleY = 1.0 / glyphCacheScaleY;

    Q_ASSERT(geometry->indexType() == GL_UNSIGNED_SHORT);
    geometry->allocate(glyphIndexes.size() * 4, glyphIndexes.size() * 6);
    QVector4D *vp = (QVector4D *)geometry->vertexDataAsTexturedPoint2D();
    Q_ASSERT(geometry->sizeOfVertex() == sizeof(QVector4D));
    ushort *ip = geometry->indexDataAsUShort();

    QPointF position(p.x(), p.y() - m_font.ascent());
    bool supportsSubPixelPositions = fontD->fontEngine->supportsSubPixelPositions();
    for (int i=0; i<glyphIndexes.size(); ++i) {
         QFixed subPixelPosition;
         if (supportsSubPixelPositions)
             subPixelPosition = fontD->fontEngine->subPixelPositionForX(QFixed::fromReal(glyphPositions.at(i).x()));

         QTextureGlyphCache::GlyphAndSubPixelPosition glyph(glyphIndexes.at(i), subPixelPosition);
         const QTextureGlyphCache::Coord &c = cache->coords.value(glyph);

         QPointF glyphPosition = glyphPositions.at(i) + position;

         // On a retina screen the glyph positions are not pre-scaled (as opposed to
         // eg. the raster paint engine). To ensure that we get the same behavior as
         // the raster engine (and CoreText itself) when it comes to rounding of the
         // coordinates, we need to apply the scale factor before rounding, and then
         // apply the inverse scale to get back to the coordinate system of the node.

         qreal x = (qFloor(glyphPosition.x() * glyphCacheScaleX) * glyphCacheInverseScaleX) +
                        (c.baseLineX * glyphCacheInverseScaleX) - margin;
         qreal y = (qRound(glyphPosition.y() * glyphCacheScaleY) * glyphCacheInverseScaleY) -
                        (c.baseLineY * glyphCacheInverseScaleY) - margin;

         qreal w = c.w * glyphCacheInverseScaleX;
         qreal h = c.h * glyphCacheInverseScaleY;

         *boundingRect |= QRectF(x + margin, y + margin, w, h);

         float cx1 = x - margins.left();
         float cx2 = x + w + margins.right();
         float cy1 = y - margins.top();
         float cy2 = y + h + margins.bottom();

         float tx1 = c.x - margins.left();
         float tx2 = c.x + c.w + margins.right();
         float ty1 = c.y - margins.top();
         float ty2 = c.y + c.h + margins.bottom();

         if (baseLine->isNull())
             *baseLine = glyphPosition;

         vp[4 * i + 0] = QVector4D(cx1, cy1, tx1, ty1);
         vp[4 * i + 1] = QVector4D(cx2, cy1, tx2, ty1);
         vp[4 * i + 2] = QVector4D(cx1, cy2, tx1, ty2);
         vp[4 * i + 3] = QVector4D(cx2, cy2, tx2, ty2);

         int o = i * 4;
         ip[6 * i + 0] = o + 0;
         ip[6 * i + 1] = o + 2;
         ip[6 * i + 2] = o + 3;
         ip[6 * i + 3] = o + 3;
         ip[6 * i + 4] = o + 1;
         ip[6 * i + 5] = o + 0;
    }
}
Exemplo n.º 10
0
bool AMExporter2DAscii::prepareDataSources()
{
	// This is a much stricter function than AMExporterGeneralAscii.  Only 2D data sources are allowed (and when we figure out the spectra files, then also 3D).
	mainTableDataSources_.clear();
	mainTableIncludeX_.clear();
	separateSectionDataSources_.clear();
	separateSectionIncludeX_.clear();
	separateFileDataSources_.clear();
	separateFileIncludeX_.clear();

	if (option_->includeAllDataSources() && option_->firstColumnOnly()){

		bool includeFirstColumn = true;

		for (int i = 0; i < currentScan_->dataSourceCount(); i++){

			switch(currentScan_->dataSourceAt(i)->rank()){
			// No 0D or 1D data sources.
			case 0:
			case 1:
				return false;

			case 2:
				mainTableDataSources_ << i;
				mainTableIncludeX_ << includeFirstColumn; // X and Y.

				if (includeFirstColumn)
					includeFirstColumn = false;

				break;

			case 3:
				if (option_->includeHigherDimensionSources())
					separateFileDataSources_ << i;
				break;
			}
		}

		int xRange = currentScan_->scanSize(0);
		int yRange = currentScan_->scanSize(1);
		QVector<double> fillerData = QVector<double>(yRange);
		currentScan_->dataSourceAt(0)->values(AMnDIndex(xRange-1,0), AMnDIndex(xRange-1, yRange-1), fillerData.data());

		for (int j = 0; j < yRange && yRange_ == -1; j++)
			if (fillerData.at(j) == -1)
				yRange_ = j+1;	// The +1 is because we want the next row.

		if (yRange_ != -1){

			fillerData = QVector<double>(xRange);
			currentScan_->dataSourceAt(0)->values(AMnDIndex(0, yRange_-1), AMnDIndex(xRange-1, yRange_-1), fillerData.data());

			for (int i = 0; i < xRange && xIndex_ == -1; i++)
				if (fillerData.at(i) == -1)
					xIndex_ = i;
		}
	}

	// There isn't much to a simple 2D map.  Put the X and Y in the first column and then put all the rest of the data.  I don't have any other options right now.
	else
		return false;

	return true;
}
Exemplo n.º 11
0
void QGLView::initializeVertexBuffer(ModelType type, const QVector<ModelVertex> &vertices)
{
    initializeVertexBuffer(type, vertices.data(), vertices.length() * sizeof(ModelVertex));
}
Exemplo n.º 12
0
void US_MPI_Analysis::dmga_master_loop( void )
{
   static const double DIGIT_FIT      = 1.0e+4;
   static const int    min_generation = 10;
   static const int    _KS_BASE_      = 6;
   static const int    _KS_STEP_      = 3;
   QString dbgtext   = parameters[ "debug_text" ];
   QString s_ksbase  = par_key_value( dbgtext, "ksame_base" );
   QString s_ksstep  = par_key_value( dbgtext, "ksame_step" );
   int ks_base       = s_ksbase.isEmpty() ? _KS_BASE_ : s_ksbase.toInt();
   int ks_step       = s_ksstep.isEmpty() ? _KS_STEP_ : s_ksstep.toInt();
   ks_base           = qMax( 2, ks_base );
   ks_step           = qMax( 1, ks_step );
//   static const int    max_same_count = my_workers * 5;
   int    max_same_count       = ( ks_base + ( nfloatc / ks_step ) * ks_step )
                                 * my_workers;
   int    avg_generation       = 0;
   bool   early_termination    = false;
   int    fitness_same_count   = 0;
   double best_overall_fitness = LARGE;
   int    tag;
   int    workers  = my_workers;
DbgLv(1) << "dmga_master start loop:  gcores_count fitsize" << gcores_count
   << best_fitness.size() << "best_overall" << best_overall_fitness;
DbgLv(0) << "dmga_master start loop:  nfloatc max_same_count"
    << nfloatc << max_same_count << "ks_base ks_step" << ks_base << ks_step;

   // Reset best fitness for each worker
   for ( int i = 0; i < gcores_count; i++ )
   {
      best_fitness[ i ].fitness = LARGE;
      best_fitness[ i ].index   = i;
   }

   QList  < DGene > emigres;     // Holds genes passed as emmigrants
   QVector< int   > v_generations( gcores_count, 0 ); 
   int    sum      = 0;
   int    avg      = 0;
   long   rsstotal = 0L;
   double fit_power      = 5;
   double fit_digit      = 1.0e4;
   double fitness_round  = 1.0e5;


   while ( workers > 0 )
   {
      MPI_GA_MSG msg;
      MPI_Status status;
      int        worker;

      MPI_Recv( &msg,          // Get a message   MPI #1
                sizeof( msg ),
                MPI_BYTE,
                MPI_ANY_SOURCE,
                MPI_ANY_TAG,
                my_communicator,
                &status );

      worker = status.MPI_SOURCE;

      max_rss();

      switch ( status.MPI_TAG )
      {
         case GENERATION:
            v_generations[ worker ] = msg.generation;

            sum = 0;
            for ( int i = 1; i <= my_workers; i++ ) 
               sum += v_generations[ i ];

            avg = qRound( (double)sum / (double)my_workers ) + 1;

            if ( avg > avg_generation )
            {
               avg_generation = avg;
               int mc_iter    = mgroup_count < 2 ? ( mc_iteration + 1 )
                                                 : mc_iteration;

               QString progress =
                  "Avg. Generation: "  + QString::number( avg_generation );

               if ( data_sets.size() > 1 )
               {
                  if ( datasets_to_process == 1 )
                     progress += "; Dataset: "
                              + QString::number( current_dataset + 1 )
                              + " of " + QString::number( count_datasets );
                  else
                     progress += "; Datasets: "
                              + QString::number( datasets_to_process );
               }

               progress += "; MonteCarlo: " + QString::number( mc_iter );
               if ( best_overall_fitness != LARGE  &&  best_overall_fitness > 0.0 )
                  progress += "; RMSD: "
                            + QString::number( sqrt( best_overall_fitness ) );

               send_udp( progress );
            }

            // Get the best gene for the current generation from the worker
DbgLv(1) << "  MAST: work" << worker << "Recv#2 nfloatc" << nfloatc;
            MPI_Recv( dgmarker.data(),                 // MPI #2
                      nfloatc,
                      MPI_DOUBLE,  
                      worker,
                      GENE,
                      my_communicator,
                      MPI_STATUS_IGNORE );

DbgLv(1) << "  MAST: work" << worker << " dgm size" << dgmarker.size()
         << "bestdg size" << best_dgenes.size();
            dgene_from_marker( dgmarker, dgene );
            best_dgenes[ worker ]  = dgene;
            max_rss();

            // Compute a current-deme best fitness value that is rounded
            //  to 4 significant digits
            fit_power      = (double)qRound( log10( msg.fitness ) );
            fit_digit      = pow( 10.0, -fit_power ) * DIGIT_FIT;
            fitness_round  = (double)qRound64( msg.fitness * fit_digit )
                             / fit_digit;

DbgLv(1) << "  MAST: work" << worker << "fit msg,round,bestw,besto"
 << msg.fitness << fitness_round << best_fitness[worker].fitness
 << best_overall_fitness;
            // Set deme's best fitness
            if ( fitness_round < best_fitness[ worker ].fitness )
               best_fitness[ worker ].fitness = fitness_round;
DbgLv(1) << "master: worker/fitness/best gene" << worker <<  msg.fitness << dgene_key( best_dgenes[worker] );

            if ( ! early_termination )
            {  // Handle normal pre-early-termination updates
               if ( avg_generation == 1  &&  mc_iterations == 1  &&
                   best_overall_fitness == LARGE )
               {  // Report first best-fit RMSD
                  DbgLv(0) << "First Best Fit RMSD" << sqrt( fitness_round );
               }
DbgLv(1) << "  MAST: work" << worker << "fit besto,round" << best_overall_fitness << fitness_round
 << "fit_power fit_digit msgfit" << fit_power << fit_digit << msg.fitness;

               if ( fitness_round < best_overall_fitness )
               {  // Update over-all best fitness value (rounded)
                  best_overall_fitness = fitness_round;
                  fitness_same_count   = 0;
               }
               else
               {  // Bump the count of consecutive same best overall fitness
                  fitness_same_count++;
               }


               if ( fitness_same_count > max_same_count  &&
                    avg_generation     > min_generation )
               {  // Mark early termination at threshold same-fitness count
                  DbgLv(0) << "Fitness has not improved in the last"
                     << fitness_same_count
                     << "deme results - Early Termination.";
                  early_termination = true;
               }

            }
//DbgLv(1) << "  best_overall_fitness" << best_overall_fitness
// << "fitness_same_count" << fitness_same_count
// << " early_term?" << early_termination;
if((worker%10)==1)
DbgLv(1) << worker << ": best_overall_fitness" << best_overall_fitness
 << "fitness_same_count" << fitness_same_count
 << " early_term?" << early_termination;

            // Tell the worker to either stop or continue
            tag            = early_termination ? FINISHED : GENERATION; 
DbgLv(1) << "dgmast: Send#3 tag" << tag << "( FINISHED,GENERATION" << FINISHED << GENERATION << " )";

            MPI_Send( &msg,            // MPI #3
                      0,               // Only interested in the tag 
                      MPI_BYTE,  
                      worker,
                      tag,
                      my_communicator );
            break;

         case FINISHED:
DbgLv(1) << "dgmast: Recv FINISH msg.size rsstotal" << msg.size << rsstotal;
            rsstotal += (long)msg.size;
            workers--;
            break;

         case EMMIGRATE:
         {
            // First get a set of genes as a concatenated marker vector.
            int gene_count    = msg.size;
            int doubles_count = gene_count * nfloatc;
            QVector< double > emmigrants( doubles_count ) ;
DbgLv(1) << "dgmast: Recv#4 EMMIG: gene_count doubles_count" << gene_count << doubles_count;

            MPI_Recv( emmigrants.data(),  // MPI #4
                      doubles_count,
                      MPI_DOUBLE,
                      worker,
                      EMMIGRATE,
                      my_communicator,
                      MPI_STATUS_IGNORE );

            // Add the genes to the emmigres list
            int emgx          = emigres.size();
DbgLv(1) << "dgmast: Recv#4 EMMIG: emgx" << emgx;
            marker_to_dgenes( emmigrants, emigres, emgx, gene_count );
DbgLv(1) << "dgmast: Recv#4 EMMIG: emigres size" << emigres.size();

//*DEBUG*
//if(emigres[0][0].s<0.0)
// DbgLv(0) << "MAST: **GENE s" << emigres[0][0].s << " Emigrant";
//*DEBUG*

            max_rss();

            // Don't send any back if the pool is too small
            if ( emigres.size() < gene_count * 5 ) doubles_count = 0;

            // Get immigrants from emmigres
            QVector< double > immigrants;
            dgmarker.resize( nfloatc );

            if ( doubles_count > 0 )
            {
               // Prepare a marker vector from the emmigrant list
               for ( int ii = 0; ii < gene_count; ii++ )
               {
                  dgene       = emigres.takeAt( u_random( emigres.size() ) );

                  marker_from_dgene( dgmarker, dgene );

                  immigrants += dgmarker;
               }
            }
            else
            {
DbgLv(1) << "dgmast: Send#5 IMMIG: count==0 migr data" << immigrants.data();
               immigrants.resize( 1 );
            }
DbgLv(1) << "dgmast: Send#5 IMMIG: immigrants size" << immigrants.size() << "doubles_count" << doubles_count
         << "migr data" << immigrants.data();

            MPI_Send( immigrants.data(),   // MPI #5
                      doubles_count,
                      MPI_DOUBLE,
                      worker,
                      IMMIGRATE,
                      my_communicator );
DbgLv(1) << "dgmast:   Send#5 IMMIG: complete";
//*DEBUG*
//if(immigrants[0].s<0.0)
// DbgLv(0) << "MAST: **GENE s" << immigrants[0].s << " Immigrant-to-send";
//*DEBUG*
            break;
         }
      }

      max_rss();
   }

DbgLv(1) << "Master maxrss" << maxrss << " worker total rss" << rsstotal
 << "rank" << my_rank;
   maxrss += rsstotal;

   if ( early_termination )
   {  // Report when we have reached early termination of generations
      int mc_iter  = mgroup_count < 2 ? ( mc_iteration + 1 ) : mc_iteration;
      DbgLv(0) << "Early termination at average generation" << avg
         << ", MC" << mc_iter;
   }
}
Exemplo n.º 13
0
void SegmentGL::RenderContour(Segment *seg, QMatrix4x4 projection, QMatrix4x4 modelview, int width, int height)
{

    QVector3D vec;
    QVector3D pos;
    QVector<GLfloat> positions;
    QEci qeci;


    CalculateSegmentContour(&positions, seg->cornerpointfirst1.latitude, seg->cornerpointfirst1.longitude, seg->cornerpointlast1.latitude, seg->cornerpointlast1.longitude);
    CalculateSegmentContour(&positions,seg->cornerpointlast1.latitude, seg->cornerpointlast1.longitude, seg->cornerpointlast2.latitude, seg->cornerpointlast2.longitude);
    CalculateSegmentContour(&positions, seg->cornerpointlast2.latitude, seg->cornerpointlast2.longitude, seg->cornerpointfirst2.latitude, seg->cornerpointfirst2.longitude);
    CalculateSegmentContour(&positions,seg->cornerpointfirst2.latitude, seg->cornerpointfirst2.longitude, seg->cornerpointfirst1.latitude, seg->cornerpointfirst1.longitude);

    seg->qsgp4->getPosition(seg->minutes_since_state_vector, qeci);
    QGeodetic qgeo = qeci.ToGeo();
    double lat1 = qgeo.latitude;
    double lon1 = qgeo.longitude;

    seg->qsgp4->getPosition(seg->minutes_since_state_vector + seg->minutes_sensing, qeci);
    qgeo = qeci.ToGeo();
    double lat2 = qgeo.latitude;
    double lon2 = qgeo.longitude;

    CalculateSegmentContour(&positions, lat1, lon1, lat2, lon2);

    positionsBuf.bind();
    positionsBuf.write(0, positions.data(), positions.size() * sizeof(GLfloat));
    positionsBuf.release();

    QOpenGLVertexArrayObject::Binder vaoBinder(&vao);

    program->bind();
    program->setUniformValue("MVP", projection * modelview);
    QColor rendercolor(opts.satsegmentcolor);
    QColor rendercolorsel(opts.satsegmentcolorsel);

    if((*seg).segmentselected)
        program->setUniformValue("outcolor", QVector4D(rendercolorsel.redF(), rendercolorsel.greenF(), rendercolorsel.blueF(), 1.0f));
    else
        program->setUniformValue("outcolor", QVector4D(rendercolor.redF(), rendercolor.greenF(), rendercolor.blueF(), 1.0f));

    QMatrix3x3 norm = modelview.normalMatrix();
    program->setUniformValue("NormalMatrix", norm);

    glDrawArrays(GL_LINE_LOOP, 0, nbrOfVertices - 10);
    glDrawArrays(GL_LINE_STRIP, nbrOfVertices - 10, 10);


    float mvmatrix[16], projmatrix[16];
    QMatrix4x4 MVP;
    MVP = projection * modelview;

    float *ptr = modelview.data();
    for(int i = 0; i < 16; i++)
        mvmatrix[i] = *(ptr + i);

    ptr = projection.data();
    for(int i = 0; i < 16; i++)
        projmatrix[i] = *(ptr + i);

    QVector2D win;

    LonLat2PointRad((float)seg->cornerpointfirst1.latitude, (float)seg->cornerpointfirst1.longitude, &vec, 1.0);
    win = glhProjectf (vec, mvmatrix, projmatrix, width, height);
    seg->winvecend1 = win;

    LonLat2PointRad((float)seg->cornerpointfirst2.latitude, (float)seg->cornerpointfirst2.longitude, &vec, 1.0);
    win = glhProjectf (vec, mvmatrix, projmatrix, width, height);
    seg->winvecend2 = win;

    LonLat2PointRad((float)seg->cornerpointlast1.latitude, (float)seg->cornerpointlast1.longitude, &vec, 1.0);
    win = glhProjectf (vec, mvmatrix, projmatrix, width, height);
    seg->winvecend3 = win;

    LonLat2PointRad((float)seg->cornerpointlast2.latitude, (float)seg->cornerpointlast2.longitude, &vec, 1.0);
    win = glhProjectf (vec, mvmatrix, projmatrix, width, height);
    seg->winvecend4 = win;

    win = glhProjectf (seg->vec1, mvmatrix, projmatrix, width, height);
    seg->winvec1 = win;

    win = glhProjectf (seg->vec2, mvmatrix, projmatrix, width, height);
    seg->winvec2 = win;

}
Exemplo n.º 14
0
bool ScaleDiv::buildLogDiv(int maxMajSteps, int maxMinSteps, double majStep)
{
   double firstTick, lastTick;
   double lFirst, lLast;
   double val, sval, minStep, minFactor;
   int nMaj, nMin, minSize, i, k, k0, kstep, kmax, i0;
   bool rv = true;
   double width;

   QVector<double> buffer;


   // Parameter range check
   maxMajSteps = MusECore::qwtMax(1, MusECore::qwtAbs(maxMajSteps));
   maxMinSteps = MusECore::qwtMax(0, MusECore::qwtAbs(maxMinSteps));
   majStep = MusECore::qwtAbs(majStep);

   // boundary check
   limRange(d_hBound, LOG_MIN, LOG_MAX);
   limRange(d_lBound, LOG_MIN, LOG_MAX);

   // reset vectors
   d_minMarks.resize(0);
   d_majMarks.resize(0);

   if (d_lBound == d_hBound) return true;

   // scale width in decades
   width = log10(d_hBound) - log10(d_lBound);

   // scale width is less than one decade -> build linear scale
   if (width < 1.0)
   {
      rv = buildLinDiv(maxMajSteps, maxMinSteps, 0.0);
      // convert step width to decades
      if (d_majStep > 0)
         d_majStep = log10(d_majStep);

      return rv;
   }

   //
   //  Set up major scale divisions
   //
   if (majStep == 0.0)
      d_majStep = MusECore::qwtCeil125( width * 0.999999 / double(maxMajSteps));
   else
      d_majStep = majStep;

   // major step must be >= 1 decade
   d_majStep = MusECore::qwtMax(d_majStep, 1.0);


   lFirst = ceil((log10(d_lBound) - step_eps * d_majStep) / d_majStep) * d_majStep;
   lLast = floor((log10(d_hBound) + step_eps * d_majStep) / d_majStep) * d_majStep;

   firstTick = pow10(lFirst);
   lastTick = pow10(lLast);

   nMaj = MusECore::qwtMin(10000, int(rint(MusECore::qwtAbs(lLast - lFirst) / d_majStep)) + 1);

   d_majMarks.resize(nMaj);
   MusECore::qwtLogSpace(d_majMarks.data(), d_majMarks.size(), firstTick, lastTick);


   //
   // Set up minor scale divisions
   //

   if ((d_majMarks.size() < 1) || (maxMinSteps < 1)) return true; // no minor marks

   if (d_majStep < 1.1)			// major step width is one decade
   {
      if (maxMinSteps >= 8)
      {
         k0 = 2;
         kmax = 9;
         kstep = 1;
         minSize = (d_majMarks.size() + 1) * 8;
      }
      else if (maxMinSteps >= 4)
      {
         k0 = 2;
         kmax = 8;
         kstep = 2;
         minSize = (d_majMarks.size() + 1) * 4;
      }
      else if (maxMinSteps >= 2)
      {
         k0 = 2;
         kmax = 5;
         kstep = 3;
         minSize = (d_majMarks.size() + 1) * 2;
      }
      else
      {
         k0 = 5;
         kmax = 5;
         kstep = 1;
         minSize = (d_majMarks.size() + 1);
      }

      // resize buffer to the max. possible number of minor marks
      buffer.resize(minSize);

      // Are there minor ticks below the first major tick?
      if ( d_lBound < firstTick )
         i0 = -1;
      else
         i0 = 0;

      minSize = 0;
      for (i = i0; i< (int)d_majMarks.size(); i++)
      {
         if (i >= 0)
            val = d_majMarks[i];
         else
            val = d_majMarks[0] / pow10(d_majStep);

         for (k=k0; k<= kmax; k+=kstep)
         {
            sval = val * double(k);
            if (limRange(sval, d_lBound, d_hBound, border_eps))
            {
               buffer[minSize] = sval;
               minSize++;
            }
         }
      }

      // copy values into the minMarks array
      //d_minMarks.duplicate(buffer.data(), minSize);
      d_minMarks.resize(minSize);
      qCopy(buffer.data(), buffer.data() + minSize, d_minMarks.begin());


   }
   else				// major step > one decade
   {

      // substep width in decades, at least one decade
      minStep = MusECore::qwtCeil125( (d_majStep - step_eps * (d_majStep / double(maxMinSteps)))
                                      /  double(maxMinSteps) );
      minStep = MusECore::qwtMax(1.0, minStep);

      // # subticks per interval
      nMin = int(rint(d_majStep / minStep)) - 1;

      // Do the minor steps fit into the interval?
      if ( MusECore::qwtAbs( double(nMin + 1) * minStep - d_majStep)  >  step_eps * d_majStep)
         nMin = 0;

      if (nMin < 1) return true;		// no subticks

      // resize buffer to max. possible number of subticks
      buffer.resize((d_majMarks.size() + 1) * nMin );

      // substep factor = 10^substeps
      minFactor = MusECore::qwtMax(pow10(minStep), 10.0);

      // Are there minor ticks below the first major tick?
      if ( d_lBound < firstTick )
         i0 = -1;
      else
         i0 = 0;

      minSize = 0;
      for (i = i0; i< (int)d_majMarks.size(); i++)
      {
         if (i >= 0)
            val = d_majMarks[i];
         else
            val = firstTick / pow10(d_majStep);

         for (k=0; k< nMin; k++)
         {
            sval = (val *= minFactor);
            if (limRange(sval, d_lBound, d_hBound, border_eps))
            {
               buffer[minSize] = sval;
               minSize++;
            }
         }
      }
      //d_minMarks.duplicate(buffer.data(), minSize);
      d_minMarks.resize(minSize);
      qCopy(buffer.data(), buffer.data() + minSize, d_minMarks.begin());

   }

   return rv;
}
Exemplo n.º 15
0
bool
PowerTapDevice::download( const QDir &tmpdir,
                         QList<DeviceDownloadFile> &files,
                         QString &err)
{
    if (!dev->open(err)) {
        err = tr("ERROR: open failed: ") + err;
        return false;
    }
    // make several attempts at reading the version
    int attempts = 3;
    int veridx = -1;
    int version_len;
    char vbuf[256];
    QByteArray version;

    do {
	if (!doWrite(dev, 0x56, false, err)) // 'V'
	    return false;

    emit updateStatus( tr("Reading version...") );
    if(m_Cancelled) {
        err = tr("download cancelled");
	    return false;
	}

	version_len = readUntilNewline(dev, vbuf, sizeof(vbuf), err);
	if (version_len < 0) {
	    err = tr("Error reading version: ") + err;
	    return false;
	}
	if (PT_DEBUG) {
	    printf("read version \"%s\"\n",
		   cEscape(vbuf, version_len).toLatin1().constData());
	}
	version = QByteArray(vbuf, version_len);

	// We expect the version string to be something like
	// "VER 02.21 PRO...", so if we see two V's, it's probably
	// because there's a hardware echo going on.
	veridx = version.indexOf("VER");

    } while ((--attempts > 0) && (veridx < 0));

    if (veridx < 0) {
	err = QString(tr("Unrecognized version \"%1\""))
	    .arg(cEscape(vbuf, version_len));
	return false;
    }
    bool hwecho = version.indexOf('V') < veridx;
    if (PT_DEBUG) printf("hwecho=%s\n", hwecho ? "true" : "false");

    emit updateStatus( tr("Reading header...") );
    if(m_Cancelled) {
        err = tr("download cancelled");
        return false;
    }

    if (!doWrite(dev, 0x44, hwecho, err)) // 'D'
        return false;
    unsigned char header[6];
    int header_len = dev->read(header, sizeof(header), err);
    if (header_len != 6) {
        if (header_len < 0)
            err = tr("ERROR: reading header: ") + err;
        else
            err = tr("ERROR: timeout reading header");
        return false;
    }
    if (PT_DEBUG) {
        printf("read header \"%s\"\n",
               cEscape((char*) header,
                       sizeof(header)).toLatin1().constData());
    }
    QVector<unsigned char> records;
    for (size_t i = 0; i < sizeof(header); ++i)
        records.append(header[i]);

    emit updateStatus( tr("Reading data...") );
    if(m_Cancelled) {
        err = tr("download cancelled");
        return false;
    }
    double recIntSecs = 0.0;

    fflush(stdout);
    while (true) {
        if (PT_DEBUG) printf("reading block\n");
        unsigned char buf[256 * 6 + 1];
        int n = dev->read(buf, 2, err);
        if (n < 2) {
            if (n < 0)
                err = tr("ERROR: reading first two: ") + err;
            else
                err = tr("ERROR: timeout reading first two");
            return false;
        }
        if (PT_DEBUG) {
            printf("read 2 bytes: \"%s\"\n",
                   cEscape((char*) buf, 2).toLatin1().constData());
        }
        if (hasNewline((char*) buf, 2))
            break;
        unsigned count = 2;
        while (count < sizeof(buf)) {
            n = dev->read(buf + count, sizeof(buf) - count, err);
            if (n < 0) {
                err = tr("ERROR: reading block: ") + err;
                return false;
            }
            if (n == 0) {
                err = tr("ERROR: timeout reading block");
                return false;
            }
            if (PT_DEBUG) {
                printf("read %d bytes: \"%s\"\n", n,
                       cEscape((char*) buf + count, n).toLatin1().constData());
            }
            count += n;
        }
        unsigned csum = 0;
        for (int i = 0; i < ((int) sizeof(buf)) - 1; ++i)
            csum += buf[i];
        if ((csum % 256) != buf[sizeof(buf) - 1]) {
            err = tr("ERROR: bad checksum");
            return false;
        }
        if (PT_DEBUG) printf("good checksum\n");
        for (size_t i = 0; i < sizeof(buf) - 1; ++i)
            records.append(buf[i]);
        if (recIntSecs == 0.0) {
            unsigned char *data = records.data();
            bool bIsVer81 = PowerTapUtil::is_Ver81(data);
            for (int i = 0; i < records.size(); i += 6) {
                if (PowerTapUtil::is_config(data + i, bIsVer81)) {
                    unsigned unused1, unused2, unused3;
                    PowerTapUtil::unpack_config(
                        data + i, &unused1, &unused2,
                        &recIntSecs, &unused3, bIsVer81);
                }
            }
        }
        if (recIntSecs != 0.0) {
            int min = (int) round(records.size() / 6 * recIntSecs);
            emit updateProgress( QString(tr("progress: %1:%2"))
                .arg(min / 60)
                .arg(min % 60, 2, 10, QLatin1Char('0')));
        }
        if(m_Cancelled){
            err = tr("download cancelled");
            return false;
        }
        if (!doWrite(dev, 0x71, hwecho, err)) // 'q'
            return false;
    }

    QString tmpl = tmpdir.absoluteFilePath(".ptdl.XXXXXX");
    QTemporaryFile tmp(tmpl);
    tmp.setAutoRemove(false);
    if (!tmp.open()) {
        err = tr("Failed to create temporary file ")
            + tmpl + ": " + tmp.error();
        return false;
    }
    // QTemporaryFile initially has permissions set to 0600.
    // Make it readable by everyone.
    tmp.setPermissions(tmp.permissions()
                       | QFile::ReadOwner | QFile::ReadUser
                       | QFile::ReadGroup | QFile::ReadOther);

    DeviceDownloadFile file;
    file.extension = "raw";
    file.name = tmp.fileName();

    QTextStream os(&tmp);
    os << hex;
    os.setPadChar('0');

    bool time_set = false;
    unsigned char *data = records.data();
    bool bIsVer81 = PowerTapUtil::is_Ver81(data);

    for (int i = 0; i < records.size(); i += 6) {
        if (data[i] == 0 && !bIsVer81)
            continue;
        for (int j = 0; j < 6; ++j) {
            os.setFieldWidth(2);
            os << data[i+j];
            os.setFieldWidth(1);
            os << ((j == 5) ? "\n" : " ");
        }
        if (!time_set && PowerTapUtil::is_time(data + i, bIsVer81)) {
            struct tm time;
            time_t timet = PowerTapUtil::unpack_time(data + i, &time, bIsVer81);
            file.startTime.setTime_t( timet );
            time_set = true;
        }
    }
    if (!time_set) {
        err = tr("Failed to find start time.");
        tmp.setAutoRemove(true);
        return false;
    }

    // hack for CERVO bug dates >= 2016 set the year to 2000 (!)
    if (file.startTime.date().year() == 2000) {

        // it's in the past... so set year to this
        QDate date(QDate::currentDate().year(), file.startTime.date().month(), file.startTime.date().day());

        // is that a future date?
        if (date > QDate::currentDate()) date = date.addYears(-1);

        // now update for file, if it's valid otherwise keep as it is
        if(date.isValid()) file.startTime.setDate(date);
    }

    files << file;
    return true;
}
Exemplo n.º 16
0
Terrain::Terrain( const QString & heightMapPath, const QVector3D & size, const QVector3D & offset, const int & smoothingPasses )
{
	QImage heightMap( heightMapPath );
	if( heightMap.isNull() )
	{
		qFatal( "\"%s\" not found!", heightMapPath.toLocal8Bit().constData() );
	}
	mMapSize = heightMap.size();
	mSize = size;
	mOffset = offset;
	mToMapFactor = QSizeF( (float)mMapSize.width()/(float)mSize.x(), (float)mMapSize.height()/(float)mSize.z() );

	mVertices.resize( mMapSize.width() * mMapSize.height() );

	// prepare positions
	QVector<QVector3D> rawPositions;
	for( int h=0; h<mMapSize.height(); h++ )
	{
		for( int w=0; w<mMapSize.width(); w++ )
		{
			rawPositions.push_back( offset + QVector3D(
				w*(mSize.x()/mMapSize.width()),
				(float)qRed( heightMap.pixel( w, h ) )*(mSize.y()/256.0),
				h*(mSize.z()/mMapSize.height())
			) );
		}
	}

	// smoothed positions
	for( int i=0; i<smoothingPasses; i++ )
		rawPositions = smoothedPositions( rawPositions, mMapSize );

	// copy smoothed positions to vertex array
	for( int i=0; i<mVertices.size(); i++ )
	{
		mVertices[i].position = rawPositions[i];
	}

	// normals
	for( int h=0; h<mMapSize.height()-1; h++ )
	{
		for( int w=0; w<mMapSize.width()-1; w++ )
		{
			vertex( w, h ).normal = QVector3D::normal(
				getVertexPosition( w,   h ),
				getVertexPosition( w,   h+1 ),
				getVertexPosition( w+1, h )
			);
		}
		vertex( mMapSize.width()-1, h ).normal = QVector3D(0,1,0);	// last vertex in row
	}
	for( int w=0; w<mMapSize.width(); w++ )
	{
		vertex( w, mMapSize.height()-1 ).normal = QVector3D(0,1,0);	// last row
	}

	// texture coordinates
	for( int h=0; h<mMapSize.height(); h++ )
	{
		for( int w=0; w<mMapSize.width(); w++ )
		{
			vertex( w, h ).texCoord = QVector2D( w, h );
		}
	}
	mVertexBuffer = QGLBuffer( QGLBuffer::VertexBuffer );
	mVertexBuffer.create();
	mVertexBuffer.bind();
	mVertexBuffer.setUsagePattern( QGLBuffer::StaticDraw );
	mVertexBuffer.allocate( mVertices.data(), mVertices.size()*VertexP3fN3fT2f::size() );
	mVertexBuffer.release();

	// indices
	QVector<unsigned int> indices;
	for( int h=0; h<mMapSize.height()-1; ++h )
	{
		for( int w=0; w<mMapSize.width(); ++w )
		{
			indices.push_back( w + h*(unsigned int)mMapSize.width() );
			indices.push_back( w + (h+1)*(unsigned int)mMapSize.width() );
		}
	}
	mIndexBuffer = QGLBuffer( QGLBuffer::IndexBuffer );
	mIndexBuffer.create();
	mIndexBuffer.bind();
	mIndexBuffer.setUsagePattern( QGLBuffer::StaticDraw );
	mIndexBuffer.allocate( indices.data(), indices.size()*sizeof(unsigned int) );
	mIndexBuffer.release();
}
Exemplo n.º 17
0
Qt::WindowFlags QXlibWindow::setWindowFlags(Qt::WindowFlags flags)
{
//    Q_ASSERT(flags & Qt::Window);
    mWindowFlags = flags;

#ifdef MYX11_DEBUG
    qDebug() << "QTestLiteWindow::setWindowFlags" << hex << x_window << "flags" << flags;
#endif
    Qt::WindowType type = static_cast<Qt::WindowType>(int(flags & Qt::WindowType_Mask));

    if (type == Qt::ToolTip)
        flags |= Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint | Qt::X11BypassWindowManagerHint;
    if (type == Qt::Popup)
        flags |= Qt::X11BypassWindowManagerHint;

    bool topLevel = (flags & Qt::Window);
    bool popup = (type == Qt::Popup);
    bool dialog = (type == Qt::Dialog
                   || type == Qt::Sheet);
    bool desktop = (type == Qt::Desktop);
    bool tool = (type == Qt::Tool || type == Qt::SplashScreen
                 || type == Qt::ToolTip || type == Qt::Drawer);

    Q_UNUSED(topLevel);
    Q_UNUSED(dialog);
    Q_UNUSED(desktop);

    bool tooltip = (type == Qt::ToolTip);

    XSetWindowAttributes wsa;

    QXlibMWMHints mwmhints;
    mwmhints.flags = 0L;
    mwmhints.functions = 0L;
    mwmhints.decorations = 0;
    mwmhints.input_mode = 0L;
    mwmhints.status = 0L;


    ulong wsa_mask = 0;
    if (type != Qt::SplashScreen) { // && customize) {
        mwmhints.flags |= MWM_HINTS_DECORATIONS;

        bool customize = flags & Qt::CustomizeWindowHint;
        if (!(flags & Qt::FramelessWindowHint) && !(customize && !(flags & Qt::WindowTitleHint))) {
            mwmhints.decorations |= MWM_DECOR_BORDER;
            mwmhints.decorations |= MWM_DECOR_RESIZEH;

            if (flags & Qt::WindowTitleHint)
                mwmhints.decorations |= MWM_DECOR_TITLE;

            if (flags & Qt::WindowSystemMenuHint)
                mwmhints.decorations |= MWM_DECOR_MENU;

            if (flags & Qt::WindowMinimizeButtonHint) {
                mwmhints.decorations |= MWM_DECOR_MINIMIZE;
                mwmhints.functions |= MWM_FUNC_MINIMIZE;
            }

            if (flags & Qt::WindowMaximizeButtonHint) {
                mwmhints.decorations |= MWM_DECOR_MAXIMIZE;
                mwmhints.functions |= MWM_FUNC_MAXIMIZE;
            }

            if (flags & Qt::WindowCloseButtonHint)
                mwmhints.functions |= MWM_FUNC_CLOSE;
        }
    } else {
        // if type == Qt::SplashScreen
        mwmhints.decorations = MWM_DECOR_ALL;
    }

    if (tool) {
        wsa.save_under = True;
        wsa_mask |= CWSaveUnder;
    }

    if (flags & Qt::X11BypassWindowManagerHint) {
        wsa.override_redirect = True;
        wsa_mask |= CWOverrideRedirect;
    }
#if 0
    if (wsa_mask && initializeWindow) {
        Q_ASSERT(id);
        XChangeWindowAttributes(dpy, id, wsa_mask, &wsa);
    }
#endif
    if (mwmhints.functions != 0) {
        mwmhints.flags |= MWM_HINTS_FUNCTIONS;
        mwmhints.functions |= MWM_FUNC_MOVE | MWM_FUNC_RESIZE;
    } else {
        mwmhints.functions = MWM_FUNC_ALL;
    }

    if (!(flags & Qt::FramelessWindowHint)
            && flags & Qt::CustomizeWindowHint
            && flags & Qt::WindowTitleHint
            && !(flags &
                 (Qt::WindowMinimizeButtonHint
                  | Qt::WindowMaximizeButtonHint
                  | Qt::WindowCloseButtonHint))) {
        // a special case - only the titlebar without any button
        mwmhints.flags = MWM_HINTS_FUNCTIONS;
        mwmhints.functions = MWM_FUNC_MOVE | MWM_FUNC_RESIZE;
        mwmhints.decorations = 0;
    }

    if (widget()->windowModality() == Qt::WindowModal) {
        mwmhints.input_mode = MWM_INPUT_PRIMARY_APPLICATION_MODAL;
    } else if (widget()->windowModality() == Qt::ApplicationModal) {
        mwmhints.input_mode = MWM_INPUT_FULL_APPLICATION_MODAL;
    }

    setMWMHints(mwmhints);

    QVector<Atom> netWmState = getNetWmState();

    if (flags & Qt::WindowStaysOnTopHint) {
        if (flags & Qt::WindowStaysOnBottomHint)
            qWarning() << "QWidget: Incompatible window flags: the window can't be on top and on bottom at the same time";
        if (!netWmState.contains(QXlibStatic::atom(QXlibStatic::_NET_WM_STATE_ABOVE)))
            netWmState.append(QXlibStatic::atom(QXlibStatic::_NET_WM_STATE_ABOVE));
        if (!netWmState.contains(QXlibStatic::atom(QXlibStatic::_NET_WM_STATE_STAYS_ON_TOP)))
            netWmState.append(QXlibStatic::atom(QXlibStatic::_NET_WM_STATE_STAYS_ON_TOP));
    } else if (flags & Qt::WindowStaysOnBottomHint) {
        if (!netWmState.contains(QXlibStatic::atom(QXlibStatic::_NET_WM_STATE_BELOW)))
            netWmState.append(QXlibStatic::atom(QXlibStatic::_NET_WM_STATE_BELOW));
    }
    if (widget()->isFullScreen()) {
        if (!netWmState.contains(QXlibStatic::atom(QXlibStatic::_NET_WM_STATE_FULLSCREEN)))
            netWmState.append(QXlibStatic::atom(QXlibStatic::_NET_WM_STATE_FULLSCREEN));
    }
    if (widget()->isMaximized()) {
        if (!netWmState.contains(QXlibStatic::atom(QXlibStatic::_NET_WM_STATE_MAXIMIZED_HORZ)))
            netWmState.append(QXlibStatic::atom(QXlibStatic::_NET_WM_STATE_MAXIMIZED_HORZ));
        if (!netWmState.contains(QXlibStatic::atom(QXlibStatic::_NET_WM_STATE_MAXIMIZED_VERT)))
            netWmState.append(QXlibStatic::atom(QXlibStatic::_NET_WM_STATE_MAXIMIZED_VERT));
    }
    if (widget()->windowModality() != Qt::NonModal) {
        if (!netWmState.contains(QXlibStatic::atom(QXlibStatic::_NET_WM_STATE_MODAL)))
            netWmState.append(QXlibStatic::atom(QXlibStatic::_NET_WM_STATE_MODAL));
    }

    if (!netWmState.isEmpty()) {
        XChangeProperty(mScreen->display()->nativeDisplay(), x_window,
                        QXlibStatic::atom(QXlibStatic::_NET_WM_STATE), XA_ATOM, 32, PropModeReplace,
                        (unsigned char *) netWmState.data(), netWmState.size());
    } else {
        XDeleteProperty(mScreen->display()->nativeDisplay(), x_window, QXlibStatic::atom(QXlibStatic::_NET_WM_STATE));
    }

//##### only if initializeWindow???

    if (popup || tooltip) {                        // popup widget
#ifdef MYX11_DEBUG
        qDebug() << "Doing XChangeWindowAttributes for popup" << wsa.override_redirect;
#endif
        // set EWMH window types
        // setNetWmWindowTypes();

        wsa.override_redirect = True;
        wsa.save_under = True;
        XChangeWindowAttributes(mScreen->display()->nativeDisplay(), x_window, CWOverrideRedirect | CWSaveUnder,
                                &wsa);
    } else {
#ifdef MYX11_DEBUG
        qDebug() << "Doing XChangeWindowAttributes for non-popup";
#endif
    }

    return flags;
}
Exemplo n.º 18
0
void Column::calculateStatistics() {
    m_column_private->statistics = ColumnStatistics();
	ColumnStatistics& statistics = m_column_private->statistics;

    QVector<double>* rowValues = reinterpret_cast<QVector<double>*>(data());

    int notNanCount = 0;
    double val;
    double columnSum = 0.0;
    double columnProduct = 1.0;
    double columnSumNeg = 0.0;
    double columnSumSquare = 0.0;
    statistics.minimum = INFINITY;
    statistics.maximum = -INFINITY;
    QMap<double, int> frequencyOfValues;
    QVector<double> rowData;
    rowData.reserve(rowValues->size());
    for (int row = 0; row < rowValues->size(); ++row) {
        val = rowValues->value(row);
        if (std::isnan(val) || isMasked(row))
            continue;

        if (val < statistics.minimum){
            statistics.minimum = val;
        }
        if (val > statistics.maximum){
            statistics.maximum = val;
        }
        columnSum+= val;
        columnSumNeg += (1.0 / val);
        columnSumSquare += pow(val, 2.0);
        columnProduct *= val;
        if (frequencyOfValues.contains(val)){
            frequencyOfValues.operator [](val)++;
        }
        else{
            frequencyOfValues.insert(val, 1);
        }
        ++notNanCount;
        rowData.push_back(val);
    }

    if (notNanCount == 0) {
		setStatisticsAvailable(true);
		return;
	}

    if (rowData.size() < rowValues->size()){
        rowData.squeeze();
    }

    statistics.arithmeticMean = columnSum / notNanCount;
    statistics.geometricMean = pow(columnProduct, 1.0 / notNanCount);
    statistics.harmonicMean = notNanCount / columnSumNeg;
    statistics.contraharmonicMean = columnSumSquare / columnSum;

    double columnSumVariance = 0;
    double columnSumMeanDeviation = 0.0;
    double columnSumMedianDeviation = 0.0;
    double sumForCentralMoment_r3 = 0.0;
    double sumForCentralMoment_r4 = 0.0;

    gsl_sort(rowData.data(), 1, notNanCount);
    statistics.median = (notNanCount % 2 ? rowData.at((notNanCount-1)/2) :
                                             (rowData.at((notNanCount-1)/2) +
                                              rowData.at(notNanCount/2))/2.0);
    QVector<double> absoluteMedianList;
    absoluteMedianList.reserve(notNanCount);
    absoluteMedianList.resize(notNanCount);

    int idx = 0;
    for(int row = 0; row < rowValues->size(); ++row){
        val = rowValues->value(row);
        if ( std::isnan(val) || isMasked(row) )
            continue;
        columnSumVariance+= pow(val - statistics.arithmeticMean, 2.0);

        sumForCentralMoment_r3 += pow(val - statistics.arithmeticMean, 3.0);
        sumForCentralMoment_r4 += pow(val - statistics.arithmeticMean, 4.0);
        columnSumMeanDeviation += fabs( val - statistics.arithmeticMean );

        absoluteMedianList[idx] = fabs(val - statistics.median);
        columnSumMedianDeviation += absoluteMedianList[idx];
        idx++;
    }

    statistics.meanDeviationAroundMedian = columnSumMedianDeviation / notNanCount;
    statistics.medianDeviation = (notNanCount % 2 ? absoluteMedianList.at((notNanCount-1)/2) :
                                                      (absoluteMedianList.at((notNanCount-1)/2) + absoluteMedianList.at(notNanCount/2))/2.0);

    const double centralMoment_r3 = sumForCentralMoment_r3 / notNanCount;
    const double centralMoment_r4 = sumForCentralMoment_r4 / notNanCount;

    statistics.variance = columnSumVariance / notNanCount;
    statistics.standardDeviation = sqrt(statistics.variance);
    statistics.skewness = centralMoment_r3 / pow(statistics.standardDeviation, 3.0);
    statistics.kurtosis = (centralMoment_r4 / pow(statistics.standardDeviation, 4.0)) - 3.0;
    statistics.meanDeviation = columnSumMeanDeviation / notNanCount;

    double entropy = 0.0;
    QList<int> frequencyOfValuesValues = frequencyOfValues.values();
    for (int i = 0; i < frequencyOfValuesValues.size(); ++i){
        double frequencyNorm = static_cast<double>(frequencyOfValuesValues.at(i)) / notNanCount;
        entropy += (frequencyNorm * log2(frequencyNorm));
    }

    statistics.entropy = -entropy;
    setStatisticsAvailable(true);
}
bool AM1DRunningAverageFilterAB::values(const AMnDIndex &indexStart, const AMnDIndex &indexEnd, double *outputValues) const
{
	if(indexStart.rank() != 1 || indexEnd.rank() != 1)
		return false;

	if(!isValid())
		return false;

#ifdef AM_ENABLE_BOUNDS_CHECKING
	if((unsigned)indexEnd.i() >= (unsigned)axes_.at(0).size || (unsigned)indexStart.i() > (unsigned)indexEnd.i())
		return false;
#endif

	int totalSize = indexStart.totalPointsTo(indexEnd);

	QVector<double> data = QVector<double>(totalSize);
	inputSource_->values(indexStart, indexEnd, data.data());

	int numberOfPoints = (filterSize_-1)/2;
	double average = 0;
	int tempNumberOfPoints = 1;

	// If the filter size is bigger then the total size of the data then we will just check every point along the way.
	if (numberOfPoints > totalSize){

		for (int i = 0; i < totalSize; i++){

			average = data.at(i);
			tempNumberOfPoints = 1;

			for (int j = 1; j < numberOfPoints; j++){

				if ((i-j) >= 0){

					average += data.at(i-j);
					tempNumberOfPoints++;
				}

				if ((i+j) < totalSize){

					average += data.at(i+j);
					tempNumberOfPoints++;
				}
			}

			outputValues[i] = average/double(tempNumberOfPoints);
		}
	}

	// Otherwise, we can optimize the middle indices of the without having to check if we will be accessing data outside of the array range.
	else {

		// Compute the beginning values.
		for (int i = 0; i < numberOfPoints; i++){

			average = data.at(i);
			tempNumberOfPoints = 1;

			// Only need the substraction check at the beginning.
			for (int j = 1; j < numberOfPoints; j++){

				if ((i-j) >= 0){

					average += data.at(i-j);
					tempNumberOfPoints++;
				}

				average += data.at(i+j);
				tempNumberOfPoints++;
			}

			outputValues[i] = average/double(tempNumberOfPoints);
		}

		// No need for conditionals in the middle of the data.
		double averagePoints = double(numberOfPoints);

		for (int i = numberOfPoints, count = totalSize-numberOfPoints; i < count; i++){

			average = data.at(i);

			for (int j = 1; j < numberOfPoints; j++)
				average += data.at(i-j) + data.at(i+j);

			outputValues[i] = average/averagePoints;
		}

		// Compute the last values.
		for (int i = totalSize-numberOfPoints; i < totalSize; i++){

			average = data.at(i);
			tempNumberOfPoints = 1;

			// Only need the addition check at the end.
			for (int j = 1; j < numberOfPoints; j++){

				average += data.at(i-j);
				tempNumberOfPoints++;

				if ((i+j) < totalSize){

					average += data.at(i+j);
					tempNumberOfPoints++;
				}
			}

			outputValues[i] = average/double(tempNumberOfPoints);
		}
	}

	return true;
}
Exemplo n.º 20
0
void QXcbNativeBackingStore::flush(QWindow *window, const QRegion &region, const QPoint &offset)
{
    if (m_pixmap.isNull())
        return;

    QSize pixmapSize = m_pixmap.size();

    QRegion clipped = region;
    clipped &= QRect(QPoint(), QHighDpi::toNativePixels(window->size(), window));
    clipped &= QRect(0, 0, pixmapSize.width(), pixmapSize.height()).translated(-offset);

    QRect br = clipped.boundingRect();
    if (br.isNull())
        return;

    QXcbWindow *platformWindow = static_cast<QXcbWindow *>(window->handle());
    if (!platformWindow) {
        qWarning("QXcbBackingStore::flush: QWindow has no platform window (QTBUG-32681)");
        return;
    }

    Window wid = platformWindow->xcb_window();
    Pixmap pid = qt_x11PixmapHandle(m_pixmap);

    QVector<XRectangle> clipRects = qt_region_to_xrectangles(clipped);

#if QT_CONFIG(xrender)
    if (m_translucentBackground)
    {
        XWindowAttributes attrib;
        XGetWindowAttributes(display(), wid, &attrib);
        XRenderPictFormat *format = XRenderFindVisualFormat(display(), attrib.visual);

        Picture srcPic = qt_x11PictureHandle(m_pixmap);
        Picture dstPic = XRenderCreatePicture(display(), wid, format, 0, 0);

        XRenderSetPictureClipRectangles(display(), dstPic, 0, 0, clipRects.constData(), clipRects.size());

        XRenderComposite(display(), PictOpSrc, srcPic, None, dstPic,
                         br.x() + offset.x(), br.y() + offset.y(),
                         0, 0,
                         br.x(), br.y(),
                         br.width(), br.height());

        XRenderFreePicture(display(), dstPic);
    }
    else
#endif
    {
        GC gc = XCreateGC(display(), wid, 0, Q_NULLPTR);

        if (clipRects.size() != 1)
            XSetClipRectangles(display(), gc, 0, 0, clipRects.data(), clipRects.size(), YXBanded);

        XCopyArea(display(), pid, wid, gc, br.x() + offset.x(), br.y() + offset.y(), br.width(), br.height(), br.x(), br.y());
        XFreeGC(display(), gc);
    }


    if (platformWindow->needsSync()) {
        platformWindow->updateSyncRequestCounter();
    } else {
        XFlush(display());
    }
}
Exemplo n.º 21
0
bool HwAccX11Trait<IMGFMT_VAAPI>::createSurfaces(int width, int height, int format, QVector<SurfaceID> &ids) {
	return VaApiStatusChecker().isSuccess(vaCreateSurfaces(VaApi::glx(), width, height, format, ids.size(), ids.data()));
}
Exemplo n.º 22
0
static GEOSGeometry *LWGEOM_GEOS_makeValidMultiLine( const GEOSGeometry *gin, QString &errorMessage )
{
  GEOSContextHandle_t handle = QgsGeos::getGEOSHandler();

  int ngeoms = GEOSGetNumGeometries_r( handle, gin );
  uint32_t nlines_alloc = ngeoms;
  QVector<GEOSGeometry *> lines;
  QVector<GEOSGeometry *> points( ngeoms );
  lines.reserve( nlines_alloc );
  points.reserve( ngeoms );

  for ( int i = 0; i < ngeoms; ++i )
  {
    const GEOSGeometry *g = GEOSGetGeometryN_r( handle, gin, i );
    GEOSGeometry *vg = LWGEOM_GEOS_makeValidLine( g, errorMessage );
    if ( GEOSisEmpty_r( handle, vg ) )
    {
      // we don't care about this one
      GEOSGeom_destroy_r( handle, vg );
    }
    if ( GEOSGeomTypeId_r( handle, vg ) == GEOS_POINT )
    {
      points.append( vg );
    }
    else if ( GEOSGeomTypeId_r( handle, vg ) == GEOS_LINESTRING )
    {
      lines.append( vg );
    }
    else if ( GEOSGeomTypeId_r( handle, vg ) == GEOS_MULTILINESTRING )
    {
      int nsubgeoms = GEOSGetNumGeometries_r( handle, vg );
      nlines_alloc += nsubgeoms;
      lines.reserve( nlines_alloc );
      for ( int j = 0; j < nsubgeoms; ++j )
      {
        // NOTE: ownership of the cloned geoms will be taken by final collection
        lines.append( GEOSGeom_clone_r( handle, GEOSGetGeometryN_r( handle, vg, j ) ) );
      }
    }
    else
    {
      // NOTE: return from GEOSGeomType will leak but we really don't expect this to happen
      errorMessage = QString( "unexpected geom type returned by LWGEOM_GEOS_makeValid: %1" ).arg( GEOSGeomTypeId_r( handle, vg ) );
    }
  }

  GEOSGeometry *mpoint_out = nullptr;
  if ( points.count() )
  {
    if ( points.count() > 1 )
    {
      mpoint_out = GEOSGeom_createCollection_r( handle, GEOS_MULTIPOINT, points.data(), points.count() );
    }
    else
    {
      mpoint_out = points[0];
    }
  }

  GEOSGeometry *mline_out = nullptr;
  if ( lines.count() )
  {
    if ( lines.count() > 1 )
    {
      mline_out = GEOSGeom_createCollection_r( handle, GEOS_MULTILINESTRING, lines.data(), lines.count() );
    }
    else
    {
      mline_out = lines[0];
    }
  }

  if ( mline_out && mpoint_out )
  {
    GEOSGeometry *collection[2];
    collection[0] = mline_out;
    collection[1] = mpoint_out;
    return GEOSGeom_createCollection_r( handle, GEOS_GEOMETRYCOLLECTION, collection, 2 );
  }
  else if ( mline_out )
  {
    return mline_out;
  }
  else if ( mpoint_out )
  {
    return mpoint_out;
  }
  else
  {
    return nullptr;
  }
}
Exemplo n.º 23
0
 const double * dashes(int *n) const {
   *n = dashPattern.size();
   return dashPattern.data();
 }
Exemplo n.º 24
0
void CharSelect::slot_insertSpecialChars(const QVector<uint> & chars)
{
	chToIns = QString::fromUcs4(chars.data(), chars.length());
	slot_insertSpecialChar();
}
Exemplo n.º 25
0
void
PowerHist::recalc(bool force)
{
    QVector<unsigned int> *array = NULL;
    QVector<unsigned int> *selectedArray = NULL;
    int arrayLength = 0;
    double delta = 0;

    // lets make sure we need to recalculate
    if (force == false &&
        LASTsource == source &&
        LASTcache == cache &&
        LASTrideItem == rideItem &&
        LASTseries == series &&
        LASTshade == shade &&
        LASTuseMetricUnits == mainWindow->useMetricUnits &&
        LASTlny == lny &&
        LASTzoned == zoned &&
        LASTbinw == binw &&
        LASTwithz == withz &&
        LASTdt == dt &&
        LASTabsolutetime == absolutetime) {
        return; // nothing has changed

    } else {

        // remember for next time
        LASTsource = source;
        LASTcache = cache;
        LASTrideItem = rideItem;
        LASTseries = series;
        LASTshade = shade;
        LASTuseMetricUnits = mainWindow->useMetricUnits;
        LASTlny = lny;
        LASTzoned = zoned;
        LASTbinw = binw;
        LASTwithz = withz;
        LASTdt = dt;
        LASTabsolutetime = absolutetime;
    }


    if (source == Ride && !rideItem) return;

    // make sure the interval length is set
    if (dt <= 0) return;

    if (series == RideFile::watts && zoned == false) {

        array = &wattsArray;
        delta = wattsDelta;
        arrayLength = wattsArray.size();
        selectedArray = &wattsSelectedArray;

    } else if ((series == RideFile::watts || series == RideFile::wattsKg) && zoned == true) {

        array = &wattsZoneArray;
        delta = 1;
        arrayLength = wattsZoneArray.size();
        selectedArray = &wattsZoneSelectedArray;

    } else if (series == RideFile::wattsKg && zoned == false) {

        array = &wattsKgArray;
        delta = wattsKgDelta;
        arrayLength = wattsKgArray.size();
        selectedArray = &wattsKgSelectedArray;

    } else if (series == RideFile::nm) {

        array = &nmArray;
        delta = nmDelta;
        arrayLength = nmArray.size();
        selectedArray = &nmSelectedArray;

    } else if (series == RideFile::hr && zoned == false) {

        array = &hrArray;
        delta = hrDelta;
        arrayLength = hrArray.size();
        selectedArray = &hrSelectedArray;

    } else if (series == RideFile::hr && zoned == true) {

        array = &hrZoneArray;
        delta = 1;
        arrayLength = hrZoneArray.size();
        selectedArray = &hrZoneSelectedArray;

    } else if (series == RideFile::kph) {

        array = &kphArray;
        delta = kphDelta;
        arrayLength = kphArray.size();
        selectedArray = &kphSelectedArray;

    } else if (series == RideFile::cad) {
        array = &cadArray;
        delta = cadDelta;
        arrayLength = cadArray.size();
        selectedArray = &cadSelectedArray;
    }

    RideFile::SeriesType baseSeries = (series == RideFile::wattsKg) ? RideFile::watts : series;

    // null curve please -- we have no data!
    if (!array || arrayLength == 0 || (source == Ride && !rideItem->ride()->isDataPresent(baseSeries))) {
        // create empty curves when no data
        const double zero = 0;
        curve->setData(&zero, &zero, 0);
        curveSelected->setData(&zero, &zero, 0);
        updatePlot();
        return;
    }

    // binning of data when not zoned - we can't zone for series besides
    // watts and hr so ignore zoning for those data series
    if (zoned == false || (zoned == true && (series != RideFile::watts && series != RideFile::wattsKg && series != RideFile::hr))) {

        // we add a bin on the end since the last "incomplete" bin
        // will be dropped otherwise
        int count = int(ceil((arrayLength - 1) / (binw)))+1;

        // allocate space for data, plus beginning and ending point
        QVector<double> parameterValue(count+2, 0.0);
        QVector<double> totalTime(count+2, 0.0);
        QVector<double> totalTimeSelected(count+2, 0.0);
        int i;
        for (i = 1; i <= count; ++i) {
            double high = i * round(binw/delta);
            double low = high - round(binw/delta);
            if (low==0 && !withz) low++;
            parameterValue[i] = high*delta;
            totalTime[i]  = 1e-9;  // nonzero to accomodate log plot
            totalTimeSelected[i] = 1e-9;  // nonzero to accomodate log plot
            while (low < high && low<arrayLength) {
                if (selectedArray && (*selectedArray).size()>low)
                    totalTimeSelected[i] += dt * (*selectedArray)[low];
                totalTime[i] += dt * (*array)[low++];
            }
        }
        totalTime[i] = 1e-9;       // nonzero to accomodate log plot
        totalTimeSelected[i] = 1e-9;       // nonzero to accomodate log plot
        parameterValue[i] = i * delta * binw;
        totalTime[0] = 1e-9;
        totalTimeSelected[0] = 1e-9;
        parameterValue[0] = 0;

        // convert vectors from absolute time to percentage
        // if the user has selected that
        if (!absolutetime) {
            percentify(totalTime, 1);
            percentify(totalTimeSelected, 1);
        }

        curve->setData(parameterValue.data(), totalTime.data(), count + 2);
        curveSelected->setData(parameterValue.data(), totalTimeSelected.data(), count + 2);

        QwtScaleDraw *sd = new QwtScaleDraw;
        sd->setTickLength(QwtScaleDiv::MajorTick, 3);
        setAxisScaleDraw(QwtPlot::xBottom, sd);

        // HR typically starts at 80 or so, rather than zero
        // lets crop the chart so we can focus on the data
        // if we're working with HR data...
        minX=0;
        if (!withz && series == RideFile::hr) {
            for (int i=1; i<hrArray.size(); i++) {
                if (hrArray[i] > 0.1) {
                    minX = i;
                    break;
                }
            }
        }
        setAxisScale(xBottom, minX, parameterValue[count + 1]);

        // we only do zone labels when using absolute values
        refreshZoneLabels();
        refreshHRZoneLabels();

    } else {

        // we're not binning instead we are prettyfing the columnar
        // display in much the same way as the weekly summary workds
        // Each zone column will have 4 points
        QVector<double> xaxis (array->size() * 4);
        QVector<double> yaxis (array->size() * 4);
        QVector<double> selectedxaxis (selectedArray->size() * 4);
        QVector<double> selectedyaxis (selectedArray->size() * 4);

        // samples to time
        for (int i=0, offset=0; i<array->size(); i++) {

            double x = (double) i - 0.5;
            double y = dt * (double)(*array)[i];

            xaxis[offset] = x +0.05;
            yaxis[offset] = 0;
            offset++;
            xaxis[offset] = x+0.05;
            yaxis[offset] = y;
            offset++;
            xaxis[offset] = x+0.95;
            yaxis[offset] = y;
            offset++;
            xaxis[offset] = x +0.95;
            yaxis[offset] = 0;
            offset++;
        }

        for (int i=0, offset=0; i<selectedArray->size(); i++) {
            double x = (double)i - 0.5;
            double y = dt * (double)(*selectedArray)[i];

            selectedxaxis[offset] = x +0.05;
            selectedyaxis[offset] = 0;
            offset++;
            selectedxaxis[offset] = x+0.05;
            selectedyaxis[offset] = y;
            offset++;
            selectedxaxis[offset] = x+0.95;
            selectedyaxis[offset] = y;
            offset++;
            selectedxaxis[offset] = x +0.95;
            selectedyaxis[offset] = 0;
            offset++;
        }

        if (!absolutetime) {
            percentify(yaxis, 2);
            percentify(selectedyaxis, 2);
        }

        // set those curves
        curve->setData(xaxis.data(), yaxis.data(), xaxis.size());
        curveSelected->setData(selectedxaxis.data(), selectedyaxis.data(), selectedxaxis.size());

        // zone scale draw
        if ((series == RideFile::watts || series == RideFile::wattsKg) && zoned && rideItem && rideItem->zones) {
            setAxisScaleDraw(QwtPlot::xBottom, new ZoneScaleDraw(rideItem->zones, rideItem->zoneRange()));
            if (rideItem->zoneRange() >= 0)
                setAxisScale(QwtPlot::xBottom, -0.99, rideItem->zones->numZones(rideItem->zoneRange()), 1);
            else
                setAxisScale(QwtPlot::xBottom, -0.99, 0, 1);
        }

        // hr scale draw
        int hrRange;
        if (series == RideFile::hr && zoned && rideItem && mainWindow->hrZones() &&
            (hrRange=mainWindow->hrZones()->whichRange(rideItem->dateTime.date())) != -1) {
            setAxisScaleDraw(QwtPlot::xBottom, new HrZoneScaleDraw(mainWindow->hrZones(), hrRange));

            if (hrRange >= 0)
                setAxisScale(QwtPlot::xBottom, -0.99, mainWindow->hrZones()->numZones(hrRange), 1);
            else
                setAxisScale(QwtPlot::xBottom, -0.99, 0, 1);
        }

        // watts zoned for a time range
        if (source == Cache && zoned && (series == RideFile::watts || series == RideFile::wattsKg) && mainWindow->zones()) {
            setAxisScaleDraw(QwtPlot::xBottom, new ZoneScaleDraw(mainWindow->zones(), 0));
            if (mainWindow->zones()->getRangeSize())
                setAxisScale(QwtPlot::xBottom, -0.99, mainWindow->zones()->numZones(0), 1); // XXX use zones from first defined range
        }

        // hr zoned for a time range
        if (source == Cache && zoned && series == RideFile::hr && mainWindow->hrZones()) {
            setAxisScaleDraw(QwtPlot::xBottom, new HrZoneScaleDraw(mainWindow->hrZones(), 0));
            if (mainWindow->hrZones()->getRangeSize())
                setAxisScale(QwtPlot::xBottom, -0.99, mainWindow->hrZones()->numZones(0), 1); // XXX use zones from first defined range
        }

        setAxisMaxMinor(QwtPlot::xBottom, 0);
    }

    setYMax();
    configChanged(); // setup the curve colors to appropriate values
    updatePlot();
}
Exemplo n.º 26
0
// Initialize all your OpenGL objects here
void MainWindow::initialize()
{
    // Initialize important variables and the MVP matrices
    mouseClick = QPoint(0,0);
    eye = QVector3D(0,0,-4);
    center = QVector3D(0,0,0) ;
    up = QVector3D(0,1,0);
    FoV = 60;
    model.setToIdentity();
    view.lookAt(eye, center, up);
    calculateProjection();

    qDebug() << "MainWindow::initialize()";
    QString glVersion;
    glVersion = reinterpret_cast<const char*>(glGetString(GL_VERSION));
    qDebug() << "Using OpenGL" << qPrintable(glVersion);

    // Initialize the shaders
    m_shaderProgram = new QOpenGLShaderProgram(this);
    // Use the ":" to load from the resources files (i.e. from the resources.qrc)
    m_shaderProgram->addShaderFromSourceFile(QOpenGLShader::Vertex, ":/shaders/vertex.glsl");
    m_shaderProgram->addShaderFromSourceFile(QOpenGLShader::Fragment, ":/shaders/fragment.glsl");
    m_shaderProgram->link();


    // Shaders are initialized
    // You can retrieve the locations of the uniforms from here


    // Initialize your objects and buffers
    QVector<QVector3D> objectVectors;
    QVector<QVector3D> generatedColors;

    OBJModel cube = OBJModel(":/models/cube.obj");

    objectVectors = cube.vertices;
    vectorsNumber = objectVectors.length();

    // Calculate the random colours using the color seed
    for(int i = 0; i < vectorsNumber/3; i++){
        float colorArray[3] = {0,0,0};
        for(unsigned int j = 0; j < 3; j++){
            srand(COLOR_SEED*(j+1)*(i+1));
            colorArray[j] = ((double)rand()/RAND_MAX);
        }
        printf("color %d, %f %f %f\n", i, colorArray[0],colorArray[1],colorArray[2] );
        generatedColors.append(QVector3D(colorArray[0], colorArray[1], colorArray[2]));
        generatedColors.append(QVector3D(colorArray[0], colorArray[1], colorArray[2]));
        generatedColors.append(QVector3D(colorArray[0], colorArray[1], colorArray[2]));
    }

    // generate VAO and bind it
    m_funcs->glGenVertexArrays(1, &VAO);
    m_funcs->glBindVertexArray(VAO);

    // generate color and vertice buffers
    m_funcs->glGenBuffers(1, &vertices);
    m_funcs->glGenBuffers(1, &colors);

    // bind vertice buffer and fill it with the vertices
    m_funcs->glBindBuffer(GL_ARRAY_BUFFER, vertices);
    m_funcs->glBufferData(GL_ARRAY_BUFFER, sizeof(QVector3D) * objectVectors.length(),objectVectors.data(), GL_STATIC_DRAW);

    m_funcs->glEnableVertexAttribArray(0);
    m_funcs->glVertexAttribPointer(0,3, GL_FLOAT, GL_FALSE, 0,0);

    // Bind color buffer, fill it with the generated colors
    m_funcs->glBindBuffer(GL_ARRAY_BUFFER, colors);
    m_funcs->glBufferData(GL_ARRAY_BUFFER, sizeof(QVector3D) * generatedColors.length(), generatedColors.data(), GL_STATIC_DRAW);

    m_funcs->glEnableVertexAttribArray(1);
    m_funcs->glVertexAttribPointer(1,3, GL_FLOAT, GL_FALSE, 0,0);

    // Create your Vertex Array Object (VAO) and Vertex Buffer Objects (VBO) here.



    // Set OpenGL to use Filled triangles (can be used to render points, or lines)
    m_funcs->glPolygonMode( GL_FRONT_AND_BACK, GL_FILL );

    // Enable Z-buffering
    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LESS);
    qDebug() << "Depth Buffer size:" <<  this->format().depthBufferSize() << "bits";

    // Function for culling, removing faces which don't face the camera
    //glEnable(GL_CULL_FACE);
    //glCullFace(GL_BACK);

    // Set the clear color to be black (color used for resetting the screen)
    glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
}
Exemplo n.º 27
0
void MagnitudeNode::onContextProcess( qint64 pTimeStamp )
{
	const int		SampleCount = variant( mPinSampleCount ).toInt();

	if( SampleCount <= 0 )
	{
		return;
	}

	if( mProducerInstance && !mProducerInstance->isValid() )
	{
		delete mProducerInstance;

		mProducerInstance = nullptr;
	}

	fugio::AudioProducerInterface	*API = input<fugio::AudioProducerInterface *>( mPinAudio );

	if( !API )
	{
		if( mProducerInstance )
		{
			delete mProducerInstance;

			mProducerInstance = nullptr;

			mSamplePosition = 0;
		}

		return;
	}

	if( !mProducerInstance )
	{
		mProducerInstance = API->audioAllocInstance( 48000, fugio::AudioSampleFormat::Format32FS, 1 );
	}

	if( !mProducerInstance )
	{
		return;
	}

	qint64	CurPos = ( pTimeStamp - API->audioLatency() ) * ( 48000 / 1000 );

	if( !mSamplePosition )
	{
		mSamplePosition = CurPos;
	}

	if( CurPos - mSamplePosition >= SampleCount )
	{
		int			ChannelCount = 1;

		mAudDat.resize( ChannelCount );

		for( auto &V : mAudDat )
		{
			V.resize( SampleCount );
		}

		QVector<float *>	AudPtr;

		AudPtr.resize( ChannelCount );

		for( int i = 0 ; i < ChannelCount ; i++ )
		{
			AudPtr[ i ] = mAudDat[ i ].data();

			memset( AudPtr[ i ], 0, sizeof( float ) * SampleCount );
		}

		mProducerInstance->audio( mSamplePosition, SampleCount, 0, 1, (void **)AudPtr.data() );

		float		Mag = 0;

		for( int c = 0 ; c < ChannelCount ; c++ )
		{
			float	*S = AudPtr[ c ];

			for( int i = 0 ; i < SampleCount ; i++, S++ )
			{
				float	M = fabs( *S );

				if( M > Mag )
				{
					Mag = M;
				}
			}
		}

		mMagnitude = Mag;

		mSamplePosition += SampleCount;
	}

	if( mMagnitude != mValOutput->variant().toFloat() )
	{
		mValOutput->setVariant( mMagnitude );

		pinUpdated( mPinOutput );
	}
}
Exemplo n.º 28
0
void ProspectiveTokenizer::tokenize(const TokenizerString& source)
{
    assert(m_inProgress);
    
    m_source.append(source);

    // This is a simplified HTML5 Tokenizer
    // http://www.whatwg.org/specs/web-apps/current-work/#tokenisation0
    while (!m_source.isEmpty()) {
        ushort cc = m_source->unicode();
        switch (m_state) {
        case Data:
            while (1) {
                rememberCharacter(cc);
                if (cc == '&') {
                    if (m_contentModel == PCDATA || m_contentModel == RCDATA) {
                        m_state = EntityData;
                        break;
                    }
                } else if (cc == '-') {
                    if ((m_contentModel == RCDATA || m_contentModel == CDATA) && !m_escape) {
                        if (lastCharactersMatch("<!--", 4))
                            m_escape = true;
                    }
                } else if (cc == '<') {
                    if (m_contentModel == PCDATA || ((m_contentModel == RCDATA || m_contentModel == CDATA) && !m_escape)) {
                        m_state = TagOpen;
                        break;
                    }
                } else if (cc == '>') {
                     if ((m_contentModel == RCDATA || m_contentModel == CDATA) && m_escape) {
                         if (lastCharactersMatch("-->", 3))
                             m_escape = false;
                     }
                }
                emitCharacter(cc);
                m_source.advance();
                if (m_source.isEmpty())
                     return;
                cc = m_source->unicode();
            }
            break;
        case EntityData:
            // should try to consume the entity but we only care about entities in attributes
            m_state = Data;
            break;
        case TagOpen:
            if (m_contentModel == RCDATA || m_contentModel == CDATA) {
                if (cc == '/')
                    m_state = CloseTagOpen;
                else {
                    m_state = Data;
                    continue;
                }
            } else if (m_contentModel == PCDATA) {
                if (cc == '!')
                    m_state = MarkupDeclarationOpen;
                else if (cc == '/')
                    m_state = CloseTagOpen;
                else if (cc >= 'A' && cc <= 'Z') {
                    m_tagName.clear();
                    m_tagName.append(cc + 0x20);
                    m_closeTag = false;
                    m_state = TagName;
                } else if (cc >= 'a' && cc <= 'z') {
                    m_tagName.clear();
                    m_tagName.append(cc);
                    m_closeTag = false;
                    m_state = TagName;
                } else if (cc == '>') {
                    m_state = Data;
                } else if (cc == '?') {
                    m_state = BogusComment;
                } else {
                    m_state = Data;
                    continue;
                }
            }
            break;
        case CloseTagOpen:
            if (m_contentModel == RCDATA || m_contentModel == CDATA) {
                if (!m_lastStartTag.size()) {
                    m_state = Data;
                    continue;
                }
                if ((unsigned)m_source.length() < m_lastStartTag.size() + 1)
                    return;
                QVector<QChar> tmpString;
                QChar tmpChar = 0;
                bool match = true;
                for (unsigned n = 0; n < m_lastStartTag.size() + 1; n++) {
                    tmpChar = m_source->toLower();
                    if (n < m_lastStartTag.size() && tmpChar != m_lastStartTag[n])
                        match = false;
                    tmpString.append(tmpChar);
                    m_source.advance();
                }
                m_source.prepend(TokenizerString(QString(tmpString.data(), tmpString.size())));
                if (!match || (!isWhitespace(tmpChar) && tmpChar != '>' && tmpChar != '/')) {
                    m_state = Data;
                    continue;
                }
            }
            if (cc >= 'A' && cc <= 'Z') {
                m_tagName.clear();
                m_tagName.append(cc + 0x20);
                m_closeTag = true;
                m_state = TagName;
            } else if (cc >= 'a' && cc <= 'z') {
                m_tagName.clear();
                m_tagName.append(cc);
                m_closeTag = true;
                m_state = TagName;
            } else if (cc == '>') {
                m_state = Data;
            } else
                m_state = BogusComment;
            break;
        case TagName:
            while (1) {
                if (isWhitespace(cc)) {
                    m_state = BeforeAttributeName;
                    break;
                }
                if (cc == '>') {
                    emitTag();
                    m_state = Data;
                    break;
                }
                if (cc == '/') {
                    m_state = BeforeAttributeName;
                    break;
                }
                if (cc >= 'A' && cc <= 'Z')
                    m_tagName.append(cc + 0x20);
                else
                    m_tagName.append(cc);
                m_source.advance();
                if (m_source.isEmpty())
                    return;
                cc = m_source->unicode();
            }
            break;
        case BeforeAttributeName:
            if (isWhitespace(cc))
                ;
            else if (cc == '>') {
                emitTag();
                m_state = Data;
            } else if (cc >= 'A' && cc <= 'Z') {
                m_attributeName.clear();
                m_attributeValue.clear();
                m_attributeName.append(cc + 0x20);
                m_state = AttributeName;
            } else if (cc == '/')
                ;
            else {
                m_attributeName.clear();
                m_attributeValue.clear();
                m_attributeName.append(cc);
                m_state = AttributeName;
            }
            break;
        case AttributeName:
            while (1) {
                if (isWhitespace(cc)) {
                    m_state = AfterAttributeName;
                    break;
                }
                if (cc == '=') {
                    m_state = BeforeAttributeValue;
                    break;
                }
                if (cc == '>') {
                    emitTag();
                    m_state = Data;
                    break;
                } 
                if (cc == '/') {
                    m_state = BeforeAttributeName;
                    break;
                }
                if (cc >= 'A' && cc <= 'Z')
                    m_attributeName.append(cc + 0x20);
                else
                    m_attributeName.append(cc);
                m_source.advance();
                if (m_source.isEmpty())
                    return;
                cc = m_source->unicode();
            }
            break;
        case AfterAttributeName:
            if (isWhitespace(cc))
                ;
            else if (cc == '=')
                m_state = BeforeAttributeValue; 
            else if (cc == '>') {
                emitTag();
                m_state = Data;
            } else if (cc >= 'A' && cc <= 'Z') {
                m_attributeName.clear();
                m_attributeValue.clear();
                m_attributeName.append(cc + 0x20);
                m_state = AttributeName;
            } else if (cc == '/')
                m_state = BeforeAttributeName;
            else {
                m_attributeName.clear();
                m_attributeValue.clear();
                m_attributeName.append(cc);
                m_state = AttributeName;
            }
            break;
        case BeforeAttributeValue:
            if (isWhitespace(cc))
                ;
            else if (cc == '"')
                m_state = AttributeValueDoubleQuoted;
            else if (cc == '&') {
                m_state = AttributeValueUnquoted;
                continue;
            } else if (cc == '\'')
                m_state = AttributeValueSingleQuoted;
            else if (cc == '>') {
                emitTag();
                m_state = Data;
            } else {
                m_attributeValue.append(cc);
                m_state = AttributeValueUnquoted;
            }
            break;
        case AttributeValueDoubleQuoted:
            while (1) {
                if (cc == '"') {
                    processAttribute();
                    m_state = BeforeAttributeName;
                    break;
                }
                if (cc == '&') {
                    m_stateBeforeEntityInAttributeValue = m_state;
                    m_state = EntityInAttributeValue;
                    break;
                } 
                m_attributeValue.append(cc);
                m_source.advance();
                if (m_source.isEmpty())
                    return;
                cc = m_source->unicode();
            }
            break;
        case AttributeValueSingleQuoted:
            while (1) {
                if (cc == '\'') {
                    processAttribute();
                    m_state = BeforeAttributeName;
                    break;
                }
                if (cc == '&') {
                    m_stateBeforeEntityInAttributeValue = m_state;
                    m_state = EntityInAttributeValue;
                    break;
                } 
                m_attributeValue.append(cc);
                m_source.advance();
                if (m_source.isEmpty())
                    return;
                cc = m_source->unicode();
            }
            break;
        case AttributeValueUnquoted:
            while (1) {
                if (isWhitespace(cc)) {
                    processAttribute();
                    m_state = BeforeAttributeName;
                    break;
                }
                if (cc == '&') {
                    m_stateBeforeEntityInAttributeValue = m_state;
                    m_state = EntityInAttributeValue;
                    break;
                }
                if (cc == '>') {
                    processAttribute();
                    emitTag();
                    m_state = Data;
                    break;
                }
                m_attributeValue.append(cc);
                m_source.advance();
                if (m_source.isEmpty())
                    return;
                cc = m_source->unicode();
            }
            break;
        case EntityInAttributeValue: 
            {
                bool notEnoughCharacters = false; 
                unsigned entity = consumeEntity(m_source, notEnoughCharacters);
                if (notEnoughCharacters)
                    return;
                if (entity > 0xFFFF) {
                    m_attributeValue.append(U16_LEAD(entity));
                    m_attributeValue.append(U16_TRAIL(entity));
                } else if (entity)
                    m_attributeValue.append(entity);
                else
                    m_attributeValue.append('&');
            }
            m_state = m_stateBeforeEntityInAttributeValue;
            continue;
        case BogusComment:
            while (1) {
                if (cc == '>') {
                    m_state = Data;
                    break;
                }
                m_source.advance();
                if (m_source.isEmpty())
                    return;
                cc = m_source->unicode();
            }
            break;
        case MarkupDeclarationOpen: {
            if (cc == '-') {
                if (m_source.length() < 2)
                    return;
                m_source.advance();
                cc = m_source->unicode();
                if (cc == '-')
                    m_state = CommentStart;
                else {
                    m_state = BogusComment;
                    continue;
                }
            // If we cared about the DOCTYPE we would test to enter those states here
            } else {
                m_state = BogusComment;
                continue;
            }
            break;
        }
        case CommentStart:
            if (cc == '-')
                m_state = CommentStartDash;
            else if (cc == '>')
                m_state = Data;
            else
                m_state = Comment;
            break;
        case CommentStartDash:
            if (cc == '-')
                m_state = CommentEnd;
            else if (cc == '>')
                m_state = Data;
            else
                m_state = Comment;
            break;
        case Comment:
            while (1) {
                if (cc == '-') {
                    m_state = CommentEndDash;
                    break;
                }
                m_source.advance();
                if (m_source.isEmpty())
                    return;
                cc = m_source->unicode();
            }
            break;
        case CommentEndDash:
            if (cc == '-')
                m_state = CommentEnd;
            else 
                m_state = Comment;
            break;
        case CommentEnd:
            if (cc == '>')
                m_state = Data;
            else if (cc == '-')
                ;
            else 
                m_state = Comment;
            break;
        }
        m_source.advance();
    }
}
Exemplo n.º 29
0
void UIVMPreviewWindow::sltRecreatePreview()
{
    /* Only do this if we are visible: */
    if (!isVisible())
        return;

    /* Remove preview if any: */
    if (m_pPreviewImg)
    {
        delete m_pPreviewImg;
        m_pPreviewImg = 0;
    }

    /* We are not creating preview for inaccessible VMs: */
    if (m_machineState == KMachineState_Null)
        return;

    if (!m_machine.isNull() && m_vRect.width() > 0 && m_vRect.height() > 0)
    {
        QImage image(size(), QImage::Format_ARGB32);
        image.fill(Qt::transparent);
        QPainter painter(&image);
        bool fDone = false;

        /* Preview enabled? */
        if (m_pUpdateTimer->interval() > 0)
        {
            /* Use the image which may be included in the save state. */
            if (   m_machineState == KMachineState_Saved
                || m_machineState == KMachineState_Restoring)
            {
                ULONG width = 0, height = 0;
                QVector<BYTE> screenData = m_machine.ReadSavedScreenshotPNGToArray(0, width, height);
                if (screenData.size() != 0)
                {
                    QImage shot = QImage::fromData(screenData.data(), screenData.size(), "PNG").scaled(m_vRect.size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
                    dimImage(shot);
                    painter.drawImage(m_vRect.x(), m_vRect.y(), shot);
                    fDone = true;
                }
            }
            /* Use the current VM output. */
            else if (   m_machineState == KMachineState_Running
//                      || m_machineState == KMachineState_Saving /* Not sure if this is valid */
                     || m_machineState == KMachineState_Paused)
            {
                if (m_session.GetState() == KSessionState_Locked)
                {
                    CVirtualBox vbox = vboxGlobal().virtualBox();
                    if (vbox.isOk())
                    {
                        const CConsole& console = m_session.GetConsole();
                        if (!console.isNull())
                        {
                            CDisplay display = console.GetDisplay();
                            /* Todo: correct aspect radio */
//                            ULONG w, h, bpp;
//                            display.GetScreenResolution(0, w, h, bpp);
//                            QImage shot = QImage(w, h, QImage::Format_RGB32);
//                            shot.fill(Qt::black);
//                            display.TakeScreenShot(0, shot.bits(), shot.width(), shot.height());
                            QVector<BYTE> screenData = display.TakeScreenShotToArray(0, m_vRect.width(), m_vRect.height());
                            if (   display.isOk()
                                && screenData.size() != 0)
                            {
                                /* Unfortunately we have to reorder the pixel
                                 * data, cause the VBox API returns RGBA data,
                                 * which is not a format QImage understand.
                                 * Todo: check for 32bit alignment, for both
                                 * the data and the scanlines. Maybe we need to
                                 * copy the data in any case. */
                                uint32_t *d = (uint32_t*)screenData.data();
                                for (int i = 0; i < screenData.size() / 4; ++i)
                                {
                                    uint32_t e = d[i];
                                    d[i] = RT_MAKE_U32_FROM_U8(RT_BYTE3(e), RT_BYTE2(e), RT_BYTE1(e), RT_BYTE4(e));
                                }

                                QImage shot = QImage((uchar*)d, m_vRect.width(), m_vRect.height(), QImage::Format_RGB32);

                                if (m_machineState == KMachineState_Paused)
                                    dimImage(shot);
                                painter.drawImage(m_vRect.x(), m_vRect.y(), shot);
                                fDone = true;
                            }
                        }
                    }
                }
            }
        }
        if (fDone)
            m_pPreviewImg = new QImage(image);
    }
    update();
}
Exemplo n.º 30
0
void SW::GLViewer::init()
{

    setGL();
    initGLSL();

#if BUFFER_
    //glClearColor(0.0, 0.0, 0.0, 0.0);

    //glDisable(GL_DITHER);

    glShadeModel(GL_FLAT);

    //glEnable(GL_DEPTH_TEST);

    enum{Vertices, Color, Elements, NumVBOs};
    GLuint buffers[NumVBOs];

    // glew init is very important or errors occur
    glewInit();
    // generate vertex arrays, and each array is corresponding to a object to be render
    glGenVertexArrays(1, &arrayId);

#ifdef QT_BUFFER
    QGLFunctions qtgl;
    qtgl.initializeGLFunctions(0);
#endif

    // 3D world coordinate of points
#ifdef QT_BUFFER
    QVector<QVector3D> Verts;
    Verts.append(QVector3D(-1.0, -1.0, -1.0));
    Verts.append(QVector3D(-1.0, -1.0, 1.0));
    Verts.append(QVector3D(-1.0, 1.0, -1.0));
    Verts.append(QVector3D(-1.0, 1.0, 1.0));
    Verts.append(QVector3D(1.0, -1.0, -1.0));
    Verts.append(QVector3D(1.0, -1.0, 1.0));
    Verts.append(QVector3D(1.0, 1.0, -1.0));
    Verts.append(QVector3D(1.0, 1.0, 1.0));
#else


    GLfloat Verts[][3] = {
        {-1.0, -1.0, -1.0},
        {-1.0, -1.0, 1.0},
        {-1.0, 1.0, -1.0},
        {-1.0, 1.0, 1.0},
        {1.0,  -1.0, -1.0},
        {1.0, -1.0, 1.0},
        {1.0, 1.0, -1.0},
        {1.0, 1.0, 1.0},
    };
#endif

    // colors of points
#ifdef QT_BUFFER
    QVector<QVector3D> Colors;
    Colors.append(QVector3D(0, 0.0, 0.0));
    Colors.append(QVector3D(0, 0.0, 1.0));
    Colors.append(QVector3D(0, 1.0, 0.0));
    Colors.append(QVector3D(0, 1.0, 1.0));
    Colors.append(QVector3D(1.0, 0.0, 0.0));
    Colors.append(QVector3D(1.0, 0.0, 1.0));
    Colors.append(QVector3D(1.0, 1.0, 0.0));
    Colors.append(QVector3D(1.0, 1.0, 1.0));
#else
    GLfloat Colors[][3] = {
        {0.0, 0.0, 0.0},
        {0.0, 0.0, 1.0},
        {0.0, 1.0, 0.0},
        {0.0, 1.0, 1.0},
        {1.0, 0.0, 0.0},
        {1.0, 0.0, 1.0},
        {1.0, 1.0, 0.0},
        {1.0, 1.0, 1.0},
    };
#endif

    // indices of points
#ifdef QT_BUFFER
    QVector<uint> Indices;
    Indices.append(0);Indices.append(1);Indices.append(3);Indices.append(2);
    Indices.append(4);Indices.append(6);Indices.append(7);Indices.append(5);
    Indices.append(2);Indices.append(3);Indices.append(7);Indices.append(6);
    Indices.append(0);Indices.append(4);Indices.append(5);Indices.append(1);
    Indices.append(0);Indices.append(2);Indices.append(6);Indices.append(4);
    Indices.append(1);Indices.append(5);Indices.append(7);Indices.append(3);
#else
    GLubyte Indices[]={
        0, 1, 3, 2,
        4, 6, 7, 5,
        2, 3, 7, 6,
        0, 4, 5, 1,
        0, 2, 6, 4,
        1, 5, 7, 3,
    };
#endif

    // active a vertex array
    glBindVertexArray(arrayId);

    // generate buffer objects, and each attribute(vertices, color, and normal..) is corresponding to one buffer

#ifdef QT_BUFFER
    qtgl.glGenBuffers(NumVBOs, buffers);
#else
    glGenBuffers(NumVBOs, buffers);
#endif

    //---------------------------------------buffer for vertices----------------------------------//
    // active a buffer object
#ifdef QT_BUFFER
    qtgl.glBindBuffer(GL_ARRAY_BUFFER, buffers[Vertices]);
#else
    glBindBuffer(GL_ARRAY_BUFFER, buffers[Vertices]);
#endif
    // alloc a space for buffer
#ifdef QT_BUFFER
    qtgl.glBufferData(GL_ARRAY_BUFFER, Verts.size()*sizeof(GLfloat), Verts.data(), GL_STATIC_DRAW);
#else
    glBufferData(GL_ARRAY_BUFFER, sizeof(Verts), Verts, GL_STATIC_DRAW);
#endif
    // put the data into the corresponding buffer
    glVertexPointer(3, GL_FLOAT, 0,BUFFER_OFFSET(0));
    glEnableClientState(GL_VERTEX_ARRAY);



    //---------------------------------------buffer for colors----------------------------------//
    // buffer for colors
#ifdef QT_BUFFER
    qtgl.glBindBuffer(GL_ARRAY_BUFFER, buffers[Color]);
#else
    glBindBuffer(GL_ARRAY_BUFFER, buffers[Color]);
#endif
#ifdef QT_BUFFER
    qtgl.glBufferData(GL_ARRAY_BUFFER, Colors.size()*sizeof(GLfloat), Colors.data(), GL_STATIC_DRAW);
#else
    glBufferData(GL_ARRAY_BUFFER, sizeof(Colors), Colors, GL_STATIC_DRAW);
#endif
    glColorPointer(3, GL_FLOAT, 0, BUFFER_OFFSET(0));
    glEnableClientState(GL_COLOR_ARRAY);


    //---------------------------------------buffer for elements----------------------------------//
    // buffer for elements
#ifdef QT_BUFFER
    numElement = Indices.size();
#else
    numElement = sizeof(Indices)/sizeof(Indices[0]);
#endif
#ifdef QT_BUFFER
    qtgl.glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffers[Elements]);
#else
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffers[Elements]);
#endif
#ifdef QT_BUFFER
    qtgl.glBufferData(GL_ELEMENT_ARRAY_BUFFER, Indices.size()*sizeof(uint), Indices.data(), GL_STATIC_DRAW);
#else
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(Indices), Indices, GL_STATIC_DRAW);
#endif

#endif
}