Пример #1
0
    void ArtworkUploader::doUploadArtworks(const QVector<ArtworkMetadata *> &artworkList) {
        int artworksCount = artworkList.length();
        if (artworksCount == 0) {
            return;
        }

        UploadInfoRepository *uploadInfoRepository = m_CommandManager->getUploadInfoRepository();
        const QVector<Models::UploadInfo *> &infos = uploadInfoRepository->getUploadInfos();
        const Encryption::SecretsManager *secretsManager = m_CommandManager->getSecretsManager();
        const Models::SettingsModel *settingsModel = m_CommandManager->getSettingsModel();

        uploadInfoRepository->resetPercents();
        uploadInfoRepository->updatePercentages();
        m_UploadCoordinator->uploadArtworks(artworkList, infos, m_IncludeVector, secretsManager, settingsModel);

        m_CommandManager->reportUserAction(Conectivity::UserActionUpload);
    }
Пример #2
0
void FrameNumberVisualizator::rescale(){
    EulerDataSeries * buffer= static_cast<EulerDataSeries *>( curve->data() );
    if(buffer==NULL||buffer==0)
        return;

    QVector<double> values = buffer->getData();
    if(values.isEmpty())
        return;

    double max = 0;
    for(int i=0;i<values.length();i++){

        if(values[i]>max)
            max=values[i];
    }
    plot->setAxisScale(QwtPlot::yLeft,max - 500 ,max + 500);

}
Пример #3
0
    void WarningsService::submitItems(const QVector<Models::ArtworkMetadata *> &items) {
        if (m_WarningsWorker == NULL) {
            return;
        }

        int length = items.length();

        std::vector<std::shared_ptr<WarningsItem> > itemsToSubmit;
        itemsToSubmit.reserve(length);

        for (int i = 0; i < length; ++i) {
            Models::ArtworkMetadata *item = items.at(i);
            itemsToSubmit.emplace_back(new WarningsItem(item));
        }

        LOG_INFO << "Submitting" << length << "item(s)";
        m_WarningsWorker->submitItems(itemsToSubmit);
    }
Пример #4
0
void Neuron::TurningWeight(float time, QVector<float> data)
{
	if(this->weight.length() != data.length())
		return;	

	float var1 = -1 * time / Param_1;
	float result1 = LearningRate * expf(var1);

	float var2 = -1 * time / Param_2;
	float result2 = NeighborDis * expf(var2);
	
	GaussianValue = expf((-1.0) * (DisWithWinner * DisWithWinner) / 2.0 * (result2 * result2));
	
	for(int i=0; i<this->weight.length(); i++)
	{
		float var3 = data[i] - weight[i];
		weight[i] += result1 * GaussianValue * var3;
	}
}
void MainWindow::addButtons(QVector<QPushButton *> buttonList, QScrollArea *symbolScrollArea, QString labelText)
{
    iter = 0;
    row++, column = 0;

    symbolLabel = new QLabel(this);
    QString HTMLtext = "<b>" + labelText + "</b>";
    symbolLabel->setText(HTMLtext);
    symbolLayout->addWidget(symbolLabel, row, column);

    row++, column = -1;

    foreach(symbolButton, buttonList)
    {
        if(column == 5)
        {
            column = 0;
            row++;
        }
        else
            column++;

        symbolButton->setStyleSheet("background-color : rgba(50,50,50,100%);"
                                    "color: white;"
                                    "border-style: solid;"
                                    "border-width: 2px;"
                                    "border-color: rgba(255,255,255,90%);");

        symbolButton->setMinimumHeight(symbolScrollArea->height() / 5);

        symbolLayout->addWidget(symbolButton, row, column);

        connect(symbolButton, SIGNAL(clicked()), this, SLOT(onNotationClicked()));

        iter++;
        if(iter == buttonList.length())
        {
            row++;
            column = -1;
        }
    }
}
Пример #6
0
    void MetadataIOCoordinator::writeMetadata(const QVector<Models::ArtworkMetadata *> &artworksToWrite, bool useBackups) {
        m_WritingWorker = new MetadataWritingWorker(artworksToWrite,
                                                    m_CommandManager->getSettingsModel(),
                                                    useBackups);
        QThread *thread = new QThread();
        m_WritingWorker->moveToThread(thread);

        QObject::connect(thread, SIGNAL(started()), m_WritingWorker, SLOT(process()));
        QObject::connect(m_WritingWorker, SIGNAL(stopped()), thread, SLOT(quit()));

        QObject::connect(m_WritingWorker, SIGNAL(stopped()), m_WritingWorker, SLOT(deleteLater()));
        QObject::connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));

        QObject::connect(m_WritingWorker, SIGNAL(finished(bool)), this, SLOT(writingWorkerFinished(bool)));
        QObject::connect(this, SIGNAL(metadataWritingFinished()), m_WritingWorker, SIGNAL(stopped()));
        setProcessingItemsCount(artworksToWrite.length());

        qDebug() << "Starting metadata writing thread";
        thread->start();
    }
Пример #7
0
void MetaModelPayload::setBlendedVertices(int blendNumber, const QVector<BlendshapeOffset>& blendshapeOffsets, const QVector<int>& blendedMeshSizes, const render::ItemIDs& subRenderItems) {
    PROFILE_RANGE(render, __FUNCTION__);
    if (blendNumber < _appliedBlendNumber) {
        return;
    }
    _appliedBlendNumber = blendNumber;

    // We have fewer meshes than before.  Invalidate everything
    if (blendedMeshSizes.length() < (int)_blendshapeBuffers.size()) {
        _blendshapeBuffers.clear();
    }

    int index = 0;
    for (int i = 0; i < blendedMeshSizes.size(); i++) {
        int numVertices = blendedMeshSizes.at(i);

        // This mesh isn't blendshaped
        if (numVertices == 0) {
            _blendshapeBuffers.erase(i);
            continue;
        }

        const auto& buffer = _blendshapeBuffers.find(i);
        const auto blendShapeBufferSize = numVertices * sizeof(BlendshapeOffset);
        if (buffer == _blendshapeBuffers.end()) {
            _blendshapeBuffers[i] = std::make_shared<gpu::Buffer>(blendShapeBufferSize, (gpu::Byte*) blendshapeOffsets.constData() + index * sizeof(BlendshapeOffset), blendShapeBufferSize);
        } else {
            buffer->second->setData(blendShapeBufferSize, (gpu::Byte*) blendshapeOffsets.constData() + index * sizeof(BlendshapeOffset));
        }

        index += numVertices;
    }

    render::Transaction transaction;
    for (auto& id : subRenderItems) {
        transaction.updateItem<ModelMeshPartPayload>(id, [this, blendedMeshSizes](ModelMeshPartPayload& data) {
            data.setBlendshapeBuffer(_blendshapeBuffers, blendedMeshSizes);
        });
    }
    AbstractViewStateInterface::instance()->getMain3DScene()->enqueueTransaction(transaction);
}
Пример #8
0
    void ArtworksRepository::cleanupEmptyDirectories() {
        LOG_DEBUG << "#";
        int count = m_DirectoriesList.length();
        QVector<int> indicesToRemove;
        indicesToRemove.reserve(count);

        for (int i = 0; i < count; ++i) {
            const QString &directory = m_DirectoriesList[i];
            if (m_DirectoriesHash[directory] == 0) {
                indicesToRemove.append(i);
            }
        }

        if (!indicesToRemove.isEmpty()) {
            LOG_INFO << indicesToRemove.length() << "empty directory(ies)...";

            QVector<QPair<int, int> > rangesToRemove;
            Helpers::indicesToRanges(indicesToRemove, rangesToRemove);
            removeItemsAtIndices(rangesToRemove);
        }
    }
