bool BitcoinAmountField::eventFilter(QObject *object, QEvent *event) { if (event->type() == QEvent::FocusIn) { // Clear invalid flag on focus setValid(true); } else if (event->type() == QEvent::KeyPress || event->type() == QEvent::KeyRelease) { QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event); if (keyEvent->key() == Qt::Key_Comma) { // Translate a comma into a period QKeyEvent periodKeyEvent(event->type(), Qt::Key_Period, keyEvent->modifiers(), ".", keyEvent->isAutoRepeat(), keyEvent->count()); QApplication::sendEvent(object, &periodKeyEvent); return true; } } return QWidget::eventFilter(object, event); }
/****************************************************************************** * Set the spin box's value. */ void TimeSpinBox::setValue(int minutes) { if (!mEnteredSetValue) { mEnteredSetValue = true; mPm = (minutes >= 720); if (minutes > maxValue()) setValid(false); else { if (mInvalid) { mInvalid = false; setSpecialValueText(QString()); setMinValue(mMinimumValue); } SpinBox2::setValue(minutes); mEnteredSetValue = false; } } }
bool KoPattern::load() { QString fileExtension; int index = filename().lastIndexOf('.'); if (index != -1) fileExtension = filename().mid(index).toLower(); bool result; if (fileExtension == ".pat") { QFile file(filename()); file.open(QIODevice::ReadOnly); QByteArray data = file.readAll(); file.close(); result = init(data); } else { result = m_image.load(filename()); setValid(result); } return result; }
bool DatabaseDialog::tablesDoNext() { m_databaseStatus->setText(i18n("Retrieving meta data of tables...")); QStringList tables; { for (int i = 0; i < m_tableView->count(); ++i) { QListWidgetItem* item = m_tableView->item(i); if (item->checkState() == Qt::Checked) { tables.append(item->text()); } } } if (tables.empty()) { KMessageBox::error(this, i18n("You have to select at least one table.")); return false; } m_columnView->clear(); QSqlRecord info; for (int i = 0; i < (int) tables.size(); ++i) { info = m_dbConnection.record(tables[i]); for (int j = 0; j < (int) info.count(); ++j) { QString name = info.fieldName(j); QSqlField field = info.field(name); QTreeWidgetItem * checkItem = new QTreeWidgetItem(QStringList() << name << tables[i] << QVariant::typeToName(field.type())); checkItem->setFlags(checkItem->flags() | Qt::ItemIsUserCheckable); checkItem->setCheckState(0, Qt::Unchecked); m_columnView->addTopLevelItem(checkItem); } } m_columnView->sortItems(1, Qt::AscendingOrder); setValid(m_columns, true); return true; }
NovellVpnSettingWidget::NovellVpnSettingWidget(Knm::Connection * connection, QWidget * parent) : SettingWidget(connection, parent), d(new Private) { setValid(false); d->ui.setupUi(this); d->ui.x509Cert->setMode(KFile::LocalOnly); d->setting = static_cast<Knm::VpnSetting *>(connection->setting(Knm::Setting::Vpn)); connect(d->ui.leGateway, SIGNAL(textChanged(QString)), this, SLOT(validate())); connect(d->ui.cbShowPasswords, SIGNAL(toggled(bool)), this, SLOT(showPasswordsChanged(bool))); connect(d->ui.cmbGwType, SIGNAL(currentIndexChanged(int)), this, SLOT(gatewayTypeChanged(int))); connect(d->ui.btnAdvanced, SIGNAL(clicked()), this, SLOT(advancedClicked())); d->advancedDialog = new KDialog(this); d->advancedDialog->setButtons(KDialog::Ok); d->advancedDialog->setCaption(i18nc("@window:title NovellVPN advanced connection options", "NovellVPN advanced options")); QWidget * advWid = new QWidget(d->advancedDialog); d->advUi.setupUi(advWid); d->advancedDialog->setMainWidget(advWid); }
Player::Player(int16_t playerId, sf::Vector2f position, OutputSocket socket, char * nick) : playerId(playerId), timeSinceLastShot(sf::Time::Zero), speed(500), rotation(0), cross_thickness(5), socket(socket), health(100), playerInfo(0), ip(socket.ip), nick(nick), ammo(10), invisibleTime(sf::Time::Zero) { boundingBox = BoundingBox(position.x, position.y, 50, 50); updateCross(); horz_rect.width = boundingBox.width; vert_rect.height = boundingBox.height; type = EntityType::Player_T; setTeam(0); setValid(0); }
void KisTextBrush::updateBrush() { QFontMetrics metric(m_font); int w = metric.width(m_txt); int h = metric.height(); // don't crash, if there is no text if (w==0) w=1; if (h==0) h=1; QPixmap px(w, h); QPainter p; p.begin(&px); p.setFont(m_font); p.fillRect(0, 0, w, h, Qt::white); p.setPen(Qt::black); p.drawText(0, metric.ascent(), m_txt); p.end(); setImage(px.toImage()); setValid(true); resetBoundary(); }
bool KoStopGradient::loadFromDevice(QIODevice *dev) { QString strExt; const int result = filename().lastIndexOf('.'); if (result >= 0) { strExt = filename().mid(result).toLower(); } QByteArray ba = dev->readAll(); QBuffer buf(&ba); if (strExt == ".kgr") { loadKarbonGradient(&buf); } else if (strExt == ".svg") { loadSvgGradient(&buf); } if (m_stops.count() >= 2) { setValid(true); } updatePreview(); return true; }
bool Sample::decompressOggVorbis(char* src, int size) { AudioFile af; QByteArray ba(src, size); start = 0; end = 0; if (!af.open(ba)) { qDebug("Sample::decompressOggVorbis: open failed: %s", af.error()); return false; } int frames = af.frames(); data = new short[frames * af.channels()]; if (frames != af.readData(data, frames)) { qDebug("Sample read failed: %s", af.error()); delete[] data; data = 0; } end = frames - 1; if (loopend > end ||loopstart >= loopend || loopstart <= start) { /* can pad loop by 8 samples and ensure at least 4 for loop (2*8+4) */ if ((end - start) >= 20) { loopstart = start + 8; loopend = end - 8; } else { // loop is fowled, sample is tiny (can't pad 8 samples) loopstart = start + 1; loopend = end - 1; } } if ((end - start) < 8) { qDebug("invalid sample"); setValid(false); } return true; }
bool cc2Point5DimEditor::RasterGrid::init(unsigned w, unsigned h) { setValid(false); if (w == width && h == height) { //simply reset values reset(); return true; } clear(); try { data.resize(h,0); for (unsigned i=0; i<h; ++i) { data[i] = new RasterCell[w]; if (!data[i]) { //not enough memory clear(); return false; } } } catch (const std::bad_alloc&) { //not enough memory return false; } width = w; height = h; return true; }
const bool CtrlrLuaMethod::setCodeInternal(const String &newMethodCode) { bool compileRet = owner.getOwner().runCode (newMethodCode); errorString.clear(); errorString.append ("Compile: "+getName()+" - ", out, Colours::black); String error; if (compileRet && getName() != String::empty) { try { setObject ( (luabind::object)luabind::globals (getLuaState()) [(const char *)getName().toUTF8()] ); } catch (const luabind::error &e) { error = String(e.what()); } } else if (compileRet == false) { error = owner.getOwner().getLastError(); } if (compileRet) { errorString.append ("OK\n", out.withStyle(Font::bold), Colours::black); } else { errorString.append ("FAILED\n", out.withStyle(Font::bold), Colours::darkred); errorString.append (error+"\n", out, Colours::darkred); } setValid(compileRet); return (compileRet); }
void Board::move(const Coord &pos) { if (pos.x == -1 && pos.y == -1) passFlag[sideFlag] = true; else if (inRange(pos.x, pos.y)) { for (int i = 0; i < 8; i++) { int dx = dir[i][0], dy = dir[i][1]; if (cell[pos.x + dx][pos.y + dy].stat == !sideFlag) { for (int p = pos.x + dx, q = pos.y + dy; inRange(p, q); p += dx, q += dy) { if (cell[p][q].stat >= Empty) break; if (cell[p][q].stat == Status(sideFlag)) { cell[pos.x][pos.y].stat = Status(sideFlag); for (int r = p - dx, s = q - dy; cell[r][s].stat != Status(sideFlag); r -= dx, s -= dy) cell[r][s].stat = Status(sideFlag); break; } } } } passFlag[sideFlag] = false; } else fatalError(1); movesRecord.push_back(pos); flipSide(); setValid(); count(); }
SetTypeTypeSectionCommand::SetTypeTypeSectionCommand(TypeSection *typeSection, TypeSection::RoadType newRoadType, DataCommand *parent) : DataCommand(parent) , typeSection_(typeSection) { // Check for validity // // if (typeSection->getRoadType() == newRoadType) { setInvalid(); // Invalid because new RoadType is the same as the old setText(QObject::tr("Set Road Type (invalid!)")); return; } else { setValid(); setText(QObject::tr("Set Road Type")); } // Road Type // // newRoadType_ = newRoadType; oldRoadType_ = typeSection->getRoadType(); }
void SetLaneRoadMarkTypeCommand::construct() { // Check for validity // // if (marks_.isEmpty()) { setInvalid(); setText(QObject::tr("Set Road Mark Type: Parameters invalid! No element given.")); return; } else { setValid(); setText(QObject::tr("Set Road Mark Type")); } // Old Types // // foreach (LaneRoadMark *element, marks_) { oldTypes_.append(element->getRoadMarkType()); }
SetLaneRoadMarkSOffsetCommand::SetLaneRoadMarkSOffsetCommand(LaneRoadMark *mark, double sOffset, DataCommand *parent) : DataCommand(parent) , mark_(mark) , newSOffset_(sOffset) { // Check for validity // // if (!mark || (sOffset == mark_->getSOffset())) { setInvalid(); setText(QObject::tr("Set Road Mark Offset: Parameters invalid! No element given or no change.")); return; } else { setValid(); setText(QObject::tr("Set Road Mark Offset")); } // Road Type // // oldSOffset_ = mark_->getSOffset(); }
void Cluster::Centroid::compute() { int size = __c.__size, dim = __dimensions; double average, total; if(size == 1) { __p = __c[0]; } else if (size > 0) { for(int i = 0; i < dim; i++) { for (int k = 0; k < size; k++) { Point p(__c[k]); total += p[i]; } average = total / size; __p.setValue(i, average); total = 0; } } else { toInfinity(); } setValid(true); //std::cout << isValid() << " should be 1" << std::endl; }
AddTypeSectionCommand::AddTypeSectionCommand(RSystemElementRoad *road, TypeSection *typeSection, DataCommand *parent) : DataCommand(parent) , road_(road) , newTypeSection_(typeSection) { // Check for validity // // double s = typeSection->getSStart(); TypeSection *sqeezedTypeSection = road->getTypeSection(s); double sStart = sqeezedTypeSection->getSStart(); double sEnd = sqeezedTypeSection->getSEnd(); if ((s - sStart < MINTYPESECTIONDISTANCE) || (sEnd - s < MINTYPESECTIONDISTANCE)) { setInvalid(); // Invalid because to close to an other type section. setText(QObject::tr("Add Type Section (invalid!)")); return; } else { setValid(); setText(QObject::tr("Add Type Section")); } }
void ContactView::publicKeyEdited(const QString& public_key_string) { ui->id_edit->clear(); //clear keyhotee id field if (gMiningIsPossible) lookupPublicKey(); //check for validly hashed public key and enable/disable save button accordingly bool public_key_is_valid = public_key_address::is_valid(public_key_string.toStdString()); bool doubleContact = false; if (public_key_is_valid) { if (! (doubleContact = existContactWithPublicKey(public_key_string.toStdString()))) { ui->id_status->setText(tr("Public Key Only Mode: valid key") ); ui->id_status->setStyleSheet("QLabel { color : green; }"); } } else { ui->id_status->setText(tr("Public Key Only Mode: not a valid key") ); ui->id_status->setStyleSheet("QLabel { color : red; }"); } setValid (public_key_is_valid && ! doubleContact); }
bool KoStopGradient::load() { QString strExt; const int result = filename().lastIndexOf('.'); if (result >= 0) { strExt = filename().mid(result).toLower(); } QFile f(filename()); if (f.open(QIODevice::ReadOnly)) { if (strExt == ".kgr") { loadKarbonGradient(&f); } else if (strExt == ".svg") { loadSvgGradient(&f); } } if (m_stops.count() >= 2) setValid(true); updatePreview(); return true; }
void BitcoinAmountField::unitChanged(int idx) { // Use description tooltip for current unit for the combobox unit->setToolTip(unit->itemData(idx, Qt::ToolTipRole).toString()); // Determine new unit ID int newUnit = unit->itemData(idx, BitcoinUnits::UnitRole).toInt(); // Parse current value and convert to new unit bool valid = false; qint64 currentValue = value(&valid); currentUnit = newUnit; // Set max length after retrieving the value, to prevent truncation amount->setDecimals(BitcoinUnits::decimals(currentUnit)); amount->setMaximum(qPow(10, BitcoinUnits::amountDigits(currentUnit)) - qPow(10, -amount->decimals())); if(currentUnit == BitcoinUnits::uBTC) amount->setSingleStep(1); else if(currentUnit == BitcoinUnits::mBTC) amount->setSingleStep(0.1); else amount->setSingleStep(0.01); if(valid) { // If value was valid, re-place it in the widget with the new unit setValue(currentValue); } else { // If current value is invalid, just clear field setText(""); } setValid(true); }
bool KeySequence::appendKey(int key, int modifiers) { if (m_Sequence.size() == 4) return true; switch(key) { case Qt::Key_AltGr: return false; case Qt::Key_Control: case Qt::Key_Alt: case Qt::Key_Shift: case Qt::Key_Meta: case Qt::Key_Menu: { int mod = modifiers & (~m_Modifiers); if (mod) { m_Sequence.append(mod); m_Modifiers |= mod; } } break; default: // see if we can handle this key, if not, don't accept it if (keyToString(key).isEmpty()) break; m_Sequence.append(key); setValid(true); return true; } return false; }
GyroscopeSensorChannel::GyroscopeSensorChannel(const QString& id) : AbstractSensorChannel(id), DataEmitter<TimedXyzData>(10), previousSample_() { SensorManager& sm = SensorManager::instance(); gyroscopeAdaptor_ = sm.requestDeviceAdaptor("gyroscopeadaptor"); Q_ASSERT( gyroscopeAdaptor_ ); gyroscopeReader_ = new BufferReader<TimedXyzData>(1); outputBuffer_ = new RingBuffer<TimedXyzData>(1); // Create buffers for filter chain filterBin_ = new Bin; filterBin_->add(gyroscopeReader_, "gyroscope"); filterBin_->add(outputBuffer_, "output"); filterBin_->join("gyroscope", "source", "output", "sink"); // Join datasources to the chain connectToSource(gyroscopeAdaptor_, "gyroscope", gyroscopeReader_); marshallingBin_ = new Bin; marshallingBin_->add(this, "sensorchannel"); outputBuffer_->join(this); // Set MetaData setDescription("x, y, and z axes angular velocity in mdps"); setRangeSource(gyroscopeAdaptor_); addStandbyOverrideSource(gyroscopeAdaptor_); setIntervalSource(gyroscopeAdaptor_); setValid(true); }
bool KisWorkspaceResource::loadFromDevice(QIODevice *dev) { QDomDocument doc; if (!doc.setContent(dev)) { return false; } QDomElement element = doc.documentElement(); setName(element.attribute("name")); QDomElement state = element.firstChildElement("state"); if (!state.isNull()) { m_dockerState = QByteArray::fromBase64(state.text().toLatin1()); } QDomElement settings = element.firstChildElement("settings"); if (!settings.isNull()) { KisPropertiesConfiguration::fromXML(settings); } setValid(true); return true; }
//----------------------------------------------------------------------------- // updateLOD() //----------------------------------------------------------------------------- BOOL LLViewerJointMesh::updateLOD(F32 pixel_area, BOOL activate) { BOOL valid = mValid; setValid(activate, TRUE); return (valid != activate); }
void DhQHttpRequestHeader::DvhsetValid(bool x1) { return setValid(x1); }
void CalWizard::slotPageSelected(KPageWidgetItem* current, KPageWidgetItem* before) { Q_UNUSED(before); if (current == wPrintPage_) { months_.clear(); KUrl image; QString month; QStringList printList; QDate d; KGlobal::locale()->calendar()->setDate(d, cSettings_->year(), 1, 1); for (int i = 1; i <= KGlobal::locale()->calendar()->monthsInYear(d); ++i) { month = KGlobal::locale()->calendar()->monthName(i, cSettings_->year(), KCalendarSystem::LongName); image = cSettings_->image(i); if (!image.isEmpty()) { months_.insert(i, image); printList.append(month); } } if (months_.empty()) { wPrintLabel_->setText("<qt>" + i18n("No valid images selected for months<br/>" "Click Back to select images") + "</qt>"); setValid(wFinishPage_, false); } else { int year = cSettings_->year(); QString extra; if ((KGlobal::locale()->calendar()->month(QDate::currentDate()) >= 6 && KGlobal::locale()->calendar()->year(QDate::currentDate()) == year) || KGlobal::locale()->calendar()->year(QDate::currentDate()) > year) extra = "<br/><br/><b>" + i18n("Please note that you are making a " "calendar for<br/>the current year or a year in the " "past.") + "</b>"; KLocale tmpLocale(*KGlobal::locale()); tmpLocale.setDateFormat("%Y"); QString year_locale = tmpLocale.formatDate(d); wPrintLabel_->setText(i18n("Click Next to start Printing<br/><br/>" "Following months will be printed for year %1:<br/>", year_locale) + printList.join(" - ") + extra); wPrintLabel_->setTextFormat(Qt::RichText); setValid(wFinishPage_, true); } } else if (current == wFinishPage_) { calProgressUI.finishLabel->clear(); calProgressUI.currentProgress->reset(); calProgressUI.totalProgress->reset(); enableButton(KDialog::User3, false); // disable 'Back' button enableButton(KDialog::User1, false); // disable 'Finish' button // Set printer settings --------------------------------------- if (!printer_) { printer_ = new QPrinter(cSettings_->resolution()); } CalParams& params = cSettings_->params; // Orientation switch (params.imgPos) { case (CalParams::Top): printer_->setOrientation(QPrinter::Portrait); break; default: printer_->setOrientation(QPrinter::Landscape); break; } kDebug() << "printing..."; // PageSize printer_->setPageSize(params.pageSize); QPrintDialog* printDialog = KdePrint::createPrintDialog(printer_, this); if (printDialog->exec() == QDialog::Accepted) { print(); } else { calProgressUI.finishLabel->setText(i18n("Printing Cancelled")); enableButton(KDialog::User3, true); // enable 'Back' button } delete printDialog; } }
void QValidatedLineEdit::clear() { setValid(true); QLineEdit::clear(); }
void QValidatedLineEdit::markValid() { // As long as a user is typing ensure we display state as valid setValid(true); }
bool cc2Point5DimEditor::RasterGrid::fillWith( ccGenericPointCloud* cloud, unsigned char projectionDimension, cc2Point5DimEditor::ProjectionType projectionType, bool interpolateEmptyCells, cc2Point5DimEditor::ProjectionType sfInterpolation/*=INVALID_PROJECTION_TYPE*/, ccProgressDialog* progressDialog/*=0*/) { if (!cloud) { assert(false); return false; } //current parameters unsigned gridTotalSize = width * height; //vertical dimension const unsigned char Z = projectionDimension; assert(Z >= 0 && Z <= 2); const unsigned char X = Z == 2 ? 0 : Z +1; const unsigned char Y = X == 2 ? 0 : X +1; //do we need to interpolate scalar fields? ccPointCloud* pc = cloud->isA(CC_TYPES::POINT_CLOUD) ? static_cast<ccPointCloud*>(cloud) : 0; bool interpolateSF = (sfInterpolation != INVALID_PROJECTION_TYPE); interpolateSF &= (pc && pc->hasScalarFields()); if (interpolateSF) { unsigned sfCount = pc->getNumberOfScalarFields(); bool memoryError = false; size_t previousCount = scalarFields.size(); if (sfCount > previousCount) { try { scalarFields.resize(sfCount,0); } catch (const std::bad_alloc&) { //not enough memory memoryError = true; } } for (size_t i=previousCount; i<sfCount; ++i) { assert(scalarFields[i] == 0); scalarFields[i] = new double[gridTotalSize]; if (!scalarFields[i]) { //not enough memory memoryError = true; break; } } if (memoryError) { ccLog::Warning(QString("[Rasterize] Failed to allocate memory for scalar fields!")); } } //filling the grid unsigned pointCount = cloud->size(); double gridMaxX = gridStep * width; double gridMaxY = gridStep * height; if (progressDialog) { progressDialog->setMethodTitle("Grid generation"); progressDialog->setInfo(qPrintable(QString("Points: %1\nCells: %2 x %3").arg(pointCount).arg(width).arg(height))); progressDialog->start(); progressDialog->show(); QCoreApplication::processEvents(); } CCLib::NormalizedProgress nProgress(progressDialog,pointCount); for (unsigned n=0; n<pointCount; ++n) { const CCVector3* P = cloud->getPoint(n); CCVector3d relativePos = CCVector3d::fromArray(P->u) - minCorner; int i = static_cast<int>(relativePos.u[X]/gridStep); int j = static_cast<int>(relativePos.u[Y]/gridStep); //specific case: if we fall exactly on the max corner of the grid box if (i == static_cast<int>(width) && relativePos.u[X] == gridMaxX) --i; if (j == static_cast<int>(height) && relativePos.u[Y] == gridMaxY) --j; //we skip points outside the box! if ( i < 0 || i >= static_cast<int>(width) || j < 0 || j >= static_cast<int>(height) ) continue; assert(i >= 0 && j >= 0); RasterCell* aCell = data[j]+i; unsigned& pointsInCell = aCell->nbPoints; if (pointsInCell) { if (P->u[Z] < aCell->minHeight) { aCell->minHeight = P->u[Z]; if (projectionType == PROJ_MINIMUM_VALUE) aCell->pointIndex = n; } else if (P->u[Z] > aCell->maxHeight) { aCell->maxHeight = P->u[Z]; if (projectionType == PROJ_MAXIMUM_VALUE) aCell->pointIndex = n; } } else { aCell->minHeight = aCell->maxHeight = P->u[Z]; aCell->pointIndex = n; } // Sum the points heights aCell->avgHeight += P->u[Z]; aCell->stdDevHeight += static_cast<double>(P->u[Z])*P->u[Z]; //scalar fields if (interpolateSF) { int pos = j*static_cast<int>(width)+i; //pos in 2D SF grid(s) assert(pos < static_cast<int>(gridTotalSize)); for (size_t k=0; k<scalarFields.size(); ++k) { if (scalarFields[k]) { CCLib::ScalarField* sf = pc->getScalarField(static_cast<unsigned>(k)); assert(sf); ScalarType sfValue = sf->getValue(n); ScalarType formerValue = static_cast<ScalarType>(scalarFields[k][pos]); if (pointsInCell && ccScalarField::ValidValue(formerValue)) { if (ccScalarField::ValidValue(sfValue)) { switch (sfInterpolation) { case PROJ_MINIMUM_VALUE: // keep the minimum value scalarFields[k][pos] = std::min<double>(formerValue,sfValue); break; case PROJ_AVERAGE_VALUE: //we sum all values (we will divide them later) scalarFields[k][pos] += sfValue; break; case PROJ_MAXIMUM_VALUE: // keep the maximum value scalarFields[k][pos] = std::max<double>(formerValue,sfValue); break; default: assert(false); break; } } } else { //for the first (vaild) point, we simply have to store its SF value (in any case) scalarFields[k][pos] = sfValue; } } } } pointsInCell++; if (!nProgress.oneStep()) { //process cancelled by user return false; } } //update SF grids for 'average' cases if (sfInterpolation == PROJ_AVERAGE_VALUE) { for (size_t k=0; k<scalarFields.size(); ++k) { if (scalarFields[k]) { double* _gridSF = scalarFields[k]; for (unsigned j=0;j<height;++j) { RasterCell* cell = data[j]; for (unsigned i=0; i<width; ++i,++cell,++_gridSF) { if (cell->nbPoints > 1) { ScalarType s = static_cast<ScalarType>(*_gridSF); if (ccScalarField::ValidValue(s)) //valid SF value { *_gridSF /= cell->nbPoints; } } } } } } } //update the main grid (average height and std.dev. computation + current 'height' value) { for (unsigned j=0; j<height; ++j) { RasterCell* cell = data[j]; for (unsigned i=0; i<width; ++i,++cell) { if (cell->nbPoints > 1) { cell->avgHeight /= cell->nbPoints; cell->stdDevHeight = sqrt(fabs(cell->stdDevHeight/cell->nbPoints - cell->avgHeight*cell->avgHeight)); } else { cell->stdDevHeight = 0; } if (cell->nbPoints != 0) { //set the right 'height' value switch (projectionType) { case PROJ_MINIMUM_VALUE: cell->h = cell->minHeight; break; case PROJ_AVERAGE_VALUE: cell->h = cell->avgHeight; break; case PROJ_MAXIMUM_VALUE: cell->h = cell->maxHeight; break; default: assert(false); break; } } } } } //compute the number of non empty cells nonEmptyCellCount = 0; { for (unsigned i=0; i<height; ++i) for (unsigned j=0; j<width; ++j) if (data[i][j].nbPoints) ++nonEmptyCellCount; } //specific case: interpolate the empty cells if (interpolateEmptyCells) { std::vector<CCVector2> the2DPoints; if (nonEmptyCellCount < 3) { ccLog::Warning("[Rasterize] Not enough non-empty cells to interpolate!"); } else if (nonEmptyCellCount < width * height) //otherwise it's useless! { try { the2DPoints.resize(nonEmptyCellCount); } catch (const std::bad_alloc&) { //out of memory ccLog::Warning("[Rasterize] Not enough memory to interpolate empty cells!"); } } //fill 2D vector with non-empty cell indexes if (!the2DPoints.empty()) { unsigned index = 0; for (unsigned j=0; j<height; ++j) { const RasterCell* cell = data[j]; for (unsigned i=0; i<width; ++i, ++cell) { if (cell->nbPoints) { //we only use the non-empty cells to interpolate the2DPoints[index++] = CCVector2(static_cast<PointCoordinateType>(i),static_cast<PointCoordinateType>(j)); } } } assert(index == nonEmptyCellCount); //mesh the '2D' points CCLib::Delaunay2dMesh delaunayMesh; char errorStr[1024]; if (delaunayMesh.buildMesh(the2DPoints,0,errorStr)) { unsigned triNum = delaunayMesh.size(); //now we are going to 'project' all triangles on the grid delaunayMesh.placeIteratorAtBegining(); for (unsigned k=0; k<triNum; ++k) { const CCLib::VerticesIndexes* tsi = delaunayMesh.getNextTriangleVertIndexes(); //get the triangle bounding box (in grid coordinates) int P[3][2]; int xMin = 0, yMin = 0, xMax = 0, yMax = 0; { for (unsigned j=0; j<3; ++j) { const CCVector2& P2D = the2DPoints[tsi->i[j]]; P[j][0] = static_cast<int>(P2D.x); P[j][1] = static_cast<int>(P2D.y); } xMin = std::min(std::min(P[0][0],P[1][0]),P[2][0]); yMin = std::min(std::min(P[0][1],P[1][1]),P[2][1]); xMax = std::max(std::max(P[0][0],P[1][0]),P[2][0]); yMax = std::max(std::max(P[0][1],P[1][1]),P[2][1]); } //now scan the cells { //pre-computation for barycentric coordinates const double& valA = data[ P[0][1] ][ P[0][0] ].h; const double& valB = data[ P[1][1] ][ P[1][0] ].h; const double& valC = data[ P[2][1] ][ P[2][0] ].h; int det = (P[1][1]-P[2][1])*(P[0][0]-P[2][0]) + (P[2][0]-P[1][0])*(P[0][1]-P[2][1]); for (int j=yMin; j<=yMax; ++j) { RasterCell* cell = data[static_cast<unsigned>(j)]; for (int i=xMin; i<=xMax; ++i) { //if the cell is empty if (!cell[i].nbPoints) { //we test if it's included or not in the current triangle //Point Inclusion in Polygon Test (inspired from W. Randolph Franklin - WRF) bool inside = false; for (int ti=0; ti<3; ++ti) { const int* P1 = P[ti]; const int* P2 = P[(ti+1)%3]; if ((P2[1] <= j &&j < P1[1]) || (P1[1] <= j && j < P2[1])) { int t = (i-P2[0])*(P1[1]-P2[1])-(P1[0]-P2[0])*(j-P2[1]); if (P1[1] < P2[1]) t = -t; if (t < 0) inside = !inside; } } //can we interpolate? if (inside) { double l1 = static_cast<double>((P[1][1]-P[2][1])*(i-P[2][0])+(P[2][0]-P[1][0])*(j-P[2][1]))/det; double l2 = static_cast<double>((P[2][1]-P[0][1])*(i-P[2][0])+(P[0][0]-P[2][0])*(j-P[2][1]))/det; double l3 = 1.0-l1-l2; cell[i].h = l1 * valA + l2 * valB + l3 * valC; assert(cell[i].h == cell[i].h); //interpolate SFs as well! for (size_t sfIndex=0; sfIndex<scalarFields.size(); ++sfIndex) { if (scalarFields[sfIndex]) { double* gridSF = scalarFields[sfIndex]; const double& sfValA = gridSF[ P[0][0] + P[0][1]*width ]; const double& sfValB = gridSF[ P[1][0] + P[1][1]*width ]; const double& sfValC = gridSF[ P[2][0] + P[2][1]*width ]; gridSF[i + j*width] = l1 * sfValA + l2 * sfValB + l3 * sfValC; } } } } } } } } } else { ccLog::Warning(QString("[Rasterize] Empty cells interpolation failed: Triangle lib. said '%1'").arg(errorStr)); } } } //computation of the average and extreme height values in the grid { minHeight = 0; maxHeight = 0; meanHeight = 0; validCellCount = 0; for (unsigned i=0; i<height; ++i) { for (unsigned j=0; j<width; ++j) { if (data[i][j].h == data[i][j].h) //valid height { double h = data[i][j].h; if (validCellCount) { if (h < minHeight) minHeight = h; else if (h > maxHeight) maxHeight = h; meanHeight += h; } else { //first valid cell meanHeight = minHeight = maxHeight = h; } ++validCellCount; } } } meanHeight /= validCellCount; } setValid(true); return true; }
void QValidatedLineEdit::markValid() { setValid(true); }