int main(int argc, char *argv[]) { #ifdef Q_WS_X11 XInitThreads(); #endif Engine engine(argc, argv,"demo_game/media/"); SceneGraph* sg = engine.getScenegraph_TEMPORARY(); g_sg = sg; QList<InputManager::Control> controls; controls.push_back(InputManager::Control(false,"avance")); controls.push_back(InputManager::Control(false,"recule")); controls.push_back(InputManager::Control(false,"gauche")); controls.push_back(InputManager::Control(false,"droite")); INPUT_MANAGER.addControls(controls); INPUT_MANAGER.addBinding("KB_Z","avance"); INPUT_MANAGER.addBinding("KB_Up","avance"); INPUT_MANAGER.addBinding("KB_S","recule"); INPUT_MANAGER.addBinding("KB_Down","recule"); INPUT_MANAGER.addBinding("KB_Q","gauche"); INPUT_MANAGER.addBinding("KB_Left","gauche"); INPUT_MANAGER.addBinding("KB_D","droite"); INPUT_MANAGER.addBinding("KB_Right","droite"); Node* nRot = new Node("Rotating node"); Node* nQt = new Node("Qt Logo"); Node* nCam = new Node("Camera"); Node* nCamFollow = new Node("Camera Follow"); Node* nHead = new Node("Head"); Node* nStar = new Node("Star"); Node* nLight = new Node("Light"); Node* nLight2 = new Node("Light2"); Node* nUni = new Node("Unicorn"); Node* nGarg = new Node("Gargoyle"); Node* nDuck = new Node("Duck"); Node* nBuddy = new Node("Buddy"); Node* nSand = new Node("Sand"); QVector<Node*> balls; QVector<Node*> walls; for(int i=0 ; i<4 ; i++) { walls.push_back(new Node("Wall" + QString().setNum(i+1))); } for(int i=0 ; i<15 ; i++) { balls.push_back(new Node("Ball" + QString().setNum(i+1))); } nRot->addProperty(new IProperty()); // nRot->addProperty(new DummyUpdatable()); // nQt->addProperty(new QtLogo(engine.getGLW_TEMPORARY())); // nQt->addProperty(new Grid(1.0f, 1.0f, 40, 40)); //nDuckGrid->addProperty(new Grid(1.0f, 1.0f, 40, 40)); nCam->addProperty(new Camera(70,1,200)); nCamFollow->addProperty(new Camera(90,1,200)); nHead->addProperty(new DummyUpdatable()); Light* light; light = new Light(false); //light->setType(Light::SUN); //light->setDiffuseColor(Vector4f(0.2,1.0,0.2,1.0)); //light->setSpecularColor(Vector4f(0.2,1.0,0.2,1.0)); light->setDiffuseColor(Vector4f(1.0,1.0,0.0,1.0)); light->setSpecularColor(Vector4f(1.0,1.0,1.0,1.0)); nLight2->addProperty(light); light = new Light(true); //light->setType(Light::SPOT); light->setDiffuseColor(Vector4f(1.0,1.0,1.0,1.0)); light->setSpecularColor(Vector4f(1.0,1.0,1.0,1.0)); //light->setDiffuseColor(Vector4f(1.0,0.2,0.2,1.0)); //light->setSpecularColor(Vector4f(1.0,0.2,0.2,1.0)); nLight->addProperty(light); Mesh plane = MESH_MANAGER.get("Plane"); Mesh cube = MESH_MANAGER.get("Cube"); Mesh sphere = MESH_MANAGER.get("Sphere_16_32"); Mesh mesh = MESH_MANAGER.get("duck"); Mesh buddymesh = MESH_MANAGER.get("buddy"); Material buddy = MATERIAL_MANAGER.get("buddy"); Material duck = MATERIAL_MANAGER.get("duck"); Material star = MATERIAL_MANAGER.get("star"); Material gargoyle = MATERIAL_MANAGER.get("gargoyle"); Material sand = MATERIAL_MANAGER.get("sand"); Material gradientmats[4]; gradientmats[0] = MATERIAL_MANAGER.get("grad1"); gradientmats[1] = MATERIAL_MANAGER.get("grad2"); gradientmats[2] = MATERIAL_MANAGER.get("grad3"); gradientmats[3] = MATERIAL_MANAGER.get("grad4"); Sample sample = SAMPLE_MANAGER.get("quacking.wav"); nDuck->addProperty(new MeshRenderer(mesh,duck)); nStar->addProperty(new MeshRenderer(plane,star)); //nUni->addProperty(new MeshRenderer(cube,unicorn)); nGarg->addProperty(new MeshRenderer(cube,gargoyle)); nBuddy->addProperty(new MeshRenderer(buddymesh,buddy)); nSand->addProperty(new MeshRenderer(cube,sand)); nDuck->addProperty(new DummyControlable()); nDuck->addProperty(new SoundEmitter(sample)); nDuck->link(nCamFollow); nDuck->link(nHead); //nDuck->link(nDuckGrid); nHead->link(nStar); nHead->link(nLight); nCam->link(nLight2); nHead->link(nUni); sg->link(nDuck); sg->link(nBuddy); sg->link(nRot); sg->link(nQt); sg->link(nSand); for(QVector<Node*>::iterator it = walls.begin() ; it != walls.end() ; it++) { sg->link(*it); } for(QVector<Node*>::iterator it = balls.begin() ; it != balls.end() ; it++) { sg->link(*it); } nRot->link(nCam); nRot->link(nGarg); nRot->moveTo(Vector3f(0,0,0)); nQt->moveTo(Vector3f(0,-0.5,0)); nQt->rotate(Vector3f(1,0,0),90); nCam->moveTo(Vector3f(0,10.0,0)); nCam->rotate(Vector3f(1,0,0),270); nCamFollow->moveTo(Vector3f(0,2,3)); nCamFollow->rotate(Vector3f(1,0,0),345); nUni->rotate(Vector3f(0,0,-1),90); nUni->rotate(Vector3f(-1,0,0),90); nHead->moveTo(Vector3f(0,0.5,0)); nUni->moveTo(Vector3f(1.5,0,0)); nStar->moveTo(Vector3f(-1.5,0,0)); nStar->rotate(Vector3f(0,0,1),270); nLight->moveTo(Vector3f(-1.5,0,0)); nLight2->moveTo(Vector3f(0,0,-3)); nSand->moveTo(Vector3f(0,-0.5,0)); nSand->rotate(Vector3f(1,0,0),270); nSand->setScale(Vector3f(10,10,0.01)); walls[0]->moveTo(Vector3f(0,1,-2)); //walls[0]->moveTo(Vector3f(0,1,-5)); walls[0]->setScale(Vector3f(10,3,0.01)); walls[1]->moveTo(Vector3f(0,1, 2)); //walls[1]->moveTo(Vector3f(0,1, 5)); walls[1]->setScale(Vector3f(10,3,0.01)); walls[2]->moveTo(Vector3f( 2,1,0)); //walls[2]->moveTo(Vector3f( 5,1,0)); walls[2]->setScale(Vector3f(0.01,3,10)); walls[3]->moveTo(Vector3f(-2,1,0)); //walls[3]->moveTo(Vector3f(-5,1,0)); walls[3]->setScale(Vector3f(0.01,3,10)); for(int i=0 ; i<balls.size() ; i++) { balls[i]->moveTo(Vector3f(0,4+2*i,0)); float s1 = 0.1+(qrand() % 900)/1000.0; float s2 = 0.1+(qrand() % 900)/1000.0; float s3 = 0.1+(qrand() % 900)/1000.0; balls[i]->setScale(Vector3f(s1,s2,s3)); } nGarg->moveTo(Vector3f(-3,3,-3)); nGarg->setScale(Vector3f(1,0.3,1)); nBuddy->moveTo(Vector3f(3,1.5,3)); nBuddy->rotate(Vector3f(1,0,0),-90); nBuddy->rotate(Vector3f(0,1,0),180); nDuck->moveTo(Vector3f(0,-0.5,-1.8)); nDuck->rotate(Vector3f(0,1,0),127); //nDuckGrid->rotate(Vector3f(1,0,0),270); PhysicObject::Properties prop; nSand->addProperty(new PhysicObject(prop)); for(QVector<Node*>::iterator it=walls.begin() ; it != walls.end() ; it++) { (*it)->addProperty(new PhysicObject(prop)); //(*it)->addProperty(new MeshRenderer(cube,gargoyle)); } prop.is_kinematic = true; nGarg->addProperty(new PhysicObject(prop)); prop.shape = PhysicObject::MESH; prop.mesh_name = "duck"; nDuck->addProperty(new PhysicObject(prop)); prop.is_kinematic = false; prop.mass = 100.0; prop.restitution = 0.1; int nbDuckLight = 0; prop.shape = PhysicObject::BOX; for(QVector<Node*>::iterator it=balls.begin() ; it != balls.end() ; it++) { (*it)->addProperty(new PhysicObject(prop)); prop.mass += 1.0; (*it)->addProperty(new MeshRenderer(cube,gradientmats[nbDuckLight%4])); if(nbDuckLight < 0) { light = new Light(false); if(nbDuckLight % 3 == 0) { light->setDiffuseColor(Vector4f(0.2,0.2,1.0,1.0)); light->setSpecularColor(Vector4f(0.2,0.2,1.0,1.0)); } else if(nbDuckLight % 3 == 1) { light->setDiffuseColor(Vector4f(1.0,0.2,0.2,1.0)); light->setSpecularColor(Vector4f(1.0,0.2,0.2,1.0)); } else { light->setDiffuseColor(Vector4f(0.2,1.0,0.2,1.0)); light->setSpecularColor(Vector4f(0.2,1.0,0.2,1.0)); } (*it)->addProperty(light); } nbDuckLight++; } // Beurk ! Mais je peux le faire alors je me prive pas ^^ //RENDER_MANAGER.setCurrentCamera(static_cast<Camera*>(nCamFollow->properties().child("Camera"))); RENDER_MANAGER.setCurrentCamera(static_cast<Camera*>(nCamFollow->properties().child("Camera"))); RenderManager::Background background; background.type = RenderManager::Background::SKYBOX; background.color = Vector3f(0.5,0.5,0.5); background.sunDirection = Vector3f(10,5,10); background.textures[0] = TEXTURE_MANAGER.get("stormy_front.tga"); background.textures[1] = TEXTURE_MANAGER.get("stormy_left.tga"); background.textures[2] = TEXTURE_MANAGER.get("stormy_back.tga"); background.textures[3] = TEXTURE_MANAGER.get("stormy_right.tga"); background.textures[4] = TEXTURE_MANAGER.get("stormy_top.tga"); background.textures[5] = TEXTURE_MANAGER.get("stormy_bottom.tga"); RENDER_MANAGER.setBackground(background); RENDER_MANAGER.setAmbient(Vector3f(0.8,0.8,0.8)); COMMAND_MANAGER.registerCommand("spawn_duck",spawn_duck); COMMAND_MANAGER.readFile("config.cfg"); int ret = engine.start(); return ret; }
void MainWindow::onReportsTabChange() { /* QMessageBox *msgBox = new QMessageBox(); msgBox->setWindowTitle("I Worked!!"); msgBox->setInformativeText("The Current index tab is "+ QString::number(ui->reportsTab->currentIndex())); msgBox->show(); */ switch(ui->reportsTab->currentIndex()) { case 0: { QVector<QPointF> data; LinkedList<GolfObject>* r_list = this->p->getRounds(this->p->getId(), new Round()); int count = 0; for(int i = r_list->getSize()-1; i > -1; i--) { int score = ((Round *)r_list->get(i))->getGross(); QPointF point; point.setX(count); point.setY(score); data.push_back(point); count++; } /* * NOTE: 0 = gross scores */ ui->plotter->setCurveData(0, data); break; } /*********************************************************************************************************************************** * This loads the first tableview of rounds tab. * One reason for it not updating when a new round is added could be due to the code location here */ case 1: { LinkedList<GolfObject>* r_List; if(!filterOn) { r_List = p->getRounds(p->getId(), new Round()); } else { r_List = getRoundList(); } ui->tableWidget->setRowCount(r_List->getSize()); ui->tableWidget->setColumnCount(6); ui->tableWidget->setHorizontalHeaderItem(0, new QTableWidgetItem("Date")); ui->tableWidget->setHorizontalHeaderItem(1, new QTableWidgetItem("Time")); ui->tableWidget->setHorizontalHeaderItem(2, new QTableWidgetItem("Weather")); ui->tableWidget->setHorizontalHeaderItem(3, new QTableWidgetItem("Gross")); ui->tableWidget->setHorizontalHeaderItem(4, new QTableWidgetItem("Nett")); ui->tableWidget->setHorizontalHeaderItem(5, new QTableWidgetItem("Stableford")); for(int i = 0 ; i < r_List->getSize(); i++) { ui->tableWidget->setItem(i,0, new QTableWidgetItem(QString::fromStdString(((Round *)r_List->get(i))->getDate()))); ui->tableWidget->setItem(i,1, new QTableWidgetItem(QString::fromStdString(((Round *)r_List->get(i))->getTime()))); ui->tableWidget->setItem(i,2, new QTableWidgetItem(QString::fromStdString(((Round *)r_List->get(i))->getWeather()))); ui->tableWidget->setItem(i,3, new QTableWidgetItem(QString::number(((Round *)r_List->get(i))->getGross()))); ui->tableWidget->setItem(i,4, new QTableWidgetItem(QString::number(((Round *)r_List->get(i))->getNett()))); ui->tableWidget->setItem(i,5, new QTableWidgetItem(QString::number(((Round *)r_List->get(i))->getPoints()))); } QHeaderView* header = ui->tableWidget->horizontalHeader(); header->setSectionResizeMode(QHeaderView::Stretch); break; } } }
void PropertySyncer::handleMessage(const GammaRay::Message& msg) { Q_ASSERT(msg.address() == m_address); switch (msg.type()) { case Protocol::PropertySyncRequest: { Protocol::ObjectAddress addr; msg.payload() >> addr; Q_ASSERT(addr != Protocol::InvalidObjectAddress); const auto it = std::find_if(m_objects.constBegin(), m_objects.constEnd(), [addr](const ObjectInfo &info) { return info.addr == addr; }); if (it == m_objects.constEnd()) break; QVector<QPair<QString, QVariant> > values; const auto propCount = (*it).obj->metaObject()->propertyCount(); values.reserve(propCount); for (int i = qobjectPropertyOffset(); i < propCount; ++i) { const auto prop = (*it).obj->metaObject()->property(i); values.push_back(qMakePair(QString(prop.name()), prop.read((*it).obj))); } Q_ASSERT(!values.isEmpty()); Message msg(m_address, Protocol::PropertyValuesChanged); msg.payload() << addr << (quint32)values.size(); foreach (const auto &value, values) msg.payload() << value.first << value.second; emit message(msg); break; } case Protocol::PropertyValuesChanged: { Protocol::ObjectAddress addr; quint32 changeSize; msg.payload() >> addr >> changeSize; Q_ASSERT(addr != Protocol::InvalidObjectAddress); Q_ASSERT(changeSize > 0); auto it = std::find_if(m_objects.begin(), m_objects.end(), [addr](const ObjectInfo &info) { return info.addr == addr; }); if (it == m_objects.end()) break; for (quint32 i = 0; i < changeSize; ++i) { QString propName; QVariant propValue; msg.payload() >> propName >> propValue; (*it).recursionLock = true; (*it).obj->setProperty(propName.toUtf8(), propValue); // it can be invalid if as a result of the above call new objects have been registered for example it = std::find_if(m_objects.begin(), m_objects.end(), [addr](const ObjectInfo &info) { return info.addr == addr; }); Q_ASSERT(it != m_objects.end()); (*it).recursionLock = false; } break; } default: Q_ASSERT(!"We should not get here!"); } }
void BDOverlayScreen::DisplayBDOverlay(BDOverlay *overlay) { if (!overlay || !m_player) return; if (!overlay->m_data) { m_overlayArea = overlay->m_position; SetArea(MythRect(m_overlayArea)); DeleteAllChildren(); m_overlayMap.clear(); SetRedraw(); LOG(VB_PLAYBACK, LOG_INFO, LOC + QString("Initialised Size: %1x%2 (%3+%4) Plane: %5 Pts: %6") .arg(overlay->m_position.width()) .arg(overlay->m_position.height()) .arg(overlay->m_position.left()) .arg(overlay->m_position.top()) .arg(overlay->m_plane) .arg(overlay->m_pts)); BDOverlay::DeleteOverlay(overlay); return; } if (!m_overlayArea.isValid()) { LOG(VB_GENERAL, LOG_ERR, LOC + "Error: Overlay image submitted before initialisation."); } VideoOutput *vo = m_player->GetVideoOutput(); if (!vo) return; QRect rect = overlay->m_position; QString hash = QString("%1+%2+%3x%4") .arg(rect.left()).arg(rect.top()) .arg(rect.width()).arg(rect.height()); // remove if we already have this overlay if (m_overlayMap.contains(hash)) { LOG(VB_PLAYBACK, LOG_DEBUG, LOC + QString("Removing %1 (%2 left)") .arg(hash).arg(m_overlayMap.size())); MythUIImage *old = m_overlayMap.take(hash); DeleteChild(old); } // convert the overlay palette to ARGB uint32_t *origpalette = (uint32_t *)(overlay->m_palette); QVector<unsigned int> palette; for (int i = 0; i < 256; i++) { int y = (origpalette[i] >> 0) & 0xff; int cr = (origpalette[i] >> 8) & 0xff; int cb = (origpalette[i] >> 16) & 0xff; int a = (origpalette[i] >> 24) & 0xff; int r = int(y + 1.4022 * (cr - 128)); int b = int(y + 1.7710 * (cb - 128)); int g = int(1.7047 * y - (0.1952 * b) - (0.5647 * r)); if (r < 0) r = 0; if (g < 0) g = 0; if (b < 0) b = 0; if (r > 0xff) r = 0xff; if (g > 0xff) g = 0xff; if (b > 0xff) b = 0xff; palette.push_back((a << 24) | (r << 16) | (g << 8) | b); } // convert the image to QImage QImage img(rect.size(), QImage::Format_Indexed8); memcpy(img.bits(), overlay->m_data, rect.width() * rect.height()); img.setColorTable(palette); img.convertToFormat(QImage::Format_ARGB32); // add to screen QRect scaled = vo->GetImageRect(rect); if (scaled.size() != rect.size()) { img = img.scaled(scaled.width(), scaled.height(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation); } MythPainter *osd_painter = vo->GetOSDPainter(); MythImage* image = NULL; if (osd_painter) image = osd_painter->GetFormatImage(); if (image) { image->Assign(img); MythUIImage *uiimage = new MythUIImage(this, "bdoverlay"); if (uiimage) { uiimage->SetImage(image); uiimage->SetArea(MythRect(scaled)); m_overlayMap.insert(hash, uiimage); LOG(VB_PLAYBACK, LOG_DEBUG, LOC + QString("Added %1 (%2 tot)") .arg(hash).arg(m_overlayMap.size())); } } SetRedraw(); BDOverlay::DeleteOverlay(overlay); }
void CTimeline::paintEvent(QPaintEvent* event) { const QRect rect = event->rect(); int tablePosY = m_viewPos.y() / m_rowHeight - 1; if (tablePosY < 0) tablePosY = 0; int tablePosX = m_viewPos.x() / m_frameWidth - 1; if (tablePosX < 0) tablePosX = 0; m_painter.begin(this); m_painter.fillRect(rect, QColor(212, 208, 200)); m_painter.setClipRect(rect); m_painter.setClipping(true); m_painter.translate(QPoint(0, -m_viewPos.y())); QVector<QLine> greyLines; QVector<QLine> blackLines; m_painter.setPen(Qt::black); m_painter.setFont(m_font); if (tablePosY == 0) m_painter.drawText(QRect(4, 0, m_leftWidth, m_rowHeight), "Frame"); greyLines.push_back(QLine(0, m_rowHeight - 1, rect.right(), m_rowHeight - 1)); greyLines.push_back(QLine(0, m_rowHeight, rect.right(), m_rowHeight)); int i, j; for (i = tablePosY; i < m_rows.size(); i++) { const Row& row = m_rows[i]; if (i == m_selection.y()) m_painter.fillRect(QRect(0, (i + 1) * m_rowHeight, rect.right(), m_rowHeight), QColor(230, 230, 230)); greyLines.push_back(QLine(rect.left(), (i + 2) * m_rowHeight, rect.right(), (i + 2) * m_rowHeight)); m_painter.drawText(QRect(4, (i + 1) * m_rowHeight, m_leftWidth, m_rowHeight), row.name); if ((i + 2) * m_rowHeight >= rect.bottom() + m_viewPos.y()) break; } if (m_frameCount != -1) { i = m_leftWidth + m_frameCount * m_frameWidth - m_viewPos.x() + 2; if (i < m_leftWidth) i = m_leftWidth; m_painter.fillRect(QRect(i, 0, i + rect.width() - m_leftWidth, rect.bottom() + m_viewPos.y() + 1), QColor(0, 0, 0, 30)); } blackLines.push_back(QLine(m_leftWidth - 4, m_viewPos.y(), m_leftWidth - 4, rect.bottom() + m_viewPos.y())); blackLines.push_back(QLine(m_leftWidth - 1, m_viewPos.y(), m_leftWidth - 1, rect.bottom() + m_viewPos.y())); m_painter.setPen(QColor(170, 170, 170)); m_painter.drawLines(greyLines); m_painter.setPen(Qt::black); m_painter.drawLines(blackLines); greyLines.clear(); blackLines.clear(); QVector<QLine> redLines; m_painter.setClipRect(QRect(m_leftWidth, m_viewPos.y(), rect.right() - m_leftWidth, m_viewPos.y() + rect.bottom())); m_painter.translate(QPoint(m_leftWidth - m_viewPos.x() + m_frameWidth / 2 + 1, 0)); const int maxRight = m_viewPos.x() + rect.right() - m_leftWidth; int pos; for (i = tablePosX; i * m_frameWidth <= maxRight; i++) { pos = i * m_frameWidth; if (i % 5 == 0) { greyLines.push_back(QLine(pos, m_rowHeight + 1, pos, m_viewPos.y() + rect.bottom() + 1)); blackLines.push_back(QLine(pos, 0, pos, m_rowHeight - 1)); m_painter.drawText(QRect(pos + 2, -2, m_frameWidth * 2 - 1, m_rowHeight), QString::number(i)); } else blackLines.push_back(QLine(pos, m_rowHeight - 5, pos, m_rowHeight - 1)); } redLines.push_back(QLine(m_currentFrame * m_frameWidth, m_viewPos.y(), m_currentFrame * m_frameWidth, m_viewPos.y() + rect.bottom() + 1)); redLines.push_back(QLine(m_currentFrame * m_frameWidth - 1, m_viewPos.y(), m_currentFrame * m_frameWidth - 1, m_viewPos.y() + rect.bottom() + 1)); m_painter.setPen(QColor(170, 170, 170)); m_painter.drawLines(greyLines); m_painter.setPen(Qt::black); m_painter.drawLines(blackLines); for (i = tablePosY; i < m_rows.size(); i++) { const Row& row = m_rows[i]; if (row.keys.size() > 0) { m_painter.setBrush(row.color); for (j = 0; j < row.keys.size(); j++) { pos = row.keys[j] * m_frameWidth; if (pos >= m_viewPos.x() - m_frameWidth && pos <= maxRight) { if (m_selection.x() == j && m_selection.y() == i) { m_painter.setBrush(QColor(255, 255, 0)); m_painter.drawEllipse(QPoint(pos, (i + 1) * m_rowHeight + m_rowHeight / 2 + 1), m_frameWidth / 2 - 2, m_rowHeight / 2 - 2); m_painter.setBrush(row.color); } else m_painter.drawEllipse(QPoint(pos, (i + 1) * m_rowHeight + m_rowHeight / 2 + 1), m_frameWidth / 2 - 2, m_rowHeight / 2 - 2); } } } } m_painter.setPen(Qt::red); m_painter.drawLines(redLines); m_painter.end(); event->accept(); }
QString Splitter::getTheSplitAsString()const{ QVector<QString> colors; colors.push_back("<font color=\"#000000\">"); colors.push_back("<font color=\"#ff0033\">"); colors.push_back("<font color=\"#aa5500\">"); colors.push_back("<font color=\"#0000ff\">"); colors.push_back("<font color=\"#00ff00\">"); colors.push_back("<font color=\"#ff0000\">"); colors.push_back("<font color=\"#ffff00\">"); colors.push_back("<font color=\"#00ffff\">"); colors.push_back("<font color=\"#ff00ff\">"); colors.push_back("<font color=\"#880088\">"); colors.push_back("<font color=\"#880000\">"); colors.push_back("<font color=\"#008800\">"); colors.push_back("<font color=\"#000088\">"); colors.push_back("<font color=\"#888800\">"); colors.push_back("<font color=\"#008888\">"); colors.push_back("<font color=\"#5533ff\">"); colors.push_back("<font color=\"#a2b64f\">"); colors.push_back("<font color=\"#000000\">"); colors.push_back("<font color=\"#000000\">"); colors.push_back("<font color=\"#000000\">"); colors.push_back("<font color=\"#000000\">"); colors.push_back("<font color=\"#000000\">"); colors.push_back("<font color=\"#000000\">"); colors.push_back("<font color=\"#000000\">"); colors.push_back("<font color=\"#000000\">"); colors.push_back("<font color=\"#000000\">"); std::cout << worlds.size(); world buffer(worlds[0]); for(int x=0; x<buffer.getSizeX(); ++x){ for(int y=0; y<buffer.getSizeY(); ++y){ buffer.setValue(x,y,0); } } for(int i=1; i<worlds.size(); ++i){ for(int x=0; x<buffer.getSizeX(); ++x){ for(int y=0; y<buffer.getSizeY(); ++y){ if(worlds[i].getValue(x,y) == 0) buffer.setValue(x,y,i); } } } std::stringstream str; str << "<html><body>" << std::endl; for(int x=0; x<buffer.getSizeX(); ++x){ for(int y=0; y<buffer.getSizeY(); ++y){ str << colors[buffer.getValue(x,y)%25].toStdString() << 0 << "</font>"; } str << "<br>" << std::endl; } str << "</body></html>" << std::endl; return str.str().c_str(); }
bool Graphics::toGif(QImage& img, QString& path) { int errcode; if(QFile(path).exists()) // Remove old file QFile::remove(path); GifFileType* t = EGifOpenFileName(path.toStdString().c_str(),true, &errcode); if(!t){ EGifCloseFile(t, &errcode); std::cout << "Can't open\n"; return false; } EGifSetGifVersion(t, true); GifColorType* colorArr = new GifColorType[256]; ColorMapObject* cmo = GifMakeMapObject(256, colorArr); bool unfinished = false; QImage tarQImg(img.width(), img.height(), QImage::Format_Indexed8); QVector<QRgb> table; for(int y = 0; y < img.height(); y++){ for(int x = 0; x < img.width(); x++){ if(table.size() >= 256){ unfinished = true; break; } QRgb pix; if(!table.contains(pix = img.pixel(x,y))){ table.push_back(pix); tarQImg.setColor(tarQImg.colorCount(), pix); } tarQImg.setPixel(x,y,table.indexOf(pix)); } if(table.size() >= 256){ unfinished = true; break; } } if(unfinished){ EGifCloseFile(t, &errcode); std::cout << "Unfinished\n"; return false; } for(int l = tarQImg.colorCount(); l < 256; l++){ tarQImg.setColor(l,0); } if(tarQImg.colorTable().size() != 256){ EGifCloseFile(t, &errcode); std::cout << "A lot of colors\n"; return false; } QVector<QRgb> clTab = tarQImg.colorTable(); for(int i = 0; i < 255; i++){ QRgb rgb = clTab[i]; colorArr[i].Red = qRed(rgb); colorArr[i].Green = qGreen(rgb); colorArr[i].Blue = qBlue(rgb); } cmo->Colors = colorArr; errcode = EGifPutScreenDesc(t, img.width(), img.height(), 256, 0, cmo); if(errcode != GIF_OK){ EGifCloseFile(t, &errcode); std::cout << "EGifPutScreenDesc error 1\n"; return false; } errcode = EGifPutImageDesc(t, 0, 0, img.width(), img.height(), false, 0); if(errcode != GIF_OK){ EGifCloseFile(t, &errcode); std::cout << "EGifPutImageDesc error 2\n"; return false; } //gen byte array GifByteType* byteArr = tarQImg.bits(); for(int h = 0; h < tarQImg.height(); h++){ errcode = EGifPutLine(t, byteArr, tarQImg.width()); if(errcode != GIF_OK){ EGifCloseFile(t, &errcode); std::cout << "EGifPutLine error 3\n"; return false; } byteArr += tarQImg.width(); byteArr += ((tarQImg.width() % 4)!=0 ? 4 - (tarQImg.width() % 4) : 0); } if(errcode != GIF_OK){ std::cout << "GIF error 4\n"; return false; } EGifCloseFile(t, &errcode); return true; }
int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); QVector<Server> servers; //wczytanie konfiguracji QSettings settings("client.cfg", QSettings::IniFormat); settings.sync(); int serversCount = settings.value("info/serversCount", 0).toInt(); if(serversCount == 0) { //błąd, nie ma adresów std::cerr << "No known servers in configuration file" << std::endl; return 2; } for(int i=1; i<=serversCount; ++i) { Server server; server.name = settings.value("server"+QString::number(i)+"/name", "unknown server").toString(); server.ip = QHostAddress(settings.value("server"+QString::number(i)+"/ip", "0.0.0.0").toString()); server.port = settings.value("server"+QString::number(i)+"/port", "0").toInt(); servers.push_back(server); } //połączenie i pobranie listy serwerów Client client; client.setServers(&servers); client.settings = &settings; //std::cout << "ACT?" << std::endl; if(client.send(QStringList() << "ACTIVE_SERVERS") == NO_SERVERS) { std::cout << "nie można się z niczym połączyć lub nikt nie akceptuje zapytań\n"; exit(10); } client.socket.waitForReadyRead(15000); /*if(client.queue == 0) exit(0);*/ //sprawdzenie parametrów wywołania QStringList args = QCoreApplication::arguments(); if(args.size() > 1) { if(args.at(1) == "list") { if(client.send(QStringList() << "GET_AVAILABLE_RESULTS" << "*") == NO_SERVERS) { std::cout << "nie można się z niczym połączyć lub nikt nie akceptuje zapytań\n"; exit(10); } } else if(args.at(1) == "get") { if(client.send(QStringList() << "GET_RESULT" << args.at(2)) == NO_SERVERS) { std::cout << "nie można się z niczym połączyć lub nikt nie akceptuje zapytań\n"; exit(10); } } else if(args.at(1) == "find") { //<nazwa badania>,<kraj>,<płeć>,<rasa>,<minimalny wiek>,<maksymalny wiek> if(client.send(QStringList() << "GET_AVAILABLE_RESULTS" << args.at(2) << args.at(3) << \ args.at(4) << args.at(5) << args.at(6) << args.at(7)) == NO_SERVERS) { std::cout << "nie można się z niczym połączyć lub nikt nie akceptuje zapytań\n"; exit(10); } } else if(args.at(1) == "stats") { //<nazwa badania>,<data od>,<data do>,<kraj>,<płeć>,<rasa>,<minimalny wiek>,<maksymalny wiek>, //{<pole grupowania 1>,<pole grupowania 2>,<...>} QStringList a = args.at(10).split(""); a.pop_back(); a.pop_front(); QString grupowanie = "{"+a.join(",")+"}"; std::cout << grupowanie.toStdString() << std::endl; if(client.send(QStringList() << "GET_AVAILABLE_RESULTS" << args.at(2) << args.at(3) << \ args.at(4) << args.at(5) << args.at(6) << args.at(7) << args.at(8) << args.at(9)\ << grupowanie) == NO_SERVERS) { std::cout << "nie można się z niczym połączyć lub nikt nie akceptuje zapytań\n"; exit(10); } } } client.socket.waitForReadyRead(15000); exit(0); return a.exec(); }
CObjectPropertiesDialog::CObjectPropertiesDialog(CObject* obj, QWidget* parent) : QDialog(parent), m_obj(null) { ui.setupUi(this); setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); QVector<int> enabledTabs; switch (obj->m_type) { case OT_MOVER: enabledTabs.append(0); enabledTabs.append(2); break; case OT_ITEM: enabledTabs.append(0); break; case OT_CTRL: enabledTabs.append(0); enabledTabs.append(3); break; case OT_REGION: switch (obj->m_modelID) { case RI_STRUCTURE: enabledTabs.append(4); break; case RI_REVIVAL: case RI_PLACE: enabledTabs.append(1); break; case RI_ATTRIBUTE: case RI_TRIGGER: enabledTabs.append(5); break; } break; case OT_PATH: enabledTabs.append(6); break; } const int count = ui.tabWidget->tabBar()->count(); for (int i = 0, j = 0; i < count; i++, j++) { if (!enabledTabs.contains(i)) { QWidget* widget = ui.tabWidget->widget(j); Delete(widget); j--; } } ui.tabWidget->setCurrentIndex(0); if (obj->m_type == OT_MOVER || obj->m_type == OT_ITEM || obj->m_type == OT_CTRL) { CSpawnObject* spawn = (CSpawnObject*)obj; ui.spawn->setChecked(spawn->m_isRespawn); ui.spawnCount->setValue(spawn->m_count); ui.spawnAttackCount->setValue(spawn->m_attackCount); ui.spawnTime->setValue(spawn->m_time); ui.spawnDayMin->setValue(spawn->m_dayMin); ui.spawnDayMax->setValue(spawn->m_dayMax); ui.spawnHourMin->setValue(spawn->m_hourMin); ui.spawnHourMax->setValue(spawn->m_hourMax); ui.spawnItemMin->setValue(spawn->m_itemMin); ui.spawnItemMax->setValue(spawn->m_itemMax); connect(ui.spawn, SIGNAL(clicked(bool)), this, SLOT(SetSpawn(bool))); connect(ui.spawnCount, SIGNAL(valueChanged(int)), this, SLOT(SetSpawnCount(int))); if (obj->m_type == OT_MOVER) { CMover* mover = (CMover*)obj; CTextFile::FillComboBox(ui.moverAI, "AII_", mover->m_AIInterface); CTextFile::FillComboBox(ui.moverBelli, "BELLI_", mover->m_belligerence); Project->FillCharacterComboBox(ui.moverNPC, mover->m_characterKey); QVector<string> states; states.push_back("STATE_INIT"); states.push_back("STATE_IDLE"); states.push_back("STATE_WANDER"); states.push_back("STATE_PURSUE"); states.push_back("STATE_EVADE"); states.push_back("STATE_RUNAWAY"); states.push_back("STATE_RAGE"); states.push_back("STATE_STAND"); states.push_back("STATE_PATROL"); states.push_back("STATE_RAGE_PATROL"); for (int i = 0; i < states.size(); i++) { ui.moverAIState->addItem(states[i]); if (i + 1 == mover->m_aiState) ui.moverAIState->setCurrentIndex(i); } if (mover->m_world) { ui.moverPatrolIndex->addItem("-", -1); int i = 1; for (auto it = mover->m_world->m_paths.begin(); it != mover->m_world->m_paths.end(); it++) { ui.moverPatrolIndex->addItem("Path " % string::number(it.key()), it.key()); if (it.key() == mover->m_patrolIndex) ui.moverPatrolIndex->setCurrentIndex(i); i++; } if (mover->m_patrolIndex == -1) ui.moverPatrolIndex->setCurrentIndex(0); } ui.moverPatrolCycle->setChecked(mover->m_patrolCycle != 0); connect(ui.moverPatrolIndex, SIGNAL(currentIndexChanged(int)), this, SLOT(SetMoverPatrolIndex(int))); connect(ui.moverNPC, SIGNAL(currentIndexChanged(const QString&)), this, SLOT(SetMoverCharacter(const QString&))); }
void QgsTextDiagram::renderDiagram( const QgsFeature& feature, QgsRenderContext& c, const QgsDiagramSettings& s, QPointF position ) { QPainter* p = c.painter(); if ( !p ) { return; } //convert from mm / map units to painter units QSizeF spu = sizePainterUnits( s.size, s, c ); double w = spu.width(); double h = spu.height(); double baseX = position.x(); double baseY = position.y() - h; QVector<QPointF> textPositions; //midpoints for text placement int nCategories = s.categoryAttributes.size(); for ( int i = 0; i < nCategories; ++i ) { if ( mOrientation == Horizontal ) { textPositions.push_back( QPointF( baseX + ( w / nCategories ) * i + w / nCategories / 2.0, baseY + h / 2.0 ) ); } else //vertical { textPositions.push_back( QPointF( baseX + w / 2.0, baseY + h / nCategories * i + w / nCategories / 2.0 ) ); } } mPen.setColor( s.penColor ); setPenWidth( mPen, s, c ); p->setPen( mPen ); mBrush.setColor( s.backgroundColor ); p->setBrush( mBrush ); //draw shapes and separator lines first if ( mShape == Circle ) { p->drawEllipse( baseX, baseY, w, h ); //draw separator lines QList<QPointF> intersect; //intersections between shape and separation lines QPointF center( baseX + w / 2.0, baseY + h / 2.0 ); double r1 = w / 2.0; double r2 = h / 2.0; for ( int i = 1; i < nCategories; ++i ) { if ( mOrientation == Horizontal ) { lineEllipseIntersection( QPointF( baseX + w / nCategories * i, baseY ), QPointF( baseX + w / nCategories * i, baseY + h ), center, r1, r2, intersect ); } else //vertical { lineEllipseIntersection( QPointF( baseX, baseY + h / nCategories * i ), QPointF( baseX + w, baseY + h / nCategories * i ), center, r1, r2, intersect ); } if ( intersect.size() > 1 ) { p->drawLine( intersect.at( 0 ), intersect.at( 1 ) ); } } } else if ( mShape == Rectangle ) { p->drawRect( QRectF( baseX, baseY, w, h ) ); for ( int i = 1; i < nCategories; ++i ) { if ( mOrientation == Horizontal ) { p->drawLine( QPointF( baseX + w / nCategories * i, baseY ), QPointF( baseX + w / nCategories * i, baseY + h ) ); } else { p->drawLine( QPointF( baseX, baseY + h / nCategories * i ), QPointF( baseX + w, baseY + h / nCategories * i ) ); } } } else //triangle { QPolygonF triangle; triangle << QPointF( baseX, baseY + h ) << QPointF( baseX + w, baseY + h ) << QPointF( baseX + w / 2.0, baseY ); p->drawPolygon( triangle ); QLineF triangleEdgeLeft( baseX + w / 2.0, baseY, baseX, baseY + h ); QLineF triangleEdgeRight( baseX + w, baseY + h, baseX + w / 2.0, baseY ); QPointF intersectionPoint1, intersectionPoint2; for ( int i = 1; i < nCategories; ++i ) { if ( mOrientation == Horizontal ) { QLineF verticalLine( baseX + w / nCategories * i, baseY + h, baseX + w / nCategories * i, baseY ); if ( baseX + w / nCategories * i < baseX + w / 2.0 ) { verticalLine.intersect( triangleEdgeLeft, &intersectionPoint1 ); } else { verticalLine.intersect( triangleEdgeRight, &intersectionPoint1 ); } p->drawLine( QPointF( baseX + w / nCategories * i, baseY + h ), intersectionPoint1 ); } else //vertical { QLineF horizontalLine( baseX, baseY + h / nCategories * i, baseX + w, baseY + h / nCategories * i ); horizontalLine.intersect( triangleEdgeLeft, &intersectionPoint1 ); horizontalLine.intersect( triangleEdgeRight, &intersectionPoint2 ); p->drawLine( intersectionPoint1, intersectionPoint2 ); } } } //draw text QFont sFont = scaledFont( s, c ); QFontMetricsF fontMetrics( sFont ); p->setFont( sFont ); QgsExpressionContext expressionContext = c.expressionContext(); expressionContext.setFeature( feature ); if ( feature.fields() ) expressionContext.setFields( *feature.fields() ); for ( int i = 0; i < textPositions.size(); ++i ) { QgsExpression* expression = getExpression( s.categoryAttributes.at( i ), expressionContext ); QString val = expression->evaluate( &expressionContext ).toString(); //find out dimesions double textWidth = fontMetrics.width( val ); double textHeight = fontMetrics.height(); mPen.setColor( s.categoryColors.at( i ) ); p->setPen( mPen ); QPointF position = textPositions.at( i ); // Calculate vertical placement double xOffset = 0; switch ( s.labelPlacementMethod ) { case QgsDiagramSettings::Height: xOffset = textHeight / 2.0; break; case QgsDiagramSettings::XHeight: xOffset = fontMetrics.xHeight(); break; } p->drawText( QPointF( position.x() - textWidth / 2.0, position.y() + xOffset ), val ); } }
bool LayoutLoader::readAsaElcFile(const QString& path, QStringList &channelNames, QList<QVector<double> > &location3D, QList<QVector<double> > &location2D, QString &unit) { //Open .elc file if(!path.contains(".elc")) return false; QFile file(path); if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) { qDebug()<<"Error opening elc file"; return false; } //Start reading from file double numberElectrodes; QTextStream in(&file); bool read2D = false; while(!in.atEnd()) { QString line = in.readLine(); QStringList fields = line.split(QRegExp("\\s+")); //Delete last element if it is a blank character if(fields.at(fields.size()-1) == "") fields.removeLast(); if(!line.contains("#")) //Skip commented areas in file { //Read number of electrodes if(line.contains("NumberPositions")) numberElectrodes = fields.at(1).toDouble(); //Read the unit of the position values if(line.contains("UnitPosition")) unit = fields.at(1); //Read actual electrode positions if(line.contains("Positions2D")) read2D = true; if(line.contains(":") && !read2D) //Read 3D positions { channelNames.push_back(fields.at(0)); QVector<double> posTemp; posTemp.push_back(fields.at(fields.size()-3).toDouble()); //x posTemp.push_back(fields.at(fields.size()-2).toDouble()); //y posTemp.push_back(fields.at(fields.size()-1).toDouble()); //z location3D.append(posTemp); } if(line.contains(":") && read2D) //Read 2D positions { QVector<double> posTemp; posTemp.push_back(fields.at(fields.size()-2).toDouble()); //x posTemp.push_back(fields.at(fields.size()-1).toDouble()); //y location2D.append(posTemp); } //Read channel names if(line.contains("Labels")) { line = in.readLine(); fields = line.split(QRegExp("\\s+")); //Delete last element if it is a blank character if(fields.at(fields.size()-1) == "") fields.removeLast(); channelNames = fields; } } } Q_UNUSED(numberElectrodes); file.close(); return true; }
void OsmAnd::MapRasterizer_P::rasterizePolygon( const Context& context, SkCanvas& canvas, const std::shared_ptr<const MapPrimitiviser::Primitive>& primitive) { const auto& points31 = primitive->sourceObject->points31; const auto& area31 = context.area31; assert(points31.size() > 2); assert(primitive->sourceObject->isClosedFigure()); assert(primitive->sourceObject->isClosedFigure(true)); ////////////////////////////////////////////////////////////////////////// //if ((primitive->sourceObject->id >> 1) == 9223372032559801460u) //{ // int i = 5; //} ////////////////////////////////////////////////////////////////////////// SkPaint paint = _defaultPaint; if (!updatePaint(context, paint, primitive->evaluationResult, PaintValuesSet::Layer_1, true)) return; // Construct and test geometry against bbox area SkPath path; bool containsAtLeastOnePoint = false; int pointIdx = 0; PointF vertex; Utilities::CHValue prevChValue; QVector< PointI > outerPoints; const auto pointsCount = points31.size(); auto pPoint = points31.constData(); for (auto pointIdx = 0; pointIdx < pointsCount; pointIdx++, pPoint++) { const auto& point = *pPoint; calculateVertex(context, point, vertex); // Hit-test if (!containsAtLeastOnePoint) { if (area31.contains(point)) containsAtLeastOnePoint = true; else outerPoints.push_back(point); const auto chValue = Utilities::computeCohenSutherlandValue(point, area31); if (Q_LIKELY(pointIdx > 0)) { // Check if line crosses area (reject only if points are on the same side) const auto intersectedChValue = prevChValue & chValue; if (static_cast<unsigned int>(intersectedChValue) != 0) containsAtLeastOnePoint = true; } prevChValue = chValue; } // Plot vertex if (pointIdx == 0) path.moveTo(vertex.x, vertex.y); else path.lineTo(vertex.x, vertex.y); } ////////////////////////////////////////////////////////////////////////// //if ((primitive->sourceObject->id >> 1) == 9223372032559801460u) //{ // int i = 5; //} ////////////////////////////////////////////////////////////////////////// if (!containsAtLeastOnePoint) { // Check area is inside polygon bool ok = true; ok = ok || containsHelper(outerPoints, area31.topLeft); ok = ok || containsHelper(outerPoints, area31.bottomRight); ok = ok || containsHelper(outerPoints, PointI(0, area31.bottom())); ok = ok || containsHelper(outerPoints, PointI(area31.right(), 0)); if (!ok) return; } ////////////////////////////////////////////////////////////////////////// //if ((primitive->sourceObject->id >> 1) == 95692962u) //{ // int i = 5; //} ////////////////////////////////////////////////////////////////////////// if (!primitive->sourceObject->innerPolygonsPoints31.isEmpty()) { path.setFillType(SkPath::kEvenOdd_FillType); for (const auto& polygon : constOf(primitive->sourceObject->innerPolygonsPoints31)) { pointIdx = 0; for (auto itVertex = cachingIteratorOf(constOf(polygon)); itVertex; ++itVertex, pointIdx++) { const auto& point = *itVertex; calculateVertex(context, point, vertex); if (pointIdx == 0) path.moveTo(vertex.x, vertex.y); else path.lineTo(vertex.x, vertex.y); } } } canvas.drawPath(path, paint); if (updatePaint(context, paint, primitive->evaluationResult, PaintValuesSet::Layer_2, false)) canvas.drawPath(path, paint); }
int l_get_next_buffer_of_timecode(QStringList &csv_data, QVector<float> &channel_1, QVector<float> &channel_2, float &expected_speed) { // Init. channel_1.clear(); channel_2.clear(); expected_speed = -99; // speed not found. if (csv_data.size() == 0) { return true; // EOF } QString line = csv_data.at(0); csv_data.removeAt(0); if (csv_data.size() == 0) { return true; // EOF } // Parse until beginning of a buffer. while (line.startsWith("buffer_size;speed") == false) { line = csv_data.at(0); csv_data.removeAt(0); if (csv_data.size() == 0) { return true; // EOF } } // Get line for buffer size and expected speed. line = csv_data.at(0); csv_data.removeAt(0); if (csv_data.size() == 0) { return true; // EOF } QStringList buffer_and_speed = line.split(';'); // Remove "channel1;channel2" line = csv_data.at(0); csv_data.removeAt(0); if (csv_data.size() == 0) { return true; // EOF } // Get buffer size. int buffer_size = buffer_and_speed.at(0).toInt(); // Get data. if (csv_data.size() >= buffer_size) { for (int i = 0; i < buffer_size; i++) { line = csv_data.at(0); csv_data.removeAt(0); channel_1.push_back(line.split(';').at(0).toFloat()); channel_2.push_back(line.split(';').at(1).toFloat()); } } else { return true; // EOF } // Get expected speed. if (buffer_and_speed.at(1) != "TODO") { expected_speed = buffer_and_speed.at(1).toFloat(); } return false; }
QVector<QVector<Tile>> Maze::setTileDistances(QVector<QVector<Tile>> maze) { // TODO: MACK - dedup some of this with hasNoInaccessibleLocations // The maze is guarenteed to be nonempty and rectangular int width = maze.size(); int height = maze.at(0).size(); // Helper lambda for retrieving and adjacent tile if one exists, nullptr if not // TODO: MACK - this should be in maze utilities too auto getNeighbor = [&maze, &width, &height](int x, int y, Direction direction) { switch (direction) { case Direction::NORTH: return (y < height - 1 ? &maze[x][y + 1] : nullptr); case Direction::EAST: return (x < width - 1 ? &maze[x + 1][y] : nullptr); case Direction::SOUTH: return (0 < y ? &maze[x][y - 1] : nullptr); case Direction::WEST: return (0 < x ? &maze[x - 1][y] : nullptr); } }; // Determine all of the center tiles // TODO: MACK - use the maze checker function for this QVector<Tile*> centerTiles; centerTiles.push_back(&maze[(width - 1) / 2][(height - 1) / 2]); if (width % 2 == 0) { centerTiles.push_back(&maze[ width / 2][(height - 1) / 2]); if (height % 2 == 0) { centerTiles.push_back(&maze[(width - 1) / 2][ height / 2]); centerTiles.push_back(&maze[ width / 2][ height / 2]); } } else if (height % 2 == 0) { centerTiles.push_back(&maze[(width - 1) / 2][ height / 2]); } // The queue for the BFS QQueue<Tile*> discovered; // Set the distances of the center tiles and push them to the queue for (Tile* tile : centerTiles) { tile->setDistance(0); discovered.enqueue(tile); } // Now do a BFS while (!discovered.empty()){ Tile* tile = discovered.dequeue(); for (Direction direction : DIRECTIONS) { if (!tile->isWall(direction)) { Tile* neighbor = getNeighbor(tile->getX(), tile->getY(), direction); if (neighbor != nullptr && neighbor->getDistance() == -1) { neighbor->setDistance(tile->getDistance() + 1); discovered.enqueue(neighbor); } } } } return maze; }
void ValgrindMemcheckParserTest::testMemcheckSample1() { initTest("memcheck-output-sample1.xml"); QList<Error> expectedErrors; { Error error; error.setKind(InvalidRead); error.setWhat("Invalid read of size 4"); error.setUnique(0x9); error.setTid(1); Frame f1; f1.setInstructionPointer(0x6E47964); f1.setObject("/usr/lib/libQtGui.so.4.7.0"); f1.setFunctionName("QFrame::frameStyle() const"); f1.setDirectory("/build/buildd/qt4-x11-4.7.0/src/gui/widgets"); f1.setFileName("qframe.cpp"); f1.setLine(252); Frame f2; f2.setInstructionPointer(0x118F2AF7); f2.setObject("/usr/lib/kde4/plugins/styles/oxygen.so"); Frame f3; f3.setInstructionPointer(0x6A81671); f3.setObject("/usr/lib/libQtGui.so.4.7.0"); f3.setFunctionName("QWidget::event(QEvent*)"); f3.setDirectory("/build/buildd/qt4-x11-4.7.0/src/gui/kernel"); f3.setFileName("qwidget.cpp"); f3.setLine(8273); Frame f4; f4.setInstructionPointer(0x6A2B6EB); f4.setObject("/usr/lib/libQtGui.so.4.7.0"); f4.setDirectory("/build/buildd/qt4-x11-4.7.0/src/gui/kernel"); f4.setFileName("qapplication.cpp"); f4.setFunctionName("QApplicationPrivate::notify_helper(QObject*, QEvent*)"); f4.setLine(4396); Stack s1; s1.setAuxWhat("Address 0x11527cb8 is not stack'd, malloc'd or (recently) free'd"); s1.setFrames(QVector<Frame>() << f1 << f2 << f3 << f4); error.setStacks( QVector<Stack>() << s1 ); expectedErrors << error; } QVector<QPair<qint64,qint64> > expectedErrorCounts; expectedErrorCounts.push_back(QPair<qint64,qint64>(9, 2)); QVector<QPair<QString,qint64> > expectedSuppCounts; expectedSuppCounts.push_back(qMakePair(QString("X on SUSE11 writev uninit padding"), static_cast<qint64>(12))); expectedSuppCounts.push_back(qMakePair(QString("dl-hack3-cond-1"), static_cast<qint64>(2))); expectedSuppCounts.push_back(qMakePair(QString("glibc-2.5.x-on-SUSE-10.2-(PPC)-2a"), static_cast<qint64>(2))); Parser parser; Recorder rec(&parser); parser.parse(m_socket); m_process->waitForFinished(); QCOMPARE(m_process->exitStatus(), QProcess::NormalExit); QCOMPARE(m_process->state(), QProcess::NotRunning); QVERIFY2(parser.errorString().isEmpty(), qPrintable(parser.errorString())); const QList<Error> actualErrors = rec.errors; if (actualErrors.first() != expectedErrors.first()) { dumpError(actualErrors.first()); dumpError(expectedErrors.first()); } QCOMPARE(actualErrors.first(), expectedErrors.first()); QCOMPARE(actualErrors.size(), 3); QCOMPARE(rec.errorcounts, expectedErrorCounts); QCOMPARE(rec.suppcounts, expectedSuppCounts); }
void HoleFinderPrivate::mergeHoles() { // Make copy, clear original, add merged holes back into original QVector<Hole> holeCopy (this->holes); const int numHoles = this->holes.size(); this->holes.clear(); this->holes.reserve(numHoles); // If the bit is on, it has not been merged. If off, it has been. QBitArray mask (holeCopy.size(), true); // Check each pair of unmerged holes. If one contains the other, merge them. QVector<Hole*> toMerge; toMerge.reserve(256); // Way bigger than we need, but certainly sufficient // Temp vars Eigen::Vector3d diffVec; // "i" indexes the "base" hole for (int i = 0; i < numHoles; ++i) { if (!mask.testBit(i)) continue; mask.clearBit(i); Hole &hole_i = holeCopy[i]; toMerge.clear(); toMerge.reserve(256); toMerge.push_back(&hole_i); // "j" indexes the compared holes for (int j = i+1; j < numHoles; ++j) { if (!mask.testBit(j)) continue; Hole &hole_j = holeCopy[j]; diffVec = hole_j.center - hole_i.center; // Use the greater of the two radii const double rad = (hole_i.radius > hole_j.radius) ? hole_i.radius : hole_j.radius; const double radSq = rad * rad; // Check periodic conditions // Convert diffVec to fractional units this->cartToFrac(&diffVec); // Adjust each component to range [-0.5, 0.5] (shortest representation) while (diffVec.x() < -0.5) ++diffVec.x(); while (diffVec.y() < -0.5) ++diffVec.y(); while (diffVec.z() < -0.5) ++diffVec.z(); while (diffVec.x() > 0.5) --diffVec.x(); while (diffVec.y() > 0.5) --diffVec.y(); while (diffVec.z() > 0.5) --diffVec.z(); // Back to cartesian this->fracToCart(&diffVec); // if j is within i's radius, add "j" to the merge list // and mark "j" as merged if (fabs(diffVec.x()) > rad || fabs(diffVec.y()) > rad || fabs(diffVec.z()) > rad || fabs(diffVec.squaredNorm()) > radSq) continue; // no match // match: // Reset j's position to account for periodic wrap-around hole_j.center = hole_i.center + diffVec; mask.clearBit(j); toMerge.push_back(&hole_j); } if (toMerge.size() == 1) this->holes.push_back(hole_i); else this->holes.push_back(reduceHoles(toMerge)); } }
void QgsSingleBandPseudoColorRendererWidget::on_mClassifyButton_clicked() { int bandComboIndex = mBandComboBox->currentIndex(); if ( bandComboIndex == -1 || !mRasterLayer ) { return; } //int bandNr = mBandComboBox->itemData( bandComboIndex ).toInt(); //QgsRasterBandStats myRasterBandStats = mRasterLayer->dataProvider()->bandStatistics( bandNr ); int numberOfEntries; QgsColorRampShader::ColorRamp_TYPE interpolation = static_cast< QgsColorRampShader::ColorRamp_TYPE >( mColorInterpolationComboBox->itemData( mColorInterpolationComboBox->currentIndex() ).toInt() ); bool discrete = interpolation == QgsColorRampShader::DISCRETE; QList<double> entryValues; QVector<QColor> entryColors; double min = lineEditValue( mMinLineEdit ); double max = lineEditValue( mMaxLineEdit ); QScopedPointer< QgsVectorColorRamp > colorRamp( mColorRampComboBox->currentColorRamp() ); if ( mClassificationModeComboBox->itemData( mClassificationModeComboBox->currentIndex() ).toInt() == Continuous ) { if ( colorRamp.data() ) { numberOfEntries = colorRamp->count(); entryValues.reserve( numberOfEntries ); if ( discrete ) { double intervalDiff = max - min; // remove last class when ColorRamp is gradient and discrete, as they are implemented with an extra stop QgsVectorGradientColorRamp* colorGradientRamp = dynamic_cast<QgsVectorGradientColorRamp*>( colorRamp.data() ); if ( colorGradientRamp != NULL && colorGradientRamp->isDiscrete() ) { numberOfEntries--; } else { // if color ramp is continuous scale values to get equally distributed classes. // Doesn't work perfectly when stops are non equally distributed. intervalDiff *= ( numberOfEntries - 1 ) / ( double )numberOfEntries; } // skip first value (always 0.0) for ( int i = 1; i < numberOfEntries; ++i ) { double value = colorRamp->value( i ); entryValues.push_back( min + value * intervalDiff ); } entryValues.push_back( std::numeric_limits<double>::infinity() ); } else { for ( int i = 0; i < numberOfEntries; ++i ) { double value = colorRamp->value( i ); entryValues.push_back( min + value * ( max - min ) ); } } // for continuous mode take original color map colors for ( int i = 0; i < numberOfEntries; ++i ) { entryColors.push_back( colorRamp->color( colorRamp->value( i ) ) ); } } } else // for other classification modes interpolate colors linearly { numberOfEntries = mNumberOfEntriesSpinBox->value(); if ( numberOfEntries < 2 ) return; // < 2 classes is not useful, shouldn't happen, but if it happens save it from crashing if ( mClassificationModeComboBox->itemData( mClassificationModeComboBox->currentIndex() ).toInt() == Quantile ) { // Quantile int bandNr = mBandComboBox->itemData( bandComboIndex ).toInt(); //QgsRasterHistogram rasterHistogram = mRasterLayer->dataProvider()->histogram( bandNr ); double cut1 = std::numeric_limits<double>::quiet_NaN(); double cut2 = std::numeric_limits<double>::quiet_NaN(); QgsRectangle extent = mMinMaxWidget->extent(); int sampleSize = mMinMaxWidget->sampleSize(); // set min and max from histogram, used later to calculate number of decimals to display mRasterLayer->dataProvider()->cumulativeCut( bandNr, 0.0, 1.0, min, max, extent, sampleSize ); entryValues.reserve( numberOfEntries ); if ( discrete ) { double intervalDiff = 1.0 / ( numberOfEntries ); for ( int i = 1; i < numberOfEntries; ++i ) { mRasterLayer->dataProvider()->cumulativeCut( bandNr, 0.0, i * intervalDiff, cut1, cut2, extent, sampleSize ); entryValues.push_back( cut2 ); } entryValues.push_back( std::numeric_limits<double>::infinity() ); } else { double intervalDiff = 1.0 / ( numberOfEntries - 1 ); for ( int i = 0; i < numberOfEntries; ++i ) { mRasterLayer->dataProvider()->cumulativeCut( bandNr, 0.0, i * intervalDiff, cut1, cut2, extent, sampleSize ); entryValues.push_back( cut2 ); } } } else // EqualInterval { entryValues.reserve( numberOfEntries ); if ( discrete ) { // in discrete mode the lowest value is not an entry and the highest // value is inf, there are ( numberOfEntries ) of which the first // and last are not used. double intervalDiff = ( max - min ) / ( numberOfEntries ); for ( int i = 1; i < numberOfEntries; ++i ) { entryValues.push_back( min + i * intervalDiff ); } entryValues.push_back( std::numeric_limits<double>::infinity() ); } else { //because the highest value is also an entry, there are (numberOfEntries - 1) intervals double intervalDiff = ( max - min ) / ( numberOfEntries - 1 ); for ( int i = 0; i < numberOfEntries; ++i ) { entryValues.push_back( min + i * intervalDiff ); } } } if ( !colorRamp.data() ) { //hard code color range from blue -> red (previous default) int colorDiff = 0; if ( numberOfEntries != 0 ) { colorDiff = ( int )( 255 / numberOfEntries ); } entryColors.reserve( numberOfEntries ); for ( int i = 0; i < numberOfEntries; ++i ) { QColor currentColor; int idx = mInvertCheckBox->isChecked() ? numberOfEntries - i - 1 : i; currentColor.setRgb( colorDiff*idx, 0, 255 - colorDiff * idx ); entryColors.push_back( currentColor ); } } else { entryColors.reserve( numberOfEntries ); for ( int i = 0; i < numberOfEntries; ++i ) { int idx = mInvertCheckBox->isChecked() ? numberOfEntries - i - 1 : i; entryColors.push_back( colorRamp->color((( double ) idx ) / ( numberOfEntries - 1 ) ) ); } } } mColormapTreeWidget->clear(); QList<double>::const_iterator value_it = entryValues.begin(); QVector<QColor>::const_iterator color_it = entryColors.begin(); // calculate a reasonable number of decimals to display double maxabs = log10( qMax( qAbs( max ), qAbs( min ) ) ); int nDecimals = qRound( qMax( 3.0 + maxabs - log10( max - min ), maxabs <= 15.0 ? maxabs + 0.49 : 0.0 ) ); for ( ; value_it != entryValues.end(); ++value_it, ++color_it ) { QgsTreeWidgetItemObject* newItem = new QgsTreeWidgetItemObject( mColormapTreeWidget ); newItem->setText( ValueColumn, QString::number( *value_it, 'g', nDecimals ) ); newItem->setBackground( ColorColumn, QBrush( *color_it ) ); newItem->setText( LabelColumn, QString() ); newItem->setFlags( Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemIsSelectable ); connect( newItem, SIGNAL( itemEdited( QTreeWidgetItem*, int ) ), this, SLOT( mColormapTreeWidget_itemEdited( QTreeWidgetItem*, int ) ) ); } autoLabel(); emit widgetChanged(); }
QVector<QString> buildBOPCheckResultVector() { QVector<QString> results; results.push_back(QObject::tr("BOPAlgo CheckUnknown")); //BOPAlgo_CheckUnknown results.push_back(QObject::tr("BOPAlgo BadType")); //BOPAlgo_BadType results.push_back(QObject::tr("BOPAlgo SelfIntersect")); //BOPAlgo_SelfIntersect results.push_back(QObject::tr("BOPAlgo TooSmallEdge")); //BOPAlgo_TooSmallEdge results.push_back(QObject::tr("BOPAlgo NonRecoverableFace")); //BOPAlgo_NonRecoverableFace results.push_back(QObject::tr("BOPAlgo IncompatibilityOfVertex")); //BOPAlgo_IncompatibilityOfVertex results.push_back(QObject::tr("BOPAlgo IncompatibilityOfEdge")); //BOPAlgo_IncompatibilityOfEdge results.push_back(QObject::tr("BOPAlgo IncompatibilityOfFace")); //BOPAlgo_IncompatibilityOfFace results.push_back(QObject::tr("BOPAlgo OperationAborted")); //BOPAlgo_OperationAborted results.push_back(QObject::tr("BOPAlgo GeomAbs_C0")); //BOPAlgo_GeomAbs_C0 results.push_back(QObject::tr("BOPAlgo_InvalidCurveOnSurface")); //BOPAlgo_InvalidCurveOnSurface results.push_back(QObject::tr("BOPAlgo NotValid")); //BOPAlgo_NotValid return results; }
void BaseSqlTableModel::select() { if (!m_bInitialized) { return; } // We should be able to detect when a select() would be a no-op. The DAO's // do not currently broadcast signals for when common things happen. In the // future, we can turn this check on and avoid a lot of needless // select()'s. rryan 9/2011 // if (!m_bDirty) { // if (sDebug) { // qDebug() << this << "Skipping non-dirty select()"; // } // return; // } if (sDebug) { qDebug() << this << "select()"; } PerformanceTimer time; time.start(); // Prepare query for id and all columns not in m_trackSource QString queryString = QString("SELECT %1 FROM %2 %3") .arg(m_tableColumnsJoined, m_tableName, m_tableOrderBy); if (sDebug) { qDebug() << this << "select() executing:" << queryString; } QSqlQuery query(m_database); // This causes a memory savings since QSqlCachedResult (what QtSQLite uses) // won't allocate a giant in-memory table that we won't use at all. query.setForwardOnly(true); query.prepare(queryString); if (!query.exec()) { LOG_FAILED_QUERY(query); return; } // Remove all the rows from the table. We wait to do this until after the // table query has succeeded. See Bug #1090888. // TODO(rryan) we could edit the table in place instead of clearing it? if (!m_rowInfo.isEmpty()) { beginRemoveRows(QModelIndex(), 0, m_rowInfo.size() - 1); m_rowInfo.clear(); m_trackIdToRows.clear(); endRemoveRows(); } // sqlite does not set size and m_rowInfo was just cleared //if (sDebug) { // qDebug() << "Rows returned" << rows << m_rowInfo.size(); //} QVector<RowInfo> rowInfo; QSet<TrackId> trackIds; while (query.next()) { TrackId trackId(query.value(kIdColumn)); trackIds.insert(trackId); RowInfo thisRowInfo; thisRowInfo.trackId = trackId; // save rows where this currently track id is located thisRowInfo.order = rowInfo.size(); // Get all the table columns and store them in the hash for this // row-info section. thisRowInfo.metadata.reserve(m_tableColumns.size()); for (int i = 0; i < m_tableColumns.size(); ++i) { thisRowInfo.metadata << query.value(i); } rowInfo.push_back(thisRowInfo); } if (sDebug) { qDebug() << "Rows actually received:" << rowInfo.size(); } if (m_trackSource) { m_trackSource->filterAndSort(trackIds, m_currentSearch, m_currentSearchFilter, m_trackSourceOrderBy, m_trackSourceSortColumn, m_trackSourceSortOrder, &m_trackSortOrder); // Re-sort the track IDs since filterAndSort can change their order or mark // them for removal (by setting their row to -1). for (QVector<RowInfo>::iterator it = rowInfo.begin(); it != rowInfo.end(); ++it) { // If the sort is not a track column then we will sort only to // separate removed tracks (order == -1) from present tracks (order == // 0). Otherwise we sort by the order that filterAndSort returned to us. if (m_trackSourceOrderBy.isEmpty()) { it->order = m_trackSortOrder.contains(it->trackId) ? 0 : -1; } else { it->order = m_trackSortOrder.value(it->trackId, -1); } } } // RowInfo::operator< sorts by the order field, except -1 is placed at the // end so we can easily slice off rows that are no longer present. Stable // sort is necessary because the tracks may be in pre-sorted order so we // should not disturb that if we are only removing tracks. qStableSort(rowInfo.begin(), rowInfo.end()); m_trackIdToRows.clear(); for (int i = 0; i < rowInfo.size(); ++i) { const RowInfo& row = rowInfo[i]; if (row.order == -1) { // We've reached the end of valid rows. Resize rowInfo to cut off // this and all further elements. rowInfo.resize(i); break; } QLinkedList<int>& rows = m_trackIdToRows[row.trackId]; rows.push_back(i); } // We're done! Issue the update signals and replace the master maps. if (!rowInfo.isEmpty()) { beginInsertRows(QModelIndex(), 0, rowInfo.size() - 1); m_rowInfo = rowInfo; endInsertRows(); } qDebug() << this << "select() took" << time.elapsed().formatMillisWithUnit() << rowInfo.size(); }
QVector<SpiceInfoData> SpiceInfo::querySpice(const QString &name) { QVector<SpiceInfoData> vecSpiceInfo; QSqlDatabase db; if(!createConnection(db)) { // 连接使用完后需要释放回数据库连接池 ConnectionPool::closeConnection(db); return vecSpiceInfo; } QSqlQuery query(db); //spice_information query.prepare("SELECT id, englishName, chineseName, typeId, property, sense, extract, origin, purpose, imagePath, FEMA, FDA, COE, GB, density, refractive, solubility FROM spice_information " "WHERE chineseName like :chineseName OR englishName like :englishName"); query.bindValue(":chineseName", "%" + name + "%"); query.bindValue(":englishName", "%" + name + "%"); if(!query.exec()) { qDebug() << __FILE__ << __LINE__ << query.lastError().text(); } while(query.next()) { SpiceInfoData spiceInfo; spiceInfo.id = query.value(0).toInt(); spiceInfo.name.EnList = query.value(1).toString().split(';'); spiceInfo.name.CnList = query.value(2).toString().split(';'); spiceInfo.type = query.value(3).toInt(); spiceInfo.property = query.value(4).toString(); spiceInfo.sense = query.value(5).toString(); spiceInfo.extract = query.value(6).toString(); spiceInfo.origin = query.value(7).toString(); spiceInfo.purpose = query.value(8).toString(); spiceInfo.imagePath = query.value(9).toString(); spiceInfo.management.FEMA = query.value(10).toString(); spiceInfo.management.FDA = query.value(11).toString(); spiceInfo.management.COE = query.value(12).toString(); spiceInfo.management.GB = query.value(13).toString(); spiceInfo.physics.density = query.value(14).toString(); spiceInfo.physics.refractive = query.value(15).toString(); spiceInfo.physics.solubility = query.value(16).toString(); //spice_content QSqlQuery query_content(db); query_content.prepare("SELECT retentionTime, absoluteValue, relativeValue, contentId FROM spice_content " "WHERE spiceId=:id"); query_content.bindValue(":id", spiceInfo.id); if(!query_content.exec()) { qDebug() << __FILE__ << __LINE__ << query_content.lastError().text(); } SpiceContent content; while(query_content.next()) { content.retentionTime = query_content.value(0).toDouble(); content.absoluteContent = query_content.value(1).toDouble(); content.relativeContent = query_content.value(2).toDouble(); int contentId = query_content.value(3).toInt(); QSqlQuery query_1(db); query_1.prepare("SELECT chineseName, englishName FROM content WHERE id=:id"); query_1.bindValue(":id",contentId); if(query_1.exec()) { if(query_1.next()) { content.chineseName = query_1.value(0).toString(); content.englishName = query_1.value(1).toString(); spiceInfo.vecContent.push_back(content); } } else { qDebug() << __FILE__ << __LINE__ << query_1.lastError().text(); } } vecSpiceInfo.push_back(spiceInfo); } // 连接使用完后需要释放回数据库连接池 ConnectionPool::closeConnection(db); return vecSpiceInfo; }
NATRON_NAMESPACE_ENTER // those parameters should be ignored (they are always secret in Natron) #define kOCIOParamInputSpace "ocioInputSpace" #define kOCIOParamOutputSpace "ocioOutputSpace" // those parameters should not have their options in the help file if generating markdown, // because the options are dinamlically constructed at run-time from the OCIO config. #define kOCIOParamInputSpaceChoice "ocioInputSpaceIndex" #define kOCIOParamOutputSpaceChoice "ocioOutputSpaceIndex" #define kOCIODisplayPluginIdentifier "fr.inria.openfx.OCIODisplay" #define kOCIODisplayParamDisplay "display" #define kOCIODisplayParamDisplayChoice "displayIndex" #define kOCIODisplayParamView "view" #define kOCIODisplayParamViewChoice "viewIndex" // not yet implemented (see OCIOCDLTransform.cpp) //#define kOCIOCDLTransformPluginIdentifier "fr.inria.openfx.OCIOCDLTransform" //#define kOCIOCDLTransformParamCCCID "cccId" //#define kOCIOCDLTransformParamCCCIDChoice "cccIdIndex" #define kOCIOFileTransformPluginIdentifier "fr.inria.openfx.OCIOFileTransform" #define kOCIOFileTransformParamCCCID "cccId" #define kOCIOFileTransformParamCCCIDChoice "cccIdIndex" // genHTML: true for live HTML output for the internal web-server, false for markdown output QString Node::makeDocumentation(bool genHTML) const { QString ret; QString markdown; QTextStream ts(&ret); QTextStream ms(&markdown); QString pluginID, pluginLabel, pluginDescription, pluginIcon; int majorVersion = getMajorVersion(); int minorVersion = getMinorVersion(); std::vector<std::string> pluginGroup; bool pluginDescriptionIsMarkdown = false; QVector<QStringList> inputs; QVector<QStringList> items; { PluginPtr plugin = getPlugin(); assert(plugin); pluginID = QString::fromUtf8(plugin->getPluginID().c_str()); pluginLabel = QString::fromUtf8( Plugin::makeLabelWithoutSuffix( plugin->getPluginLabel() ).c_str()); pluginDescription = QString::fromUtf8( plugin->getPropertyUnsafe<std::string>(kNatronPluginPropDescription).c_str() ); pluginIcon = QString::fromUtf8(plugin->getPropertyUnsafe<std::string>(kNatronPluginPropIconFilePath).c_str()); pluginGroup = plugin->getPropertyNUnsafe<std::string>(kNatronPluginPropGrouping); pluginDescriptionIsMarkdown = plugin->getPropertyUnsafe<bool>(kNatronPluginPropDescriptionIsMarkdown); for (int i = 0; i < _imp->effect->getNInputs(); ++i) { QStringList input; input << convertFromPlainTextToMarkdown( QString::fromStdString( getInputLabel(i) ), genHTML, true ); input << convertFromPlainTextToMarkdown( QString::fromStdString( getInputHint(i) ), genHTML, true ); input << ( isInputOptional(i) ? tr("Yes") : tr("No") ); inputs.push_back(input); // Don't show more than doc for 4 inputs otherwise it will just clutter the page if (i == 3) { break; } } } // check for plugin icon QString pluginIconUrl; if ( !pluginIcon.isEmpty() ) { QFile iconFile(pluginIcon); if ( iconFile.exists() ) { if (genHTML) { pluginIconUrl.append( QString::fromUtf8("/LOCAL_FILE/") ); pluginIconUrl.append(pluginIcon); pluginIconUrl.replace( QString::fromUtf8("\\"), QString::fromUtf8("/") ); } else { pluginIconUrl.append(pluginID); pluginIconUrl.append(QString::fromUtf8(".png")); } } } // check for extra markdown file QString extraMarkdown; QString pluginMD = pluginIcon; pluginMD.replace( QString::fromUtf8(".png"), QString::fromUtf8(".md") ); QFile pluginMarkdownFile(pluginMD); if ( pluginMarkdownFile.exists() ) { if ( pluginMarkdownFile.open(QIODevice::ReadOnly | QIODevice::Text) ) { extraMarkdown = QString::fromUtf8( pluginMarkdownFile.readAll() ); pluginMarkdownFile.close(); } } // generate knobs info KnobsVec knobs = getEffectInstance()->getKnobs_mt_safe(); for (KnobsVec::const_iterator it = knobs.begin(); it != knobs.end(); ++it) { #pragma message WARN("TODO: restore getDefaultIsSecret from RB-2.2") //if ( (*it)->getDefaultIsSecret() ) { if ( (*it)->getIsSecret() ) { continue; } if ((*it)->getKnobDeclarationType() != KnobI::eKnobDeclarationTypePlugin) { continue; } // do not escape characters in the scriptName, since it will be put between backquotes QString knobScriptName = /*NATRON_NAMESPACE::convertFromPlainTextToMarkdown(*/ QString::fromUtf8( (*it)->getName().c_str() )/*, genHTML, true)*/; QString knobLabel = NATRON_NAMESPACE::convertFromPlainTextToMarkdown( QString::fromUtf8( (*it)->getLabel().c_str() ), genHTML, true); QString knobHint = NATRON_NAMESPACE::convertFromPlainTextToMarkdown( QString::fromUtf8( (*it)->getHintToolTip().c_str() ), genHTML, true); // totally ignore the documentation for these parameters (which are always secret in Natron) if ( knobScriptName.startsWith( QString::fromUtf8("NatronOfxParam") ) || knobScriptName == QString::fromUtf8("exportAsPyPlug") || knobScriptName == QString::fromUtf8(kOCIOParamInputSpace) || knobScriptName == QString::fromUtf8(kOCIOParamOutputSpace) || ( ( pluginID == QString::fromUtf8(kOCIODisplayPluginIdentifier) ) && ( knobScriptName == QString::fromUtf8(kOCIODisplayParamDisplay) ) ) || ( ( pluginID == QString::fromUtf8(kOCIODisplayPluginIdentifier) ) && ( knobScriptName == QString::fromUtf8(kOCIODisplayParamView) ) ) || //( ( pluginID == QString::fromUtf8(kOCIOCDLTransformPluginIdentifier) ) && // ( knobScriptName == QString::fromUtf8(kOCIOCDLTransformParamCCCID) ) ) || ( ( pluginID == QString::fromUtf8(kOCIOFileTransformPluginIdentifier) ) && ( knobScriptName == QString::fromUtf8(kOCIOFileTransformParamCCCID) ) ) || false) { continue; } QString defValuesStr, knobType; std::vector<std::pair<QString, QString> > dimsDefaultValueStr; KnobIntPtr isInt = toKnobInt(*it); KnobChoicePtr isChoice = toKnobChoice(*it); KnobBoolPtr isBool = toKnobBool(*it); KnobDoublePtr isDbl = toKnobDouble(*it); KnobStringPtr isString = toKnobString(*it); bool isLabel = isString && isString->isLabel(); KnobSeparatorPtr isSep = toKnobSeparator(*it); KnobButtonPtr isBtn = toKnobButton(*it); KnobParametricPtr isParametric = toKnobParametric(*it); KnobGroupPtr isGroup = toKnobGroup(*it); KnobPagePtr isPage = toKnobPage(*it); KnobColorPtr isColor = toKnobColor(*it); if (isInt) { knobType = tr("Integer"); } else if (isChoice) { knobType = tr("Choice"); } else if (isBool) { knobType = tr("Boolean"); } else if (isDbl) { knobType = tr("Double"); } else if (isString) { if (isLabel) { knobType = tr("Label"); } else { knobType = tr("String"); } } else if (isSep) { knobType = tr("Separator"); } else if (isBtn) { knobType = tr("Button"); } else if (isParametric) { knobType = tr("Parametric"); } else if (isGroup) { knobType = tr("Group"); } else if (isPage) { knobType = tr("Page"); } else if (isColor) { knobType = tr("Color"); } else { knobType = tr("N/A"); } if (!isGroup && !isPage) { for (int i = 0; i < (*it)->getNDimensions(); ++i) { QString valueStr; if (!isBtn && !isSep && !isParametric) { // If this is a ChoiceParam and we are not generating live HTML doc, // only add the list of entries and their halp if this node should not be // ignored (eg. OCIO colorspace knobs). if ( isChoice && (genHTML || !( knobScriptName == QString::fromUtf8(kOCIOParamInputSpaceChoice) || knobScriptName == QString::fromUtf8(kOCIOParamOutputSpaceChoice) || ( ( pluginID == QString::fromUtf8(kOCIODisplayPluginIdentifier) ) && ( knobScriptName == QString::fromUtf8(kOCIODisplayParamDisplayChoice) ) ) || ( ( pluginID == QString::fromUtf8(kOCIODisplayPluginIdentifier) ) && ( knobScriptName == QString::fromUtf8(kOCIODisplayParamViewChoice) ) ) || //( ( pluginID == QString::fromUtf8(kOCIOCDLTransformPluginIdentifier) ) && // ( knobScriptName == QString::fromUtf8(kOCIOCDLTransformParamCCCIDChoice) ) ) || ( ( pluginID == QString::fromUtf8(kOCIOFileTransformPluginIdentifier) ) && ( knobScriptName == QString::fromUtf8(kOCIOFileTransformParamCCCIDChoice) ) ) || ( ( pluginID == QString::fromUtf8("net.fxarena.openfx.Text") ) && ( knobScriptName == QString::fromUtf8("name") ) ) || // font family from Text plugin ( ( pluginID == QString::fromUtf8("net.fxarena.openfx.Polaroid") ) && ( knobScriptName == QString::fromUtf8("font") ) ) || // font family from Polaroid plugin ( ( pluginID == QString::fromUtf8(PLUGINID_NATRON_PRECOMP) ) && ( knobScriptName == QString::fromUtf8("writeNode") ) ) || ( ( pluginID == QString::fromUtf8(PLUGINID_NATRON_ONEVIEW) ) && ( knobScriptName == QString::fromUtf8("view") ) ) ) ) ) { // see also KnobChoice::getHintToolTipFull() int index = isChoice->getDefaultValue(DimIdx(i)); std::vector<ChoiceOption> entries = isChoice->getEntries(); if ( (index >= 0) && ( index < (int)entries.size() ) ) { valueStr = QString::fromUtf8( entries[index].id.c_str() ); } bool first = true; for (size_t i = 0; i < entries.size(); i++) { QString entryHelp = QString::fromUtf8( entries[i].tooltip.c_str() ); QString entry; if (entries[i].id != entries[i].label) { entry = QString::fromUtf8( "%1 (%2)" ).arg(QString::fromUtf8( entries[i].label.c_str() )).arg(QString::fromUtf8( entries[i].id.c_str() )); } else { entry = QString::fromUtf8( entries[i].label.c_str() ); } if (!entry.isEmpty()) { if (first) { // empty line before the option descriptions if (genHTML) { if ( !knobHint.isEmpty() ) { knobHint.append( QString::fromUtf8("<br />") ); } knobHint.append( tr("Possible values:") + QString::fromUtf8("<br />") ); } else { // we do a hack for multiline elements, because the markdown->rst conversion by pandoc doesn't use the line block syntax. // what we do here is put a supplementary dot at the beginning of each line, which is then converted to a pipe '|' in the // genStaticDocs.sh script by a simple sed command after converting to RsT if ( !knobHint.isEmpty() ) { if (!knobHint.startsWith( QString::fromUtf8(". ") )) { knobHint.prepend( QString::fromUtf8(". ") ); } knobHint.append( QString::fromUtf8("\\\n") ); } knobHint.append( QString::fromUtf8(". ") + tr("Possible values:") + QString::fromUtf8("\\\n") ); } first = false; } if (genHTML) { knobHint.append( QString::fromUtf8("<br />") ); } else { knobHint.append( QString::fromUtf8("\\\n") ); // we do a hack for multiline elements, because the markdown->rst conversion by pandoc doesn't use the line block syntax. // what we do here is put a supplementary dot at the beginning of each line, which is then converted to a pipe '|' in the // genStaticDocs.sh script by a simple sed command after converting to RsT knobHint.append( QString::fromUtf8(". ") ); } if (entryHelp.isEmpty()) { knobHint.append( QString::fromUtf8("**%1**").arg( convertFromPlainTextToMarkdown(entry, genHTML, true) ) ); } else { knobHint.append( QString::fromUtf8("**%1**: %2").arg( convertFromPlainTextToMarkdown(entry, genHTML, true) ).arg( convertFromPlainTextToMarkdown(entryHelp, genHTML, true) ) ); } } } } else if (isInt) { valueStr = QString::number( isInt->getDefaultValue( DimIdx(i) ) ); } else if (isDbl) { valueStr = QString::number( isDbl->getDefaultValue( DimIdx(i) ) ); } else if (isBool) { valueStr = isBool->getDefaultValue( DimIdx(i) ) ? tr("On") : tr("Off"); } else if (isString) { valueStr = QString::fromUtf8( isString->getDefaultValue( DimIdx(i) ).c_str() ); } else if (isColor) { valueStr = QString::number( isColor->getDefaultValue( DimIdx(i) ) ); } } dimsDefaultValueStr.push_back( std::make_pair(convertFromPlainTextToMarkdown( QString::fromUtf8( (*it)->getDimensionName( DimIdx(i) ).c_str() ), genHTML, true ), convertFromPlainTextToMarkdown(valueStr, genHTML, true)) ); } for (std::size_t i = 0; i < dimsDefaultValueStr.size(); ++i) { if ( !dimsDefaultValueStr[i].second.isEmpty() ) { if (dimsDefaultValueStr.size() > 1) { defValuesStr.append(dimsDefaultValueStr[i].first); defValuesStr.append( QString::fromUtf8(": ") ); } defValuesStr.append(dimsDefaultValueStr[i].second); if (i < dimsDefaultValueStr.size() - 1) { defValuesStr.append( QString::fromUtf8(" ") ); } } } if ( defValuesStr.isEmpty() ) { defValuesStr = tr("N/A"); } } if (!isPage && !isSep && !isGroup && !isLabel) { QStringList row; row << knobLabel << knobScriptName << knobType << defValuesStr << knobHint; items.append(row); } } // for (KnobsVec::const_iterator it = knobs.begin(); it!=knobs.end(); ++it) { // generate plugin info ms << tr("%1 node").arg(pluginLabel) << "\n==========\n\n"; // a hack to avoid repeating the documentation for the various merge plugins if ( pluginID.startsWith( QString::fromUtf8("net.sf.openfx.Merge") ) ) { std::string id = pluginID.toStdString(); std::string op; if (id == PLUGINID_OFX_MERGE) { // do nothing } else if (id == "net.sf.openfx.MergeDifference") { op = "difference (a.k.a. absminus)"; } else if (id == "net.sf.openfx.MergeIn") { op = "in"; } else if (id == "net.sf.openfx.MergeMatte") { op = "matte"; } else if (id == "net.sf.openfx.MergeMax") { op = "max"; } else if (id == "net.sf.openfx.MergeMin") { op = "min"; } else if (id == "net.sf.openfx.MergeMultiply") { op = "multiply"; } else if (id == "net.sf.openfx.MergeOut") { op = "out"; } else if (id == "net.sf.openfx.MergePlus") { op = "plus"; } else if (id == "net.sf.openfx.MergeScreen") { op = "screen"; } if ( !op.empty() ) { // we should use the custom link "[Merge node](|http::/plugins/" PLUGINID_OFX_MERGE ".html||rst::net.sf.openfx.MergePlugin|)" // but pandoc borks it ms << tr("The *%1* node is a convenience node identical to the %2, except that the operator is set to *%3* by default.") .arg(pluginLabel) .arg(genHTML ? QString::fromUtf8("<a href=\"" PLUGINID_OFX_MERGE ".html\">Merge node</a>") : QString::fromUtf8(":ref:`" PLUGINID_OFX_MERGE "`") //QString::fromUtf8("[Merge node](http::/plugins/" PLUGINID_OFX_MERGE ".html)") ) .arg( QString::fromUtf8( op.c_str() ) ); goto OUTPUT; } } if (!pluginIconUrl.isEmpty()) { // add a nonbreaking space so that pandoc doesn't use the alt-text as a caption // http://pandoc.org/MANUAL.html#images ms << "![pluginIcon](" << pluginIconUrl << ")"; if (!genHTML) { // specify image width for pandoc-generated printed doc // (for hoedown-generated HTML, this handled by the CSS using the alt=pluginIcon attribute) // see http://pandoc.org/MANUAL.html#images // note that only % units are understood both by pandox and sphinx ms << "{ width=10% }"; } ms << " \n\n"; // required so that there is no legend when converted to rst by pandoc } ms << tr("*This documentation is for version %2.%3 of %1.*").arg(pluginLabel).arg(majorVersion).arg(minorVersion) << "\n\n"; ms << "\n" << tr("Description") << "\n--------------------------------------------------------------------------------\n\n"; if (!pluginDescriptionIsMarkdown) { if (genHTML) { pluginDescription = NATRON_NAMESPACE::convertFromPlainText(pluginDescription, NATRON_NAMESPACE::WhiteSpaceNormal); // replace URLs with links QRegExp re( QString::fromUtf8("((http|ftp|https)://([\\w_-]+(?:(?:\\.[\\w_-]+)+))([\\w.,@?^=%&:/~+#-]*[\\w@?^=%&/~+#-])?)") ); pluginDescription.replace( re, QString::fromUtf8("<a href=\"\\1\">\\1</a>") ); } else { pluginDescription = convertFromPlainTextToMarkdown(pluginDescription, genHTML, false); } } ms << pluginDescription << "\n"; // create markdown table ms << "\n" << tr("Inputs") << "\n--------------------------------------------------------------------------------\n\n"; ms << tr("Input") << " | " << tr("Description") << " | " << tr("Optional") << "\n"; ms << "--- | --- | ---\n"; if (inputs.size() > 0) { Q_FOREACH(const QStringList &input, inputs) { QString inputName = input.at(0); QString inputDesc = input.at(1); QString inputOpt = input.at(2); ms << inputName << " | " << inputDesc << " | " << inputOpt << "\n"; }
QVector<SpiceByContent> SpiceInfo::queryContent(const QString &name) { QVector<SpiceByContent> vecSpice; QSqlDatabase db; if(!createConnection(db)) { return vecSpice; } QSqlQuery query(db); //content query.prepare("SELECT id, englishName, chineseName FROM content " "WHERE chineseName like :chineseName OR englishName like :englishName"); query.bindValue(":chineseName", "%" + name + "%"); query.bindValue(":englishName", "%" + name + "%"); if(!query.exec()) { qDebug() << __FILE__ << __LINE__ << query.lastError().text(); } SpiceByContent content; while(query.next()) { int contentId = query.value(0).toInt(); QSqlQuery query_content(db); query_content.prepare("SELECT spiceId, relativeValue, absoluteValue FROM spice_content " "WHERE contentId=:id"); query_content.bindValue(":id", contentId); if(query_content.exec()) { while(query_content.next()) { content.id = query_content.value(0).toInt(); content.relativeContent = query_content.value(1).toDouble(); content.absoluteContent = query_content.value(2).toDouble(); QSqlQuery query_information(db); query_information.prepare("SELECT englishName, chineseName FROM spice_information " "WHERE id=:id"); query_information.bindValue(":id", content.id); if(query_information.exec()) { if(query_information.next()) { content.name.EnList = query_information.value(0).toString().split(';'); content.name.CnList = query_information.value(1).toString().split(';'); vecSpice.push_back(content); } } else { qDebug() << __FILE__ << __LINE__ << query_information.lastError().text(); } } } else { qDebug() << __FILE__ << __LINE__ << query_content.lastError().text(); } } // 连接使用完后需要释放回数据库连接池 ConnectionPool::closeConnection(db); return vecSpice; }
/** * @brief TriggerSetupDialog::assignTrigger this function presents dialog and when users * clicks OK it assigns trigger to selected device's probe. * @param device * @param kind * @param channel */ void TriggerSetupDialog::assignTrigger(AbstractDevice* device, int kind, int channel) { QPair<int, QVector<uint8_t> > triggerSetup = device->getTrigger(kind, channel); if(kind == ANALOG) { ui->stackedWidget->setCurrentIndex(0); if(triggerSetup.first == RISING) { ui->risingRadio->toggle(); ui->thresholdRadio->toggle(); } else if(triggerSetup.first == FALLING) { ui->fallingRadio->toggle(); ui->thresholdRadio->toggle(); } else if(triggerSetup.first == RISING_SLOPE) { ui->risingRadio->toggle(); ui->edgeRadio->toggle(); } else if(triggerSetup.first == FALLING_SLOPE) { ui->fallingRadio->toggle(); ui->edgeRadio->toggle(); } ui->valueSpinBox->setValue(triggerSetup.second.at(0)); } else { ui->stackedWidget->setCurrentIndex(1); } ui->formatCombo->addItem("Decimal"); ui->formatCombo->addItem("Hex"); ui->formatCombo->addItem("Binary"); ui->formatCombo->addItem("Octal"); for(int i = 1; i < 5; ++i) { ui->samplesCombo->addItem(QString::number(i)); } ui->formatCombo->setCurrentIndex(0); if(triggerSetup.second.count() > 0) { ui->sample1Edit->setText(QString::number(triggerSetup.second.at(0))); ui->samplesCombo->setCurrentIndex(0); } if(triggerSetup.second.count() > 1) { ui->sample2Edit->setText(QString::number(triggerSetup.second.at(1))); ui->samplesCombo->setCurrentIndex(1); } if(triggerSetup.second.count() > 2) { ui->sample3Edit->setText(QString::number(triggerSetup.second.at(2))); ui->samplesCombo->setCurrentIndex(2); } if(triggerSetup.second.count() > 3) { ui->sample4Edit->setText(QString::number(triggerSetup.second.at(3))); ui->samplesCombo->setCurrentIndex(3); } int result = this->exec(); if(result == QDialog::Accepted) { if(kind == ANALOG) { QVector<uint8_t> val; val.push_back(ui->valueSpinBox->value()); if(ui->edgeRadio->isChecked() and ui->risingRadio->isChecked()) { device->setTrigger(kind, RISING_SLOPE, val, channel); } else if(ui->edgeRadio->isChecked() and ui->fallingRadio->isChecked()) { device->setTrigger(kind, FALLING_SLOPE, val, channel); } else if(ui->thresholdRadio->isChecked() and ui->risingRadio->isChecked()) { device->setTrigger(kind, RISING, val, channel); } else if(ui->thresholdRadio->isChecked() and ui->fallingRadio->isChecked()) { device->setTrigger(kind, FALLING, val, channel); } } else { QVector<uint8_t> val; int base; if(ui->formatCombo->currentIndex() == DEC) { base = 10; } else if(ui->formatCombo->currentIndex() == HEX) { base = 16; } else if(ui->formatCombo->currentIndex() == OCT) { base = 8; } else if(ui->formatCombo->currentIndex() == BIN) { base = 2; } if(ui->samplesCombo->currentIndex() >= 0) { bool ok; uint8_t value = ui->sample1Edit->text().toUInt(&ok, base); if(not ok) { QMessageBox::warning(this, "Data error", WRONG_DATA); return; } val.push_back(value); } if(ui->samplesCombo->currentIndex() >= 1) { bool ok; uint8_t value = ui->sample2Edit->text().toUInt(&ok, base); if(not ok) { QMessageBox::warning(this, "Data error", WRONG_DATA); return; } val.push_back(value); } if(ui->samplesCombo->currentIndex() >= 2) { bool ok; uint8_t value = ui->sample3Edit->text().toUInt(&ok, base); if(not ok) { QMessageBox::warning(this, "Data error", WRONG_DATA); return; } val.push_back(value); } if(ui->samplesCombo->currentIndex() >= 3) { bool ok; uint8_t value = ui->sample4Edit->text().toUInt(&ok, base); if(not ok) { QMessageBox::warning(this, "Data error", WRONG_DATA); return; } val.push_back(value); } device->setTrigger(kind, ui->samplesCombo->currentIndex(), val, 0); } } }
void LocalImageLoaderPrivate::prepareImages() { QString file, filename, mime; int32 filesize = 0; QImage img; QByteArray data; PeerId peer; uint64 id, jpeg_id = 0; ToPrepareMediaType type; { QMutexLocker lock(loader->toPrepareMutex()); ToPrepareMedias &list(loader->toPrepareMedias()); if (list.isEmpty()) return; file = list.front().file; img = list.front().img; data = list.front().data; peer = list.front().peer; id = list.front().id; type = list.front().type; } if (img.isNull()) { if (!file.isEmpty()) { QFileInfo info(file); if (type == ToPrepareAuto) { QString lower(file.toLower()); const QStringList &photoExtensions(cPhotoExtensions()); for (QStringList::const_iterator i = photoExtensions.cbegin(), e = photoExtensions.cend(); i != e; ++i) { if (lower.lastIndexOf(*i) == lower.size() - i->size()) { if (info.size() < MaxUploadPhotoSize) { type = ToPreparePhoto; break; } } } if (type == ToPrepareAuto && info.size() < MaxUploadDocumentSize) { type = ToPrepareDocument; } } if (type != ToPrepareAuto && info.size() < MaxUploadPhotoSize) { img = App::readImage(file); } if (type == ToPrepareDocument) { mime = QMimeDatabase().mimeTypeForFile(info).name(); } filename = info.fileName(); filesize = info.size(); } else if (!data.isEmpty()) { img = App::readImage(data); if (type == ToPrepareAuto) { if (!img.isNull() && data.size() < MaxUploadPhotoSize) { type = ToPreparePhoto; } else if (data.size() < MaxUploadDocumentSize) { type = ToPrepareDocument; } else { img = QImage(); } } QMimeType mimeType = QMimeDatabase().mimeTypeForData(data); if (type == ToPrepareDocument) { mime = mimeType.name(); } filename = qsl("Document"); QStringList patterns = mimeType.globPatterns(); if (!patterns.isEmpty()) { filename = patterns.front().replace('*', filename); } filesize = data.size(); } } else { if (type == ToPrepareDocument) { filename = filedialogDefaultName(qsl("image"), qsl(".png"), QString(), true); QMimeType mimeType = QMimeDatabase().mimeTypeForName("image/png"); data = QByteArray(); { QBuffer b(&data); img.save(&b, "PNG"); } filesize = data.size(); } else { type = ToPreparePhoto; // only photo from QImage filename = qsl("Untitled.jpg"); filesize = 0; } } if ((img.isNull() && (type != ToPrepareDocument || !filesize)) || type == ToPrepareAuto || (img.isNull() && file.isEmpty() && data.isEmpty())) { // if could not decide what type { QMutexLocker lock(loader->toPrepareMutex()); ToPrepareMedias &list(loader->toPrepareMedias()); list.pop_front(); } QTimer::singleShot(1, this, SLOT(prepareImages())); emit imageFailed(id); } else { PreparedPhotoThumbs photoThumbs; QVector<MTPPhotoSize> photoSizes; MTPPhotoSize thumb(MTP_photoSizeEmpty(MTP_string(""))); MTPPhoto photo(MTP_photoEmpty(MTP_long(0))); MTPDocument document(MTP_documentEmpty(MTP_long(0))); QByteArray jpeg; if (type == ToPreparePhoto) { int32 w = img.width(), h = img.height(); QPixmap thumb = (w > 100 || h > 100) ? QPixmap::fromImage(img.scaled(100, 100, Qt::KeepAspectRatio, Qt::SmoothTransformation)) : QPixmap::fromImage(img); photoThumbs.insert('s', thumb); photoSizes.push_back(MTP_photoSize(MTP_string("s"), MTP_fileLocationUnavailable(MTP_long(0), MTP_int(0), MTP_long(0)), MTP_int(thumb.width()), MTP_int(thumb.height()), MTP_int(0))); QPixmap medium = (w > 320 || h > 320) ? QPixmap::fromImage(img.scaled(320, 320, Qt::KeepAspectRatio, Qt::SmoothTransformation)) : QPixmap::fromImage(img); photoThumbs.insert('m', medium); photoSizes.push_back(MTP_photoSize(MTP_string("m"), MTP_fileLocationUnavailable(MTP_long(0), MTP_int(0), MTP_long(0)), MTP_int(medium.width()), MTP_int(medium.height()), MTP_int(0))); QPixmap full = (w > 800 || h > 800) ? QPixmap::fromImage(img.scaled(800, 800, Qt::KeepAspectRatio, Qt::SmoothTransformation)) : QPixmap::fromImage(img); photoThumbs.insert('x', full); photoSizes.push_back(MTP_photoSize(MTP_string("x"), MTP_fileLocationUnavailable(MTP_long(0), MTP_int(0), MTP_long(0)), MTP_int(full.width()), MTP_int(full.height()), MTP_int(0))); { QBuffer jpegBuffer(&jpeg); full.save(&jpegBuffer, "JPG", 87); } if (!filesize) filesize = jpeg.size(); photo = MTP_photo(MTP_long(id), MTP_long(0), MTP_int(user), MTP_int(unixtime()), MTP_string(""), MTP_geoPointEmpty(), MTP_vector<MTPPhotoSize>(photoSizes)); jpeg_id = id; } else if ((type == ToPrepareVideo || type == ToPrepareDocument) && !img.isNull()) { int32 w = img.width(), h = img.height(); QPixmap full = (w > 90 || h > 90) ? QPixmap::fromImage(img.scaled(90, 90, Qt::KeepAspectRatio, Qt::SmoothTransformation)) : QPixmap::fromImage(img); { QBuffer jpegBuffer(&jpeg); full.save(&jpegBuffer, "JPG", 87); } photoThumbs.insert('0', full); thumb = MTP_photoSize(MTP_string(""), MTP_fileLocationUnavailable(MTP_long(0), MTP_int(0), MTP_long(0)), MTP_int(full.width()), MTP_int(full.height()), MTP_int(0)); jpeg_id = MTP::nonce<uint64>(); } if (type == ToPrepareDocument) { document = MTP_document(MTP_long(id), MTP_long(0), MTP_int(MTP::authedId()), MTP_int(unixtime()), MTP_string(filename), MTP_string(mime), MTP_int(filesize), thumb, MTP_int(MTP::maindc())); } { QMutexLocker lock(loader->readyMutex()); loader->readyList().push_back(ReadyLocalMedia(type, file, filename, filesize, data, id, jpeg_id, peer, photo, photoThumbs, document, jpeg)); } { QMutexLocker lock(loader->toPrepareMutex()); ToPrepareMedias &list(loader->toPrepareMedias()); list.pop_front(); } QTimer::singleShot(1, this, SLOT(prepareImages())); emit imageReady(); } }
QVector<ImageLink> VUtils::fetchImagesFromMarkdownFile(VFile *p_file, ImageLink::ImageLinkType p_type) { Q_ASSERT(p_file->getDocType() == DocType::Markdown); QVector<ImageLink> images; bool isOpened = p_file->isOpened(); if (!isOpened && !p_file->open()) { return images; } const QString &text = p_file->getContent(); if (text.isEmpty()) { if (!isOpened) { p_file->close(); } return images; } // Used to de-duplicate the links. Url as the key. QSet<QString> fetchedLinks; QVector<VElementRegion> regions = fetchImageRegionsUsingParser(text); QRegExp regExp(c_imageLinkRegExp); QString basePath = p_file->fetchBasePath(); for (int i = 0; i < regions.size(); ++i) { const VElementRegion ® = regions[i]; QString linkText = text.mid(reg.m_startPos, reg.m_endPos - reg.m_startPos); bool matched = regExp.exactMatch(linkText); if (!matched) { // Image links with reference format will not match. continue; } QString imageUrl = regExp.capturedTexts()[2].trimmed(); ImageLink link; link.m_url = imageUrl; QFileInfo info(basePath, imageUrl); if (info.exists()) { if (info.isNativePath()) { // Local file. link.m_path = QDir::cleanPath(info.absoluteFilePath()); if (QDir::isRelativePath(imageUrl)) { link.m_type = p_file->isInternalImageFolder(VUtils::basePathFromPath(link.m_path)) ? ImageLink::LocalRelativeInternal : ImageLink::LocalRelativeExternal; } else { link.m_type = ImageLink::LocalAbsolute; } } else { link.m_type = ImageLink::Resource; link.m_path = imageUrl; } } else { QUrl url(imageUrl); link.m_path = url.toString(); link.m_type = ImageLink::Remote; } if (link.m_type & p_type) { if (!fetchedLinks.contains(link.m_url)) { fetchedLinks.insert(link.m_url); images.push_back(link); qDebug() << "fetch one image:" << link.m_type << link.m_path << link.m_url; } } } if (!isOpened) { p_file->close(); } return images; }
void Game::arrangementTiles() { qsrand (QDateTime::currentMSecsSinceEpoch()); int new_numbTilesH = numbTilesH +2; int new_numbTilesW = numbTilesW +2; setHelpArray(new_numbTilesH, new_numbTilesW); qsrand (QDateTime::currentMSecsSinceEpoch()); int summ = 0; while (summ < (new_numbTilesH-2)*(new_numbTilesW-2)) { for (int i = 1; i < new_numbTilesH - 1; i++) for (int j = 1; j < new_numbTilesW - 1; j++) if (isPosUnlock(i,j,A) && A[i][j] != 0) { summ++; vector.push_back(new Unknown(i,j,100)); } for (int k = 0; k < vector.size(); k++) { A[vector[k]->i][vector[k]->j] = 0; } std::cout << "\n\n"; vector.push_back(new Unknown(0,0,0)); } QVector <Unknown*> mainVector; for (int l = 0; l < 14; l++) { int c = 0; int mas[new_numbTilesW]; do { mas[c] = vector[c]->data; c++; } while (vector[c]->data != 0); for (int i = 0; i < c/2; i++) { int temp = (qrand() % numbTiles + qrand() % qrand()%10 + 1) % numbTiles + 1; mas[i] = temp; mas[c-i-1] = temp; } for (int i = 0; i < rand()%c + 3; i++) { int randIndex1 = rand()%c; int randIndex2 = rand()%c; int t; t = mas[randIndex1]; mas[randIndex1] = mas[randIndex2]; mas[randIndex2] = t; } for (int i = 0; i < c; i++) { vector[i]->data = mas[i]; mainVector.push_back(vector[i]); } for (int i = 0; i < c+1; i++) vector.pop_front(); } for (int i = 0; i < mainVector.size(); i++) tileArray[mainVector[i]->i][mainVector[i]->j] = mainVector[i]->data; for (int i = 0; i < mainVector.size(); i++) delete mainVector[i]; for (int i = 0; i < vector.size(); i++) delete vector[i]; }
void ImageMeta::show() { const TagDefinition& tagDef = CurrentProject::instance().project().getTagDefinition(); QList< TagGroup > tagGroups; tagDef.getTagGroups(tagGroups); FileMeta fm; QVector< int > photoIDs; foreach (int i, this->selectedIndex_) { photoIDs.push_back(Mediator::instance().fileID(i)); } CurrentProject::instance().project().addToXMPMap(xmpMap_); Cameras::instance().addToXMPMap(Mediator::instance().getCurrentCamera(), xmpMap_); Mediator::instance().getFileMeta(photoIDs, fm); foreach (TagGroup m, tagGroups) { if (!Mediator::instance().isMetaEnabled(m)) continue; QVector< PhotoTagDefinition > photoTag; tagDef.getPhotoTagDefinition(m, photoTag); tabWidget_[m] = new QScrollArea; layout_[m] = new QGridLayout; tabWidget_[m]->setMinimumHeight(30*photoTag.count()); foreach (PhotoTagDefinition pm, photoTag) { xmpMap_[pm.xmpName] = ""; if (pm.valueType == "Checkbox") { widget_[m][pm.name] = new QCheckBox(pm.name); widget_[m][pm.name]->setObjectName(m + "___" + pm.name); if (!fm.isEmpty()) { if (fm.find(m) != fm.end()) { if ((fm[m]).find(pm.name) != (fm[m]).end()) { dynamic_cast< QCheckBox * >(widget_[m][pm.name])->setChecked(true); } } } connect(dynamic_cast< QCheckBox * >(widget_[m][pm.name]), SIGNAL(clicked()), this, SLOT(checboxClicked())); dynamic_cast< QCheckBox * >(widget_[m][pm.name])->setShortcut(pm.shortcut); layout_[m]->addWidget(dynamic_cast< QCheckBox *>(widget_[m][pm.name])); } else // if (pm.valueType == "Text") { widget_[m][pm.name] = new QLineEdit(); widget_[m][pm.name]->setObjectName(m + "___" + pm.name); widget_[m][pm.name]->setToolTip(pm.name); dynamic_cast< QLineEdit * >(widget_[m][pm.name])->setPlaceholderText(pm.name); if (!fm.isEmpty()) { if (fm.find(m) != fm.end()) { if ((fm[m]).find(pm.name) != (fm[m]).end()) { dynamic_cast< QLineEdit * >(widget_[m][pm.name])->setText(fm[m][pm.name]); } } } connect(dynamic_cast< QLineEdit * >(widget_[m][pm.name]), SIGNAL(editingFinished()), this, SLOT(textboxChanged())); // dynamic_cast< QLineEdit * >(widget_[m][pm.name])->setShortcut(pm.shortcut); layout_[m]->addWidget(dynamic_cast< QLineEdit *>(widget_[m][pm.name])); } } tabWidget_[m]->setLayout(layout_[m]); Mediator::instance().addMetaTable(tabWidget_[m], m); }
int main(int argc, char *argv[]) { QApplication a(argc, argv); // using Config::config; // if( !config.read()){ // qDebug()<<"config file not exist"; // } // QTextCodec::setCodecForLocale(QTextCodec::codecForName("utf-8")); int start_year = 2010; int end_year = 2130; QVector<QString> curves; curves.push_back(QObject::tr("北京农业_现行_非农业_现行回归估计2010全员婚配有偶中迁移合计多龄概率分释模式")); curves.push_back(QObject::tr("辽宁农业_现行_非农业_现行回归估计2010全员婚配有偶中迁移合计多龄概率分释模式")); curves.push_back(QObject::tr("浙江农业_现行_非农业_现行回归估计2010全员婚配有偶中迁移合计多龄概率分释模式")); curves.push_back(QObject::tr("上海农业_现行_非农业_现行回归估计2010全员婚配有偶中迁移合计多龄概率分释模式")); curves.push_back(QObject::tr("湖南农业_现行_非农业_现行回归估计2010全员婚配有偶中迁移合计多龄概率分释模式")); curves.push_back(QObject::tr("湖北农业_现行_非农业_现行回归估计2010全员婚配有偶中迁移合计多龄概率分释模式")); curves.push_back(QObject::tr("云南农业_现行_非农业_现行回归估计2010全员婚配有偶中迁移合计多龄概率分释模式")); curves.push_back(QObject::tr("山西农业_现行_非农业_现行回归估计2010全员婚配有偶中迁移合计多龄概率分释模式")); QVector<FileInfo> files; FileInfo f1; // f1.m_FileName = QObject::tr("I:/生育政策演示/生育政策仿真结果文件0926/北京合计人口概要_回归分释_多龄_农X行_非X行_Z.TXT"); f1.m_FileName = QObject::tr("北京合计人口概要_回归分释_多龄_农X行_非X行_Z.TXT"); f1.m_index = 92; files.push_back(f1); // f1.m_FileName = QObject::tr("I:/生育政策演示/生育政策仿真结果文件0926/辽宁合计人口概要_回归分释_多龄_农X行_非X行_Z.TXT"); f1.m_FileName = QObject::tr("辽宁合计人口概要_回归分释_多龄_农X行_非X行_Z"); f1.m_index = 92; files.push_back(f1); f1.m_FileName = QObject::tr("I:/生育政策演示/生育政策仿真结果文件0926/浙江合计人口概要_回归分释_多龄_农X行_非X行_Z.TXT"); // f1.m_FileName = QObject::tr("I:/生育政策演示/生育政策仿真结果文件0926/浙江合计人口概要_回归分释_多龄_农X行_非X行_Z"); f1.m_index = 92; files.push_back(f1); // f1.m_FileName = QObject::tr("I:/生育政策演示/生育政策仿真结果文件0926/上海合计人口概要_回归分释_多龄_农X行_非X行_Z.TXT"); f1.m_FileName = QObject::tr("上海合计人口概要_回归分释_多龄_农X行_非X行_Z"); f1.m_index = 92; files.push_back(f1); // f1.m_FileName = QObject::tr("I:/生育政策演示/生育政策仿真结果文件0926/湖南合计人口概要_回归分释_多龄_农X行_非X行_Z.TXT"); f1.m_FileName = QObject::tr("湖南合计人口概要_回归分释_多龄_农X行_非X行_Z.TXT"); f1.m_index = 92; files.push_back(f1); // f1.m_FileName = QObject::tr("I:/生育政策演示/生育政策仿真结果文件0926/湖北合计人口概要_回归分释_多龄_农X行_非X行_Z.TXT"); f1.m_FileName = QObject::tr("湖北合计人口概要_回归分释_多龄_农X行_非X行_Z.TXT"); f1.m_index = 92; files.push_back(f1); // f1.m_FileName = QObject::tr("I:/生育政策演示/生育政策仿真结果文件0926/云南合计人口概要_回归分释_多龄_农X行_非X行_Z.TXT"); f1.m_FileName = QObject::tr("云南合计人口概要_回归分释_多龄_农X行_非X行_Z.TXT"); f1.m_index = 92; files.push_back(f1); // f1.m_FileName = QObject::tr("I:/生育政策演示/生育政策仿真结果文件0926/山西合计人口概要_回归分释_多龄_农X行_非X行_Z.TXT"); f1.m_FileName = QObject::tr("山西合计人口概要_回归分释_多龄_农X行_非X行_Z.TXT"); f1.m_index = 92; files.push_back(f1); QWidget* l = LineType3::makeLineType3(curves, files, start_year, end_year); l->show(); // //汉字支持 // QTextCodec::setCodecForLocale(QTextCodec::codecForName("utf-8")); // std::shared_ptr<schememetadata> meta; // if(files.front().m_FileName.contains(QObject::tr("夫妇子女"))) // { // meta = std::shared_ptr<schememetadata>( new schememetadata(QString("META_FUFUZINV"))); // } // else if(files.front().m_FileName.contains(QObject::tr("人口概要"))) // { // meta = std::shared_ptr<schememetadata>( new schememetadata(QString("META_RENKOUGAIYAO"))); // } // else if(files.front().m_FileName.contains(QObject::tr("生育孩次"))) // { // meta = std::shared_ptr<schememetadata>( new schememetadata(QString("META_SHENGYUHAICI"))); // } // else //if(files.front().m_FileName.contains(QObject::tr("政策生育"))) // { // meta = std::shared_ptr<schememetadata>( new schememetadata(QString("META_ZHENGCESHENGYU"))); // } // std::shared_ptr<SchemeBuffer> buffer(new SchemeBuffer); // try{ // for(int i=0; i<files.size(); ++i){ // QString filename = files[i].m_FileName.section('/', -1).section('.', 0 ,0); // qDebug()<<"main()"<<filename; // SchemePtr ptr(new Scheme(meta, buffer, filename)); // for(int j=start_year; j<=end_year; ++j){ // double num = ptr->getInstance(j)[files[i].m_index]; // qDebug()<<num; // } // } // } // catch(const RecordNotExist& e){ // qDebug() << "Record not exist at" << e.name(); // } return a.exec(); }
void BurstSearchWidget::on_pushButtonBurstView_clicked() { qDebug("on_pushButtonBurstView_clicked"); if(ad->isEmpty()) return; JKQtPlotter* plot = new JKQtPlotter(true,NULL); getParameters(); double binwidth=5e-6, alternationPeriod=ad->getExcitationPeriodDonor(); int nbins=(int)(alternationPeriod/binwidth+1); gsl_histogram * histCh1 = gsl_histogram_alloc (nbins); gsl_histogram * histCh2 = gsl_histogram_alloc (nbins); gsl_histogram_set_ranges_uniform (histCh1, 0, alternationPeriod*1.1); gsl_histogram_set_ranges_uniform (histCh2, 0, alternationPeriod*1.1); int last=0; int lastExc=0; while(ad->photons.at(last).time<ad->markerTimeDexc.at(lastExc)) ++last; uint ch1=ui->comboBoxChannel1->channel(); uint ch2=ui->comboBoxChannel2->channel(); while((lastExc<1e4)&&(lastExc<ad->markerTimeDexc.size()+1)) { // average first 10000 periods while ((last<ad->photons.size()) && ad->photons[last].time<ad->markerTimeDexc.at(lastExc+1)) { // qDebug()<<QString::number(ad->photons[last].flags,2)+"\t"<<ch1<<ch2<<"\t"<<ad->photons[last].isPhotonFlag(ch1)<<ad->photons[last].isPhotonFlag(ch2); #ifdef PHOTONMACRO if(isPhotonFlag(ad->photons[last],ch1)) gsl_histogram_increment (histCh1, ad->photons[last].time-ad->markerTimeDexc[lastExc]); if(isPhotonFlag(ad->photons[last],ch2)) gsl_histogram_increment (histCh2, ad->photons[last].time-ad->markerTimeDexc[lastExc]); #else if(ad->photons[last].isPhotonFlag(ch1)) gsl_histogram_increment (histCh1, ad->photons[last].time-ad->markerTimeDexc[lastExc]); if(ad->photons[last].isPhotonFlag(ch2)) gsl_histogram_increment (histCh2, ad->photons[last].time-ad->markerTimeDexc[lastExc]); #endif last++; } // end of excitation period lastExc++; } JKQTPdatastore* ds=plot->get_plotter()->getDatastore(); ds->clear(); plot->get_plotter()->clearGraphs(true); plot->get_plotter()->setGrid(false); qDebug("plotHist DA"); unsigned long long nrows=(unsigned long long)histCh1->n; for(size_t i=0;i<histCh1->n;++i) histCh1->range[i] *= 1e6; plot->get_xAxis()->set_axisLabel("time in us"); plot->get_yAxis()->set_axisLabel("countrate in Hz"); gsl_histogram_scale(histCh1,(1.0)/(lastExc*binwidth)); // convert bins to countrate in Hz (counts averaged over lastDex excitation periods in bin of width binwidth) gsl_histogram_scale(histCh2,(1.0)/(lastExc*binwidth)); size_t xColumn=ds->addCopiedColumn(histCh1->range, nrows, "time"); // adds column (copies values!) and returns column ID QVector<size_t> yColumns; yColumns.push_back(ds->addCopiedColumn(histCh1->bin, nrows, "Channel 1")); yColumns.push_back(ds->addCopiedColumn(histCh2->bin, nrows, "Channel 2")); QList<QColor> colors; colors.append(QColor(COUNTRATE_COLOR_CH1)); colors.append(QColor(COUNTRATE_COLOR_CH2)); gsl_histogram_free(histCh1); gsl_histogram_free(histCh2); // plot double width=0.5; double s=-0.5+width/2.0; for (int i=0; i<yColumns.size(); ++i) { JKQTPbarHorizontalGraph* g=new JKQTPbarHorizontalGraph(plot->get_plotter()); g->set_xColumn(xColumn); g->set_yColumn(yColumns[i]); g->set_shift(s); g->set_width(width); g->set_style(Qt::NoPen); g->set_fillColor(colors.at(i)); s=s+width; plot->addGraph(g); } plot->get_plotter()->set_keyPosition(JKQTPkeyInsideTopRight); // set legend position plot->get_plotter()->set_showKey(true); plot->zoomToFit(); plot->show(); // old: // if(ad->burstVectorDual.isEmpty()) // runBurstSearch(); // analysisFRET(ad->burstVectorDual,ad->FRETparams); // BurstView *burstView= new BurstView(this, ad); // burstView->exec(); }
int QgsMapCanvasSnapper::snapToBackgroundLayers( const QgsPoint& point, QList<QgsSnappingResult>& results, const QList<QgsPoint>& excludePoints ) { results.clear(); if ( !mSnapper ) return 5; //topological editing on? int topologicalEditing = QgsProject::instance()->readNumEntry( "Digitizing", "/TopologicalEditing", 0 ); //snapping on intersection on? int intersectionSnapping = QgsProject::instance()->readNumEntry( "Digitizing", "/IntersectionSnapping", 0 ); if ( topologicalEditing == 0 ) { if ( intersectionSnapping == 0 ) mSnapper->setSnapMode( QgsSnapper::SnapWithOneResult ); else mSnapper->setSnapMode( QgsSnapper::SnapWithResultsWithinTolerances ); } else if ( intersectionSnapping == 0 ) { mSnapper->setSnapMode( QgsSnapper::SnapWithResultsForSamePosition ); } else { mSnapper->setSnapMode( QgsSnapper::SnapWithResultsWithinTolerances ); } QgsVectorLayer* currentVectorLayer = dynamic_cast<QgsVectorLayer*>( mMapCanvas->currentLayer() ); if ( !currentVectorLayer ) { return 1; } //read snapping settings from project QStringList layerIdList, enabledList, toleranceList, toleranceUnitList, snapToList; bool ok, snappingDefinedInProject; QSettings settings; QString snappingMode = QgsProject::instance()->readEntry( "Digitizing", "/SnappingMode", "current_layer", &snappingDefinedInProject ); QString defaultSnapToleranceUnit = snappingDefinedInProject ? QgsProject::instance()->readEntry( "Digitizing", "/DefaultSnapToleranceUnit" ) : settings.value( "/qgis/digitizing/default_snapping_tolerance_unit", "0" ).toString(); QString defaultSnapType = snappingDefinedInProject ? QgsProject::instance()->readEntry( "Digitizing", "/DefaultSnapType" ) : settings.value( "/qgis/digitizing/default_snap_mode", "off" ).toString(); QString defaultSnapTolerance = snappingDefinedInProject ? QString::number( QgsProject::instance()->readDoubleEntry( "Digitizing", "/DefaultSnapTolerance" ) ) : settings.value( "/qgis/digitizing/default_snapping_tolerance", "0" ).toString(); if ( !snappingDefinedInProject && defaultSnapType == "off" ) { return 0; } if ( snappingMode == "current_layer" || !snappingDefinedInProject ) { layerIdList.append( currentVectorLayer->id() ); enabledList.append( "enabled" ); toleranceList.append( defaultSnapTolerance ); toleranceUnitList.append( defaultSnapToleranceUnit ); snapToList.append( defaultSnapType ); } else if ( snappingMode == "all_layers" ) { QList<QgsMapLayer*> allLayers = mMapCanvas->layers(); QList<QgsMapLayer*>::const_iterator layerIt = allLayers.constBegin(); for ( ; layerIt != allLayers.constEnd(); ++layerIt ) { if ( !( *layerIt ) ) { continue; } layerIdList.append(( *layerIt )->id() ); enabledList.append( "enabled" ); toleranceList.append( defaultSnapTolerance ); toleranceUnitList.append( defaultSnapToleranceUnit ); snapToList.append( defaultSnapType ); } } else //advanced { layerIdList = QgsProject::instance()->readListEntry( "Digitizing", "/LayerSnappingList", QStringList(), &ok ); enabledList = QgsProject::instance()->readListEntry( "Digitizing", "/LayerSnappingEnabledList", QStringList(), &ok ); toleranceList = QgsProject::instance()->readListEntry( "Digitizing", "/LayerSnappingToleranceList", QStringList(), &ok ); toleranceUnitList = QgsProject::instance()->readListEntry( "Digitizing", "/LayerSnappingToleranceUnitList", QStringList(), &ok ); snapToList = QgsProject::instance()->readListEntry( "Digitizing", "/LayerSnapToList", QStringList(), &ok ); } if ( !( layerIdList.size() == enabledList.size() && layerIdList.size() == toleranceList.size() && layerIdList.size() == toleranceUnitList.size() && layerIdList.size() == snapToList.size() ) ) { // lists must have the same size, otherwise something is wrong return 1; } QList<QgsSnapper::SnapLayer> snapLayers; QgsSnapper::SnapLayer snapLayer; // set layers, tolerances, snap to segment/vertex to QgsSnapper QStringList::const_iterator layerIt( layerIdList.constBegin() ); QStringList::const_iterator tolIt( toleranceList.constBegin() ); QStringList::const_iterator tolUnitIt( toleranceUnitList.constBegin() ); QStringList::const_iterator snapIt( snapToList.constBegin() ); QStringList::const_iterator enabledIt( enabledList.constBegin() ); for ( ; layerIt != layerIdList.constEnd(); ++layerIt, ++tolIt, ++tolUnitIt, ++snapIt, ++enabledIt ) { if ( *enabledIt != "enabled" ) { // skip layer if snapping is not enabled continue; } //layer QgsVectorLayer *vlayer = qobject_cast<QgsVectorLayer *>( QgsMapLayerRegistry::instance()->mapLayer( *layerIt ) ); if ( !vlayer || !vlayer->hasGeometryType() ) continue; snapLayer.mLayer = vlayer; //tolerance snapLayer.mTolerance = tolIt->toDouble(); snapLayer.mUnitType = ( QgsTolerance::UnitType ) tolUnitIt->toInt(); // segment or vertex if ( *snapIt == "to vertex" || *snapIt == "to_vertex" ) { snapLayer.mSnapTo = QgsSnapper::SnapToVertex; } else if ( *snapIt == "to segment" || *snapIt == "to_segment" ) { snapLayer.mSnapTo = QgsSnapper::SnapToSegment; } else if ( *snapIt == "to vertex and segment" || *snapIt == "to_vertex_and_segment" ) { snapLayer.mSnapTo = QgsSnapper::SnapToVertexAndSegment; } else //off { continue; } snapLayers.append( snapLayer ); } mSnapper->setSnapLayers( snapLayers ); if ( mSnapper->snapMapPoint( point, results, excludePoints ) != 0 ) return 4; if ( intersectionSnapping != 1 ) return 0; QVector<QgsSnappingResult> segments; QVector<QgsSnappingResult> points; for ( QList<QgsSnappingResult>::const_iterator it = results.constBegin(); it != results.constEnd(); ++it ) { if ( it->snappedVertexNr == -1 ) { QgsDebugMsg( "segment" ); segments.push_back( *it ); } else { QgsDebugMsg( "no segment" ); points.push_back( *it ); } } if ( segments.count() < 2 ) return 0; QList<QgsSnappingResult> myResults; for ( QVector<QgsSnappingResult>::const_iterator oSegIt = segments.constBegin(); oSegIt != segments.constEnd(); ++oSegIt ) { QgsDebugMsg( QString::number( oSegIt->beforeVertexNr ) ); QVector<QgsPoint> vertexPoints; vertexPoints.append( oSegIt->beforeVertex ); vertexPoints.append( oSegIt->afterVertex ); QgsGeometry* lineA = QgsGeometry::fromPolyline( vertexPoints ); for ( QVector<QgsSnappingResult>::iterator iSegIt = segments.begin(); iSegIt != segments.end(); ++iSegIt ) { QVector<QgsPoint> vertexPoints; vertexPoints.append( iSegIt->beforeVertex ); vertexPoints.append( iSegIt->afterVertex ); QgsGeometry* lineB = QgsGeometry::fromPolyline( vertexPoints ); QgsGeometry* intersectionPoint = lineA->intersection( lineB ); delete lineB; if ( intersectionPoint && intersectionPoint->type() == Qgis::Point ) { //We have to check the intersection point is inside the tolerance distance for both layers double toleranceA = 0; double toleranceB = 0; for ( int i = 0 ;i < snapLayers.size();++i ) { if ( snapLayers[i].mLayer == oSegIt->layer ) { toleranceA = QgsTolerance::toleranceInMapUnits( snapLayers[i].mTolerance, snapLayers[i].mLayer, mMapCanvas->mapSettings(), snapLayers[i].mUnitType ); } if ( snapLayers[i].mLayer == iSegIt->layer ) { toleranceB = QgsTolerance::toleranceInMapUnits( snapLayers[i].mTolerance, snapLayers[i].mLayer, mMapCanvas->mapSettings(), snapLayers[i].mUnitType ); } } QgsGeometry* cursorPoint = QgsGeometry::fromPoint( point ); double distance = intersectionPoint->distance( *cursorPoint ); if ( distance < toleranceA && distance < toleranceB ) { iSegIt->snappedVertex = intersectionPoint->asPoint(); myResults.append( *iSegIt ); } delete cursorPoint; } delete intersectionPoint; } delete lineA; } if ( myResults.length() > 0 ) { results.clear(); results = myResults; } return 0; }