Пример #9
0
    void SpellCheckerService::submitItems(const QVector<ISpellCheckable *> &itemsToCheck) {
        if (!m_WorkerIsAlive) { return; }

        if (m_SpellCheckWorker != NULL && !m_SpellCheckWorker->isCancelled()) {
            QVector<SpellCheckItemBase *> items;
            int length = itemsToCheck.length();

            items.reserve(length);

            for (int i = 0; i < length; ++i) {
                SpellCheck::ISpellCheckable *itemToCheck = itemsToCheck.at(i);
                SpellCheckItem *item = new SpellCheckItem(itemToCheck, Common::SpellCheckAll);
                itemToCheck->connectSignals(item);
                items.append(item);
            }

            qInfo() << "SpellCheck service: about to submit" << length << "items";

            m_SpellCheckWorker->submitItems(items);
            m_SpellCheckWorker->submitItem(new SpellCheckSeparatorItem());
        }
    }
Пример #10
0
// horizontalPoints is an auxiliar method for the button position computation.
// starts from a known center and keeps adding elements horizontally
// and returns the computed positions.
QVector<QPoint> ButtonHandler::horizontalPoints(
        const QPoint &center, const int elements, const bool leftToRight) const
{
    QVector<QPoint> res;
    // Distance from the center to start adding buttons
    int shift = 0;
    if (elements % 2 == 0) {
        shift = m_buttonExtendedSize * (elements / 2) - (m_separator / 2);
    } else {
        shift = m_buttonExtendedSize * ((elements-1) / 2) + m_buttonBaseSize / 2;
    }
    if (!leftToRight) { shift -= m_buttonBaseSize; }
    int x = leftToRight ? center.x() - shift :
                          center.x() + shift;
    QPoint i(x, center.y());
    while (elements > res.length()) {
        res.append(i);
        leftToRight ? i.setX(i.x() + m_buttonExtendedSize) :
                      i.setX(i.x() - m_buttonExtendedSize);
    }
    return res;
}
Пример #11
0
// verticalPoints is an auxiliar method for the button position computation.
// starts from a known center and keeps adding elements vertically
// and returns the computed positions.
QVector<QPoint> ButtonHandler::verticalPoints(
        const QPoint &center, const int elements, const bool upToDown) const
{
    QVector<QPoint> res;
    // Distance from the center to start adding buttons
    int shift = 0;
    if (elements % 2 == 0) {
        shift = m_buttonExtendedSize * (elements / 2) - (m_separator / 2);
    } else {
        shift = m_buttonExtendedSize * ((elements-1) / 2) + m_buttonBaseSize / 2;
    }
    if (!upToDown) { shift -= m_buttonBaseSize; }
    int y = upToDown ? center.y() - shift :
                       center.y() + shift;
    QPoint i(center.x(), y);
    while (elements > res.length()) {
        res.append(i);
        upToDown ? i.setY(i.y() + m_buttonExtendedSize) :
                      i.setY(i.y() - m_buttonExtendedSize);
    }
    return res;
}
Пример #12
0
Файл: csv.cpp Проект: ambah/KTAB
void CSV::exportActorColors(QString path, QVector<int> actorIds, QVector<QString> colorCode)
{
    QFile f(path);

    if (f.open(QFile::WriteOnly | QFile::Truncate))
    {
        QTextStream data( &f );
        QStringList strList;

        //appending data
        for (int row=0; row < actorIds.length(); row++)
        {
            strList.clear();

            strList << QString::number(actorIds.at(row));
            strList << colorCode.at(row);
            data << strList.join(",") + "\n";
//            qDebug() << strList;
        }
        f.close();
    }
}
Пример #13
0
void MainWindow::on_btnRemove_clicked()
{
    QModelIndexList selected = ui->listView->selectionModel()->selectedIndexes();
    if (!selected.isEmpty())
    {
        QString str = list.at(selected.first().row());

        QVector<QString> vRemove = readFile(str);

        for(int i = 0; i < vGlobal.length(); i++)
            for(int k = 0; k < vRemove.length(); k++)
            {
                if(vGlobal.at(i) == vRemove.at(k))
                {
                    vGlobal.removeAt(i);
                    showDataInTableView(tvModel, vGlobal);
                    ui->tableView->setModel(tvModel);
                }
            }

        QStandardItemModel *tModel = new QStandardItemModel(0,0,this);
        tModel->setHorizontalHeaderItem(0, new QStandardItem(QString("Site A")));
        tModel->setHorizontalHeaderItem(1, new QStandardItem(QString("Site B")));

        showDataInTableView(tModel, vGlobal);
        ui->tableView->setModel(tModel);

        list.removeAt(selected.first().row());
        ((QStringListModel*) ui->listView->model())->setStringList(list);

        vRemove.clear();

        if(list.isEmpty())
            ui->btnRemove->setEnabled(false);

        ui->btnStart->setEnabled(false);
    }
}
Пример #14
0
void WireCreator::createLine()
{
    QVector<int> usedPoints;
    int currPoint=deadEnds[0];
    //currPath.push_back(vertices[currPoint]);
    usedPoints.push_back(currPoint);
    //while(currPoint!=deadEnds.last()){
    while(deadEnds.indexOf(currPoint)==-1||usedPoints.length()==1){

        for(auto p: edges){
            if(p.first==currPoint){
                currPoint=p.second;
                break;
            }
        }
      //currPath.push_back(vertices[currPoint]);
      usedPoints.push_back(currPoint);
    }
    //usedPoints.pop_back();
    qDebug()<<containsAllE(usedPoints);
    //modifiedPath=currPath;
    //qDebug()<<currPath;
    rawPath=usedPoints;
}
Пример #15
0
void MainWindow::on_btnSelectDB_clicked()
{


    model = new QStringListModel(this);

    QString fileName = getFileName();
    QVector<QString> vRead = readFile(fileName);

    for(int i = 0; i < vRead.length(); i++)
        vGlobal.append(vRead.at(i));


    vRead.clear();

    showDataInTableView(tvModel, vGlobal);

    setListViewElements(fileName);


    ui->tableView->setModel(tvModel);
    model->setStringList(list);
    ui->listView->setModel(model);
}
Пример #16
0
bool CGDReader::makeCGData(QVector<QVector<double> > p3r, QVector<QVector<int> > ftr, CGData* cgd) {
    cgd->pointAmount = p3r.length() - 1;
    cgd->surfaceAmount = ftr.length() - 1;
    cgd->verticesData = new CGPoint[p3r.length() - 1];
    for(int i = 1; i < p3r.length(); i ++) {
        cgd->verticesData[i - 1].x = p3r[i][1];
        cgd->verticesData[i - 1].y = p3r[i][2];
        cgd->verticesData[i - 1].z = p3r[i][3];
        cgd->verticesData[i - 1].rear = p3r[i][4];
    }

    cgd->surfacesData = new CGFace[ftr.length() - 1];
    for(int i = 1; i < ftr.length(); i ++) {
        cgd->surfacesData[i - 1].vertexAmount = ftr[i][0];
        cgd->surfacesData[i - 1].vertices = new int[ftr[i].length()];
        for(int j = 1; j <= ftr[i][0]; j ++) {
            cgd->surfacesData[i - 1].vertices[j - 1] = ftr[i][j];
        }
    }
    return true;
}
Пример #17
0
QString Rig::ApplyDrawToCanvas(QPainter *painter, const QMatrix4x4 view, const QMatrix4x4 perspective, const int width, const int hei)
{


    if (skeleton != NULL && skin != NULL && bindMesh != NULL){
//        skeleton->SetRotation(QVector3D(0,0,90), 20);
//        ++ang;
//        for (int i = 0; i <= skeleton->joints.length(); i++)
//            skeleton->SetRotation(QVector3D(-ang , 0, 0), i);
//        //skeleton->SetRotation(QVector3D(ang, ang+=5, ang), 0);

        BendSkinToSkeleton();
    }
    // vertexes
    // ...

    QVector<QVector2D> Vertexes2D = From3DTo2D(bindMesh->vertexes, view, perspective);
    QVector<QVector2D> Vertexes2DBend;
    QVector<QPoint> appliedToScreenCoords;
    QVector<QPoint> appliedToScreenCoordsBended;

    if (bendedMesh != NULL)Vertexes2DBend = From3DTo2D(bendedMesh->vertexes, view, perspective);
    for (int curPoint = 0; curPoint < Vertexes2D.length(); curPoint++)
    {
        int x,y;
        painter->setPen(ChangeQPainter(QColor(0,255, 0,120), 4));
        if (ApplyScreen(x,y, Vertexes2D[curPoint], width, hei))
            painter->drawPoint(x,y);
        appliedToScreenCoords << QPoint(x,y);
        // ...
        // bended mods
        if (bendedMesh != NULL)
        {
            int xb,yb;
            painter->setPen(ChangeQPainter(QColor(255,150,0,255), 2));
            if (ApplyScreen(xb,yb, Vertexes2DBend[curPoint], width, hei))
                painter->drawPoint(xb,yb);
            appliedToScreenCoordsBended << QPoint(xb, yb);
            //painter->setPen(ChangeQPainter(QColor(255,0,0,10), 1));
            //painter->drawLine(xb,yb,x,y);
        }
        // ...
        // draw a attend
        if (false && skin != NULL){
            QVector<QVector3D> attened3D = {};
            QVector<QVector2D> attened2D = {};

            for (int att = 0; att < skin->vertAttends[curPoint].localJointCoords.length(); att++)
                attened3D << bindMesh->vertexes[curPoint] + skin->vertAttends[curPoint].localJointCoords[att];
            attened2D = From3DTo2D(attened3D, view, perspective);
            for (int att = 0; att < attened2D.length(); att++){
                int xa, ya;
                ApplyScreen(xa,ya, attened2D[att], width, hei);
                painter->setPen(ChangeQPainter(QColor(255,0,0,5), 2));
                painter->drawLine(x,y,xa,ya);
            }
        }
    }
    // draw a mf polygons
    // ..................................................................................................................................
    Mesh* drawMesh = (bendedMesh == NULL)? bindMesh : bendedMesh;

    QVector<QPainterPath> polygonDrawArray;
    QVector<QColor> polygonColorArray;
    QVector<float> distFromPolygonCentersToCamera;

    for (int currentPolygon = 0; currentPolygon < drawMesh->polygonStartIndexes.length() - 1; currentPolygon++){
        QPolygon poly;

        QVector<int> selectedIndexes;
        QVector3D VertexInPolygonSumm = QVector3D();
        int totalVertexInPolygonCount = 0;
        for (int selecInd = drawMesh->polygonStartIndexes[currentPolygon]; selecInd < drawMesh->polygonStartIndexes[currentPolygon + 1]; selecInd++){
            totalVertexInPolygonCount ++;
            VertexInPolygonSumm += drawMesh->vertexes[drawMesh->polygonIndexes[selecInd]];
            selectedIndexes << drawMesh->polygonIndexes[selecInd];

            poly << ((drawMesh == bindMesh)? appliedToScreenCoords/*Bended*/[drawMesh->polygonIndexes[selecInd]]
                     : appliedToScreenCoordsBended[drawMesh->polygonIndexes[selecInd]]);
        }
        //
        //int colorIntenese = (int)(((double)currentPolygon * 254.0)/(bindMesh->polygonStartIndexes.length() - 1));

        QPainterPath newPolyg; newPolyg.addPolygon(poly);
        polygonDrawArray << newPolyg;
        polygonColorArray << QColor(200,200,200,200);//(QColor(colorIntenese,colorIntenese,colorIntenese));

        distFromPolygonCentersToCamera << (VertexInPolygonSumm * (1.0 / totalVertexInPolygonCount)).distanceToPoint(*cameraCenter);
    }
    QBrush brush;
    painter->setPen(QPen(Qt::darkGray));

    QVector<int> needPolygonInds = GetSortedIndex(distFromPolygonCentersToCamera);
    for (int cPath = 0; cPath < polygonDrawArray.length(); cPath ++){
        brush = QBrush(polygonColorArray[needPolygonInds[cPath]]);
        painter->fillPath(polygonDrawArray[needPolygonInds[cPath]], brush);
        painter->drawPath(polygonDrawArray[needPolygonInds[cPath]]);
    }
    // ..................................................................................................................................

    if (skeleton == NULL)
        return QString("No skeleton detected");
    // joints
    // ...
    QVector<QVector3D> Joints3D;
    for (int curJoint = 0; curJoint < skeleton->joints.length(); curJoint++){
        QVector3D parentVect = QVector3D(0,0,0),
                childVect = skeleton->getJointCoordByIndex(curJoint, parentVect);
        Joints3D << childVect << parentVect;
    }

    Vertexes2D = From3DTo2D(Joints3D, view,perspective);
    painter->setPen(ChangeQPainter(QColor(255,130,0), 1));
    for (int curPoint = 0; curPoint < Vertexes2D.length() / 2; curPoint++)
    {
        int xc,yc,xp,yp;
        ApplyScreen(xc,yc,Vertexes2D[curPoint * 2], width, hei);
        ApplyScreen(xp,yp,Vertexes2D[curPoint * 2 + 1], width, hei);
        painter->drawLine(xc,yc,xp,yp);
        painter->drawText(xc, yc,300,150,0, QString::number(curPoint));//+" " +skeleton->joints[curPoint]->name);// +", "+ QString::number(skeleton->joints[curPoint]->currentRotation.y()) +", "+ QString::number(skeleton->joints[curPoint]->currentRotation.z()));

        //painter->drawText(xc, yc,300,150,0, QString::number(Joints3D[curPoint*2].x()) +"\n"+ QString::number(Joints3D[curPoint*2].y()) +"\n"+ QString::number(Joints3D[curPoint*2].z()));
    }


    QString logs = "";
    QVector<QVector3D> jointLocalRots = skeleton->getJointsLocalRotations();
    for (int curJointInd = 0; curJointInd < skeleton->joints.length(); curJointInd++)
        logs += ("#" + QString::number(curJointInd) + " : ")
                + QString::number(jointLocalRots[curJointInd].x()) + ", "
                + QString::number(jointLocalRots[curJointInd].y()) + ", "
                + QString::number(jointLocalRots[curJointInd].z()) + "\n";
    painter->drawText(width, 40, 200, hei - 40,0, logs);//+" " +skeleton->joints[curPoint]->name);// +", "+ QString::number(skeleton->joints[curPoint]->currentRotation.y()) +", "+ QString::number(skeleton->joints[curPoint]->currentRotation.z()));

    //painter->end();
    return QString();
}
Пример #18
0
bool QgsCurve::snapToGridPrivate( double hSpacing, double vSpacing, double dSpacing, double mSpacing,
                                  const QVector<double> &srcX, const QVector<double> &srcY, const QVector<double> &srcZ, const QVector<double> &srcM,
                                  QVector<double> &outX, QVector<double> &outY, QVector<double> &outZ, QVector<double> &outM ) const
{
  int length = numPoints();

  if ( length <= 0 )
    return false;

  bool hasZ = is3D();
  bool hasM = isMeasure();

  // helper functions
  auto roundVertex = [hSpacing, vSpacing, dSpacing, mSpacing, hasZ, hasM, &srcX, &srcY, &srcZ, &srcM]( QgsPoint & out, int i )
  {
    if ( hSpacing > 0 )
      out.setX( std::round( srcX.at( i ) / hSpacing ) * hSpacing );
    else
      out.setX( srcX.at( i ) );

    if ( vSpacing > 0 )
      out.setY( std::round( srcY.at( i ) / vSpacing ) * vSpacing );
    else
      out.setY( srcY.at( i ) );

    if ( hasZ )
    {
      if ( dSpacing > 0 )
        out.setZ( std::round( srcZ.at( i ) / dSpacing ) * dSpacing );
      else
        out.setZ( srcZ.at( i ) );
    }

    if ( hasM )
    {
      if ( mSpacing > 0 )
        out.setM( std::round( srcM.at( i ) / mSpacing ) * mSpacing );
      else
        out.setM( srcM.at( i ) );
    }
  };


  auto append = [hasZ, hasM, &outX, &outY, &outM, &outZ]( QgsPoint const & point )
  {
    outX.append( point.x() );

    outY.append( point.y() );

    if ( hasZ )
      outZ.append( point.z() );

    if ( hasM )
      outM.append( point.m() );
  };

  auto isPointEqual = [dSpacing, mSpacing, hasZ, hasM]( const QgsPoint & a, const QgsPoint & b )
  {
    return ( a.x() == b.x() )
           && ( a.y() == b.y() )
           && ( !hasZ || dSpacing <= 0 || a.z() == b.z() )
           && ( !hasM || mSpacing <= 0 || a.m() == b.m() );
  };

  // temporary values
  QgsWkbTypes::Type pointType = QgsWkbTypes::zmType( QgsWkbTypes::Point, hasZ, hasM );
  QgsPoint last( pointType );
  QgsPoint current( pointType );

  // Actual code (what does all the work)
  roundVertex( last, 0 );
  append( last );

  for ( int i = 1; i < length; ++i )
  {
    roundVertex( current, i );
    if ( !isPointEqual( current, last ) )
    {
      append( current );
      last = current;
    }
  }

  // if it's not closed, with 2 points you get a correct line
  // if it is, you need at least 4 (3 + the vertex that closes)
  if ( outX.length() < 2 || ( isClosed() && outX.length() < 4 ) )
    return false;

  return true;
}
Пример #19
0
QStringList Manager::fetchMonster(const int &id, const int &level) {

    QTextStream cout(stdout); // set cout for console debug

    QStringList array;

    QString idString;
    if ( id < 10 )
        idString = "00" + QString::number(id);
    else if ( id < 100)
        idString = "0" + QString::number(id);
    else
        idString =  QString::number(id);

    array.append(QString::number(id));
    array.append(idString);
    array.append(QString::number(level));

    cout << QDir::setCurrent("/usr/share/harbour-pocketmonsters/qml/pages/xmls/") << endl;
    QFile pokedex( idString + ".xml");

    cout << pokedex.open(QIODevice::ReadOnly) << endl;

    QXmlStreamReader xml(&pokedex);


    while (!xml.atEnd() && !xml.hasError()) {

        xml.readNext();

        if ( xml.isStartElement() && xml.name().toString() == "index" && xml.attributes().value("id").toString() == idString) {
            xml.readNext();
        } else if ( ( xml.name().toString() == "moveset" ) ) {
            break;
        }
        if ( xml.isStartElement() ) {
            QString string = xml.readElementText();
            array.append(string);
        }


    }

    if (xml.hasError())
    {
        cout << "XML error: " << xml.errorString() << "line:column - " << xml.lineNumber() << ":" << xml.columnNumber() << endl;
    }
    else if (xml.atEnd())
    {
        cout << "Reached end, done" << endl;
    }

    QVector <int> levelsArray;
    QVector <int> idsArray;

    while (!xml.atEnd() && !xml.hasError()) {
        xml.readNext();
        QXmlStreamAttributes attributes = xml.attributes();
        if ( xml.isStartElement() && xml.name().toString() == "move") {
            levelsArray.append(attributes.value("level").toInt());
            idsArray.append(attributes.value("id").toInt());
        }
    }

    if (xml.hasError())
    {
        cout << "XML error: " << xml.errorString() << "line:column - " << xml.lineNumber() << ":" << xml.columnNumber() << endl;
    }
    else if (xml.atEnd())
    {
        cout << "Reached end, done" << endl;
    }

    if ( levelsArray.length() < 5 ) {
        if ( level >= levelsArray[0])
            array.append(QString::number(idsArray[0]));
        if ( level >= levelsArray[1])
            array.append(QString::number(idsArray[1]));
        if ( level >= levelsArray[2])
            array.append(QString::number(idsArray[2]));
        if ( level >= levelsArray[3])
            array.append(QString::number(idsArray[3]));
    }
    while ( array.length() < 23 )
        array.append(QString::number(0));

    for ( int i = 0; i < array.length(); i++) {
        cout << array[i] << ";";
    }

    cout << endl;

    fetchMonsterDone();
    return array;
}
Пример #20
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);
}
Пример #21
0
void mergeFiles(QString XMLFile){
    QString outname;
    QMap<int,O3DPFile*> o3dpfileMap;
    QVector<fileWithLocation> files;
    QVector<long> outGridSize(3,0);
    QVector<float> voxDims(3,0);
    QVector<double> outBBox(6,0);
    quint32 nmat = 0;

/// Parse XML into
///  - fileWithLocations
///  - a fixed gridsize
///  - bbox
///  - outfilename

    QFile f(XMLFile);
    f.open(QIODevice::ReadOnly);



    QXmlStreamReader xml(&f);
    while(!xml.atEnd() && !xml.hasError()){
        QXmlStreamReader::TokenType token = xml.readNext();
        if(token == QXmlStreamReader::StartDocument){
            //we don’t want any of this data, it isn’t any element
            //we need.
            continue;
        }

        if(token == QXmlStreamReader::StartElement) {
            if(xml.name() == "files"){
                continue;
            }
            if(xml.name() == "filename"){
                outname = xml.readElementText();
                qDebug()<<"outname: "<<outname;
            }
            if(xml.name() == "inputfile"){
                int id = xml.attributes().value("id").toInt();
                QString filename = xml.readElementText();
                O3DPFile* input = new O3DPFile(filename);
                o3dpfileMap[id] = input;
            }
            if (xml.name() == "insertfile"){
                int id = xml.attributes().value("id").toInt();
                QVector<int> indecies(3,0.0);
                indecies[0] = xml.attributes().value("x").toFloat();
                indecies[1] = xml.attributes().value("y").toFloat();
                indecies[2] = xml.attributes().value("z").toFloat();

                fileWithLocation loc;
                loc.o3dp = o3dpfileMap[id];
                loc.indices = indecies;
                nmat = std::max(nmat,loc.o3dp->num_mat);

                files.append(loc);
            }
            if(xml.name() == "gridsize"){
                outGridSize[0] = xml.attributes().value("x").toLong();
                outGridSize[1] = xml.attributes().value("y").toLong();
                outGridSize[2] = xml.attributes().value("z").toLong();
            }
            if(xml.name() == "voxeldims"){
                voxDims[0] = xml.attributes().value("x").toFloat();
                voxDims[1] = xml.attributes().value("y").toFloat();
                voxDims[2] = xml.attributes().value("z").toFloat();
            }
        }
    }
    if (xml.hasError()){qDebug()<<"Error:"<<xml.error();}

    for(int i=0;i<3;i++){
        outBBox[3+i] = outGridSize[i]*voxDims[i];
    }



    O3DPFile OutFile(outname,outGridSize,outBBox);
    OutFile.num_mat=nmat;
    OutFile.writeHeader();
    for( int z=0; z<outGridSize[2]; z++){
        QByteArray layer( outGridSize[1]*outGridSize[0],0);

        for(int f=0; f<files.length();f++){
            int file_layer_number = z-files.at(f).indices[2];
            // if the file is in this layer then add the values
            if( (file_layer_number > -1) &&
                (file_layer_number < files.at(f).o3dp->gridSize[2]) ){
                // get the layer
                QByteArray fileLayer = files.at(f).o3dp->layer(file_layer_number);

                // for each row write out
                for (int y=0;y<files.at(f).o3dp->gridSize[1];y++){
                    ///  *-------->
                    ///  |   |
                    ///  |---x
                    /// \|/
                    int indexInLayer = (y+files.at(f).indices[1])*outGridSize[0]+
                                       files.at(f).indices[0];
                    int len = files.at(f).o3dp->gridSize[0];
                    QByteArray col = fileLayer.mid(y*len,len);
                    layer.replace(indexInLayer,len,col);
                }
            }
        }
        //OutFile.grid[z] = layer;
        qDebug()<<"layer:"<<z<<" : "<<OutFile.writeLayer(layer);
    }

    //qDebug()<<"generated";
    //OutFile.writeAll(outname);
    qDebug()<<"done writing";
}
Пример #22
0
void QGLView::initializeVertexBuffer(ModelType type, const QVector<ModelVertex> &vertices)
{
    initializeVertexBuffer(type, vertices.data(), vertices.length() * sizeof(ModelVertex));
}
void Algorithm::FFT(QVector< std::complex<double> > &a, bool invert)
{
    //qDebug()<<a;
    int n=a.length();
    if(n==1)
    {
        return;
    }
    int i;
    QVector< std::complex<double> >a0(n/2),a1(n/2);
    for(i=0;i<n;i+=2)
    {

        a0[i/2]=a[i];
        a1[i/2]=a[i+1];
    }
    FFT(a0,invert);
    FFT(a1,invert);
    static double pi_2;//=M_PI *2;
    double ang=(pi_2/n)*(invert?-1:1);
    std::complex<double> w(1),wn(cos(ang),sin(ang));
    for(i=0;i<n/2;i++)
    {
        a[i]=a0[i]+w*a1[i];
        a[i+ n/2 ]=a0[i]-w*a1[i];
        if(invert)
        {
            a[i]/=2;
            a[i+ n/2 ]/=2;
        }
        w*=wn;

    }
    /*/
    int i,j=0;
    int n=a.length();
    //double pi_2=M_PI *2;
    double ang;
    std::complex<double> w,wn;
    QVector< std::complex<double> > _a(n);
    for(i=0;i<n;i++)
    {
        a_[j]=a[i];
        j=j+n/2;
    }
    n/=2;
    for(;n>1;n/=2)
    {
        ang=(M_PI/n)*(invert?-1:1);
        qDebug()<<"length"<<n;
        w=1,wn={cos(ang),sin(ang)};
        i=0;
        j=0;
        while(1)
        {
            _a[i]=a[i]+w*a[i+n/2];
            _a[i+n]=a[i]-w*a[i+n/2];
            i++,j++;
            if(j==n/2)
            {
                w*=wn;
                j=0;
                i+=n/2;
            }
            qDebug()<<i<<j;
            if(i>=a.length())
            {
                break;
            }
            a=_a;
        }

    }
    /*/
}
/**
 * @brief DelaunayTriangulation::checkDelaunayConditionLocaly
 * @param triangles
 * @return {bool} is triangulation restructured
 */
