void SimulationBar::forEachSimulator(boost::function<void(SimulatorItem* simulator)> callback, bool doSelect)
{
    MessageView* mv = MessageView::instance();
    /*
      ItemList<SimulatorItem> simulators =
      ItemTreeView::mainInstance()->selectedItems<SimulatorItem>();
    */
    ItemList<SimulatorItem> simulators =
        ItemTreeView::mainInstance()->selectedItems<SimulatorItem>();

    if(simulators.empty()){
        simulators.extractChildItems(RootItem::instance());
        if(simulators.empty()){
            mv->notify(_("There is no simulator item."));
        } else  if(simulators.size() > 1){
            simulators.clear();
            mv->notify(_("Please select a simulator item to simulate."));
        } else {
            if(doSelect){
                ItemTreeView::instance()->selectItem(simulators.front());
            }
        }
    }

    typedef map<WorldItem*, SimulatorItem*> WorldToSimulatorMap;
    WorldToSimulatorMap worldToSimulator;

    for(int i=0; i < simulators.size(); ++i){
        SimulatorItem* simulator = simulators.get(i);
        WorldItem* world = simulator->findOwnerItem<WorldItem>();
        if(world){
            WorldToSimulatorMap::iterator p = worldToSimulator.find(world);
            if(p == worldToSimulator.end()){
                worldToSimulator[world] = simulator;
            } else {
                p->second = 0; // skip if multiple simulators are selected
            }
        }
    }

    for(int i=0; i < simulators.size(); ++i){
        SimulatorItem* simulator = simulators.get(i);
        WorldItem* world = simulator->findOwnerItem<WorldItem>();
        if(!world){
            mv->notify(format(_("%1% cannot be processed because it is not related with a world."))
                       % simulator->name());
        } else {
            WorldToSimulatorMap::iterator p = worldToSimulator.find(world);
            if(p != worldToSimulator.end()){
                if(!p->second){
                    mv->notify(format(_("%1% cannot be processed because another simulator"
                                        "in the same world is also selected."))
                               % simulator->name());
                } else {
                    callback(simulator);
                }
            }
        }
    }
}
bool KSIImpl::setupBodies()
{
    if(TRACE_FUNCTIONS){
        cout << "KSIImpl::setupBodies()" << endl;
    }
    
    mainFrameRate = 0;
    bodyUnits.clear();
    
    WorldItemPtr worldItem = self->findOwnerItem<WorldItem>();
    if(worldItem){
        ItemList<BodyItem> bodyItems = worldItem->getBodyItems();
        for(size_t i=0; i < bodyItems.size(); ++i){
            BodyUnit unit;
            if(unit.initialize(bodyItems[i])){
                bodyUnits.push_back(unit);
                if(unit.frameRate > mainFrameRate){
                    mainFrameRate = unit.frameRate;
                }
            }
        }
    }

    return (!bodyUnits.empty() && mainFrameRate > 0);
}
bool EditableSceneBodyImpl::storeProperties(Archive& archive)
{
    ListingPtr states = new Listing();

    ItemList<BodyItem> bodyItems;
    bodyItems.extractChildItems(RootItem::instance());
    
    for(size_t i=0; i < bodyItems.size(); ++i){
        BodyItem* bodyItem = bodyItems[i];
        EditableSceneBody* sceneBody = bodyItem->existingSceneBody();
        if(sceneBody){
            ValueNodePtr id = archive.getItemId(bodyItem);
            if(id){
                EditableSceneBodyImpl* impl = sceneBody->impl;
                MappingPtr state = new Mapping();
                state->insert("bodyItem", id);
                state->write("showCenterOfMass", impl->isCmVisible);
                state->write("showZmp", impl->isZmpVisible);
                states->append(state);
            }
        }
    }
    if(!states->empty()){
        archive.insert("editableSceneBodies", states);
        return true;
    }
    return false;
}
Exemple #4
0
void ScriptBar::executeCheckedScriptItems()
{
    ItemList<ScriptItem> scripts = ItemTreeView::mainInstance()->checkedItems<ScriptItem>();
    for(int i=0; i < scripts.size(); ++i){
        scripts[i]->execute();
    }
}
Exemple #5
0
DropList::DropList (Window &win, const ItemList &items_, size_t default_select)
	: Control (win)
	, FocusColorControl (win)
	, items (items_.empty () ? ItemList (1) : items_)
	, select (default_select < items_.size () ? default_select : 0)
{
}
    /**
     * Calculate prefix paths that end with a node that has the given ItemID.
     * These nodes can be retrieved very quickly using the FPTree's itemPaths.
     * A prefix path is a list of Items that reflects a path from the bottom
     * of the tree to the root (but excluding the root), following along the
     * path of an FPNode that has the ItemID itemID. Because it is a list of
     * Items, it also includes both the ItemID and the SupportCount. The
     * original SupportCount of the Item encapsulated by the FPNode is erased
     * and replaced by the SupportCount of the FPNode we started from, i.e. a
     * node that has the ItemID itemID, because we're looking at only the
     * paths that include this node.
     * Exclude the leaf node itself, as it will no longer be needed.
     */
    QList<ItemList> FPTree::calculatePrefixPaths(ItemID itemID) const {
        QList<ItemList> prefixPaths;
        ItemList prefixPath;
        FPNode<SupportCount> * node;
        SupportCount supportCount;
        Item item;

        QList<FPNode<SupportCount> *> leafNodes = this->getItemPath(itemID);
        foreach (FPNode<SupportCount> * leafNode, leafNodes) {
            // Build the prefix path starting from the given leaf node, by
            // traversing up the tree (but do not include the leaf node's item
            // in the prefix path).
            // Don't copy the item's original count, but the count of the leaf
            // node instead, because we're looking at only the paths that
            // include this leaf node.
            node = leafNode;
            supportCount = leafNode->getValue();
            while ((node = node->getParent()) != NULL && node->getItemID() != ROOT_ITEMID) {
                item.id = node->getItemID();
                item.supportCount = supportCount;
                prefixPath.prepend(item);
            }

            // Store the built prefix path & clear it, so we can calculate the
            // next. Of course only if there *is* a prefix path, which is not
            // the case if the given itemID is at the root level.
            if (prefixPath.size() > 0) {
                prefixPaths.append(prefixPath);
                prefixPath.clear();
            }
        }
Exemple #7
0
void
TrafficListWidget::UpdateList()
{
  assert(filter_widget != nullptr);

  items.clear();
  last_update.Clear();

  const TCHAR *callsign = filter_widget->GetValueString(CALLSIGN);
  if (!StringIsEmpty(callsign)) {
    FlarmId ids[30];
    unsigned count = FlarmDetails::FindIdsByCallSign(callsign, ids, 30);

    for (unsigned i = 0; i < count; ++i)
      AddItem(ids[i]);
  } else {
    /* if no filter was set, show a list of current traffic and known
       traffic */

    /* add live FLARM traffic */
    for (const auto &i : CommonInterface::Basic().flarm.traffic.list) {
      AddItem(i.id);
    }

    /* add FLARM peers that have a user-defined color */
    for (const auto &i : traffic_databases->flarm_colors) {
      Item &item = AddItem(i.first);
      item.color = i.second;
    }

    /* add FLARM peers that have a user-defined name */
    for (const auto &i : traffic_databases->flarm_names) {
      AddItem(i.id);
    }

#ifdef HAVE_SKYLINES_TRACKING_HANDLER
    /* show SkyLines traffic unless this is a FLARM traffic picker
       dialog (from dlgTeamCode) */
    if (action_listener == nullptr) {
      const auto &data = tracking->GetSkyLinesData();
      const ScopeLock protect(data.mutex);
      for (const auto &i : data.traffic) {
        items.emplace_back(i.first, i.second.location);
        Item &item = items.back();

        if (i.second.location.IsValid() &&
            CommonInterface::Basic().location_available)
          item.vector = GeoVector(CommonInterface::Basic().location,
                                  i.second.location);
      }
    }
#endif
  }

  GetList().SetLength(items.size());

  UpdateVolatile();
  UpdateButtons();
}
void OnlineViewerServerImpl::load(string name, string url)
{
    string filepath;

    QRegExp filePattern("(\\w+)://(.+)");
    if(filePattern.exactMatch(url.c_str())){
        string protocol = filePattern.cap(1).toStdString();
        if(protocol == "file"){
            filepath = filePattern.cap(2).toStdString();
        } else {
            mv->putln(
                fmt(_("OnlineViewer: The model file at \"%1%\" cannot be read. %2% protocol is not supported."))
                % url % protocol);
            return;
        }
    } else {
        filepath = url;
    }
        
    // search for registered body items
    BodyItemInfo* info = findInfo(name);
    if(info && info->bodyItem->filePath() == filepath){
        info->needToSelectLogItem = true;
        // mv->putln(fmt(_("OnlineViewer: \"%1%\" at \"%2%\" has already been loaded.")) % name % url);
        return;
    }
    
    // search for existing body items
    RootItem* rootItem = RootItem::instance();
    ItemList<BodyItem> bodyItems;
    bodyItems.extractChildItems(rootItem);
    for(int i=0; i < bodyItems.size(); ++i){
        BodyItemPtr bodyItem = bodyItems[i];
        if(bodyItem->name() == name && bodyItem->filePath() == filepath){
            registerBodyItem(bodyItem);
            return;
        }
    }
    // load a new body item
    BodyItemPtr bodyItem = new BodyItem();
    mv->putln(fmt(_("OnlineViewer: Loading \"%1%\" at \"%2%\"."))
              % name % url);
    mv->flush();
    if(!bodyItem->load(filepath)){
        mv->putln(fmt(_("OnlineViewer: Loading \"%1%\" failed.")) % name);

    } else {
        bodyItem->setName(name);
        ItemList<WorldItem> worldItems;
        if(worldItems.extractChildItems(rootItem)){
            worldItems.front()->addChildItem(bodyItem);
        } else {
            rootItem->addChildItem(bodyItem);
        }
        ItemTreeView::instance()->checkItem(bodyItem, true);
        registerBodyItem(bodyItem);
    }
}
void KinematicFaultCheckerImpl::apply()
{
    bool processed = false;
        
    ItemList<BodyMotionItem> items = ItemTreeView::mainInstance()->selectedItems<BodyMotionItem>();
    if(items.empty()){
        mes.notify(_("No BodyMotionItems are selected."));
    } else {
        for(size_t i=0; i < items.size(); ++i){
            BodyMotionItem* motionItem = items.get(i);
            BodyItem* bodyItem = motionItem->findOwnerItem<BodyItem>();
            if(!bodyItem){
                mes.notify(str(fmt(_("%1% is not owned by any BodyItem. Check skiped.")) % motionItem->name()));
            } else {
                mes.putln();
                mes.notify(str(fmt(_("Applying the Kinematic Fault Checker to %1% ..."))
                               % motionItem->headItem()->name()));
                
                dynamic_bitset<> linkSelection;
                if(selectedJointsRadio.isChecked()){
                    linkSelection = LinkSelectionView::mainInstance()->linkSelection(bodyItem);
                } else if(nonSelectedJointsRadio.isChecked()){
                    linkSelection = LinkSelectionView::mainInstance()->linkSelection(bodyItem);
                    linkSelection.flip();
                } else {
                    linkSelection.resize(bodyItem->body()->numLinks(), true);
                }
                
                double beginningTime = 0.0;
                double endingTime = motionItem->motion()->getTimeLength();
                std::numeric_limits<double>::max();
                if(onlyTimeBarRangeCheck.isChecked()){
                    TimeBar* timeBar = TimeBar::instance();
                    beginningTime = timeBar->minTime();
                    endingTime = timeBar->maxTime();
                }
                
                int n = checkFaults(bodyItem, motionItem, mes.cout(),
                                    positionCheck.isChecked(),
                                    velocityCheck.isChecked(),
                                    collisionCheck.isChecked(),
                                    linkSelection,
                                    beginningTime, endingTime);
                
                if(n > 0){
                    if(n == 1){
                        mes.notify(_("A fault has been detected."));
                    } else {
                        mes.notify(str(fmt(_("%1% faults have been detected.")) % n));
                    }
                } else {
                    mes.notify(_("No faults have been detected."));
                }
                processed = true;
            }
        }
    }
}
void MultiAffine3SeqGraphView::onItemSelectionChanged(const ItemList<MultiAffine3SeqItem>& items)
{
    if(items.empty()){
        return;
    }

    if(itemInfos.size() == items.size()){
        bool unchanged = true;
        int i=0;
        for(list<ItemInfo>::iterator it = itemInfos.begin(); it != itemInfos.end(); ++it){
            if(it->item != items[i++]){
                unchanged = false;
                break;
            }
        }
        if(unchanged){
            return;
        }
    }
            
    itemInfos.clear();

    for(size_t i=0; i < items.size(); ++i){
        BodyItemPtr bodyItem = items[i]->findOwnerItem<BodyItem>();
        if(bodyItem){
            itemInfos.push_back(ItemInfo());
            list<ItemInfo>::iterator it = --itemInfos.end();
            it->item = items[i];
            it->seq = it->item->seq();
            it->bodyItem = bodyItem;

            it->connections.add(it->item->sigUpdated().connect(
                                    bind(&MultiAffine3SeqGraphView::onDataItemUpdated, this, it)));

            it->connections.add(it->item->sigDetachedFromRoot().connect(
                                    bind(&MultiAffine3SeqGraphView::onDataItemDetachedFromRoot, this, it)));
        }
    }

    updateBodyItems();
    setupGraphWidget();
}
Exemple #11
0
LibraryFile::LibraryFile( DatFormat* format, const ItemList& items, QObject* parent ) : TibiaModule( parent )
{
	m_thread = new LibraryThread( this );
	m_idle = false;
	m_mustIdle = false;
	m_count = items.size();
	m_datFormat = format;
	m_version = m_datFormat->getVersion();
	m_items = items;
	QObject::connect( m_thread, SIGNAL( finished() ), this, SLOT( deleteLater() ) );
}
Exemple #12
0
void
TrafficListWidget::UpdateButtons()
{
  if (buttons == nullptr)
    return;

  unsigned cursor = GetList().GetCursorIndex();
  bool valid_cursor = cursor < items.size();
  bool flarm_cursor = valid_cursor && items[cursor].IsFlarm();

  buttons->SetRowVisible(DETAILS, flarm_cursor);
}
void GraphViewBaseImpl::onItemSelectionChanged(const ItemList<>& allItems)
{
    ItemList<> items = self->extractTargetItems(allItems);

    if(items.empty()){
        return;
    }

    if(itemInfos.size() == items.size()){
        bool unchanged = true;
        int i=0;
        for(list<ItemInfo>::iterator it = itemInfos.begin(); it != itemInfos.end(); ++it){
            if(it->item != items[i++]){
                unchanged = false;
                break;
            }
        }
        if(unchanged){
            return;
        }
    }

    itemInfos.clear();

    for(size_t i=0; i < items.size(); ++i){

        itemInfos.push_back(ItemInfo(this));
        list<ItemInfo>::iterator it = --itemInfos.end();
        it->item = items[i];

        ConnectionSet& connections = itemToConnectionSetMap[it->item.get()];
        connections.add(it->item->sigUpdated().connect(
                            boost::bind(&GraphViewBaseImpl::onItemUpdated, this, it)));

        connections.add(it->item->sigDetachedFromRoot().connect(
                            boost::bind(&GraphViewBaseImpl::onItemDetachedFromRoot, this, it)));
    }

    updatePartList();
}
Exemple #14
0
void
TrafficListWidget::Prepare(ContainerWindow &parent,
                           const PixelRect &rc)
{
  const DialogLook &look = UIGlobals::GetDialogLook();
  ListControl &list = CreateList(parent, look, rc,
                                 GetRowHeight(look));

  if (filter_widget != nullptr)
    UpdateList();
  else
    list.SetLength(items.size());
}
Exemple #15
0
void
TrafficListWidget::OpenMap(unsigned index)
{
  if (index >= items.size())
    return;

  Item &item = items[index];
  if (!item.location.IsValid())
    return;

  if (PanTo(item.location))
    action_listener.OnAction(mrCancel);
}
Exemple #16
0
void
TrafficListWidget::OpenDetails(unsigned index)
{
  if (index >= items.size())
    return;

  Item &item = items[index];

  if (item.IsFlarm()) {
    dlgFlarmTrafficDetailsShowModal(item.id);
    UpdateList();
  }
}
bool
PictureAspectRatioBox::list( MP4FileHandle file, ItemList& itemList )
{
    itemList.clear();
    MP4File& mp4 = *((MP4File*)file);

    const uint16_t trackc = mp4.GetNumberOfTracks();
    for( uint16_t i = 0; i < trackc; i++) {
        MP4TrackId id = mp4.FindTrackId( i );
        if( id == MP4_INVALID_TRACK_ID )
            continue;

        const char* type = mp4.GetTrackType( id );
        if( !type )
            continue;

        itemList.resize( itemList.size() + 1 );
        IndexedItem& xitem = itemList[itemList.size()-1];

        xitem.trackIndex = i;
        xitem.trackId    = id;

        bool success = false;
        try {
            success = !get( file, i, xitem.item );
        }
        catch( MP4Exception* x ) {
            delete x;
        }

        if( !success ) {
            itemList.resize( itemList.size() - 1 );
            continue;
        }
    }

    return false;
}
Exemple #18
0
void ItemTreeViewImpl::storeItemIds(Archive& archive, const char* key, const ItemList<>& items)
{
    ListingPtr idseq = new Listing();
    idseq->setFlowStyle(true);
    for(size_t i=0; i < items.size(); ++i){
        ValueNodePtr id = archive.getItemId(items[i]);
        if(id){
            idseq->append(id);
        }
    }
    if(!idseq->empty()){
        archive.insert(key, idseq);
    }
}
Exemple #19
0
void
TrafficListWidget::Prepare(ContainerWindow &parent,
                           const PixelRect &rc)
{
  const DialogLook &look = UIGlobals::GetDialogLook();
  ListControl &list = CreateList(parent, look, rc,
                                 row_renderer.CalculateLayout(*look.list.font_bold,
                                                              look.small_font));

  if (filter_widget != nullptr)
    UpdateList();
  else
    list.SetLength(items.size());
}
Exemple #20
0
void ItemTreeViewImpl::forEachTopItems(const ItemList<>& items, boost::function<void(Item*)> callback)
{
    set<Item*> itemSet;
    for(size_t i=0; i < items.size(); ++i){
        itemSet.insert(items.get(i));
    }

    for(size_t i=0; i < items.size(); ++i){
        Item* item = items.get(i);
        bool isChild = false;
        Item* parentItem = item->parentItem();
        while(parentItem){
            set<Item*>::iterator p = itemSet.find(parentItem);
            if(p != itemSet.end()){
                isChild = true;
                break;
            }
            parentItem = parentItem->parentItem();
        }
        if(!isChild){
            callback(item);
        }
    }
}
Exemple #21
0
qmimap4::CopyOfflineJob::CopyOfflineJob(const WCHAR* pwszFolderFrom,
										const WCHAR* pwszFolderTo,
										const UidList& listUidFrom,
										const ItemList& listItemTo,
										bool bMove) :
	OfflineJob(pwszFolderFrom),
	listUidFrom_(listUidFrom),
	listItemTo_(listItemTo),
	bMove_(bMove)
{
	assert(!listUidFrom.empty());
	assert(listUidFrom.size() == listItemTo.size());
	
	wstrFolderTo_ = allocWString(pwszFolderTo);
}
bool AbstractSortingStrategy::moveItem(AbstractGroupableItem *item, int newIndex)
{
    //qDebug() << "move to " << newIndex;
    if (!item->parentGroup()) {
        qWarning() << "error: no parentgroup but the item was asked to move";
        return false;
    }

    const ItemList list = item->parentGroup()->members();
    if ((newIndex < 0) || (newIndex >= list.size())) {
        newIndex = list.size();
    }

    int oldIndex = list.indexOf(item);
    if (newIndex > oldIndex) {
        newIndex--; //the index has to be adjusted if we move the item from right to left because the item on the left is removed first
    }

    if (oldIndex != newIndex) {
        return item->parentGroup()->moveItem(oldIndex, newIndex);
    }

    return false;
}
Exemple #23
0
bool BodyBarImpl::makeSingleSelection(BodyItem* bodyItem)
{
    ItemTreeView* tree = ItemTreeView::mainInstance()->mainInstance();

    ItemList<BodyItem> prevSelected = selectedBodyItems;

    for(size_t i=0; i < prevSelected.size(); ++i){
        BodyItem* item = prevSelected[i];
        if(item != bodyItem && tree->isItemSelected(item)){
            tree->selectItem(item, false);
        }
    }

    bool selected = tree->isItemSelected(bodyItem);
    if(!selected){
        selected = tree->selectItem(bodyItem, true);
    }
    return selected;
}
void MeshShapeItemImpl::onSelectionChanged()
{
    ItemList<Item> items = ItemTreeView::mainInstance()->selectedItems();
    bool selected = false;
    for(size_t i=0; i < items.size(); ++i){
        Item* item = items.get(i);
        if (item == self) {
            selected = true;
        }
    }
    if (isselected != selected) {
        isselected = selected;
        //positionDragger->setDraggerAlwaysShown(selected);
        if (isselected) {
            positionDragger->setDraggerAlwaysShown(true);
        } else {
            positionDragger->setDraggerAlwaysHidden(true);
        }
    }
}
Exemple #25
0
static void forEachTargetBodyItem(boost::function<void(BodyItem*)> callback)
{
    ItemTreeView* itemTreeView = ItemTreeView::instance();

    ItemList<BodyItem> bodyItems;
    bodyItems.extractChildItems(RootItem::instance());
    
    for(int i=0; i < bodyItems.size(); ++i){
        BodyItem* bodyItem = bodyItems.get(i);
        bool isTarget = itemTreeView->isItemSelected(bodyItem);
        if(!isTarget){
            WorldItem* worldItem = bodyItem->findOwnerItem<WorldItem>();
            if(worldItem && itemTreeView->isItemSelected(worldItem)){
                isTarget = true;
            }
        }
        if(isTarget){
            callback(bodyItem);
        }
    }
}
void BodyMotionGenerationBar::onGenerationButtonClicked()
{
    set<BodyMotionItem*> motionItems; // for avoiding overlap
    ItemList<Item> selectedItems = ItemTreeView::mainInstance()->selectedItems<Item>();

    for(size_t i=0; i < selectedItems.size(); ++i){
        PoseSeqItem* poseSeqItem = dynamic_cast<PoseSeqItem*>(selectedItems[i]);
        if(poseSeqItem){
            motionItems.insert(poseSeqItem->bodyMotionItem());
        } else {
            BodyMotionItem* motionItem = dynamic_cast<BodyMotionItem*>(selectedItems[i]);
            if(motionItem){
                motionItems.insert(motionItem);
            }
        }
    }

    for(set<BodyMotionItem*>::iterator p = motionItems.begin(); p != motionItems.end(); ++p){
        BodyMotionItem* motionItem = *p;
        BodyItem* bodyItem = motionItem->findOwnerItem<BodyItem>(true);
        if(bodyItem){
            PoseProvider* provider = 0;
            PoseSeqItem* poseSeqItem = dynamic_cast<PoseSeqItem*>(motionItem->parentItem());
            if(poseSeqItem){
                provider = poseSeqItem->interpolator().get();
            } else {
                bodyMotionPoseProvider->initialize(bodyItem->body(), motionItem->motion());
                provider = bodyMotionPoseProvider;

                if(setup->newBodyItemCheck.isChecked()){
                    BodyMotionItem* newMotionItem = new BodyMotionItem();
                    newMotionItem->setName(motionItem->name() + "'");
                    motionItem->parentItem()->insertChildItem(newMotionItem, motionItem->nextItem());
                    motionItem = newMotionItem;
                }
            }
            shapeBodyMotion(bodyItem->body(), provider, motionItem, true);
        }
    }
}
/**
   \todo use cache of the cloned scene graph nodes
*/
void VisionRenderer::initializeScene(const vector<SimulationBody*>& simBodies)
{
    sceneGroup = new SgGroup;

#ifndef CNOID_REFERENCED_USE_ATOMIC_COUNTER
    simImpl->cloneMap.clear();
#endif

    // create scene bodies
    for(size_t i=0; i < simBodies.size(); ++i){
        SceneBody* sceneBody = new SceneBody(simBodies[i]->body());

#ifndef CNOID_REFERENCED_USE_ATOMIC_COUNTER
        sceneBody->cloneShapes(simImpl->cloneMap);
#endif
        sceneBodies.push_back(sceneBody);
        sceneGroup->addChild(sceneBody);
    }

    if(simImpl->shootAllSceneObjects){
        WorldItem* worldItem = simImpl->self->findOwnerItem<WorldItem>();
        if(worldItem){
            ItemList<> items;
            items.extractChildItems(worldItem);
            for(size_t i=0; i < items.size(); ++i){
                Item* item = items.get(i);
                SceneProvider* sceneProvider = dynamic_cast<SceneProvider*>(item);
                if(sceneProvider && !dynamic_cast<BodyItem*>(item)){
                    SgNode* scene = sceneProvider->getScene(simImpl->cloneMap);
                    if(scene){
                        sceneGroup->addChild(scene);
                    }
                }
            }
        }
    }
}
bool BodyUnit::initialize(BodyItemPtr bodyItem)
{
    if(TRACE_FUNCTIONS){
        cout << "BodyUnit::initialize()" << endl;
    }

    if(bodyItem->body()->isStaticModel()){
        return false;
    }
        
    frame = 0;
    body = bodyItem->body()->duplicate();
    baseLink = 0;

    ItemList<BodyMotionItem> motionItems = bodyItem->getSubItems<BodyMotionItem>();
    if(!motionItems.empty()){
        BodyMotionItemPtr motionItem;
        // prefer the first checked item
        for(size_t i=0; i < motionItems.size(); ++i){
            if(ItemTreeView::mainInstance()->isItemChecked(motionItems[i])){
                motionItem = motionItems[i];
                break;
            }
        }
        if(!motionItem){
            motionItem = motionItems[0];
        }
        
        frameRate = motionItem->motion()->frameRate();
        qseqRef = motionItem->jointPosSeq();
        if(qseqResult){
            qseqResultBuf.reset(new MultiValueSeq(qseqResult->numParts(), 0, frameRate));
        }

        if(motionItem->hasRelativeZmpSeqItem()){
            zmpSeq = motionItem->relativeZmpSeq();
        }

        rootResultItem = motionItem->linkPosSeqItem();
        rootResultBuf.reset(new MultiAffine3Seq(1, 0, frameRate));
        rootResult = motionItem->linkPosSeq();
        rootResult->setFrameRate(frameRate);
        rootResult->setDimension(1, 1);
    }

    const YamlMapping& info = *bodyItem->body()->info();
    const YamlSequence& footLinkInfos = *info.findSequence("footLinks");
    if(footLinkInfos.isValid()){
        for(int i=0; i < footLinkInfos.size(); ++i){
            const YamlMapping& footLinkInfo = *footLinkInfos[i].toMapping();
            Link* link = body->link(footLinkInfo["link"].toString());
            Vector3 soleCenter;
            if(link && read(footLinkInfo, "soleCenter", soleCenter)){
                footLinks.push_back(link);
                footLinkOriginHeights.push_back(-soleCenter[2]);
            }
        }
    }

    if(!footLinks.empty()){
        if(zmpSeq){
            setBaseLinkByZmp(0);
        } else {
            if(bodyItem->currentBaseLink()){
                int currentBaseLinkIndex = bodyItem->currentBaseLink()->index;
                for(size_t i=0; i < footLinks.size(); ++i){
                    Link* footLink = footLinks[i];
                    if(footLink->index == currentBaseLinkIndex){
                        setBaseLink(footLink, footLinkOriginHeights[i]);
                    }
                }
            } else{
                setBaseLink(footLinks[0], footLinkOriginHeights[0]);
            }
        }
    }

    if(!baseLink){
        if(bodyItem->currentBaseLink()){
            baseLink = body->link(bodyItem->currentBaseLink()->index);
        } else {
            baseLink = body->rootLink();
        }
        fkTraverse.find(baseLink, true, true);
    }

    if(rootResult){
        Link* rootLink = body->rootLink();
        Affine3& initialPos = rootResult->at(0, 0);
        initialPos.translation() = rootLink->p;
        initialPos.linear() = rootLink->R;
    }

    return (qseqRef != 0);
}
Exemple #29
0
void
TrafficListWidget::OnPaintItem(Canvas &canvas, PixelRect rc,
                               unsigned index)
{
  assert(index < items.size());
  Item &item = items[index];

  assert(item.IsFlarm()
#ifdef HAVE_SKYLINES_TRACKING_HANDLER
         || item.IsSkyLines()
#endif
         );

  item.AutoLoad();

  const FlarmNetRecord *record = item.record;
  const TCHAR *callsign = item.callsign;

  const DialogLook &look = UIGlobals::GetDialogLook();
  const Font &name_font = *look.list.font_bold;
  const Font &small_font = look.small_font;

  const unsigned text_padding = Layout::GetTextPadding();
  const unsigned frame_padding = text_padding / 2;

  TCHAR tmp_id[10];
  item.id.Format(tmp_id);

  canvas.Select(name_font);

  StaticString<256> tmp;

  if (item.IsFlarm()) {
    if (record != nullptr)
      tmp.Format(_T("%s - %s - %s"),
                 callsign, record->registration.c_str(), tmp_id);
    else if (callsign != nullptr)
      tmp.Format(_T("%s - %s"), callsign, tmp_id);
    else
      tmp.Format(_T("%s"), tmp_id);
#ifdef HAVE_SKYLINES_TRACKING_HANDLER
  } else if (item.IsSkyLines()) {
    if (!item.name.empty())
      tmp = item.name.c_str();
    else
      tmp.UnsafeFormat(_T("SkyLines %u"), item.skylines_id);
#endif
  } else {
    tmp = _T("?");
  }

  if (item.color != FlarmColor::NONE) {
    const TrafficLook &traffic_look = UIGlobals::GetLook().traffic;

    switch (item.color) {
    case FlarmColor::NONE:
    case FlarmColor::COUNT:
      gcc_unreachable();

    case FlarmColor::GREEN:
      canvas.Select(traffic_look.team_pen_green);
      break;
    case FlarmColor::BLUE:
      canvas.Select(traffic_look.team_pen_blue);
      break;
    case FlarmColor::YELLOW:
      canvas.Select(traffic_look.team_pen_yellow);
      break;
    case FlarmColor::MAGENTA:
      canvas.Select(traffic_look.team_pen_magenta);
      break;
    }

    canvas.SelectHollowBrush();

    const PixelSize size = canvas.CalcTextSize(tmp);
    canvas.Rectangle(rc.left + row_renderer.GetX() - frame_padding,
                     rc.top + row_renderer.GetFirstY() - frame_padding,
                     rc.left + row_renderer.GetX() + size.cx + frame_padding,
                     rc.top + row_renderer.GetFirstY() + size.cy + frame_padding);
  }

  row_renderer.DrawFirstRow(canvas, rc, tmp);

  canvas.Select(small_font);

  /* draw bearing and distance on the right */
  if (item.vector.IsValid()) {
    row_renderer.DrawRightFirstRow(canvas, rc,
                                            FormatUserDistanceSmart(item.vector.distance).c_str());

    // Draw leg bearing
    rc.right = row_renderer.DrawRightSecondRow(canvas, rc,
                                               FormatBearing(item.vector.bearing).c_str());
  }

  if (record != nullptr) {
    tmp.clear();

    if (!record->pilot.empty())
      tmp = record->pilot.c_str();

    if (!record->plane_type.empty()) {
      if (!tmp.empty())
        tmp.append(_T(" - "));

      tmp.append(record->plane_type);
    }

    if (!record->airfield.empty()) {
      if (!tmp.empty())
        tmp.append(_T(" - "));

      tmp.append(record->airfield);
    }

    if (!tmp.empty())
      row_renderer.DrawSecondRow(canvas, rc, tmp);
#ifdef HAVE_SKYLINES_TRACKING_HANDLER
  } else if (item.IsSkyLines()) {
    if (CommonInterface::Basic().time_available) {
      tmp.UnsafeFormat(_("%u minutes ago"),
                       SinceInMinutes(CommonInterface::Basic().time,
                                      item.time_of_day_ms));
    } else
      tmp.clear();

    if (!item.near_name.empty())
      tmp.AppendFormat(_T(" near %s (%s)"),
                       item.near_name.c_str(),
                       FormatUserDistanceSmart(item.near_distance).c_str());

    if (!tmp.empty())
      tmp.append(_T("; "));
    tmp.append(FormatUserAltitude(item.altitude));

    if (!tmp.empty())
      row_renderer.DrawSecondRow(canvas, rc, tmp);
#endif
  }
}
Exemple #30
0
void
TrafficListWidget::OnPaintItem(Canvas &canvas, const PixelRect rc,
                               unsigned index)
{
  assert(index < items.size());
  Item &item = items[index];

  assert(item.IsFlarm()
#ifdef HAVE_SKYLINES_TRACKING_HANDLER
         || item.IsSkyLines()
#endif
         );

  item.AutoLoad();

  const FlarmNetRecord *record = item.record;
  const TCHAR *callsign = item.callsign;

  const DialogLook &look = UIGlobals::GetDialogLook();
  const Font &name_font = *look.list.font_bold;
  const Font &small_font = *look.small_font;

  const unsigned text_padding = Layout::GetTextPadding();
  const unsigned frame_padding = text_padding / 2;

  TCHAR tmp_id[10];
  item.id.Format(tmp_id);

  canvas.Select(name_font);

  StaticString<256> tmp;

  if (item.IsFlarm()) {
    if (record != NULL)
      tmp.Format(_T("%s - %s - %s"),
                 callsign, record->registration.c_str(), tmp_id);
    else if (callsign != NULL)
      tmp.Format(_T("%s - %s"), callsign, tmp_id);
    else
      tmp.Format(_T("%s"), tmp_id);
#ifdef HAVE_SKYLINES_TRACKING_HANDLER
  } else if (item.IsSkyLines()) {
    tmp.UnsafeFormat(_T("SkyLines %u"), item.skylines_id);
#endif
  } else {
    tmp = _T("?");
  }

  const int name_x = rc.left + text_padding, name_y = rc.top + text_padding;

  if (item.color != FlarmColor::NONE) {
    const TrafficLook &traffic_look = UIGlobals::GetLook().traffic;

    switch (item.color) {
    case FlarmColor::NONE:
    case FlarmColor::COUNT:
      gcc_unreachable();

    case FlarmColor::GREEN:
      canvas.Select(traffic_look.team_pen_green);
      break;
    case FlarmColor::BLUE:
      canvas.Select(traffic_look.team_pen_blue);
      break;
    case FlarmColor::YELLOW:
      canvas.Select(traffic_look.team_pen_yellow);
      break;
    case FlarmColor::MAGENTA:
      canvas.Select(traffic_look.team_pen_magenta);
      break;
    }

    canvas.SelectHollowBrush();

    const PixelSize size = canvas.CalcTextSize(tmp);
    canvas.Rectangle(name_x - frame_padding,
                     name_y - frame_padding,
                     name_x + size.cx + frame_padding,
                     name_y + size.cy + frame_padding);
  }

  canvas.DrawText(name_x, name_y, tmp);

  if (record != NULL) {
    tmp.clear();

    if (!record->pilot.empty())
      tmp = record->pilot.c_str();

    if (!record->plane_type.empty()) {
      if (!tmp.empty())
        tmp.append(_T(" - "));

      tmp.append(record->plane_type);
    }

    if (!record->airfield.empty()) {
      if (!tmp.empty())
        tmp.append(_T(" - "));

      tmp.append(record->airfield);
    }

    if (!tmp.empty()) {
      canvas.Select(small_font);
      canvas.DrawText(rc.left + text_padding,
                      rc.bottom - small_font.GetHeight() - text_padding,
                      tmp);
    }
  }

  /* draw bearing and distance on the right */
  if (item.vector.IsValid()) {
    FormatUserDistanceSmart(item.vector.distance, tmp.buffer(), true);
    unsigned width = canvas.CalcTextWidth(tmp.c_str());
    canvas.DrawText(rc.right - text_padding - width,
                    name_y +
                    (name_font.GetHeight() - small_font.GetHeight()) / 2,
                    tmp.c_str());

    // Draw leg bearing
    FormatBearing(tmp.buffer(), tmp.MAX_SIZE, item.vector.bearing);
    width = canvas.CalcTextWidth(tmp.c_str());
    canvas.DrawText(rc.right - text_padding - width,
                    rc.bottom - small_font.GetHeight() - text_padding,
                    tmp.c_str());
  }

}