QList<int> ValueModelBase::getCompositeNumber(QList<int> in) { QList<int> prime = getPrimeNumber(in); QList<int> composite = in; for (auto& obj: composite) { if (prime.contains(obj)) { composite.removeOne(obj); } } return composite; }
QList<core::GraphicObject *> core::Connector::removeIgnoredObjects(const QList<GraphicObject *> &list) const { GraphicObject *obj; QList<GraphicObject*> returnedList = list; for(auto i = 0; i < returnedList.size(); i++){ obj = returnedList[i]; if(obj->type() == gotConnector || obj == beginObject){ returnedList.removeOne(obj); i--; } } return returnedList; }
void Library::updateTrackMetadata(Track track) { Track ntrack = track; if (track.id() > 0) { ntrack = _library_storage->updateTrack(track); } // update all playlists QList<QString> playlists = getPlaylistsNames(); foreach (QString name, playlists) { Playlist pl = getPlaylist(name); QList<Track> tracks = pl.tracks(); int pos = tracks.indexOf(ntrack); // comparing using source tracks.removeOne(ntrack); // comparing using source tracks.insert(pos, ntrack); pl.setTracks(tracks); savePlaylist(pl); }
short TankBuilder::getHighestAndRemove(QList<short> &aNumberList) { short highestValue = -1; if (!aNumberList.isEmpty()) { foreach(short number, aNumberList) { if (number > highestValue) { highestValue = number; } } aNumberList.removeOne(highestValue); }
void Test::checkTiles( int boardSize, vector< int >& squares ) { QList< int > values; for ( int i = 0; i < boardSize * boardSize; i++ ) { values.append( i ); } for ( int i = 0; i < boardSize * boardSize; i++ ) { QCOMPARE( values.contains( squares[i] ), true ); values.removeOne( squares[i] ); } QCOMPARE( values.size(), 0 ); }
void PersistantConfig::AddRecentFile(QList<QString> &recentList, const QString &file, int maxItems) { QDir dir(file); QString path = dir.canonicalPath(); if(!recentList.contains(path)) { recentList.push_back(path); if(recentList.count() >= maxItems) recentList.removeAt(0); } else { recentList.removeOne(path); recentList.push_back(path); } }
void DocumentManager::closeAllOther( AbstractDocument* keptDocument ) { // TODO: is it better for remove the document from the list before emitting closing(document)? // TODO: or better emit close(documentList)? who would use this? QList<AbstractDocument*> closedDocuments = mList; closedDocuments.removeOne( keptDocument ); mList.clear(); mList.append( keptDocument ); emit closing( closedDocuments ); foreach( AbstractDocument* document, closedDocuments ) { delete document; } }
void RewriteActionCompressor::compressImports(QList<RewriteAction *> &actions) const { QList<RewriteAction *> actionsToRemove; QHash<Import, RewriteAction *> addedImports; QHash<Import, RewriteAction *> removedImports; QMutableListIterator<RewriteAction *> iter(actions); iter.toBack(); while (iter.hasPrevious()) { RewriteAction *action = iter.previous(); if (RemoveImportRewriteAction *removeImportAction = action->asRemoveImportRewriteAction()) { const Import import = removeImportAction->import(); if (removedImports.contains(import)) { actionsToRemove.append(action); } else if (RewriteAction *addImportAction = addedImports.value(import, 0)) { actionsToRemove.append(action); actionsToRemove.append(addImportAction); addedImports.remove(import); delete addImportAction; } else { removedImports.insert(import, action); } } else if (AddImportRewriteAction *addImportAction = action->asAddImportRewriteAction()) { const Import import = addImportAction->import(); if (RewriteAction *duplicateAction = addedImports.value(import, 0)) { actionsToRemove.append(duplicateAction); addedImports.remove(import); delete duplicateAction; addedImports.insert(import, action); } else if (RewriteAction *removeAction = removedImports.value(import, 0)) { actionsToRemove.append(action); actionsToRemove.append(removeAction); removedImports.remove(import); delete removeAction; } else { addedImports.insert(import, action); } } } foreach (RewriteAction *action, actionsToRemove) { actions.removeOne(action); delete action; }
void TestKeePass2Format::testXmlEntry2() { const Entry* entry = m_xmlDb->rootGroup()->entries().at(1); QCOMPARE(entry->uuid(), QUuid::fromRfc4122(QByteArray::fromBase64("4jbADG37hkiLh2O0qUdaOQ=="))); QCOMPARE(entry->iconNumber(), 0); QCOMPARE(entry->iconUuid(), QUuid::fromRfc4122(QByteArray::fromBase64("++vyI+daLk6omox4a6kQGA=="))); // TODO: test entry->icon() QCOMPARE(entry->foregroundColor(), QColor(255, 0, 0)); QCOMPARE(entry->backgroundColor(), QColor(255, 255, 0)); QCOMPARE(entry->overrideUrl(), QString("http://override.net/")); QCOMPARE(entry->tags(), QString("")); const TimeInfo ti = entry->timeInfo(); QCOMPARE(ti.usageCount(), 7); QList<QString> attrs = entry->attributes()->keys(); QCOMPARE(entry->attributes()->value("CustomString"), QString("isavalue")); QVERIFY(attrs.removeOne("CustomString")); QCOMPARE(entry->attributes()->value("Notes"), QString("")); QVERIFY(attrs.removeOne("Notes")); QCOMPARE(entry->attributes()->value("Password"), QString("Jer60Hz8o9XHvxBGcRqT")); QVERIFY(attrs.removeOne("Password")); QCOMPARE(entry->attributes()->value("Protected String"), QString("y")); // TODO: should have a protection attribute QVERIFY(attrs.removeOne("Protected String")); QCOMPARE(entry->attributes()->value("Title"), QString("Sample Entry 2")); QVERIFY(attrs.removeOne("Title")); QCOMPARE(entry->attributes()->value("URL"), QString("http://www.keepassx.org/")); QVERIFY(attrs.removeOne("URL")); QCOMPARE(entry->attributes()->value("UserName"), QString("notDEFUSERNAME")); QVERIFY(attrs.removeOne("UserName")); QVERIFY(attrs.isEmpty()); QCOMPARE(entry->attachments()->keys().size(), 1); QCOMPARE(QString::fromLatin1(entry->attachments()->value("myattach.txt")), QString("abcdefghijk")); QCOMPARE(entry->autoTypeEnabled(), true); QCOMPARE(entry->autoTypeObfuscation(), 1); QCOMPARE(entry->defaultAutoTypeSequence(), QString("{USERNAME}{TAB}{PASSWORD}{ENTER}")); QCOMPARE(entry->autoTypeAssociations()->size(), 2); const AutoTypeAssociations::Association assoc1 = entry->autoTypeAssociations()->get(0); QCOMPARE(assoc1.window, QString("Target Window")); QCOMPARE(assoc1.sequence, QString("{Title}{UserName}")); const AutoTypeAssociations::Association assoc2 = entry->autoTypeAssociations()->get(1); QCOMPARE(assoc2.window, QString("Target Window 2")); QCOMPARE(assoc2.sequence, QString("{Title}{UserName} test")); }
virtual bool trigger(TriggerEvent event, ServerPlayer *player, QVariant &data) const{ Room *room = player->getRoom(); QList<const Card *> clubs; if(event == CardUsed){ CardUseStruct use = data.value<CardUseStruct>(); const SkillCard *skill_card = qobject_cast<const SkillCard *>(use.card); if(skill_card && skill_card->subcardsLength() > 0 && skill_card->willThrow()){ clubs = getClubs(skill_card); } }else if(event == CardDiscarded){ const Card *card = data.value<CardStar>(); if(card->subcardsLength() == 0) return false; clubs = getClubs(card); }else if(event == FinishJudge){ JudgeStar judge = data.value<JudgeStar>(); if(room->getCardPlace(judge->card->getEffectiveId()) == Player::DiscardedPile && judge->card->getSuit() == Card::Club) clubs << judge->card; } ServerPlayer *caozhi = room->findPlayerBySkillName(objectName()); foreach(const Card* card, clubs) if(card->objectName() == "shit") if(caozhi && room->askForChoice(caozhi, objectName(), "yes+no") == "no") clubs.removeOne(card); if(clubs.isEmpty()) return false; if(caozhi && caozhi->askForSkillInvoke(objectName(), data)){ if(player->getGeneralName() == "zhenji") room->playSkillEffect("luoying", 2); else room->playSkillEffect("luoying", 1); foreach(const Card *club, clubs) caozhi->obtainCard(club); } return false; }
QList<QByteArray> SkyNet::filter_existing_chans(QList<QByteArray> peer_ids) { QList<QByteArray> ret = peer_ids; if (!nodelink) return ret; struct PICA_chaninfo *iptr = nodelink->chan_list_head; while(iptr) { if (peer_ids.contains(QByteArray((const char*)iptr->peer_id, PICA_ID_SIZE))) ret.removeOne((const char*)iptr->peer_id); iptr = iptr->next; } return ret; }
void CookieManager::removeCookie() { QTreeWidgetItem* current = ui->cookieTree->currentItem(); if (!current) { return; } QList<QNetworkCookie> allCookies = mApp->cookieJar()->getAllCookies(); if (current->text(1).isEmpty()) { //Remove whole cookie group QString domain = current->whatsThis(0); foreach(const QNetworkCookie & cookie, allCookies) { if (cookie.domain() == domain || cookie.domain() == domain.mid(1)) { allCookies.removeOne(cookie); } } ui->cookieTree->deleteItem(current); }
void ToolBars::load(const QJsonArray & bars) { if (bars.count() > 0) { QList<QString> barsList; barsList << TOOLBAR_MEDIA_KEY << TOOLBAR_MEDIA_PLUS_KEY << TOOLBAR_MEDIA_POS_KEY << TOOLBAR_MEDIA_PAN_KEY << TOOLBAR_MEDIA_TEMPO_KEY << TOOLBAR_SEARCH_KEY << TOOLBAR_MEDIA_TIME_KEY << TOOLBAR_MEDIA_VOLUME_KEY << TOOLBAR_PL_ITEM_FEATURES_KEY << TOOLBAR_SL_ITEM_FEATURES_KEY << TOOLBAR_CONTROLS_KEY << TOOLBAR_SETTINGS_KEY << TOOLBAR_SPECTRUM_KEY << TOOLBAR_EQUALIZER_KEY << TOOLBAR_EQUALIZER_BUTTON_KEY; QJsonObject obj, actionObj; QString barName; QToolBar * curr_bar; for(QJsonArray::ConstIterator bar = bars.constBegin(); bar != bars.constEnd(); bar++) { obj = (*bar).toObject(); barName = obj.value(Keys::title).toString(); barsList.removeOne(barName); curr_bar = linkNameToToolbar(barName); curr_bar -> setObjectName(obj.value(Keys::name).toString(curr_bar -> objectName())); curr_bar -> setMovable(obj.value(Keys::movable).toBool()); container -> addToolBar(Qt::BottomToolBarArea, curr_bar); if (obj.contains(Keys::actions)) { QJsonArray actions = obj.value(Keys::actions).toArray(); foreach(QJsonValue act, actions) { // rewrite on for actionObj = act.toObject(); addPanelButton(actionObj.value(Keys::name).toString(), actionObj.value(Keys::path).toString(), curr_bar); } }
int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); QList<int> list; for (unsigned int i = 0; i < 10; i++) { list.append(i); } list.removeOne(5); foreach (int mNumber, list) { qDebug() << mNumber; } return a.exec(); }
void QDeclarativeLandmarkCategoryModel::convertCategoriesToDeclarative() { QList<QString> categoriesToRemove = m_categoryMap.keys(); foreach(const QLandmarkCategory& category, m_categories) { if (!m_categoryMap.contains(category.categoryId().localId())) { QDeclarativeLandmarkCategory* declarativeLandmarkCategory = new QDeclarativeLandmarkCategory(this); declarativeLandmarkCategory->setCategory(category); m_categoryMap.insert(category.categoryId().localId(), declarativeLandmarkCategory); } else { // The landmark exists already, update it m_categoryMap.value(category.categoryId().localId())->setCategory(category); // Item is still valid, remove it from the list of removables categoriesToRemove.removeOne(category.categoryId().localId()); } } foreach (const QString removable, categoriesToRemove) { delete m_categoryMap.value(removable); m_categoryMap.remove(removable); }
void ServerConnector::loadAndPruneChunks() { ChunkPosition currentPosition = world().chunkPosition(me()->v_position.x, me()->v_position.z); QList<ChunkPosition> wantedChunks; // The chunks we still want to be active // Create a list of the wanted chunks for(int x = - i_viewDistance; x < i_viewDistance+1; ++x) { for(int z = - i_viewDistance; z < i_viewDistance+1; ++z) { ChunkPosition position = ChunkPosition(currentPosition.first + x, currentPosition.second + z); wantedChunks.push_back(position); } } // Let's see if we have to prune unwanted ones... for (int i = 0; i < m_loadedChunks.size(); ++i) { ChunkPosition processingChunk = m_loadedChunks.at(i); // If the chunk is wanted if(wantedChunks.contains(processingChunk)) { // delete it from the wanted ones wantedChunks.removeOne(processingChunk); } else { // The chunk is unwanted, get rid of it ChunkConnectEvent* event = new ChunkConnectEvent(processingChunk, ChunkConnectEvent::ChunkConnection_Disconnect); emit postEvent(event); // Delete it from the loaded chunks list m_loadedChunks.removeAt(i); i--; } } // Now we load the chunks that were not in the loaded chunks for (int i = 0; i < wantedChunks.size(); ++i) { ChunkPosition processingChunk = wantedChunks.at(i); ChunkConnectEvent* event = new ChunkConnectEvent(processingChunk, ChunkConnectEvent::ChunkConnection_Connect); emit postEvent(event); m_loadedChunks.push_back(processingChunk); } }
bool Method::WhetherToBeat(QList<card> &myCards) { if (myCards.isEmpty()) return true; Player* hitPlayer = m_player->getHitPlayer(); QList<card> hitCards = m_player->getHitCards(); if (m_player->getRole() == hitPlayer->getRole()) // punch的是同家 { QList<card> left = m_cards; for(int i=0;i<myCards.size();i++) left.removeOne(myCards[i]); if (Hand(left).getHandType() != Hand_Unknown) return true; CardPoint basePoint = CardPoint(Hand(myCards).getBasePoint()); if (basePoint == Card_2 || basePoint == Card_SJ || basePoint == Card_BJ) { return false; } } else // punch的是对家 { Hand myHand(myCards); if ( (myHand.getHandType() == Hand_Triple_Single || myHand.getHandType() == Hand_Triple_Pair) && (myHand.getBasePoint() == Card_2) ) // 三个2就不打出去了 { return false; } if (myHand.getHandType() == Hand_Pair && myHand.getBasePoint() == Card_2 && hitPlayer->getCards().size() >= 10 && m_player->getCards().size() >= 5) { return false; } } return true; }
/** * Removes all currently selected waypoints. */ void WaypointListWidget::deleteSelectedWaypoints() { QList<Waypoint *> wpList; QList<QTreeWidgetItem *> itemList = list->selectedItems(); if( itemList.size() ) { list->setUpdatesEnabled(false); QList<Waypoint>& wpList = _globalMapContents->getWaypointList(); for( int i = 0; i < itemList.size(); i++ ) { WaypointItem* wpi = dynamic_cast<WaypointItem *> (itemList.at(i)); if( ! wpi ) { continue; } // Get waypoint reference from item. Waypoint& wp = wpi->wp; // At first remove waypoint from filter because there is a reference // to the global waypoint list. filter->removeListItem( itemList.at(i) ); // At last remove waypoint from global list in MapContents wpList.removeOne( wp ); } // save the modified catalog _globalMapContents->saveWaypointList(); filter->reset(); resizeListColumns(); list->setUpdatesEnabled(true); } }
void WorkflowTabView::updateDashboards(const QList<DashboardInfo> &dashboards) { QList<DashboardInfo> dbs = dashboards; int i = 0; while (i < count()) { Dashboard *db = dynamic_cast<Dashboard*>(widget(i)); if (db->isWorkflowInProgress()) { i++; continue; } DashboardInfo info(db->directory()); if (dbs.contains(info)) { dbs.removeOne(info); i++; } else { db->setClosed(); removeTab(i); delete db; } } foreach (const DashboardInfo &info, dbs) { addDashboard(new Dashboard(info.path, this)); }
void AllPlotInterval::sortIntervals(QList<IntervalItem*> &intervals, QList< QList<IntervalItem*> > &intervalsGroups) { // Sort by duration qSort(intervals.begin(), intervals.end(), intervalBiggerThan); QList<IntervalItem*> matchesGroup; for (int i=0; i<intervals.count(); i++) { IntervalItem* interval = intervals.at(i); if (groupMatch && interval->type == RideFileInterval::USER) { matchesGroup.append(interval); intervals.removeOne(interval); //intervals.move(i, place++); } } if (matchesGroup.count() > 0) intervalsGroups.append(matchesGroup); }
QList<QGraphicsItem*> FaceGroup::Private::hotItems(const QPointF& scenePos) { if (!q->hasVisibleItems()) { return QList<QGraphicsItem*>(); } const int distance = 15; QRectF hotSceneRect = QRectF(scenePos, QSize(0, 0)).adjusted(-distance, -distance, distance, distance); QList<QGraphicsItem*> closeItems = view->scene()->items(hotSceneRect, Qt::IntersectsItemBoundingRect); closeItems.removeOne(view->previewItem()); return closeItems; /* qreal distance; d->faceGroup->closestItem(mapToScene(e->pos()), &distance); if (distance < 15) return false; */ }
QList<Cue*> CueDAO::getCuesForTrack(const int trackId) const { //qDebug() << "CueDAO::getCuesForTrack" << QThread::currentThread() << m_database.connectionName(); QList<Cue*> cues; // A hash from hotcue index to cue id and cue*, used to detect if more // than one cue has been assigned to a single hotcue id. QMap<int, QPair<int, Cue*> > dupe_hotcues; QSqlQuery query(m_database); query.prepare("SELECT * FROM " CUE_TABLE " WHERE track_id = :id"); query.bindValue(":id", trackId); if (query.exec()) { const int idColumn = query.record().indexOf("id"); const int hotcueIdColumn = query.record().indexOf("hotcue"); while (query.next()) { Cue* cue = NULL; int cueId = query.value(idColumn).toInt(); if (m_cues.contains(cueId)) { cue = m_cues[cueId]; } if (cue == NULL) { cue = cueFromRow(query); } int hotcueId = query.value(hotcueIdColumn).toInt(); if (hotcueId != -1) { if (dupe_hotcues.contains(hotcueId)) { m_cues.remove(dupe_hotcues[hotcueId].first); cues.removeOne(dupe_hotcues[hotcueId].second); } dupe_hotcues[hotcueId] = qMakePair(cueId, cue); } if (cue != NULL) { cues.push_back(cue); } } } else { LOG_FAILED_QUERY(query); } return cues; }
bool OSSMidiPortDriver::setPortProperties(MidiPropertiesDialog *mpd, MidiSession *midiSession) { int sessionIx = -1; QString midiPortName = ""; if (midiSession != NULL) { for (int i = 0; i < sessions.size(); i++) { if (sessions[i]->midiSession == midiSession) { sessionIx = i; midiPortName = sessions[i]->midiPortName; break; } } } QList<QString> midiInPortNames; OSSMidiPortDriver::enumPorts(midiInPortNames); midiInPortNames.removeOne(sequencerName); mpd->setMidiList(midiInPortNames, -1); mpd->setMidiPortName(midiPortName); if (mpd->exec() != QDialog::Accepted) return false; if (sessionIx == -1 || midiPortName == mpd->getMidiPortName()) return true; stopSession(sessions[sessionIx]); midiSession->getSynthRoute()->setMidiSessionName(midiSession, mpd->getMidiPortName()); return startSession(midiSession, mpd->getMidiPortName(), false); }
void Method::PickSeqSingles(QList<QList<QList<card> > >& allSeqRecord, const QList<QList<card> >& seqInherited, QList<card> cards) { QList<QList<card> > allSeqScheme = Method(m_player, cards).FindHand(Hand(Hand_Seq_Single, Card_Begin, 0), false); if (allSeqScheme.isEmpty()) { allSeqRecord << seqInherited; } else { QList<card> savedCards = cards; for (int i = 0; i < allSeqScheme.size(); i++) { QList<card> aScheme = allSeqScheme[i]; QList<card> leftCards = savedCards; for(int j=0;j<aScheme.size();j++) leftCards.removeOne(aScheme[j]); QList<QList<card> > seqArray = seqInherited; seqArray.append(aScheme); PickSeqSingles(allSeqRecord, seqArray, leftCards); } } }
/*! * A method for getting AlertTone objects for all * available settings (ringing, voip, email, sms, im) * * \return AlertTone instances... */ QList<AlertTone *> AlertTone::alertTones () { QList<AlertTone *> v; #ifdef HAVE_LIBPROFILE #ifdef WANT_PROFILED_CHECKS QList<QString> keys; profileval_t *vals = profile_get_values(NULL); if (vals) { for (int profile = 0 ; vals[profile].pv_key != NULL ; profile++) { QStringList split_key = QString (vals[profile].pv_key).split ('.'); if (split_key.size() == 3) { if (split_key[0] != "clock" && split_key[1] == "alert" && split_key[2] == "tone") keys.push_back (vals[profile].pv_key); } } profile_free_values (vals); } QVector<QString> toneKeys (0); toneKeys << "ringing.alert.tone" << "voip.alert.tone" << "email.alert.tone" << "sms.alert.tone" << "im.alert.tone" << "calendar.alert.tone"; for (int i = 0 ; i < toneKeys.size() ; i++) { if (keys.contains (toneKeys.at (i))) { keys.removeOne (toneKeys.at (i)); v << new AlertTone (QString (toneKeys.at (i)) + "@general"); } } #else // do not WANT_PROFILED_CHECKS QVector<QString> toneKeys (0); toneKeys << "ringing.alert.tone@general" << "voip.alert.tone@general" << "email.alert.tone@general" << "sms.alert.tone@general" << "im.alert.tone@general" << "calendar.alert.tone@general"; for (int i = 0; i < toneKeys.size (); i++) { v << new AlertTone (toneKeys.at (i)); } #endif #endif // HAVE_LIBPROFILE return v; }
void UIMultiScreenLayout::update() { LogRelFlow(("UIMultiScreenLayout::update: Started...\n")); /* Clear screen-map initially: */ m_screenMap.clear(); /* Make a pool of available host screens: */ QList<int> availableScreens; for (int i = 0; i < m_cHostScreens; ++i) availableScreens << i; /* Load all combinations stored in the settings file. * We have to make sure they are valid, which means there have to be unique combinations * and all guests screens need there own host screen. */ CDisplay display = m_pMachineLogic->session().GetConsole().GetDisplay(); bool fShouldWeAutoMountGuestScreens = gEDataManager->autoMountGuestScreensEnabled(vboxGlobal().managedVMUuid()); LogRel(("GUI: UIMultiScreenLayout::update: GUI/AutomountGuestScreens is %s\n", fShouldWeAutoMountGuestScreens ? "enabled" : "disabled")); foreach (int iGuestScreen, m_guestScreens) { /* Initialize variables: */ bool fValid = false; int iHostScreen = -1; if (!fValid) { /* If the user ever selected a combination in the view menu, we have the following entry: */ iHostScreen = gEDataManager->hostScreenForPassedGuestScreen(iGuestScreen, vboxGlobal().managedVMUuid()); /* Revalidate: */ fValid = iHostScreen >= 0 && iHostScreen < m_cHostScreens /* In the host screen bounds? */ && m_screenMap.key(iHostScreen, -1) == -1; /* Not taken already? */ } if (!fValid) { /* Check the position of the guest window in normal mode. * This makes sure that on first use fullscreen/seamless window opens on the same host-screen as the normal window was before. * This even works with multi-screen. The user just have to move all the normal windows to the target host-screens * and they will magically open there in fullscreen/seamless also. */ QRect geo = gEDataManager->machineWindowGeometry(UIVisualStateType_Normal, iGuestScreen, vboxGlobal().managedVMUuid()); /* If geometry is valid: */ if (!geo.isNull()) { /* Get top-left corner position: */ QPoint topLeftPosition(geo.topLeft()); /* Check which host-screen the position belongs to: */ iHostScreen = vboxGlobal().screenNumber(topLeftPosition); /* Revalidate: */ fValid = iHostScreen >= 0 && iHostScreen < m_cHostScreens /* In the host screen bounds? */ && m_screenMap.key(iHostScreen, -1) == -1; /* Not taken already? */ } } if (!fValid) { /* If still not valid, pick the next one * if there is still available host screen: */ if (!availableScreens.isEmpty()) { iHostScreen = availableScreens.first(); fValid = true; } } if (fValid) { /* Register host screen for the guest screen: */ m_screenMap.insert(iGuestScreen, iHostScreen); /* Remove it from the list of available host screens: */ availableScreens.removeOne(iHostScreen); } /* Do we have opinion about what to do with excessive guest-screen? */ else if (fShouldWeAutoMountGuestScreens) { /* Then we have to disable excessive guest-screen: */ LogRel(("GUI: UIMultiScreenLayout::update: Disabling excessive guest-screen %d\n", iGuestScreen)); display.SetVideoModeHint(iGuestScreen, false, false, 0, 0, 0, 0, 0); } }
void ProcessModel::dynUpdateTopolSort(QList<ListDigraph::Node> &topolOrdering, const ListDigraph::Node &i, const ListDigraph::Node &k) { QTextStream out(stdout); /** Algorithm: * * 1. Find the positions of i and k * 2. IF posi < posk => no changes to the topological sorting needs to be performed. Return. * 3. IF posi > posk => reorder the nodes. The affected region is [posi, posk]. Return. */ int posi = -1; int posk = -1; if (k == INVALID) { posk = (int) Math::MAX_INTUNI; } else { posk = topolOrdering.indexOf(k); } if (i == INVALID) { posi = 0; } else { posi = topolOrdering.indexOf(i); } if (posi < posk) { // No changes to perform return; } // ##################### DEBUG ########################################### /* out << "Before DTO:" << endl; out << "posj = " << posj << " ID = " << ((j == INVALID) ? -1 : pm->ops[j]->ID) << endl; out << "posi = " << posi << " ID = " << ((i == INVALID) ? -1 : pm->ops[i]->ID) << endl; out << "posk = " << posk << " ID = " << ((k == INVALID) ? -1 : pm->ops[k]->ID) << endl; for (int l = 0; l < topolOrdering.size(); l++) { out << pm->ops[topolOrdering[l]]->ID << " "; } out << endl; //getchar(); */ // ######################################################################### if (posi == posk) { out << "posi = " << posi << " ID = " << ((i == INVALID) ? -1 : this->ops[i]->ID) << endl; out << "posk = " << posk << " ID = " << ((k == INVALID) ? -1 : this->ops[k]->ID) << endl; for (int l = 0; l < topolOrdering.size(); l++) { out << this->ops[topolOrdering[l]]->ID << " "; } out << endl; Debugger::err << "ProcessModel::dynUpdateTopolSort : posi == posk which is impossible!!!" << ENDL; } // Find the affected region int arbegin = -1; int arend = -1; ListDigraph::Node arstartnode = INVALID; ListDigraph::Node arendnode = INVALID; if (posi > posk) { arbegin = posk; arend = posi; arstartnode = k; arendnode = i; } // ##################### DEBUG ########################################### /* out << "arbegin = " << arbegin << endl; out << "arend = " << arend << endl; out << "arstartnode = " << pm->ops[arstartnode]->ID << endl; out << "arendnode = " << pm->ops[arendnode]->ID << endl; */ // ######################################################################### // Update the affected region // The nodes of the affected region QList<ListDigraph::Node> ar = topolOrdering.mid(arbegin, arend - arbegin + 1); QList<bool> visited; visited.reserve(ar.size()); QQueue<ListDigraph::Node> q; ListDigraph::Node curnode; ListDigraph::Node tmpnode; int tmpidx; //QList<int> deltaBIdx; // ##################### DEBUG ########################################### /* out << "ar:" << endl; for (int l = 0; l < ar.size(); l++) { out << pm->ops[ar[l]]->ID << " "; } out << endl; */ // ######################################################################### // Find nodes which are contained in ar and are reachable from arstartnode //out << "Finding deltaF..." << endl; QList<ListDigraph::Node> deltaF; deltaF.reserve(ar.size()); for (int l = 0; l < ar.size(); l++) { visited.append(false); } q.clear(); q.enqueue(arstartnode); deltaF.append(arstartnode); while (q.size() != 0) { curnode = q.dequeue(); // Check the successors of the current node for (ListDigraph::OutArcIt oait(this->graph, curnode); oait != INVALID; ++oait) { tmpnode = this->graph.target(oait); tmpidx = ar.indexOf(tmpnode); if (tmpidx >= 0 && !visited[tmpidx]) { // This successor is within the affected region q.enqueue(tmpnode); visited[tmpidx] = true; // Add the node to the deltaF deltaF.append(tmpnode); } } } //out << "Found deltaF." << endl; //###################### DEBUG ########################################### /* out << "deltaF:" << endl; for (int l = 0; l < deltaF.size(); l++) { out << pm->ops[deltaF[l]]->ID << " "; } out << endl; */ //########################################################################## // IMPORTANT!!! Actually deltaB is not needed! If we find deltaF and move it to the end of the affected region then the elements // of deltaB preserve their initial positions and are placed directly before the elements of deltaF. Thus, the backward arc becomes a forward one /* // Find the nodes which are in ar and are BACKWARD reachable from arendnode QList<ListDigraph::Node> deltaB; deltaB.reserve(ar.size()); for (int l = 0; l < visited.size(); l++) { visited[l] = false; } q.clear(); q.enqueue(arendnode); deltaB.prepend(arendnode); deltaBIdx.prepend(ar.size() - 1); visited.clear(); for (int l = 0; l < ar.size(); l++) { visited.append(false); } while (q.size() != 0) { curnode = q.dequeue(); // Check the predecessors of the current node for (ListDigraph::InArcIt iait(pm->graph, curnode); iait != INVALID; ++iait) { tmpnode = pm->graph.source(iait); tmpidx = ar.indexOf(tmpnode); if (tmpidx >= 0 && !visited[tmpidx]) { // This successor is within the affected region q.enqueue(tmpnode); visited[tmpidx] = true; // Add the node to the deltaF deltaB.prepend(tmpnode); // IMPORTANT!!! PREpend! deltaBIdx.prepend(tmpidx); } } } */ // Move elements of deltaB to the left and the elements of deltaF to the right until the backward ark does not disappear //int posB = 0; //out << "Shifting deltaF to the right..." << endl; int posF = ar.size() - 1; // Move elements in deltaF to the right while (!deltaF.isEmpty()) { // Find the first element in ar starting from posB that is in deltaB tmpidx = -1; for (int l = posF; l >= 0; l--) { if (deltaF.contains(ar[l])) { tmpidx = l; break; } } if (tmpidx == -1) { Debugger::err << "ProcessModel::dynUpdateTopolSort : tmpidx = -1 while shifting deltaF. Probably the graph is NOT DAG! " << ENDL; } // Erase this element from deltaF deltaF.removeOne(ar[tmpidx]); // Move this element to the left ar.move(tmpidx, posF); posF--; } //out << "Shifted deltaF to the right." << endl; // Moving elements of deltaB is not necessary, since they are automatically found before any element of deltaF, since these were moved to the right /* // Move elements in deltaB to the left so that the last element of deltaB is on the position posF (right before elements of deltaF) while (!deltaB.isEmpty()) { // Find the first element in ar starting from posB that is in deltaB tmpidx = -1; for (int l = posB; l < ar.size(); l++) { if (deltaB.contains(ar[l])) { tmpidx = l; break; } } // Erase this element from deltaB deltaB.removeOne(ar[tmpidx]); // Move this element to the left ar.move(tmpidx, posB); posB++; } */ // Modify the final topological ordering for (int l = 0; l < ar.size(); l++) { topolOrdering[arbegin + l] = ar[l]; } //###################### DEBUG ########################################### /* out << "After DTO:" << endl; out << "posj = " << posj << " ID = " << ((j == INVALID) ? -1 : pm->ops[j]->ID) << endl; out << "posi = " << posi << " ID = " << ((i == INVALID) ? -1 : pm->ops[i]->ID) << endl; out << "posk = " << posk << " ID = " << ((k == INVALID) ? -1 : pm->ops[k]->ID) << endl; out << "ar later:" << endl; for (int l = 0; l < ar.size(); l++) { out << pm->ops[ar[l]]->ID << " "; } out << endl; //out << "deltaB:" << endl; //for (int l = 0; l < deltaB.size(); l++) { //out << pm->ops[deltaB[l]]->ID << " "; //} //out << endl; out << "deltaF:" << endl; for (int l = 0; l < deltaF.size(); l++) { out << pm->ops[deltaF[l]]->ID << " "; } out << endl; for (int l = 0; l < topolOrdering.size(); l++) { out << pm->ops[topolOrdering[l]]->ID << " "; } out << endl; */ // Check the correctness of the topological sorting /* QList<ListDigraph::Node> list; for (int i = 0; i < topolOrdering.size() - 1; i++) { for (int j = i + 1; j < topolOrdering.size(); j++) { list.clear(); list.append(topolOrdering[j]); if (reachableFrom(list).contains(topolOrdering[i])) { out << *this << endl; out << this->ops[topolOrdering[j]]->ID << " -> " << this->ops[topolOrdering[i]]->ID << endl; Debugger::err << "Topological sorting is not correct after DTO!!!" << ENDL; } } } */ //getchar(); //########################################################################## }
sta::StateVector ScenarioReEntryTrajectory::propagate(PropagationFeedback& propFeedback, const sta::StateVector& initialState, QList<double>& sampleTimes, QList<sta::StateVector>& samples) { ScenarioSpaceVehicle* spacevehicle = dynamic_cast<ScenarioSpaceVehicle*>(this->parent()->parent()); ScenarioProperties* vehicleproperties= spacevehicle->properties(); EntrySettings inputSettings = createEntrySettings(this, vehicleproperties); EntryTrajectory trajectory(inputSettings); //Removing atmosphericDrag from the list of perturbations, as it is considered as a major force. QList<Perturbations*> perturbationsList = environment()->createListPerturbations(vehicleproperties); foreach (Perturbations* perturbation, perturbationsList) { if (dynamic_cast<AtmosphericDragPerturbations*>(perturbation)) perturbationsList.removeOne(perturbation); } if (simulationMode()->isActive()) { const double startTime = simulationMode()->simulationParameters()->timeline()->startTime(); double time_jd = sta::MjdToJd(startTime); double dt = trajectoryPropagation()->timeStep(); double time_s = sta::daysToSecs(startTime); EntryParameters parameters = createEntryParametersSimulation(this, vehicleproperties); //Message errors on input parameters : if (dt == 0.0) { propFeedback.raiseError(QObject::tr("Time step is zero!")); return initialState; } if (parameters.m == 0.0) { propFeedback.raiseError(QObject::tr("Vehicle mass is zero!")); return initialState; } if (parameters.R == 0.0) { propFeedback.raiseError(QObject::tr("Vehicle base radius is zero!")); return initialState; } if (inputSettings.maxheatrate == 0) { propFeedback.raiseError(QObject::tr("The maximum heat rate is zero!")); return initialState; } if (inputSettings.maxloadfactor == 0) { propFeedback.raiseError(QObject::tr("The maximum load factor is zero!")); return initialState; } if (trajectory.capsule.flag == 1) { propFeedback.raiseError(QObject::tr("Cd coefficient file name is not valid!")); return initialState; } if (trajectory.capsule.flag == 2) { propFeedback.raiseError(QObject::tr("Cd parachute coefficient file name is not valid!")); return initialState; } sta::StateVector stateVector; stateVector = trajectory.initialise(parameters, initialState, time_jd); _status status = OK; while (status == OK) { stateVector = trajectory.integrate(stateVector, perturbationsList); status = trajectory.status; time_jd += sta::secsToDays(dt); double theta = getGreenwichHourAngle(time_jd); time_s += dt; JulianDate jd = sta::secsToDays(time_s); sampleTimes << jd; double posx, posy, posz, velx, vely, velz; int celestialbody; if (inputSettings.bodyname == "Earth") celestialbody = 0; else if (inputSettings.bodyname == "Mars") celestialbody = 3; fixedTOinertial(celestialbody, theta , stateVector.position.x(), stateVector.position.y(), stateVector.position.z(), stateVector.velocity.x(), stateVector.velocity.y(), stateVector.velocity.z(), posx, posy, posz, velx, vely, velz); Eigen::Vector3d pos = Vector3d(posx/1000, posy/1000, posz/1000); Eigen::Vector3d vel = Vector3d(velx/1000, vely/1000, velz/1000); sta::StateVector statevector = sta::StateVector(pos, vel); samples << statevector; } //trajectory.printReport(); return stateVector; } // else if (windowMode()->isActive()) // { // qDebug() << "I'm propagating the window mode"; // EntryParameterIntervals parameterIntervals = reentryValues.createEntryParameterIntervals(this); // EntryParameters parameters = reentryValues.createEntryParametersWindow(this, parameterIntervals); // const ScenarioTimeline* timeline = windowMode()->simulationParameters()->timeline(); // double startTime = sta::daysToSecs(timeline->startTime()); // trajectory.initialise(parameters, startTime); // // int InputNsimulations, Npoints, Nsimulations; // double cd = 1.5; // bool failed_target = false; // // InputNsimulations = windowMode()->numSimulations();//800 // Npoints = int ( round (pow(InputNsimulations,0.5)) ); // Nsimulations = Npoints * Npoints; // angle TargetLatitude = reentryValues.createTargetAngleLatitudeWindow(this); // angle TargetLongitude = reentryValues.createTargetAngleLongitudeWindow(this); // // Endstate endresult = trajectory.getEndstate(); // // qDebug() << endresult.status; // // if (endresult.status == landed) { // double difflong, difflat; // do { // //Initialise the entry trajectory // trajectory.initialise(parameters, startTime); // // // //Get the landing location // Endstate endresult = trajectory.getEndstate(); // if (endresult.status != landed) { // cout << "Target not reached with middle point trajectory, entering at (0, 0)" << endl; // parameters.inputstate[1] = 0.0; // parameters.inputstate[2] = 0.0; // failed_target = true; // qDebug() << failed_target; // break; // } // //Update the entry location // difflong = endresult.longitude - windowMode()->simulationParameters()->finalState()->targetLon(); // difflat = endresult.latitude - windowMode()->simulationParameters()->finalState()->targetLat();; // parameters.inputstate[1] -= difflong; // parameters.inputstate[2] -= difflat; // // } while (abs(difflong) > 0.0001 || abs(difflat) > 0.0001); // if (!failed_target) { // qDebug() << "Target reached with middle point trajectory, entering at (" << parameters.inputstate[1] << "," << parameters.inputstate[2] << ")"; // } // } // else { // qDebug() << "Target not reached with middle point trajectory, entering at (0, 0)"; // parameters.inputstate[1] = 0.0; // parameters.inputstate[2] = 0.0; // } // //Open the output file // //-------------------- // ofstream window_output ("C:/Users/Tizy/Desktop/Code/trunk/sta-src/Entry/REMWindowOutput.stap"); // //-------------------- // qDebug() << "window1"; // //Create the matrices to store the results // //---------------------------------------- // double * xArray = new double [Npoints]; // double * yArray = new double [Npoints]; // TNT::Array2D< double > MaxCqdotMatrix(Npoints, Npoints); // TNT::Array2D< double > MaxCqdotAltMatrix(Npoints, Npoints); // TNT::Array2D< double > MaxCqdotTimeMatrix(Npoints, Npoints); // TNT::Array2D< double > MaxRqdotMatrix(Npoints, Npoints); // TNT::Array2D< double > MaxRqdotAltMatrix(Npoints, Npoints); // TNT::Array2D< double > MaxRqdotTimeMatrix(Npoints, Npoints); // TNT::Array2D< double > MaxTqdotMatrix(Npoints, Npoints); // TNT::Array2D< double > MaxTqdotAltMatrix(Npoints, Npoints); // TNT::Array2D< double > MaxTqdotTimeMatrix(Npoints, Npoints); // TNT::Array2D< double > MaxGMatrix(Npoints, Npoints) ; // TNT::Array2D< double > MaxGAltMatrix(Npoints, Npoints); // TNT::Array2D< double > MaxGTimeMatrix(Npoints, Npoints); // TNT::Array2D< double > Mach1AltMatrix(Npoints, Npoints); // TNT::Array2D< double > Mach1TimeMatrix(Npoints, Npoints); // TNT::Array2D< double > DeployAltMatrix(Npoints, Npoints); // TNT::Array2D< double > DeployTimeMatrix(Npoints, Npoints); // TNT::Array2D< double > TotalQMatrix(Npoints, Npoints); // TNT::Array2D< double > TPSMassMatrix(Npoints, Npoints); // TNT::Array2D< double > TofMatrix(Npoints, Npoints); // TNT::Array2D< double > ImpactVMatrix(Npoints, Npoints); // TNT::Array2D< double > StatusMatrix(Npoints, Npoints); // //---------------------------------------- // // //Create the parameter arrays and fill them // //----------------------------------------- // double * KArray = new double[Nsimulations]; // double * RnArray = new double[Nsimulations]; // double * VArray = new double[Nsimulations]; // double * gammaArray = new double[Nsimulations]; // double * chiArray = new double[Nsimulations]; // int xparameter = 2;//windowMode()->window()->xAxisVariable()->returnType(); // int yparameter = 4;//windowMode()->window()->yAxisVariable()->returnType(); // //------ // switch (xparameter) { // case 1: for (int i = 0; i < Npoints; i++) { xArray[i] = parameterIntervals.K.low + ( i * (parameterIntervals.K.high-parameterIntervals.K.low) / (Npoints-1) );} break; // case 2: for (int i = 0; i < Npoints; i++) { xArray[i] = parameterIntervals.Rn.low + ( i * (parameterIntervals.Rn.high-parameterIntervals.Rn.low) / (Npoints-1) );}; break; // case 3: for (int i = 0; i < Npoints; i++) { xArray[i] = parameterIntervals.velocity.low + ( i * (parameterIntervals.velocity.high-parameterIntervals.velocity.low) / (Npoints-1) );}; break; // case 4: for (int i = 0; i < Npoints; i++) { xArray[i] = parameterIntervals.gamma.low + ( i * (parameterIntervals.gamma.high-parameterIntervals.gamma.low) / (Npoints-1) );}; break; // case 5: for (int i = 0; i < Npoints; i++) { xArray[i] = parameterIntervals.chi.low + ( i * (parameterIntervals.chi.high-parameterIntervals.chi.low) / (Npoints-1) );}; break; // } // switch (yparameter) { // case 1: for (int i = 0; i < Npoints; i++) { yArray[i] = parameterIntervals.K.high - ( i * (parameterIntervals.K.high-parameterIntervals.K.low) / (Npoints-1) );}; break; // case 2: for (int i = 0; i < Npoints; i++) { yArray[i] = parameterIntervals.Rn.high - ( i * (parameterIntervals.Rn.high-parameterIntervals.Rn.low) / (Npoints-1) );}; break; // case 3: for (int i = 0; i < Npoints; i++) { yArray[i] = parameterIntervals.velocity.high - ( i * (parameterIntervals.velocity.high-parameterIntervals.velocity.low) / (Npoints-1) );}; break; // case 4: for (int i = 0; i < Npoints; i++) { yArray[i] = parameterIntervals.gamma.high - ( i * (parameterIntervals.gamma.high-parameterIntervals.gamma.low) / (Npoints-1) );}; break; // case 5: for (int i = 0; i < Npoints; i++) { yArray[i] = parameterIntervals.chi.high - ( i * (parameterIntervals.chi.high-parameterIntervals.chi.low) / (Npoints-1) );}; break; // } // qDebug() << "window2"; // //------ // if (xparameter == 1) { for (int i = 0; i < Npoints; i++){ for (int j = 0; j < Npoints; j++) KArray[i*Npoints + j] = xArray[i];}} // else if (yparameter == 1) { for (int i = 0; i < Npoints; i++){ for (int j = 0; j < Npoints; j++) KArray[i*Npoints + j] = yArray[j];}} // else for (int i = 0; i < Nsimulations; i++) KArray[i] = parameterIntervals.K.low; // //------ // if (xparameter == 2) { for (int i = 0; i < Npoints; i++){ for (int j = 0; j < Npoints; j++) RnArray[i*Npoints + j] = xArray[i];}} // else if (yparameter == 2) { for (int i = 0; i < Npoints; i++){ for (int j = 0; j < Npoints; j++) RnArray[i*Npoints + j] = yArray[j];}} // else for (int i = 0; i < Nsimulations; i++) RnArray[i] = parameterIntervals.Rn.low; // //------ // if (xparameter == 3) { for (int i = 0; i < Npoints; i++){ for (int j = 0; j < Npoints; j++) VArray[i*Npoints + j] = xArray[i];}} // else if (yparameter == 3) { for (int i = 0; i < Npoints; i++){ for (int j = 0; j < Npoints; j++) VArray[i*Npoints + j] = yArray[j];}} // else for (int i = 0; i < Nsimulations; i++) VArray[i] = parameterIntervals.velocity.low; // //------ // if (xparameter == 4) { for (int i = 0; i < Npoints; i++){ for (int j = 0; j < Npoints; j++) gammaArray[i*Npoints + j] = xArray[i];}} // else if (yparameter == 4) { for (int i = 0; i < Npoints; i++){ for (int j = 0; j < Npoints; j++) gammaArray[i*Npoints + j] = yArray[j];}} // else for (int i = 0; i < Nsimulations; i++) gammaArray[i] = parameterIntervals.gamma.low; // //------ // if (xparameter == 5) { for (int i = 0; i < Npoints; i++){ for (int j = 0; j < Npoints; j++) chiArray[i*Npoints + j] = xArray[i];}} // else if (yparameter == 5) { for (int i = 0; i < Npoints; i++){ for (int j = 0; j < Npoints; j++) chiArray[i*Npoints + j] = yArray[j];}} // else for (int i = 0; i < Nsimulations; i++) chiArray[i] = parameterIntervals.chi.low; // //------------------------------------------------------------------------- //qDebug() << "window3"; // // //Main loop // //===================== // qDebug() << "Number of steps: " << Npoints; // for (int xstep = 0; xstep < Npoints; xstep++) { // // for (int ystep = 0; ystep < Npoints; ystep++) { // // //Make the parameter structure // //---------------------------- // parameters.m = 100.0; // double localK = KArray[xstep * Npoints + ystep]; // parameters.R = sqrt( parameters.m/ (localK * acos(-1) * cd) ); // parameters.Rn = RnArray [xstep * Npoints + ystep]; // parameters.inputstate[3] = VArray [xstep * Npoints + ystep]; // parameters.inputstate[4] = gammaArray [xstep * Npoints + ystep]; // parameters.inputstate[5] = chiArray [xstep * Npoints + ystep]; // //---------------------------- // // //Initialise the entry trajectory // //----------------------------------------- // trajectory.initialise(parameters, startTime); // //----------------------------------------- // // //Get the endstate of the trajectory // //---------------------------------- // Endstate endresult = trajectory.getEndstate(); // //---------------------------------- // // //Fill the output matrices // //------------------------ // MaxCqdotMatrix[xstep][ystep] = endresult.maxconvheatrate.value * (1 - endresult.status); // MaxCqdotAltMatrix[xstep][ystep] = endresult.maxconvheatrate.altitude * (1 - endresult.status); // MaxCqdotTimeMatrix[xstep][ystep] = endresult.maxconvheatrate.time * (1 - endresult.status); // MaxRqdotMatrix[xstep][ystep] = endresult.maxradheatrate.value * (1 - endresult.status); // MaxRqdotAltMatrix[xstep][ystep] = endresult.maxradheatrate.altitude * (1 - endresult.status); // MaxRqdotTimeMatrix[xstep][ystep] = endresult.maxradheatrate.time * (1 - endresult.status); // MaxTqdotMatrix[xstep][ystep] = endresult.maxtotalheatrate.value * (1 - endresult.status); // MaxTqdotAltMatrix[xstep][ystep] = endresult.maxtotalheatrate.altitude * (1 - endresult.status); // MaxTqdotTimeMatrix[xstep][ystep] = endresult.maxtotalheatrate.time * (1 - endresult.status); // MaxGMatrix[xstep][ystep] = endresult.maxloadfactor.value * (1 - endresult.status); // MaxGAltMatrix[xstep][ystep] = endresult.maxloadfactor.value * (1 - endresult.status); // MaxGTimeMatrix[xstep][ystep] = endresult.maxloadfactor.value * (1 - endresult.status); // Mach1AltMatrix[xstep][ystep] = endresult.Machone_transition_altitude * (1 - endresult.status); // Mach1TimeMatrix[xstep][ystep] = endresult.Machone_transition_time * (1 - endresult.status); // DeployAltMatrix[xstep][ystep] = endresult.parachutedeploy_altitude * (1 - endresult.status); // DeployTimeMatrix[xstep][ystep] = endresult.parachutedeploy_time * (1 - endresult.status); // TotalQMatrix[xstep][ystep] = endresult.totalheatload * (1 - endresult.status); // TPSMassMatrix[xstep][ystep] = endresult.tpsmass * (1 - endresult.status); // TofMatrix[xstep][ystep] = endresult.timeofflight * (1 - endresult.status); // ImpactVMatrix[xstep][ystep] = endresult.impactvelocity * (1 - endresult.status); // StatusMatrix[xstep][ystep] = endresult.status; // //----------------- // } //qDebug() << "window4"; // //Give feedback about progress // //---------------------------- // qDebug() << xstep+1; // //---------------------------- // } // //===================== // // // //Write the output file // //--------------------- // for (int i=0; i<Npoints; i++) { // window_output << xArray[i] << " "; // } // window_output << "\n"; // //------ // for (int i=0; i<Npoints; i++) { // window_output << yArray[i] << " "; // } // window_output << "\n"; // //----------------------------------------------------- // for (int j=0; j<Npoints; j++) {for (int i=0; i<Npoints; i++) {window_output << MaxCqdotMatrix[i][j] << " ";} window_output << "\n";} // for (int j=0; j<Npoints; j++) {for (int i=0; i<Npoints; i++) {window_output << MaxCqdotAltMatrix[i][j] << " ";} window_output << "\n";} // for (int j=0; j<Npoints; j++) {for (int i=0; i<Npoints; i++) {window_output << MaxCqdotTimeMatrix[i][j] << " ";} window_output << "\n";} // for (int j=0; j<Npoints; j++) {for (int i=0; i<Npoints; i++) {window_output << MaxRqdotMatrix[i][j] << " ";} window_output << "\n";} // for (int j=0; j<Npoints; j++) {for (int i=0; i<Npoints; i++) {window_output << MaxRqdotAltMatrix[i][j] << " ";} window_output << "\n";} // for (int j=0; j<Npoints; j++) {for (int i=0; i<Npoints; i++) {window_output << MaxRqdotTimeMatrix[i][j] << " ";} window_output << "\n";} // for (int j=0; j<Npoints; j++) {for (int i=0; i<Npoints; i++) {window_output << MaxTqdotMatrix[i][j] << " ";} window_output << "\n";} // for (int j=0; j<Npoints; j++) {for (int i=0; i<Npoints; i++) {window_output << MaxTqdotAltMatrix[i][j] << " ";} window_output << "\n";} // for (int j=0; j<Npoints; j++) {for (int i=0; i<Npoints; i++) {window_output << MaxTqdotTimeMatrix[i][j] << " ";} window_output << "\n";} // for (int j=0; j<Npoints; j++) {for (int i=0; i<Npoints; i++) {window_output << MaxGMatrix[i][j] << " ";} window_output << "\n";} // for (int j=0; j<Npoints; j++) {for (int i=0; i<Npoints; i++) {window_output << MaxGAltMatrix[i][j] << " ";} window_output << "\n";} // for (int j=0; j<Npoints; j++) {for (int i=0; i<Npoints; i++) {window_output << MaxGTimeMatrix[i][j] << " ";} window_output << "\n";} // for (int j=0; j<Npoints; j++) {for (int i=0; i<Npoints; i++) {window_output << Mach1AltMatrix[i][j] << " ";} window_output << "\n";} // for (int j=0; j<Npoints; j++) {for (int i=0; i<Npoints; i++) {window_output << Mach1TimeMatrix[i][j] << " ";} window_output << "\n";} // for (int j=0; j<Npoints; j++) {for (int i=0; i<Npoints; i++) {window_output << DeployAltMatrix[i][j] << " ";} window_output << "\n";} // for (int j=0; j<Npoints; j++) {for (int i=0; i<Npoints; i++) {window_output << DeployTimeMatrix[i][j] << " ";} window_output << "\n";} // for (int j=0; j<Npoints; j++) {for (int i=0; i<Npoints; i++) {window_output << TotalQMatrix[i][j] << " ";} window_output << "\n";} // for (int j=0; j<Npoints; j++) {for (int i=0; i<Npoints; i++) {window_output << TPSMassMatrix[i][j] << " ";} window_output << "\n";} // for (int j=0; j<Npoints; j++) {for (int i=0; i<Npoints; i++) {window_output << TofMatrix[i][j] << " ";} window_output << "\n";} // for (int j=0; j<Npoints; j++) {for (int i=0; i<Npoints; i++) {window_output << ImpactVMatrix[i][j] << " ";} window_output << "\n";} // for (int j=0; j<Npoints; j++) {for (int i=0; i<Npoints; i++) {window_output << StatusMatrix[i][j] << " ";} window_output << "\n";} // qDebug() << "window5";//----------------------------------------------------- // window_output.close(); // //---------------------- // } // // //Dispersion analysis mode ++++++++++++++++++++++++++++ // if (simulationMode()->dispersionAnalysis()->isActive()) // { // //Set the seed of the random number generator // srand ( time(NULL) ); // // Uncertainties_struct inputuncertainties = reentryValues.createUncertainties_struct(this); // EntryParameters parameters; // //ifstream dispersion_input ("REMDispersionInput.stap"); // int Nsimulations; // double inputstate_temp[6]; // double mass_temp; // Nsimulations = simulationMode()->dispersionAnalysis()->numSimulations(); // parameters.R = vehicle()->mainBodyCharacteristics()->radiusBase(); // mass_temp = vehicle()->mainBodyCharacteristics()->mass(); // parameters.Rn = vehicle()->mainBodyCharacteristics()->radiusNose(); // // const ScenarioTimeline* timeline = simulationMode()->simulationParameters()->timeline(); // double startTime = sta::daysToSecs(timeline->startTime()); // // QString coordinatesystem = simulationMode()->simulationParameters()->initialStatePosition()->initialState()->elementName(); // // if (coordinatesystem=="SphericalCoordinates") // { // parameters.coordselector = 1; // ScenarioSphericalCoordinates* sphericalCoord = dynamic_cast<ScenarioSphericalCoordinates*>(simulationMode()->simulationParameters()->initialStatePosition()->initialState()); // inputstate_temp[1] = sphericalCoord->altitude(); // inputstate_temp[2] = sphericalCoord->longitude(); // inputstate_temp[3] = sphericalCoord->latitude(); // inputstate_temp[4] = sphericalCoord->inertialVelocity(); // inputstate_temp[5] = sphericalCoord->inertialFlightPathAngle(); // inputstate_temp[6] = sphericalCoord->inertialHeading(); // // } // else if (coordinatesystem=="KeplerianElements") // { // parameters.coordselector = 2; // ScenarioKeplerianElements* elements = dynamic_cast<ScenarioKeplerianElements*>(simulationMode()->simulationParameters()->initialStatePosition()->initialState()); // inputstate_temp[1] = elements->semimajorAxis(); // inputstate_temp[2] = elements->eccentricity(); // inputstate_temp[3] = elements->inclination(); // inputstate_temp[4] = elements->raan(); // inputstate_temp[5] = elements->argumentOfPeriapsis(); // inputstate_temp[6] = elements->trueAnomaly(); // } // else qFatal("Error in the initial state position coordinate systems"); // // angle TargetLongitude, TargetLatitude; // AngleConversion angleconversion; // double latitudeDecimal = simulationMode()->dispersionAnalysis()->deviations()->entryLat(); // double longitudeDecimal = simulationMode()->dispersionAnalysis()->deviations()->entryLong(); // angleconversion.decimalToDegMinSec(latitudeDecimal, TargetLatitude.degrees, TargetLatitude.minutes, TargetLatitude.seconds); // angleconversion.decimalToDegMinSec(longitudeDecimal, TargetLongitude.degrees, TargetLongitude.minutes, TargetLongitude.seconds); // // // //------------------------------------------- // // //Open the output file // //-------------------- // ofstream dispersion_output ("REMDispersionOutput.stap"); // dispersion_output << longitudeDecimal << "\t" << latitudeDecimal << "\t" << 0 << "\t" << 0 << endl; // //-------------------- // // //Creat the dynamic arrays // //------------------------ // double * dispersion_longitudes = new double [Nsimulations]; // double * dispersion_latitudes = new double [Nsimulations]; // double * dispersion_crosstracks = new double [Nsimulations]; // double * dispersion_alongtracks = new double [Nsimulations]; // double maxalongtrack = 0.0, maxcrosstrack = 0.0; // //------------------------ // // //Main loop // //======================== // for (int i=0; i<Nsimulations; i++) { // // //Create the uncertainties based on the variances // //------------------------------------------- // parameters.uncertainties.mass = (2 * ((double)rand() / (double)RAND_MAX) * inputuncertainties.mass) - inputuncertainties.mass; // parameters.uncertainties.altitude = (2 * ((double)rand() / (double)RAND_MAX) * inputuncertainties.altitude) - inputuncertainties.altitude; // parameters.uncertainties.tau = (2 * ((double)rand() / (double)RAND_MAX) * inputuncertainties.tau) - inputuncertainties.tau; // parameters.uncertainties.delta = (2 * ((double)rand() / (double)RAND_MAX) * inputuncertainties.delta) - inputuncertainties.delta; // parameters.uncertainties.velocity = (2 * ((double)rand() / (double)RAND_MAX) * inputuncertainties.velocity) - inputuncertainties.velocity; // parameters.uncertainties.gamma = (2 * ((double)rand() / (double)RAND_MAX) * inputuncertainties.gamma) - inputuncertainties.gamma; // parameters.uncertainties.chi = (2 * ((double)rand() / (double)RAND_MAX) * inputuncertainties.chi) - inputuncertainties.chi; // parameters.uncertainties.density = (2 * ((double)rand() / (double)RAND_MAX) * inputuncertainties.density) - inputuncertainties.density; // parameters.uncertainties.temperature = (2 * ((double)rand() / (double)RAND_MAX) * inputuncertainties.temperature) - inputuncertainties.temperature; // parameters.uncertainties.pressure = (2 * ((double)rand() / (double)RAND_MAX) * inputuncertainties.pressure) - inputuncertainties.pressure; // parameters.uncertainties.speedofsound = (2 * ((double)rand() / (double)RAND_MAX) * inputuncertainties.speedofsound) - inputuncertainties.speedofsound; // parameters.uncertainties.cdcapsule = (2 * ((double)rand() / (double)RAND_MAX) * inputuncertainties.cdcapsule) - inputuncertainties.cdcapsule; // parameters.uncertainties.cdparachute = (2 * ((double)rand() / (double)RAND_MAX) * inputuncertainties.cdparachute) - inputuncertainties.cdparachute; // //------------------------------------------- // // //Construct the parameter structure // //------------------------------------------- // parameters.m = mass_temp + parameters.uncertainties.mass; // parameters.inputstate[0] = inputstate_temp[0] + parameters.uncertainties.altitude; // parameters.inputstate[1] = inputstate_temp[1] + parameters.uncertainties.tau; // parameters.inputstate[2] = inputstate_temp[2] + parameters.uncertainties.delta; // parameters.inputstate[3] = inputstate_temp[3] + parameters.uncertainties.velocity; // parameters.inputstate[4] = inputstate_temp[4] + parameters.uncertainties.gamma; // parameters.inputstate[5] = inputstate_temp[5] + parameters.uncertainties.chi; // //------------------------------------------- // // //Initialise the entry trajectory // //----------------------------------------- // trajectory.initialise(parameters, startTime); // //----------------------------------------- // // //Get the endstate of the trajectory // //---------------------------------- // Endstate endresult = trajectory.getEndstate(); // //---------------------------------- // // //Write the output file // //---------------------------------- // dispersion_longitudes[i] = endresult.longitude; // dispersion_latitudes[i] = endresult.latitude; // AngleConversion angleconversion; // dispersion_alongtracks[i] = (dispersion_longitudes[i]-angleconversion.DegMinSecToDecimal(TargetLongitude.degrees, TargetLongitude.minutes, TargetLongitude.seconds))*cos((inputstate_temp[5]-90.0)) - (dispersion_latitudes[i]-angleconversion.DegMinSecToDecimal(TargetLatitude.degrees, TargetLatitude.minutes, TargetLatitude.seconds))*sin((inputstate_temp[5]-90.0)) ;//- angle2double(TargetLongitude); // dispersion_crosstracks[i] = (dispersion_longitudes[i]-angleconversion.DegMinSecToDecimal(TargetLongitude.degrees, TargetLongitude.minutes, TargetLongitude.seconds))*sin((inputstate_temp[5]-90.0)) + (dispersion_latitudes[i]-angleconversion.DegMinSecToDecimal(TargetLatitude.degrees, TargetLatitude.minutes, TargetLatitude.seconds))*cos((inputstate_temp[5]-90.0)) ;//- angle2double(TargetLatitude); // dispersion_output << dispersion_longitudes[i] << "\t" << dispersion_latitudes[i] << "\t" << dispersion_alongtracks[i] << "\t" << dispersion_crosstracks[i] << endl; // if (dispersion_alongtracks[i] > maxalongtrack) maxalongtrack = dispersion_alongtracks[i]; // if (dispersion_crosstracks[i] > maxcrosstrack) maxcrosstrack = dispersion_crosstracks[i]; // //---------------------------------- // // //Give feedback about progress // //---------------------------- // cout << i << endl; // //---------------------------- // } // //======================== // dispersion_output.close(); // // //Write out a report // //------------------ // ofstream dispersion_report ("REMDispersionReport.stap"); // dispersion_report << "Dispersion analysis: report" << endl; // dispersion_report << "===========================" << endl << " " << endl; // dispersion_report << "Nominal mission parameters" << endl; // dispersion_report << "--------------------------" << endl; // dispersion_report << "Capsule radius:\t\t " << parameters.R << " m" << endl; // dispersion_report << "Capsule mass:\t\t " << mass_temp << " kg" << endl; // dispersion_report << "Capsule nose radius:\t " << parameters.Rn << " m" << endl; // dispersion_report << "Entry altitude:\t\t " << inputstate_temp[0] << " m" << endl; // dispersion_report << "Entry longitude:\t " << inputstate_temp[1] << " °" << endl; // dispersion_report << "Entry latitude:\t\t " << inputstate_temp[2] << " °" << endl; // dispersion_report << "Entry velocity:\t\t " << inputstate_temp[3] << " m/s" << endl; // dispersion_report << "Entry flight path angle: " << inputstate_temp[4] << " °" << endl; // dispersion_report << "Entry heading:\t\t " << inputstate_temp[5] << " °" << endl; // dispersion_report << "--------------------------" << endl << " " << endl; // dispersion_report << "Variances of uncertainties" << endl; // dispersion_report << "--------------------------" << endl; // dispersion_report << "Capsule mass:\t " << "+-" << inputuncertainties.mass << " kg" << endl; // dispersion_report << "Capsule Cd profile:\t " << "+-" << inputuncertainties.cdcapsule*100 << "%" << endl; // dispersion_report << "Parachute Cd profile:\t " << "+-" << inputuncertainties.cdparachute*100 << "%" << endl; // dispersion_report << "Entry altitude:\t " << "+-" << inputuncertainties.altitude << " m" << endl; // dispersion_report << "Entry longitude:\t " << "+-" << inputuncertainties.tau << " deg" << endl; // dispersion_report << "Entry latitude:\t " << "+-" << inputuncertainties.delta << " deg" << endl; // dispersion_report << "Entry velocity:\t\t " << "+-" << inputuncertainties.velocity << " m/s" << endl; // dispersion_report << "Entry flight path angle:\t " << "+-" << inputuncertainties.gamma << " deg" << endl; // dispersion_report << "Entry heading:\t " << "+-" << inputuncertainties.chi << " deg" << endl; // dispersion_report << "--------------------------" << endl << " " << endl; // dispersion_report << "Dispersion results" << endl; // dispersion_report << "--------------------------" << endl; // dispersion_report << "Maximum along track dispersion: " << maxalongtrack*111111.11 << "m" << endl; // dispersion_report << "Maximum cross track dispersion: " << maxcrosstrack*111111.11 << "m" << endl; // dispersion_report << "--------------------------" << endl; // //------------------ // } // //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //return 0; }
IAnalyzerEngine *QmlProfilerTool::createEngine(const AnalyzerStartParameters &sp, RunConfiguration *runConfiguration) { QmlProfilerEngine *engine = new QmlProfilerEngine(this, sp, runConfiguration); engine->registerProfilerStateManager(d->m_profilerState); bool isTcpConnection = true; if (runConfiguration) { // Check minimum Qt Version. We cannot really be sure what the Qt version // at runtime is, but guess that the active build configuraiton has been used. QtSupport::QtVersionNumber minimumVersion(4, 7, 4); if (Qt4ProjectManager::Qt4BuildConfiguration *qt4Config = qobject_cast<Qt4ProjectManager::Qt4BuildConfiguration*>( runConfiguration->target()->activeBuildConfiguration())) { if (qt4Config->qtVersion()->isValid() && qt4Config->qtVersion()->qtVersion() < minimumVersion) { int result = QMessageBox::warning(QApplication::activeWindow(), tr("QML Profiler"), tr("The QML profiler requires Qt 4.7.4 or newer.\n" "The Qt version configured in your active build configuration is too old.\n" "Do you want to continue?"), QMessageBox::Yes, QMessageBox::No); if (result == QMessageBox::No) return 0; } } // Check whether we should use OST instead of TCP if (Qt4ProjectManager::S60DeployConfiguration *deployConfig = qobject_cast<Qt4ProjectManager::S60DeployConfiguration*>( runConfiguration->target()->activeDeployConfiguration())) { if (deployConfig->communicationChannel() == Qt4ProjectManager::S60DeployConfiguration::CommunicationCodaSerialConnection) { d->m_profilerConnections->setOstConnection(deployConfig->serialPortName()); isTcpConnection = false; } } } // FIXME: Check that there's something sensible in sp.connParams if (isTcpConnection) { d->m_profilerConnections->setTcpConnection(sp.connParams.host, sp.connParams.port); } d->m_runConfiguration = runConfiguration; // // Initialize m_projectFinder // QString projectDirectory; if (d->m_runConfiguration) { Project *project = d->m_runConfiguration->target()->project(); projectDirectory = project->projectDirectory(); } // get files from all the projects in the session QStringList sourceFiles; SessionManager *sessionManager = ProjectExplorerPlugin::instance()->session(); QList<Project *> projects = sessionManager->projects(); if (Project *startupProject = ProjectExplorerPlugin::instance()->startupProject()) { // startup project first projects.removeOne(ProjectExplorerPlugin::instance()->startupProject()); projects.insert(0, startupProject); } foreach (Project *project, projects) sourceFiles << project->files(Project::ExcludeGeneratedFiles); d->m_projectFinder.setProjectDirectory(projectDirectory); d->m_projectFinder.setProjectFiles(sourceFiles); d->m_projectFinder.setSysroot(sp.sysroot); connect(engine, SIGNAL(processRunning(quint16)), d->m_profilerConnections, SLOT(connectClient(quint16))); connect(engine, SIGNAL(finished()), d->m_profilerConnections, SLOT(disconnectClient())); connect(d->m_profilerConnections, SIGNAL(connectionFailed()), engine, SLOT(cancelProcess())); return engine; }
/** * Updates the Hatch. Called when the * hatch or it's data, position, alignment, .. changes. */ void RS_Hatch::update() { RS_DEBUG->print("RS_Hatch::update"); RS_DEBUG->print("RS_Hatch::update: contour has %d loops", count()); updateError = HATCH_OK; if (updateRunning) { return; } if (updateEnabled==false) { return; } if (data.solid==true) { calculateBorders(); return; } RS_DEBUG->print("RS_Hatch::update"); updateRunning = true; // delete old hatch: if (hatch) { removeEntity(hatch); hatch = nullptr; } if (isUndone()) { updateRunning = false; return; } if (!validate()) { RS_DEBUG->print(RS_Debug::D_WARNING, "RS_Hatch::update: invalid contour in hatch found"); updateRunning = false; updateError = HATCH_INVALID_CONTOUR; return; } // search pattern: RS_DEBUG->print("RS_Hatch::update: requesting pattern"); RS_Pattern* pat = RS_PATTERNLIST->requestPattern(data.pattern); if (!pat) { updateRunning = false; RS_DEBUG->print("RS_Hatch::update: requesting pattern: not found"); updateError = HATCH_PATTERN_NOT_FOUND; return; } RS_DEBUG->print("RS_Hatch::update: requesting pattern: OK"); RS_DEBUG->print("RS_Hatch::update: cloning pattern"); pat = (RS_Pattern*)pat->clone(); RS_DEBUG->print("RS_Hatch::update: cloning pattern: OK"); // scale pattern RS_DEBUG->print("RS_Hatch::update: scaling pattern"); pat->scale(RS_Vector(0.0,0.0), RS_Vector(data.scale, data.scale)); pat->calculateBorders(); forcedCalculateBorders(); RS_DEBUG->print("RS_Hatch::update: scaling pattern: OK"); // find out how many pattern-instances we need in x/y: int px1, py1, px2, py2; double f; RS_Hatch* copy = (RS_Hatch*)this->clone(); copy->rotate(RS_Vector(0.0,0.0), -data.angle); copy->forcedCalculateBorders(); // create a pattern over the whole contour. RS_Vector pSize = pat->getSize(); RS_Vector rot_center=pat->getMin(); // RS_Vector cPos = getMin(); RS_Vector cSize = getSize(); RS_DEBUG->print("RS_Hatch::update: pattern size: %f/%f", pSize.x, pSize.y); RS_DEBUG->print("RS_Hatch::update: contour size: %f/%f", cSize.x, cSize.y); if (cSize.x<1.0e-6 || cSize.y<1.0e-6 || pSize.x<1.0e-6 || pSize.y<1.0e-6 || cSize.x>RS_MAXDOUBLE-1 || cSize.y>RS_MAXDOUBLE-1 || pSize.x>RS_MAXDOUBLE-1 || pSize.y>RS_MAXDOUBLE-1) { delete pat; delete copy; updateRunning = false; RS_DEBUG->print("RS_Hatch::update: contour size or pattern size too small"); updateError = HATCH_TOO_SMALL; return; } // avoid huge memory consumption: else if ( cSize.x* cSize.y/(pSize.x*pSize.y)>1e4) { RS_DEBUG->print("RS_Hatch::update: contour size too large or pattern size too small"); delete pat; delete copy; updateError = HATCH_AREA_TOO_BIG; return; } f = copy->getMin().x/pSize.x; px1 = (int)floor(f); f = copy->getMin().y/pSize.y; py1 = (int)floor(f); f = copy->getMax().x/pSize.x; px2 = (int)ceil(f); f = copy->getMax().y/pSize.y; py2 = (int)ceil(f); RS_Vector dvx=RS_Vector(data.angle)*pSize.x; RS_Vector dvy=RS_Vector(data.angle+M_PI*0.5)*pSize.y; pat->rotate(rot_center, data.angle); pat->move(-rot_center); RS_EntityContainer tmp; // container for untrimmed lines // adding array of patterns to tmp: RS_DEBUG->print("RS_Hatch::update: creating pattern carpet"); for (int px=px1; px<px2; px++) { for (int py=py1; py<py2; py++) { for(auto e: *pat){ RS_Entity* te=e->clone(); te->move(dvx*px + dvy*py); tmp.addEntity(te); } } } delete pat; pat = nullptr; delete copy; copy = nullptr; RS_DEBUG->print("RS_Hatch::update: creating pattern carpet: OK"); RS_DEBUG->print("RS_Hatch::update: cutting pattern carpet"); // cut pattern to contour shape: RS_EntityContainer tmp2; // container for small cut lines RS_Line* line = nullptr; RS_Arc* arc = nullptr; RS_Circle* circle = nullptr; RS_Ellipse* ellipse = nullptr; for(auto e: tmp){ line = nullptr; arc = nullptr; circle = nullptr; ellipse = nullptr; RS_Vector startPoint; RS_Vector endPoint; RS_Vector center = RS_Vector(false); bool reversed=false; switch(e->rtti()){ case RS2::EntityLine: line=static_cast<RS_Line*>(e); startPoint = line->getStartpoint(); endPoint = line->getEndpoint(); break; case RS2::EntityArc: arc=static_cast<RS_Arc*>(e); startPoint = arc->getStartpoint(); endPoint = arc->getEndpoint(); center = arc->getCenter(); reversed = arc->isReversed(); break; case RS2::EntityCircle: circle=static_cast<RS_Circle*>(e); startPoint = circle->getCenter() + RS_Vector(circle->getRadius(), 0.0); endPoint = startPoint; center = circle->getCenter(); break; case RS2::EntityEllipse: ellipse = static_cast<RS_Ellipse*>(e); startPoint = ellipse->getStartpoint(); endPoint = ellipse->getEndpoint(); center = ellipse->getCenter(); reversed = ellipse->isReversed(); break; default: continue; } // getting all intersections of this pattern line with the contour: QList<std::shared_ptr<RS_Vector> > is; for(auto loop: entities){ if (loop->isContainer()) { for(auto p: * static_cast<RS_EntityContainer*>(loop)){ RS_VectorSolutions sol = RS_Information::getIntersection(e, p, true); for (const RS_Vector& vp: sol){ if (vp.valid) { is.append(std::shared_ptr<RS_Vector>( new RS_Vector(vp) )); RS_DEBUG->print(" pattern line intersection: %f/%f", vp.x, vp.y); } } } } } QList<std::shared_ptr<RS_Vector> > is2;//to be filled with sorted intersections is2.append(std::shared_ptr<RS_Vector>(new RS_Vector(startPoint))); // sort the intersection points into is2 (only if there are intersections): if(is.size() == 1) {//only one intersection is2.append(is.first()); } else if(is.size() > 1) { RS_Vector sp = startPoint; double sa = center.angleTo(sp); if(ellipse ) sa=ellipse->getEllipseAngle(sp); bool done; double minDist; double dist = 0.0; std::shared_ptr<RS_Vector> av; std::shared_ptr<RS_Vector> v; RS_Vector last = RS_Vector(false); do { done = true; minDist = RS_MAXDOUBLE; av.reset(); for (int i = 0; i < is.size(); ++i) { v = is.at(i); double a; switch(e->rtti()){ case RS2::EntityLine: dist = sp.distanceTo(*v); break; case RS2::EntityArc: case RS2::EntityCircle: a = center.angleTo(*v); dist = reversed? fmod(sa - a + 2.*M_PI,2.*M_PI): fmod(a - sa + 2.*M_PI,2.*M_PI); break; case RS2::EntityEllipse: a = ellipse->getEllipseAngle(*v); dist = reversed? fmod(sa - a + 2.*M_PI,2.*M_PI): fmod(a - sa + 2.*M_PI,2.*M_PI); break; default: break; } if (dist<minDist) { minDist = dist; done = false; av = v; } } // copy to sorted list, removing double points if (!done && av.get()) { if (last.valid==false || last.distanceTo(*av)>RS_TOLERANCE) { is2.append(std::shared_ptr<RS_Vector>(new RS_Vector(*av))); last = *av; } #if QT_VERSION < 0x040400 emu_qt44_removeOne(is, av); #else is.removeOne(av); #endif av.reset(); } } while(!done); } is2.append(std::shared_ptr<RS_Vector>(new RS_Vector(endPoint))); // add small cut lines / arcs to tmp2: for (int i = 1; i < is2.size(); ++i) { auto v1 = is2.at(i-1); auto v2 = is2.at(i); if (line) { tmp2.addEntity(new RS_Line{&tmp2, *v1, *v2}); } else if (arc || circle) { if(fabs(center.angleTo(*v2)-center.angleTo(*v1)) > RS_TOLERANCE_ANGLE) {//don't create an arc with a too small angle tmp2.addEntity(new RS_Arc(&tmp2, RS_ArcData(center, center.distanceTo(*v1), center.angleTo(*v1), center.angleTo(*v2), reversed))); } } } } // updating hatch / adding entities that are inside RS_DEBUG->print("RS_Hatch::update: cutting pattern carpet: OK"); //RS_EntityContainer* rubbish = new RS_EntityContainer(getGraphic()); // the hatch pattern entities: hatch = new RS_EntityContainer(this); hatch->setPen(RS_Pen(RS2::FlagInvalid)); hatch->setLayer(nullptr); hatch->setFlag(RS2::FlagTemp); //calculateBorders(); for(auto e: tmp2){ RS_Vector middlePoint; RS_Vector middlePoint2; if (e->rtti()==RS2::EntityLine) { RS_Line* line = static_cast<RS_Line*>(e); middlePoint = line->getMiddlePoint(); middlePoint2 = line->getNearestDist(line->getLength()/2.1, line->getStartpoint()); } else if (e->rtti()==RS2::EntityArc) { RS_Arc* arc = static_cast<RS_Arc*>(e); middlePoint = arc->getMiddlePoint(); middlePoint2 = arc->getNearestDist(arc->getLength()/2.1, arc->getStartpoint()); } else { middlePoint = RS_Vector{false}; middlePoint2 = RS_Vector{false}; } if (middlePoint.valid) { bool onContour=false; if (RS_Information::isPointInsideContour( middlePoint, this, &onContour) || RS_Information::isPointInsideContour(middlePoint2, this)) { RS_Entity* te = e->clone(); te->setPen(RS2::FlagInvalid); te->setLayer(nullptr); te->reparent(hatch); hatch->addEntity(te); } } } addEntity(hatch); //getGraphic()->addEntity(rubbish); forcedCalculateBorders(); // deactivate contour: activateContour(false); updateRunning = false; RS_DEBUG->print("RS_Hatch::update: OK"); }