bool DelaunayTriangulation::
    checkDelaunayConditionLocaly(QVector<TriangularUnit>& trianglesToCheck) {

    bool isRestructured = false;

    for (int i = 0; i < trianglesToCheck.length(); i++) {
        int triangleIndex = i;
        TriangularUnit triangle = trianglesToCheck.at(triangleIndex);
        QVector< int > neighborsIndexes = getTriangularUnitNeighbors(triangle);
        QVectorIterator< int > itNeighbors( neighborsIndexes );

        QVector<Point> triangleVertexes = triangle.getVertexes();

        if (neighborsIndexes.length() > 3) {
            ExMath::consoleLog(neighborsIndexes.length());
        }

        while (itNeighbors.hasNext()) {
            int neighborIndex = itNeighbors.next();
            TriangularUnit neighbor = triangles.at(neighborIndex);
            Point p0 = triangle.getNotAdjacentPoint(neighbor);
            Edge mutualEdge = neighbor.getMutualEdge(triangle);
            double x0 = p0.x(), y0 = p0.y();

            int indexMutualVertex1 = triangleVertexes.indexOf(mutualEdge.getStartPoint());
            int indexMutualVertex2 = triangleVertexes.indexOf(mutualEdge.getEndPoint());
            int i1 = (abs(indexMutualVertex1 - indexMutualVertex2) == 1)?
                         std::min(indexMutualVertex1, indexMutualVertex2):
                         std::max(indexMutualVertex1, indexMutualVertex2);
            int i3 = (i1 == indexMutualVertex1)? indexMutualVertex2: indexMutualVertex1;
            int i2 = 3 - i1 - i3;
            double x1 = triangleVertexes.at(i1).x(), y1 = triangleVertexes.at(i1).y();
            double x2 = triangleVertexes.at(i2).x(), y2 = triangleVertexes.at(i2).y();
            double x3 = triangleVertexes.at(i3).x(), y3 = triangleVertexes.at(i3).y();

            double targetValue = fabs((x0 - x1)*(y0 - y3) - (x0 - x3)*(y0 - y1))*
                                 ((x2 - x1)*(x2 - x3) + (y2 - y1)*(y2 - y3)) +
                                 ((x0 - x1)*(x0 - x3) + (y0 - y1)*(y0 - y3))*
                                 fabs((x2 - x1)*(y2 - y3) - (x2 - x3)*(y2 - y1));

            //targetValue = (x1*x1 + y1*y1)*(y2*x3 - x2*y3) + (x2*x2 + y2*y2)*(x1*y3 - y1*x3) + (x3*x3 + y3*y3)*(y1*x2 - x1*y2) <= 0;
            if (targetValue < 0) {
                Point p4 = neighbor.getNotAdjacentPoint(triangle);
                Edge newMutualEdge(p0, p4);
                TriangularUnit newTriangle1(newMutualEdge, mutualEdge.getEndPoint());
                TriangularUnit newTriangle2(newMutualEdge, mutualEdge.getStartPoint());

                edges.remove(mutualEdge);
                edges.insert(newMutualEdge);
                triangles[neighborIndex] = newTriangle1;
                triangles[triangles.indexOf(triangle)] = newTriangle2;
                trianglesToCheck.append(newTriangle1);
                trianglesToCheck.append(newTriangle2);
                break;

                ExMath::consoleLog("swapped");
                isRestructured = true;
            }
        }
    }

    return isRestructured;
}
QVariantMap QgsCollectorAlgorithm::processCollection( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback,
    const std::function<QgsGeometry( const QVector< QgsGeometry >& )> &collector, int maxQueueLength )
{
  std::unique_ptr< QgsFeatureSource > source( parameterAsSource( parameters, QStringLiteral( "INPUT" ), context ) );
  if ( !source )
    throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "INPUT" ) ) );

  QString dest;
  std::unique_ptr< QgsFeatureSink > sink( parameterAsSink( parameters, QStringLiteral( "OUTPUT" ), context, dest, source->fields(), QgsWkbTypes::multiType( source->wkbType() ), source->sourceCrs() ) );

  if ( !sink )
    throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "OUTPUT" ) ) );

  QStringList fields = parameterAsFields( parameters, QStringLiteral( "FIELD" ), context );

  long count = source->featureCount();

  QgsFeature f;
  QgsFeatureIterator it = source->getFeatures();

  double step = count > 0 ? 100.0 / count : 1;
  int current = 0;

  if ( fields.isEmpty() )
  {
    // dissolve all - not using fields
    bool firstFeature = true;
    // we dissolve geometries in blocks using unaryUnion
    QVector< QgsGeometry > geomQueue;
    QgsFeature outputFeature;

    while ( it.nextFeature( f ) )
    {
      if ( feedback->isCanceled() )
      {
        break;
      }

      if ( firstFeature )
      {
        outputFeature = f;
        firstFeature = false;
      }

      if ( f.hasGeometry() && !f.geometry().isNull() )
      {
        geomQueue.append( f.geometry() );
        if ( maxQueueLength > 0 && geomQueue.length() > maxQueueLength )
        {
          // queue too long, combine it
          QgsGeometry tempOutputGeometry = collector( geomQueue );
          geomQueue.clear();
          geomQueue << tempOutputGeometry;
        }
      }

      feedback->setProgress( current * step );
      current++;
    }

    outputFeature.setGeometry( collector( geomQueue ) );
    sink->addFeature( outputFeature, QgsFeatureSink::FastInsert );
  }
  else
  {
    QList< int > fieldIndexes;
    Q_FOREACH ( const QString &field, fields )
    {
      int index = source->fields().lookupField( field );
      if ( index >= 0 )
        fieldIndexes << index;
    }

    QHash< QVariant, QgsAttributes > attributeHash;
    QHash< QVariant, QVector< QgsGeometry > > geometryHash;

    while ( it.nextFeature( f ) )
    {
      if ( feedback->isCanceled() )
      {
        break;
      }

      QVariantList indexAttributes;
      Q_FOREACH ( int index, fieldIndexes )
      {
        indexAttributes << f.attribute( index );
      }

      if ( !attributeHash.contains( indexAttributes ) )
      {
        // keep attributes of first feature
        attributeHash.insert( indexAttributes, f.attributes() );
      }

      if ( f.hasGeometry() && !f.geometry().isNull() )
      {
        geometryHash[ indexAttributes ].append( f.geometry() );
      }
    }
Пример #26
0
// Initialize all your OpenGL objects here
void MainWindow::initialize()
{
    rotate = false;
    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
    // Initialize objects and buffers

    OBJModel sphere = OBJModel(":/models/sphere.obj");
    QVector<QVector3D> vertices = sphere.vertices;

    nVertices = vertices.length();

    QVector<QVector3D> normals = sphere.normals;

    QVector<QVector3D> colors;
    for (int i = 0; i < sphere.indices.length(); i += 3){
        QVector3D c = QVector3D((double) rand() / RAND_MAX, (double) rand() / RAND_MAX, (double) rand() / RAND_MAX);
        colors.append(c);
        colors.append(c);
        colors.append(c);
    }

    // Create your Vertex Array Object (VAO) and Vertex Buffer Objects (VBO) here.
    object.create();
    object.bind();
    
    coordinates = new QOpenGLBuffer(QOpenGLBuffer::VertexBuffer);
    coordinates->create();
    coordinates->bind();

    coordinates->allocate(vertices.data(), vertices.length() * sizeof(QVector3D));
	glVertexAttribPointer(0,3,GL_FLOAT,GL_FALSE,0,0);
	
    normal_buffer = new QOpenGLBuffer(QOpenGLBuffer::VertexBuffer);
    normal_buffer->create();
    normal_buffer->bind();
    
    normal_buffer->allocate(normals.data(), normals.length() * sizeof(QVector3D));
    glVertexAttribPointer(2,3,GL_FLOAT,GL_FALSE,0,0);

    m_shaderProgram->setUniformValue("normal", normal);
    
   // for (int index = 0; index < sphere.indices.length(); index++)
        glEnableVertexAttribArray(0);
        glEnableVertexAttribArray(2);
		
	object.release();

    // Set OpenGL to use Filled triangles (can be used to render points, or lines)
    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";

    // Set the clear color to be black (color used for resetting the screen)
    glClearColor(0.0f, 0.0f, 0.0f, 1.0f);



}
Пример #27
0
void Rig::BendSkinToSkeleton()
{
    Q_ASSERT(bindMesh->vertexes.length() == skin->vertAttends.length());

    if (!skeleton->CalculateGlobalCoordForEachJointMatrix())
        return;

    Mesh* newMesh = new Mesh();
    newMesh->polygonIndexes = bindMesh->polygonIndexes;
    newMesh->polygonStartIndexes = bindMesh->polygonStartIndexes;
    int vertexesTransformed = 0;
    QVector<int> failedIndexes;
    for (int currentVertexInd = 0; currentVertexInd < skin->vertAttends.length(); currentVertexInd ++){
        QVector<QVector3D> bendedVariants;
        QVector<float> weightes;

        // we have 0.3 && QVec3D && from joint a place and rotation
        for (int jointInd = 0; jointInd < skin->vertAttends[currentVertexInd].jointIndexs.length(); jointInd++){
            int jointBendInd = skin->vertAttends[currentVertexInd].jointIndexs[jointInd];
            QVector3D originalOffset = skin->vertAttends[currentVertexInd].localJointCoords[jointInd];
            QVector3D jointBendTranslation, jointBendRotation;
            skeleton->getJointTranslationAndRotation(jointBendInd, jointBendTranslation, jointBendRotation);

            //qDebug() << currentVertexInd<< jointBendInd<< originalOffset << jointBendTranslation << jointBendRotation;
            ///bendedVariants <<
            ///CommonFuncs::AddDirect(jointBendTranslation, -originalOffset, jointBendRotation);
            QMatrix4x4 localAttendTransformMatrix = QMatrix4x4(),
                       localRotateMatrix = CommonFuncs::GetNormalRotateMatrix(skeleton->joints[jointBendInd]->currentRotation);

            localAttendTransformMatrix.translate(- skin->vertAttends[currentVertexInd].localJointCoords[jointInd]);

            bendedVariants <<
            CommonFuncs::AddDirectMatrx(QVector3D(1,1,1),
                                        //skin->vertAttends[currentVertexInd].localJointCoords
                                        skeleton->joints[jointBendInd]->globalTransformMatrix
                                        * localRotateMatrix
                                        * localAttendTransformMatrix
                                        );


            weightes << skin->vertAttends[currentVertexInd].weights[jointInd];
        }

        QVector3D result = QVector3D();
        float bendedSumm = 0;
        for (int curPoint = 0; curPoint < weightes.length(); curPoint++)
            bendedSumm += weightes[curPoint];
        if (bendedSumm == 0)
            failedIndexes << currentVertexInd;
        else
            for (int curPoint = 0; curPoint < bendedVariants.length(); curPoint++)
                result = result +  weightes[curPoint]/ bendedSumm * bendedVariants[curPoint] ;

        if (bendedVariants.length() > 0)
            vertexesTransformed ++;
        newMesh->vertexes << result;
    }

    qDebug() << QString::number(vertexesTransformed) + " / " + QString::number(skin->vertAttends.length()) + " / " + QString::number(bindMesh->vertexes.length()) +" vertexes transformed ( "+QString::number(failedIndexes.length())+" failed)";
    //
    bendedMesh = newMesh;
}
Пример #28
0
void CharSelect::slot_insertSpecialChars(const QVector<uint> & chars)
{
	chToIns = QString::fromUcs4(chars.data(), chars.length());
	slot_insertSpecialChar();
}
Пример #29
0
QVariantMap QgsClipAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
{
  std::unique_ptr< QgsFeatureSource > featureSource( parameterAsSource( parameters, QStringLiteral( "INPUT" ), context ) );
  if ( !featureSource )
    throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "INPUT" ) ) );

  std::unique_ptr< QgsFeatureSource > maskSource( parameterAsSource( parameters, QStringLiteral( "OVERLAY" ), context ) );
  if ( !maskSource )
    throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "OVERLAY" ) ) );

  QString dest;
  QgsWkbTypes::GeometryType sinkType = QgsWkbTypes::geometryType( featureSource->wkbType() );
  std::unique_ptr< QgsFeatureSink > sink( parameterAsSink( parameters, QStringLiteral( "OUTPUT" ), context, dest, featureSource->fields(), QgsWkbTypes::multiType( featureSource->wkbType() ), featureSource->sourceCrs() ) );

  if ( !sink )
    throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "OUTPUT" ) ) );

  // first build up a list of clip geometries
  QVector< QgsGeometry > clipGeoms;
  QgsFeatureIterator it = maskSource->getFeatures( QgsFeatureRequest().setSubsetOfAttributes( QList< int >() ).setDestinationCrs( featureSource->sourceCrs(), context.transformContext() ) );
  QgsFeature f;
  while ( it.nextFeature( f ) )
  {
    if ( f.hasGeometry() )
      clipGeoms << f.geometry();
  }

  QVariantMap outputs;
  outputs.insert( QStringLiteral( "OUTPUT" ), dest );

  if ( clipGeoms.isEmpty() )
    return outputs;

  // are we clipping against a single feature? if so, we can show finer progress reports
  bool singleClipFeature = false;
  QgsGeometry combinedClipGeom;
  if ( clipGeoms.length() > 1 )
  {
    combinedClipGeom = QgsGeometry::unaryUnion( clipGeoms );
    if ( combinedClipGeom.isEmpty() )
    {
      throw QgsProcessingException( QObject::tr( "Could not create the combined clip geometry: %1" ).arg( combinedClipGeom.lastError() ) );
    }
    singleClipFeature = false;
  }
  else
  {
    combinedClipGeom = clipGeoms.at( 0 );
    singleClipFeature = true;
  }

  // use prepared geometries for faster intersection tests
  std::unique_ptr< QgsGeometryEngine > engine( QgsGeometry::createGeometryEngine( combinedClipGeom.constGet() ) );
  engine->prepareGeometry();

  QgsFeatureIds testedFeatureIds;

  int i = -1;
  Q_FOREACH ( const QgsGeometry &clipGeom, clipGeoms )
  {
    i++;
    if ( feedback->isCanceled() )
    {
      break;
    }
    QgsFeatureIterator inputIt = featureSource->getFeatures( QgsFeatureRequest().setFilterRect( clipGeom.boundingBox() ) );
    QgsFeatureList inputFeatures;
    QgsFeature f;
    while ( inputIt.nextFeature( f ) )
      inputFeatures << f;

    if ( inputFeatures.isEmpty() )
      continue;

    double step = 0;
    if ( singleClipFeature )
      step = 100.0 / inputFeatures.length();

    int current = 0;
    Q_FOREACH ( const QgsFeature &inputFeature, inputFeatures )
    {
      if ( feedback->isCanceled() )
      {
        break;
      }

      if ( !inputFeature.hasGeometry() )
        continue;

      if ( testedFeatureIds.contains( inputFeature.id() ) )
      {
        // don't retest a feature we have already checked
        continue;
      }
      testedFeatureIds.insert( inputFeature.id() );

      if ( !engine->intersects( inputFeature.geometry().constGet() ) )
        continue;

      QgsGeometry newGeometry;
      if ( !engine->contains( inputFeature.geometry().constGet() ) )
      {
        QgsGeometry currentGeometry = inputFeature.geometry();
        newGeometry = combinedClipGeom.intersection( currentGeometry );
        if ( newGeometry.wkbType() == QgsWkbTypes::Unknown || QgsWkbTypes::flatType( newGeometry.wkbType() ) == QgsWkbTypes::GeometryCollection )
        {
          QgsGeometry intCom = inputFeature.geometry().combine( newGeometry );
          QgsGeometry intSym = inputFeature.geometry().symDifference( newGeometry );
          newGeometry = intCom.difference( intSym );
        }
      }
      else
      {
        // clip geometry totally contains feature geometry, so no need to perform intersection
        newGeometry = inputFeature.geometry();
      }

      if ( !QgsOverlayUtils::sanitizeIntersectionResult( newGeometry, sinkType ) )
        continue;

      QgsFeature outputFeature;
      outputFeature.setGeometry( newGeometry );
      outputFeature.setAttributes( inputFeature.attributes() );
      sink->addFeature( outputFeature, QgsFeatureSink::FastInsert );


      if ( singleClipFeature )
        feedback->setProgress( current * step );
    }

    if ( !singleClipFeature )
    {
      // coarse progress report for multiple clip geometries
      feedback->setProgress( 100.0 * static_cast< double >( i ) / clipGeoms.length() );
    }
  }
/*
 * Load the file with chosen filename and emit the signal sendFileData() when the file is read.
 */
void ConvertEcgToIbi::run()
{
	QFile myFile(fname);
	if (myFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
		time.start();
		QTextStream ecgInfo(&myFile);
		QVector<int > ecgVals;
        QVector<double> timeData;
		int iterations;
		if (!ecgInfo.atEnd()) {
			QString strVals = ecgInfo.readLine();
			ecgInfo.readLine();
			ecgInfo.readLine();
			double tmp;
			int i=0;
			while (!ecgInfo.atEnd()) {

				strVals = ecgInfo.readLine();
				QStringList strPieces = strVals.split(QRegularExpression("\\s+"));


				if (strPieces.length()==4) {
                    tmp=strPieces[2].toDouble();
                    ecgVals.append((tmp*500)); ///< @todo normalize input to work with more files

				}
				else if (strPieces.length()==3) {
                                    tmp=strPieces[2].toDouble();
                                    ecgVals.append((tmp*500));
                                                    }
				else if (strPieces.length()==5){

					tmp=strPieces[2].toDouble();
                    ecgVals.append((tmp*500));
                    }
				else {
					std::cerr << "Wrong File" << std::endl;
					return;
				}
				i++;
                }
            QVector<double> qrsPeaks;
			extractRtoR(&ecgVals, &qrsPeaks);
            qrsPeaks.takeFirst();// Remove the influense of the QRS-detectors learning period
            qrsPeaks.takeFirst();// Remove the influense of the QRS-detectors learning period
            qrsPeaks.takeFirst();// Remove the influense of the QRS-detectors learning period
            tmp=0;
            for (int i; i<qrsPeaks.length(); i++){
                tmp=tmp+(qrsPeaks.at(i));
                timeData.append(tmp);
            }
            if (qrsPeaks.length()>10){   ///@todo FIX this check neater
                emit sendFileData(qrsPeaks,timeData);
                saveAsIbiFile(&qrsPeaks);
            }
            else
                std::cerr << "Not enough R peaks detected" << std::endl;
            qDebug("Time elapsed: %d ms", time.elapsed());

		}
		ecgInfo.flush();
		myFile.close();



	}

}