Beispiel #1
0
SoMaterial *
SoToVRMLActionP::find_or_create_material(void)
{
  SoMaterial * mat = NULL;
  SoGroup * tail = this->get_current_tail();

  int num = tail->getNumChildren();
  while (--num >= 0 && mat == NULL) {
    SoNode * node = tail->getChild(num);
    if (node->isOfType(SoMaterial::getClassTypeId())) {
      mat = coin_assert_cast<SoMaterial*>(node);
    }
  }
  if (mat == NULL) {
    mat = new SoMaterial;
    tail->addChild(mat);
  }
  return mat;
}
void SceneModel::setNode(QModelIndex index, SoNode* node)
{
    this->setData(index, QVariant(QString::fromLatin1(node->getTypeId().getName())));
    if (node->getTypeId().isDerivedFrom(SoGroup::getClassTypeId())) {
        SoGroup *group = static_cast<SoGroup*>(node);
        // insert SoGroup icon
        this->insertColumns(0,2,index);
        this->insertRows(0,group->getNumChildren(), index);
        for (int i=0; i<group->getNumChildren();i++) {
            SoNode* child = group->getChild(i);
            setNode(this->index(i, 0, index), child);
            // See ViewProviderDocumentObject::updateData
            QByteArray name(child->getName());
            name = QByteArray::fromPercentEncoding(name);
            this->setData(this->index(i, 1, index), QVariant(QString::fromUtf8(name)));
        }
    }
    // insert icon
}
SoCallbackAction::Response
SoIntersectionDetectionAction::PImpl::dragger(SoCallbackAction * action, const SoNode *)
{
  if ( !this->draggersenabled ) // dragger setting overrides setting for manipulators
    return SoCallbackAction::PRUNE;
#ifdef HAVE_MANIPULATORS
  if ( !this->manipsenabled ) {
    const SoPath * path = action->getCurPath();
    SoNode * tail = path->getTail();
    SoType type = tail->getTypeId();
    if ( type.isDerivedFrom(SoTransformManip::getClassTypeId()) ||
         type.isDerivedFrom(SoClipPlaneManip::getClassTypeId()) ||
         type.isDerivedFrom(SoDirectionalLightManip::getClassTypeId()) ||
         type.isDerivedFrom(SoPointLightManip::getClassTypeId()) ||
         type.isDerivedFrom(SoSpotLightManip::getClassTypeId()) )
      return SoCallbackAction::PRUNE;
  }
#endif // HAVE_MANIPULATORS
  return SoCallbackAction::CONTINUE;
}
Beispiel #4
0
/*!
  Returns the indexth node in path.
*/
SoNode *
SoLightPath::getNode(const int index) const
{
#if COIN_DEBUG && 1 // debug
  if (index < 0 || index >= this->indices.getLength()) {
    SoDebugError::postInfo("SoLightPath::getNode",
                           "index %d out of bounds", index);
  }
#endif // debug

  SoNode *node = this->headnode;
  for (int i = 1; i < index; i++) {
    int childidx = this->indices[i];
    SoChildList *children = node->getChildren();
    node = NULL;
    if (children == NULL || childidx < 0 || childidx >= children->getLength()) break;
    node = (*children)[childidx];
  }
  return node;
}
Beispiel #5
0
int
ModList::findToken(const SoPath *path)
{
    SoNode	*node = NULL;
    char	*str = NULL;
    int		id = -1;
    int		i;
    char	c;

    for (i = path->getLength() - 1; i >= 0; --i) {
        node = path->getNode(i);
        str = (char *)(node->getName().getString());
        if (strlen(str) && str[0] == theModListId) {
	    sscanf(str, "%c%d", &c, &id);
	    break;
	}
    }

    return id;
}
/**
 * Takes the name of the selected node and sets to de editor to display it.
 */
void NodeNameDelegate::setEditorData(QWidget *editor,
                                     const QModelIndex &index) const
{
    const SceneModel* model = static_cast< const SceneModel* >( index.model() );

    QString value = model->data(index, Qt::DisplayRole).toString();

    QLineEdit  *textEdit = static_cast<QLineEdit *>(editor);

    SoNode* coinNode = model->NodeFromIndex( index )->GetNode();

    QString nodeName;
    if ( coinNode->getName() == SbName() )
        nodeName = QString( coinNode->getTypeId().getName().getString() );
    else
        nodeName = QString( coinNode->getName().getString() );

    textEdit->setText( nodeName );

}
Beispiel #7
0
/*!
  Set the node which is top of the scene graph we're managing.  The \a
  sceneroot node reference count will be increased by 1, and any
  previously set scene graph top node will have it's reference count
  decreased by 1.

  \sa getSceneGraph()
*/
void
SoSceneManager::setSceneGraph(SoNode * const sceneroot)
{
  // Don't unref() until after we've set up the new root, in case the
  // old root == the new sceneroot. (Just to be that bit more robust.)
  SoNode * oldroot = PRIVATE(this)->scene;
  
  PRIVATE(this)->scene = sceneroot;

  PRIVATE(this)->rendermanager->setSceneGraph(sceneroot);
  PRIVATE(this)->eventmanager->setSceneGraph(sceneroot);

  if (PRIVATE(this)->scene) {
    PRIVATE(this)->scene->ref();
    this->setCamera(PRIVATE(this)->searchForCamera(PRIVATE(this)->scene));
  } else {
    this->setCamera(NULL);
  }
  
  if (oldroot) oldroot->unref();
}
Beispiel #8
0
void
SoGuiTranslation::doAction(SoAction * action)
{
  // SoDebugError::postInfo("SoGuiTranslation::doAction", "invoked by %s", action->getTypeId().getName().getString());
  int i;
  SoGuiPane * pane = NULL;
  const SoFullPath * path = (const SoFullPath *) action->getCurPath();
  for ( i = path->getLength() - 1; (i >= 0) && (pane == NULL); i-- ) {
    SoNode * node = path->getNode(i);
    assert(node);
    if ( node->isOfType(SoGuiPane::getClassTypeId()) ) pane = (SoGuiPane *) node;
  }
  if ( pane == NULL ) {
    SoDebugError::postInfo("SoGuiTranslation::doAction", "SoGuiTranslation only works below an SoGuiPane node");
    return;
  }
  SoModelMatrixElement::translateBy(action->getState(), this,
                                    this->translation.getValue());

//  pane->moveBy(action->getState(), this->translation.getValue());
}
SoNode * InventorViewer::getIntStr(const std::string& sscanfStr, const SoPath * path, std::string& extStr, int& extNum, int& pathIdx)
{
    if (path->getLength()==0) return NULL;
    for (int i = path->getLength() - 1; i >= 0;  --i)
    {
        SoNode * n = path->getNode(i);
        std::string name = n->getName().getString();
        
        //ROS_INFO("Path[%i]: %s, type %s",i,name.c_str(),n->getTypeId().getName().getString());

        char ln[1000];
        int num;
        if (sscanf(name.c_str(), sscanfStr.c_str(), &num, ln) < 2) continue;
        // ROS_INFO("num: %i rest: %s\n",num,ln);
        extStr = ln; //urdf2inventor::helpers::getFilename(ln); // take only the name after the last '/'
        extNum = num;
        pathIdx = i;
        return n;
    }
    return NULL;
}
void
SoBoxSelectionRenderAction::apply(SoPath * path)
{
    SoGLRenderAction::apply(path);
    SoNode* node = path->getTail();
    if (node && node->getTypeId() == SoFCSelection::getClassTypeId()) {
        SoFCSelection * selection = (SoFCSelection *) node;

        // This happens when dehighlighting the current shape
        if (PRIVATE(this)->highlightPath == path) {
            PRIVATE(this)->highlightPath->unref();
            PRIVATE(this)->highlightPath = 0;
            // FIXME: Doing a redraw to remove the shown bounding box causes
            // some problems when moving the mouse from one shape to another
            // because this will destroy the box immediately
            selection->touch(); // force a redraw when dehighlighting
        }
        else if (selection->isHighlighted() &&
                 selection->selected.getValue() == SoFCSelection::NOTSELECTED &&
                 selection->style.getValue() == SoFCSelection::BOX) {
            PRIVATE(this)->basecolor->rgb.setValue(selection->colorHighlight.getValue());

            if (PRIVATE(this)->selectsearch == NULL) {
              PRIVATE(this)->selectsearch = new SoSearchAction;
            }
            PRIVATE(this)->selectsearch->setType(SoShape::getClassTypeId());
            PRIVATE(this)->selectsearch->setInterest(SoSearchAction::FIRST);
            PRIVATE(this)->selectsearch->apply(selection);
            SoPath* shapepath = PRIVATE(this)->selectsearch->getPath();
            if (shapepath) {
                SoPathList list;
                list.append(shapepath);
                PRIVATE(this)->highlightPath = path;
                PRIVATE(this)->highlightPath->ref();
                this->drawBoxes(path, &list);
            }
            PRIVATE(this)->selectsearch->reset();
        }
    }
}
osgDB::ReaderWriter::WriteResult
ReaderWriterIV::writeNode(const osg::Node& node, const std::string& fileName,
                          const osgDB::ReaderWriter::Options* /*options*/) const
{
    // accept extension
    std::string ext = osgDB::getLowerCaseFileExtension(fileName);
    if (!acceptsExtension(ext)) return WriteResult::FILE_NOT_HANDLED;
    bool useVRML1 = !isInventorExtension(osgDB::getFileExtension(fileName));

    OSG_NOTICE << "osgDB::ReaderWriterIV::writeNode() Writing file "
                             << fileName.data() << std::endl;

    // Convert OSG graph to Inventor graph
    ConvertToInventor osg2iv;
    osg2iv.setVRML1Conversion(useVRML1);
    (const_cast<osg::Node*>(&node))->accept(osg2iv);
    SoNode *ivRoot = osg2iv.getIvSceneGraph();
    if (ivRoot == NULL)
        return WriteResult::ERROR_IN_WRITING_FILE;
    ivRoot->ref();

    // Change prefix according to VRML spec:
    // Node names must not begin with a digit, and must not contain spaces or
    // control characters, single or double quote characters, backslashes, curly braces,
    // the sharp (#) character, the plus (+) character or the period character.
    if (useVRML1)
      SoBase::setInstancePrefix("_");

    // Write Inventor graph to file
    SoOutput out;
    out.setHeaderString((useVRML1) ? "#VRML V1.0 ascii" : "#Inventor V2.1 ascii");
    if (!out.openFile(fileName.c_str()))
        return WriteResult::ERROR_IN_WRITING_FILE;
    SoWriteAction wa(&out);
    wa.apply(ivRoot);
    ivRoot->unref();

    return WriteResult::FILE_SAVED;
}
Beispiel #12
0
/*!
  Make a duplicate of this node and return a pointer to the duplicate.

  If this node is a group node, children are also copied and we return
  a pointer to the root of a full copy of the subgraph rooted here.

  If \a copyconnections is \c TRUE, we also copy the connections to
  fields within this node (and ditto for any children and children's
  children etc).


  Note that this function has been made virtual in Coin, which is not
  the case in the original Open Inventor API. We may change this
  method back into being non-virtual again for major Coin versions
  after this, as it was made virtual more or less by mistake. So
  please don't write application code that depends on SoNode::copy()
  being virtual.

  The reason this method should not be virtual is because this is \e
  not the function the application programmer should override in
  extension nodes if she needs some special behavior during a copy
  operation (like copying the value of internal data not exposed as
  fields).

  For that purpose, override the copyContents() method. Your
  overridden copyContents() method should then \e both copy internal
  data aswell as calling the parent superclass' copyContents() method
  for automatically handling of fields and other common data.
*/
SoNode *
SoNode::copy(SbBool copyconnections) const
{
  // FIXME: "de-virtualize" this method for next major Coin release?
  // See method documentation above. 20011220 mortene.

  SoFieldContainer::initCopyDict();
  SoNode * cp = this->addToCopyDict();
  // ref() to make sure the copy is not destructed while copying
  cp->ref();
  // Call findCopy() to have copyContents() run only once.
#if COIN_DEBUG
  SoNode * cp2 = (SoNode *)SoFieldContainer::findCopy(this, copyconnections);
  assert(cp == cp2);
#else // COIN_DEBUG
  (void) SoFieldContainer::findCopy(this, copyconnections);
#endif
  SoFieldContainer::copyDone();
  // unrefNoDelete() so that we return a copy with reference count 0
  cp->unrefNoDelete();
  return cp;
}
Beispiel #13
0
SoNode *
SoUnknownNode::addToCopyDict() const
//
////////////////////////////////////////////////////////////////////////
{
    // If this node is already in the dictionary, nothing else to do
    SoNode *copy = (SoNode *) checkCopy(this);
    if (copy == NULL) {

	// Create and add a new instance to the dictionary
	copy = new SoUnknownNode;
	copy->ref();
	addCopy(this, copy);		// Adds a ref()
	copy->unrefNoDelete();

	// Recurse on children, if any
	for (int i = 0; i < hiddenChildren.getLength(); i++)
	    hiddenChildren[i]->addToCopyDict();
    }

    return copy;
}
Beispiel #14
0
void
SoUnknownNode::write(SoWriteAction *action)
//
////////////////////////////////////////////////////////////////////////
{
    int i;

    SbBool saveNotify = enableNotify(FALSE);

    // Remember alternateRep, if set:
    SoNode *alternateRep = NULL;

    if (hasChildren) {
	if (getNumChildren() != 0) {
	    alternateRep = getChild(0);
	    alternateRep->ref();
	}

	// Add hiddenChildren to regular child list temporarily:
	removeAllChildren();
	for (i = 0; i < hiddenChildren.getLength(); i++) {
	    addChild(hiddenChildren[i]);
	}
	// Now write:
	SoGroup::write(action);

	removeAllChildren();
    }
    else {
	SoNode::write(action);
    }

    if (alternateRep != NULL) {
	addChild(alternateRep);
	alternateRep->unref();
    }

    enableNotify(saveNotify);
}
Beispiel #15
0
void
SoDebug::writeField(SoField *field)
//
////////////////////////////////////////////////////////////////////////
{
    SoFieldContainer *fc = field->getContainer();

    SbName fieldName;
    fc->getFieldName(field, fieldName);
    printf("Field name is: %s\n", fieldName.getString());
    if (fc->isOfType(SoNode::getClassTypeId())) {
	printf("Field is part of node:\n");

	SoNode *node = (SoNode *)fc;
	node->ref();

	SoWriteAction	wa;
	wa.apply(node);

	node->unrefNoDelete();
    }
}
Beispiel #16
0
void SceneModel::setNode(QModelIndex index, SoNode* node)
{
    this->setData(index, QVariant(QString::fromLatin1(node->getTypeId().getName())));
    if (node->getTypeId().isDerivedFrom(SoGroup::getClassTypeId())) {
        SoGroup *group = static_cast<SoGroup*>(node);
        // insert SoGroup icon
        this->insertColumns(0,2,index);
        this->insertRows(0,group->getNumChildren(), index);
        for (int i=0; i<group->getNumChildren();i++) {
            SoNode* child = group->getChild(i);
            setNode(this->index(i, 0, index), child);

            QHash<SoNode*, QString>::iterator it = nodeNames.find(child);
            if (it != nodeNames.end()) {
                this->setData(this->index(i, 1, index), QVariant(it.value()));
            }
            else {
                this->setData(this->index(i, 1, index), QVariant(QString::fromLatin1(child->getName())));
            }
        }
    }
    // insert icon
}
Beispiel #17
0
// private convenience method
void
SoFCSelection::turnoffcurrent(SoAction * action)
{
#ifdef NO_FRONTBUFFER
    if (SoFCSelection::currenthighlight &&
        SoFCSelection::currenthighlight->getLength()) {
        SoNode * tail = SoFCSelection::currenthighlight->getTail();
        if (tail->isOfType(SoFCSelection::getClassTypeId())) {
            ((SoFCSelection*)tail)->highlighted = FALSE;
            ((SoFCSelection*)tail)->touch(); // force scene redraw
            if (action) ((SoFCSelection*)tail)->redrawHighlighted(action, FALSE);
        }
    }
    if (SoFCSelection::currenthighlight) {
        SoFCSelection::currenthighlight->unref();
        SoFCSelection::currenthighlight = NULL;
    }
#else
    if (currenthighlight == NULL)
        return;

    SoNode *tail = currenthighlight->getTail();
    if (tail->isOfType(SoFCSelection::getClassTypeId())) {

        // don't redraw if we already are in the middle of rendering
        // (processing events during render abort might cause this)
        SoState *state = action->getState();
        if (state && state->getDepth() == 1)
            ((SoFCSelection *)tail)->redrawHighlighted(action, FALSE);
    }
    else {
        // Just get rid of the path. It's no longer valid for redraw.
        currenthighlight->unref();
        currenthighlight = NULL;
    }
#endif
}
Beispiel #18
0
/*!
  Action method for SoWriteAction.

  Writes out a node object, and any connected nodes, engines etc, if
  necessary.
*/
void
SoNode::write(SoWriteAction * action)
{
  SoOutput * out = action->getOutput();

  SoNode * node = this;

  SoProtoInstance * proto = SoProtoInstance::findProtoInstance(this);
  if (proto) { node = proto; }

  if (out->getStage() == SoOutput::COUNT_REFS) {
    node->addWriteReference(out, FALSE);
  }
  else if (out->getStage() == SoOutput::WRITE) {
    if (node->writeHeader(out, FALSE, FALSE)) return;

    // check for special case where we actually have to write out an
    // SoEngineOutput "field". An engine output might be connected via
    // an IS reference in a PROTO, and we then need to write back this
    // IS reference when exporting the VRML file.
    SoProto * proto = out->getCurrentProto();
    if (proto && node->isOfType(SoNodeEngine::getClassTypeId())) {
      SoEngineOutputList l;
      const int num = ((SoNodeEngine*)node)->getOutputs(l);

      for (int i = 0; i < num; i++) {
        SbName name;
        if (((SoNodeEngine*)node)->getOutputName(l[i], name)) {
          SbName pname = proto->findISReference(node, name);
          if (pname.getLength()) {
            out->indent();
            out->write(name.getString());
            out->write(" IS ");
            out->write(pname.getString());
            out->write("\n");
          }
        }
      }
    }
    node->getFieldData()->write(out, node);
    node->writeFooter(out);
  }
  else assert(0 && "unknown stage");
}
Beispiel #19
0
// Store the \a newval node pointer in this field. If \a newval is not
// \c NULL, will add 1 to the reference count of the node.
void
SoSFNode::setValue(SoNode * newval)
{
  // Don't use getValue() to find oldptr, since this might trigger a
  // recursive evaluation call if the field is connected.
  SoNode * oldptr = this->value;
  if (oldptr == newval) return;

  if (oldptr) {
#ifdef COIN_INTERNAL_SOSFPATH
    SoNode * h = oldptr->getHead();
    // The path should be audited by us at all times. So don't use
    // SoSFPath to wrap SoTempPath or SoLightPath, for instance.
    assert(h==this->head && "Path head changed without notification!");
    if (h) {
      h->removeAuditor(this, SoNotRec::FIELD);
      h->unref();
    }
#endif // COIN_INTERNAL_SOSFPATH
    oldptr->removeAuditor(this, SoNotRec::FIELD);
    oldptr->unref();
  }

  if (newval) {
    newval->addAuditor(this, SoNotRec::FIELD);
    newval->ref();
#ifdef COIN_INTERNAL_SOSFPATH
    this->head = newval->getHead();
    if (this->head) {
      this->head->addAuditor(this, SoNotRec::FIELD);
      this->head->ref();
    }
#endif // COIN_INTERNAL_SOSFPATH
  }

  this->value = newval;
  this->valueChanged();
}
Beispiel #20
0
//////////////////////////////////////////////////////////////////////////////
//
//  beginTraversal - have the base class render the passed scene graph,
//  then render highlights for our selection node.
//
void
SoBoxHighlightRenderAction::apply(SoNode *renderRoot)
//
//////////////////////////////////////////////////////////////////////////////
{
    // Render the scene
    SoGLRenderAction::apply(renderRoot);
    
    // Render the highlight?
    if (! hlVisible) return;
    
    // Is our cached path still valid?
    if ((selPath == NULL) ||
	(selPath->getHead() != renderRoot) ||
	(! selPath->getTail()->isOfType(SoSelection::getClassTypeId()))) {

	// Find the selection node under the render root
	static SoSearchAction *sa1 = NULL;
	if (sa1 == NULL)
	    sa1 = new SoSearchAction;
	else
	    sa1->reset();
	sa1->setFind(SoSearchAction::TYPE);
	sa1->setInterest(SoSearchAction::FIRST);
	sa1->setType(SoSelection::getClassTypeId());
	sa1->apply(renderRoot);
	
	// Cache this path
	if (selPath != NULL)
	    selPath->unref();
	selPath = sa1->getPath();
	if (selPath != NULL) {
	    selPath = selPath->copy();
	    selPath->ref();
	}
    }
    
    if (selPath != NULL) {
	// Make sure something is selected
	SoSelection *sel = (SoSelection *) selPath->getTail();
	if (sel->getNumSelected() == 0) return;
	
	// Keep the length from the root to the selection
	// as an optimization so we can reuse this data
	int reusablePathLength = selPath->getLength();

	// For each selection path, create a new path rooted under our
	// localRoot
	for (int j = 0; j < sel->getNumSelected(); j++) {
	    // Continue the path down to the selected object.
	    // No need to deal with p[0] since that is the sel node.
	    SoFullPath *p = (SoFullPath *) sel->getPath(j);	    
	    SoNode *pathTail = p->getTail();

	    if ( pathTail->isOfType(SoBaseKit::getClassTypeId())) {
		// Find the last nodekit on the path.
		SoNode *kitTail = ((SoNodeKitPath *)p)->getTail();

		// Extend the selectionPath until it reaches this last kit.
		SoFullPath *fp = (SoFullPath *) p;
		int k = 0;
		do {
		    selPath->append(fp->getIndex(++k));
		} 
		while ( fp->getNode(k) != kitTail );
	    }
	    else {
		for (int k = 1; k < p->getLength(); k++)
		    selPath->append(p->getIndex(k));
	    }
    
	    // Find the camera used to render the selected object and
	    // insert it into the highlight graph as the first child
	    SoNode *camera;

	    static SoSearchAction *sa2 = NULL;
	    if (sa2 == NULL)
		sa2 = new SoSearchAction;
	    else
		sa2->reset();

	    sa2->setFind(SoSearchAction::TYPE);
	    sa2->setInterest(SoSearchAction::LAST);
	    sa2->setType(SoCamera::getClassTypeId());
	    sa2->apply(selPath);
	    camera =(sa2->getPath() == NULL ? NULL : sa2->getPath()->getTail());
	    if (camera != NULL)
		localRoot->insertChild(camera, 0);
	    
	    // Get the bounding box of the object and update the
	    // local highlight graph
	    updateBbox(selPath);
	    
	    // Make sure the box has some size
	    if ((cube->width.getValue() == 0) &&
		(cube->height.getValue() == 0) &&
		(cube->depth.getValue() == 0)) {
#ifdef DEBUG
		SoDebugError::postWarning("SoBoxHighlightRenderAction::apply",
			"selected object has no bounding box - no highlight rendered");
#endif		    
	    }
	    else {
		// Render the highlight
		SoGLRenderAction::apply(localRoot);
	    }
	    	    
	    // Restore selPath for reuse
	    selPath->truncate(reusablePathLength);

	    // Remove the camera for the next path
	    if (camera != NULL)
		localRoot->removeChild(0);
	}
    }
}    
Beispiel #21
0
// call this callback either from your application level selection CB
// or use it as selection CB
void
InvPlaneMover::selectionCB(void *me, SoPath *sp)
{
    InvPlaneMover *mee = static_cast<InvPlaneMover *>(me);

    // get the label next to the geometry = tail
    int len = sp->getLength();
    char objNme[20];
    int showFlg = 0;
    if (len > 2)
    {
        SoNode *grp = sp->getNode(len - 2);
        if (grp->getTypeId() == SoGroup::getClassTypeId())
        {
            int gLen = ((SoGroup *)grp)->getNumChildren();
            int i;
            for (i = 0; i < gLen; ++i)
            {
                SoNode *lbl = ((SoGroup *)grp)->getChild(i);
                if (lbl->getTypeId() == SoLabel::getClassTypeId())
                {
                    char *fbs = (char *)((SoLabel *)lbl)->label.getValue().getString();
                    size_t l = strlen(fbs);
                    // make sure that feedbackInfo_ is correctly allocated
                    if (mee->feedbackInfo_)
                    {
                        delete[] mee -> feedbackInfo_;
                    }
                    char *tmpStr = new char[l + 1];
                    strcpy(tmpStr, fbs);
                    // extract the object name (for feedback-info attached to CuttingSurface)
                    if (l > 1)
                    {
                        strncpy(objNme, &fbs[1], 14);
                        if (strncmp(objNme, "CuttingSurface", 14) == 0)
                            showFlg = 1;
                        // separate feedback-attribute and ignore-attribute
                        // separator is <IGNORE>
                        char *tok = strtok(tmpStr, "<IGNORE>");
                        if (tok)
                        {
                            mee->feedbackInfo_ = new char[1 + strlen(tok)];
                            strcpy(mee->feedbackInfo_, tok);
                            tok = strtok(NULL, "<IGNORE>");
                            if (tok)
                            {
                                float dum;
                                int idum;
                                int retval;
                                retval = sscanf(tok, "%f%f%f%f%d", &(mee->planeNormal_[0]), &(mee->planeNormal_[1]), &(mee->planeNormal_[2]), &dum, &idum);
                                if (retval != 5)
                                {
                                    std::cerr << "InvPlaneMover::selectionCB: sscanf failed" << std::endl;
                                    return;
                                }
                                fprintf(stderr, "planeNormal=(%f %f %f)\n",
                                        mee->planeNormal_[0],
                                        mee->planeNormal_[1],
                                        mee->planeNormal_[2]);
                                mee->setPosition(mee->distOffset_);
                            }
                        }
                    }
                    delete[] tmpStr;
                }
            }
        }
    }
    // the handle is shown if the feedback-attribute contains "CuttingSurface"
    // ..and if it is not shown at all
    if ((!mee->show_) && showFlg)
    {
        mee->show();
    }
}
void ViewProviderDragger::unsetEditViewer(Gui::View3DInventorViewer* viewer)
{
  SoNode *child = static_cast<SoFCUnifiedSelection*>(viewer->getSceneGraph())->getChild(0);
  if (child && child->isOfType(SoPickStyle::getClassTypeId()))
    static_cast<SoFCUnifiedSelection*>(viewer->getSceneGraph())->removeChild(child);
}
Beispiel #23
0
//////////////////////////////////////////////////////////////////////////////
//
//  beginTraversal - have the base class render the passed scene graph,
//  then render highlights for our selection node.
//
void
SoLineHighlightRenderAction::apply(SoNode *node)
//
//////////////////////////////////////////////////////////////////////////////
{
    // Render the scene
    SoGLRenderAction::apply(node);

    // Render the highlight?
    if (! hlVisible) return;

    // Add the rendering localRoot beneath our local scene graph localRoot
    // so that we can find a path from localRoot to the selection node 
    // which is under the render root.
    localRoot->addChild(node);
    
    // Find the selection node under the local root
    static SoSearchAction *sa = NULL;
    if (sa == NULL)
	sa = new SoSearchAction;
    else
	sa->reset();
    sa->setFind(SoSearchAction::TYPE);
    sa->setInterest(SoSearchAction::FIRST);
    sa->setType(SoSelection::getClassTypeId());
    sa->apply(localRoot);
    
    SoPath *hlPath = sa->getPath();
    if (hlPath != NULL) {
	hlPath = hlPath->copy();
	hlPath->ref();
	
	// Make sure something is selected
	SoSelection *sel = (SoSelection *) hlPath->getTail();
	if (sel->getNumSelected() > 0) {
	    // Keep the length from the root to the selection
	    // as an optimization so we can reuse this data
	    int reusablePathLength = hlPath->getLength();
    
	    // For each selection path, create a new path rooted under our localRoot
	    for (int j = 0; j < sel->getNumSelected(); j++) {
		// Continue the path down to the selected object.
		// No need to deal with p[0] since that is the sel node.
		SoFullPath *p = (SoFullPath *) sel->getPath(j);
		SoNode *pathTail = p->getTail();

		if ( pathTail->isOfType(SoBaseKit::getClassTypeId())) {
		    // Find the last nodekit on the path.
		    SoNode *kitTail = ((SoNodeKitPath *)p)->getTail();

		    // Extend the selectionPath until it reaches this last kit.
		    SoFullPath *fp = (SoFullPath *) p;
		    int k = 0;
		    do {
			hlPath->append(fp->getIndex(++k));
		    } 
		    while ( fp->getNode(k) != kitTail );
		}
		else {
		    for (int k = 1; k < p->getLength(); k++)
			hlPath->append(p->getIndex(k));
		}
	
		// Render the shape with the local draw style to make the highlight
		SoGLRenderAction::apply(hlPath);
			
		// Restore hlPath for reuse
		hlPath->truncate(reusablePathLength);
	    }
	}
	
	hlPath->unref();
    }
    
    // Remove the rendering localRoot from our local scene graph
    localRoot->removeChild(node);
}    
Beispiel #24
0
// doc from parent
void
SoFCSelection::handleEvent(SoHandleEventAction * action)
{
    static char buf[513];
    HighlightModes mymode = (HighlightModes) this->highlightMode.getValue();
    const SoEvent * event = action->getEvent();
#ifdef NO_FRONTBUFFER
    // mouse move events for preselection
    if (event->isOfType(SoLocation2Event::getClassTypeId())) {
        // NOTE: If preselection is off then we do not check for a picked point because otherwise this search may slow
        // down extremely the system on really big data sets. In this case we just check for a picked point if the data
        // set has been selected.
        if (mymode == AUTO || mymode == ON) {
            const SoPickedPoint * pp = this->getPickedPoint(action);
            if (pp && pp->getPath()->containsPath(action->getCurPath())) {
                if (!highlighted) {
                    if (Gui::Selection().setPreselect(documentName.getValue().getString()
                                           ,objectName.getValue().getString()
                                           ,subElementName.getValue().getString()
                                           ,pp->getPoint()[0]
                                           ,pp->getPoint()[1]
                                           ,pp->getPoint()[2])){
                        SoFCSelection::turnoffcurrent(action);
                        SoFCSelection::currenthighlight = (SoFullPath*)action->getCurPath()->copy();
                        SoFCSelection::currenthighlight->ref();
                        highlighted = TRUE;
                        this->touch(); // force scene redraw
                        this->redrawHighlighted(action, TRUE);
                    }
                }
                
                snprintf(buf,512,"Preselected: %s.%s.%s (%f,%f,%f)",documentName.getValue().getString()
                                           ,objectName.getValue().getString()
                                           ,subElementName.getValue().getString()
                                           ,pp->getPoint()[0]
                                           ,pp->getPoint()[1]
                                           ,pp->getPoint()[2]);

                getMainWindow()->showMessage(QString::fromAscii(buf),3000);
            }
            else { // picked point
                if (highlighted) {
                    if (mymode == AUTO)
                        SoFCSelection::turnoffcurrent(action);
                    //FIXME: I think we should set 'highlighted' to false whenever no point is picked
                    //else
                    highlighted = FALSE;
                    Gui::Selection().rmvPreselect();
                }
            }
        }
    } // key press events
    else if (event->isOfType(SoKeyboardEvent ::getClassTypeId())) {
        SoKeyboardEvent  * const e = (SoKeyboardEvent  *) event;
        if (SoKeyboardEvent::isKeyPressEvent(e,SoKeyboardEvent::LEFT_SHIFT)     ||
            SoKeyboardEvent::isKeyPressEvent(e,SoKeyboardEvent::RIGHT_SHIFT)     )
            bShift = true;
        if (SoKeyboardEvent::isKeyReleaseEvent(e,SoKeyboardEvent::LEFT_SHIFT)   ||
            SoKeyboardEvent::isKeyReleaseEvent(e,SoKeyboardEvent::RIGHT_SHIFT)   )
            bShift = false;
        if (SoKeyboardEvent::isKeyPressEvent(e,SoKeyboardEvent::LEFT_CONTROL)   ||
            SoKeyboardEvent::isKeyPressEvent(e,SoKeyboardEvent::RIGHT_CONTROL)   )
            bCtrl = true;
        if (SoKeyboardEvent::isKeyReleaseEvent(e,SoKeyboardEvent::LEFT_CONTROL) ||
            SoKeyboardEvent::isKeyReleaseEvent(e,SoKeyboardEvent::RIGHT_CONTROL) )
            bCtrl = false;
    } // mouse press events for (de)selection
    else if (event->isOfType(SoMouseButtonEvent::getClassTypeId())) {
        SoMouseButtonEvent * const e = (SoMouseButtonEvent *) event;
        if (SoMouseButtonEvent::isButtonReleaseEvent(e,SoMouseButtonEvent::BUTTON1)) {
            //FIXME: Shouldn't we remove the preselection for newly selected objects?
            //       Otherwise the tree signals that an object is preselected even though it is hidden. (Werner)
            const SoPickedPoint * pp = this->getPickedPoint(action);
            if (pp && pp->getPath()->containsPath(action->getCurPath())) {
                if (bCtrl) {
                    if (Gui::Selection().isSelected(documentName.getValue().getString()
                                         ,objectName.getValue().getString()
                                         ,subElementName.getValue().getString())) {
                        Gui::Selection().rmvSelection(documentName.getValue().getString()
                                          ,objectName.getValue().getString()
                                          ,subElementName.getValue().getString());
                    } else {
                        Gui::Selection().addSelection(documentName.getValue().getString()
                                          ,objectName.getValue().getString()
                                          ,subElementName.getValue().getString()
                                          ,pp->getPoint()[0]
                                          ,pp->getPoint()[1]
                                          ,pp->getPoint()[2]);

                        if (mymode == OFF) {
                            snprintf(buf,512,"Selected: %s.%s.%s (%f,%f,%f)",documentName.getValue().getString()
                                                       ,objectName.getValue().getString()
                                                       ,subElementName.getValue().getString()
                                                       ,pp->getPoint()[0]
                                                       ,pp->getPoint()[1]
                                                       ,pp->getPoint()[2]);

                            getMainWindow()->showMessage(QString::fromAscii(buf),3000);
                        }
                    }
                }
                else { // Ctrl
                    if (!Gui::Selection().isSelected(documentName.getValue().getString()
                                         ,objectName.getValue().getString()
                                         ,subElementName.getValue().getString())) {
                        Gui::Selection().clearSelection(documentName.getValue().getString());
                        Gui::Selection().addSelection(documentName.getValue().getString()
                                              ,objectName.getValue().getString()
                                              ,subElementName.getValue().getString()
                                              ,pp->getPoint()[0]
                                              ,pp->getPoint()[1]
                                              ,pp->getPoint()[2]);
                    }
                    else {
                        Gui::Selection().clearSelection(documentName.getValue().getString());
                        Gui::Selection().addSelection(documentName.getValue().getString()
                                              ,objectName.getValue().getString()
                                              ,0
                                              ,pp->getPoint()[0]
                                              ,pp->getPoint()[1]
                                              ,pp->getPoint()[2]);
                    }

                    if (mymode == OFF) {
                        snprintf(buf,512,"Selected: %s.%s.%s (%f,%f,%f)",documentName.getValue().getString()
                                                   ,objectName.getValue().getString()
                                                   ,subElementName.getValue().getString()
                                                   ,pp->getPoint()[0]
                                                   ,pp->getPoint()[1]
                                                   ,pp->getPoint()[2]);

                        getMainWindow()->showMessage(QString::fromAscii(buf),3000);
                    }
                }

                action->setHandled(); 
            } // picked point
        } // mouse release
    }

    inherited::handleEvent(action);
#else
    // If we don't need to pick for locate highlighting,
    // then just behave as separator and return.
    // NOTE: we still have to pick for ON even though we don't have
    // to re-render, because the app needs to be notified as the mouse
    // goes over locate highlight nodes.
    //if (highlightMode.getValue() == OFF) {
    //    inherited::handleEvent( action );
    //    return;
    //}

    
    //
    // If this is a mouseMotion event, then check for locate highlighting
    //
    if (event->isOfType(SoLocation2Event::getClassTypeId())) {
        // check to see if the mouse is over our geometry...
        SbBool underTheMouse = FALSE;
        const SoPickedPoint * pp = this->getPickedPoint(action);
        SoFullPath *pPath = (pp != NULL) ? (SoFullPath *) pp->getPath() : NULL;
        if (pPath && pPath->containsPath(action->getCurPath())) {
            // Make sure I'm the lowest LocHL in the pick path!
            underTheMouse = TRUE;
            for (int i = 0; i < pPath->getLength(); i++) {
                SoNode *node = pPath->getNodeFromTail(i);
                if (node->isOfType(SoFCSelection::getClassTypeId())) {
                    if (node != this)
                    underTheMouse = FALSE;
                    break; // found the lowest LocHL - look no further
                }
            }
        }
        // Am I currently highlighted?
        if (isHighlighted(action)) {
            if (! underTheMouse) {
                // re-draw the object with it's normal color
                //if(mymode != OFF)
                redrawHighlighted(action, FALSE);
                Gui::Selection().rmvPreselect();
            }
            else {
                action->setHandled();
                //const SoPickedPoint * pp = action->getPickedPoint();
                Gui::Selection().setPreselectCoord(pp->getPoint()[0]
                                                 ,pp->getPoint()[1]
                                                 ,pp->getPoint()[2]);
            }
        }
        // Else I am not currently highlighted
        else {
            // If under the mouse, then highlight!
            if (underTheMouse) {
                // draw this object highlighted
                if (mymode != OFF)
                    redrawHighlighted(action, TRUE);
                //const SoPickedPoint * pp = action->getPickedPoint();
                Gui::Selection().setPreselect(documentName.getValue().getString()
                                                 ,objectName.getValue().getString()
                                                 ,subElementName.getValue().getString()
                                                 ,pp->getPoint()[0]
                                                 ,pp->getPoint()[1]
                                                 ,pp->getPoint()[2]);
            }
        }
        //if(selected == SELECTED){
        //    redrawHighlighted(action, TRUE);
        //}
        //if(selectionCleared ){
        //    redrawHighlighted(action, FALSE);
        //    selectionCleared = false;
        //}
    }
    // key press events
    else if (event->isOfType(SoKeyboardEvent ::getClassTypeId())) {
        SoKeyboardEvent  * const e = (SoKeyboardEvent  *) event;
        if (SoKeyboardEvent::isKeyPressEvent(e,SoKeyboardEvent::LEFT_SHIFT)     ||
            SoKeyboardEvent::isKeyPressEvent(e,SoKeyboardEvent::RIGHT_SHIFT)     )
            bShift = true;
        if (SoKeyboardEvent::isKeyReleaseEvent(e,SoKeyboardEvent::LEFT_SHIFT)   ||
            SoKeyboardEvent::isKeyReleaseEvent(e,SoKeyboardEvent::RIGHT_SHIFT)   )
            bShift = false;
        if (SoKeyboardEvent::isKeyPressEvent(e,SoKeyboardEvent::LEFT_CONTROL)   ||
            SoKeyboardEvent::isKeyPressEvent(e,SoKeyboardEvent::RIGHT_CONTROL)   )
            bCtrl = true;
        if (SoKeyboardEvent::isKeyReleaseEvent(e,SoKeyboardEvent::LEFT_CONTROL) ||
            SoKeyboardEvent::isKeyReleaseEvent(e,SoKeyboardEvent::RIGHT_CONTROL) )
            bCtrl = false;
    }
    // mouse press events for (de)selection (only if selection is enabled on this node)
    else if (event->isOfType(SoMouseButtonEvent::getClassTypeId()) && 
             selectionMode.getValue() == SoFCSelection::SEL_ON) {
        SoMouseButtonEvent * const e = (SoMouseButtonEvent *) event;
        if (SoMouseButtonEvent::isButtonReleaseEvent(e,SoMouseButtonEvent::BUTTON1)) {
            //FIXME: Shouldn't we remove the preselection for newly selected objects?
            //       Otherwise the tree signals that an object is preselected even though it is hidden. (Werner)
            const SoPickedPoint * pp = this->getPickedPoint(action);
            if (pp && pp->getPath()->containsPath(action->getCurPath())) {
                if (bCtrl) {
                    if (Gui::Selection().isSelected(documentName.getValue().getString()
                                         ,objectName.getValue().getString()
                                         ,subElementName.getValue().getString())) {
                        Gui::Selection().rmvSelection(documentName.getValue().getString()
                                          ,objectName.getValue().getString()
                                          ,subElementName.getValue().getString());
                    }
                    else {
                        Gui::Selection().addSelection(documentName.getValue().getString()
                                          ,objectName.getValue().getString()
                                          ,subElementName.getValue().getString()
                                          ,pp->getPoint()[0]
                                          ,pp->getPoint()[1]
                                          ,pp->getPoint()[2]);

                        if (mymode == OFF) {
                            snprintf(buf,512,"Selected: %s.%s.%s (%f,%f,%f)",documentName.getValue().getString()
                                                       ,objectName.getValue().getString()
                                                       ,subElementName.getValue().getString()
                                                       ,pp->getPoint()[0]
                                                       ,pp->getPoint()[1]
                                                       ,pp->getPoint()[2]);

                            getMainWindow()->statusBar()->showMessage(QString::fromAscii(buf),3000);
                        }
                    }
                }
                else { // Ctrl
                    if (!Gui::Selection().isSelected(documentName.getValue().getString()
                                         ,objectName.getValue().getString()
                                         ,subElementName.getValue().getString())) {
                        Gui::Selection().clearSelection(documentName.getValue().getString());
                        Gui::Selection().addSelection(documentName.getValue().getString()
                                              ,objectName.getValue().getString()
                                              ,subElementName.getValue().getString()
                                              ,pp->getPoint()[0]
                                              ,pp->getPoint()[1]
                                              ,pp->getPoint()[2]);
                    }
                    else {
                        Gui::Selection().clearSelection(documentName.getValue().getString());
                        Gui::Selection().addSelection(documentName.getValue().getString()
                                              ,objectName.getValue().getString()
                                              ,0
                                              ,pp->getPoint()[0]
                                              ,pp->getPoint()[1]
                                              ,pp->getPoint()[2]);
                    }
 
                    if (mymode == OFF) {
                        snprintf(buf,512,"Selected: %s.%s.%s (%f,%f,%f)",documentName.getValue().getString()
                                                   ,objectName.getValue().getString()
                                                   ,subElementName.getValue().getString()
                                                   ,pp->getPoint()[0]
                                                   ,pp->getPoint()[1]
                                                   ,pp->getPoint()[2]);

                        getMainWindow()->statusBar()->showMessage(QString::fromAscii(buf),3000);
                    }
                }

                action->setHandled(); 
            } // picked point
        } // mouse release
    }

    // Let the base class traverse the children.
    if (action->getGrabber() != this)
        inherited::handleEvent(action);
#endif
}
Beispiel #25
0
void SoVtkAssembly::updateChildren()
{
	for (int i = 0; i < SoGroup::getNumChildren(); i++)
	{
		SoNode *child = SoGroup::getChild(i);
	
		if (child->isOfType(SoVtkAssembly::getClassTypeId()))
		{
			// assembly
			SoVtkAssembly *assembly = (SoVtkAssembly *) child;
			assembly->updateChildren();
		}
	}

	vtkProp3DCollection *parts = mAssembly->GetParts();

	for (int i = 0; i < parts->GetNumberOfItems(); i++)
	{
		mAssembly->RemovePart(vtkProp3D::SafeDownCast(parts->GetItemAsObject(i)));
	}

	for (int i = 0; i < SoGroup::getNumChildren(); i++)
	{
		SoNode *child = SoGroup::getChild(i);

		if (child->isOfType(SoVtkActor::getClassTypeId()))
		{
			// actor
			SoVtkActor *actor = (SoVtkActor *) child;
			mAssembly->AddPart(actor->getActor());
		}

		if (child->isOfType(SoVtkLODActor::getClassTypeId()))
		{
			// actor
			SoVtkLODActor *actor = (SoVtkLODActor *) child;
			mAssembly->AddPart(actor->getLODActor());
		}

		if (child->isOfType(SoVtkActor2D::getClassTypeId()))
		{
			// actor 2D
			SoVtkActor2D *actor = (SoVtkActor2D *) child;
			mAssembly->AddPart(vtkProp3D::SafeDownCast(actor->getActor2D()));
		}

		if (child->isOfType(SoVtkImageActor::getClassTypeId()))
		{
			// image actor
			SoVtkImageActor *actor = (SoVtkImageActor *) child;
			mAssembly->AddPart(actor->getImageActor());
		}

		if (child->isOfType(SoVtkVolume::getClassTypeId()))
		{
			// volume
			SoVtkVolume *vol = (SoVtkVolume *) child;
			mAssembly->AddPart(vol->getVolume());
		}
		
		if (child->isOfType(SoVtkAssembly::getClassTypeId()))
		{
			// assembly
			SoVtkAssembly *assembly = (SoVtkAssembly *) child;
			mAssembly->AddPart(vtkAssembly::SafeDownCast(assembly->getAssembly()));
		}
	}
}
Beispiel #26
0
void CmdRaytracingWriteCamera::activated(int iMsg)
{
    const char* ppReturn=0;
    getGuiApplication()->sendMsgToActiveView("GetCamera",&ppReturn);
    if (ppReturn) {
        std::string str(ppReturn);
        if (str.find("PerspectiveCamera") == std::string::npos) {
            int ret = QMessageBox::warning(Gui::getMainWindow(), 
                qApp->translate("CmdRaytracingWriteView","No perspective camera"),
                qApp->translate("CmdRaytracingWriteView","The current view camera is not perspective"
                                " and thus the result of the povray image later might look different to"
                                " what you expect.\nDo you want to continue?"),
                QMessageBox::Yes|QMessageBox::No);
            if (ret != QMessageBox::Yes)
                return;
        }
    }

    SoInput in;
    in.setBuffer((void*)ppReturn,std::strlen(ppReturn));

    SoNode* rootNode;
    SoDB::read(&in,rootNode);

    if (!rootNode || !rootNode->getTypeId().isDerivedFrom(SoCamera::getClassTypeId()))
        throw Base::Exception("CmdRaytracingWriteCamera::activated(): Could not read "
                              "camera information from ASCII stream....\n");

    // root-node returned from SoDB::readAll() has initial zero
    // ref-count, so reference it before we start using it to
    // avoid premature destruction.
    SoCamera * Cam = static_cast<SoCamera*>(rootNode);
    Cam->ref();

    SbRotation camrot = Cam->orientation.getValue();

    SbVec3f upvec(0, 1, 0); // init to default up vector
    camrot.multVec(upvec, upvec);

    SbVec3f lookat(0, 0, -1); // init to default view direction vector
    camrot.multVec(lookat, lookat);

    SbVec3f pos = Cam->position.getValue();
    float Dist = Cam->focalDistance.getValue();

    QStringList filter;
    filter << QObject::tr("Povray(*.pov)");
    filter << QObject::tr("All Files (*.*)");
    QString fn = Gui::FileDialog::getSaveFileName(Gui::getMainWindow(), QObject::tr("Export page"), QString(), filter.join(QLatin1String(";;")));
    if (fn.isEmpty()) 
        return;
    std::string cFullName = (const char*)fn.toUtf8();

    // building up the python string
    std::stringstream out;
    out << "Raytracing.writeCameraFile(\"" << strToPython(cFullName) << "\"," 
        << "(" << pos.getValue()[0]    <<"," << pos.getValue()[1]    <<"," << pos.getValue()[2]    <<")," 
        << "(" << lookat.getValue()[0] <<"," << lookat.getValue()[1] <<"," << lookat.getValue()[2] <<")," ;
    lookat *= Dist;
    lookat += pos;
    out << "(" << lookat.getValue()[0] <<"," << lookat.getValue()[1] <<"," << lookat.getValue()[2] <<")," 
        << "(" << upvec.getValue()[0]  <<"," << upvec.getValue()[1]  <<"," << upvec.getValue()[2]  <<") )" ;

    doCommand(Doc,"import Raytracing");
    doCommand(Gui,out.str().c_str());


    // Bring ref-count of root-node back to zero to cause the
    // destruction of the camera.
    Cam->unref();
}
Beispiel #27
0
/*!
  Empty method in Coin. Can be used by subclasses to be told
  when status change.
*/
void
SoFCSelection::redrawHighlighted(SoAction *  action , SbBool  doHighlight )
{
    //Base::Console().Log("SoFCSelection::redrawHighlighted() (%p) doHigh=%d \n",this,doHighlight?1:0);

#ifdef NO_FRONTBUFFER
#else
    // If we are about to highlight, and there is something else highlighted,
    // that something else needs to unhighlight.
    if (doHighlight && currenthighlight != NULL &&
        !(*((SoFullPath *)action->getCurPath()) == *currenthighlight)) {

        SoNode *tail = currenthighlight->getTail();
        if (tail->isOfType( SoFCSelection::getClassTypeId()))
            ((SoFCSelection *)tail)->redrawHighlighted(action, FALSE);
        else {
            // Just get rid of the path. It's no longer valid for redraw.
            currenthighlight->unref();
            currenthighlight = NULL;
        }
    }

    SoPath *pathToRender;
    // save the path to ourself for later de-highlight
    if (doHighlight) {
        if (currenthighlight != NULL)
            currenthighlight->unref();
        currenthighlight = (SoFullPath *) action->getCurPath()->copy();
        currenthighlight->ref();

        // We will be rendering this new path to highlight it
        pathToRender = currenthighlight;
        pathToRender->ref();
    }
    // delete our path if we are no longer highlighted
    else {
        if (currenthighlight) {
            // We will be rendering this old path to unhighlight it
            pathToRender = currenthighlight;
            pathToRender->ref();

            currenthighlight->unref();
            currenthighlight = NULL;
        }
    }

    // If highlighting is forced on for this node, we don't need this special render.
    if (highlightMode.getValue() != AUTO) {
        pathToRender->unref();
        return;
    }

    SoState *state = action->getState();

    //void* window;
    //void* context;
    //void *display;
    QGLWidget* window;
    SoGLRenderAction *glAction;
    //SoWindowElement::get(state, window, context, display, glAction);
    SoGLWidgetElement::get(state, window);
    SoGLRenderActionElement::get(state, glAction);

    // If we don't have a current window, then simply return...
    if (window == 0 /*|| context == NULL || display == NULL*/ || glAction == NULL)
        return;

    window->makeCurrent();
#ifndef WIN32
    // set the current window
    //glXMakeCurrent(display, window, context);
#endif
    // render into the front buffer (save the current buffering type)
    GLint whichBuffer;
    glGetIntegerv(GL_DRAW_BUFFER, &whichBuffer);
    if (whichBuffer != GL_FRONT)
        glDrawBuffer(GL_FRONT);

    highlighted = TRUE;
    glAction->apply(pathToRender);
    highlighted = FALSE;

    // restore the buffering type
    if (whichBuffer != GL_FRONT)
        glDrawBuffer((GLenum)whichBuffer);
    glFlush();

    pathToRender->unref();
#endif
}
Beispiel #28
0
void
InvAnnoManager::selectionCB(void *me, SoPath *selectedObject)
{
    InvAnnoManager *mee = static_cast<InvAnnoManager *>(me);

    mee->initCheck();

    if (!mee->isActive_)
        return;

    int isAnnoFlg = 0;

    int len = selectedObject->getLength();
    int ii;
    char *selObjNm;

    SoNode *obj = NULL;
    int objIndex;

    int mode = mee->mode_;

    // we find out if the selected obj is a InvAnnotationFlag
    // and obtain its index from the name of the (sub)-toplevel
    // separator node
    for (ii = 0; ii < len; ii++)
    {
        obj = selectedObject->getNode(ii);
        char *tmp = (char *)obj->getName().getString();
        selObjNm = new char[1 + strlen(tmp)];
        char *chNum = new char[1 + strlen(tmp)];
        strcpy(selObjNm, tmp);
        if (strncmp(selObjNm, "ANNOTATION", 10) == 0)
        {
            strcpy(chNum, &selObjNm[11]);
            int ret = sscanf(chNum, "%d", &objIndex);
            if (ret != 1)
            {
                fprintf(stderr, "InvAnnoManager::selectionCB: sscanf failed\n");
            }
            isAnnoFlg = 1;
            break;
        }
    }

    // we have got an InvAnnoFlag
    // and remove it from the scene graph
    if (isAnnoFlg == 1)
    {
        if (obj->getTypeId() == SoSeparator::getClassTypeId())
        {
            if (mode == InvAnnoManager::EDIT)
            {
                vector<InvAnnoFlag *>::iterator it, selPos;
                // search flag with instance nr = objIndex;
                for (it = mee->flags_.begin(); it != mee->flags_.end(); ++it)
                {
                    if ((*it)->getInstance() == objIndex)
                    {
                        selPos = it;
                        break;
                    }
                }
                mee->viewer_->createAnnotationEditor(*selPos);
            }

            if (mode == InvAnnoManager::REMOVE)
            {
                // deletion of an InvAnnoFlag leads to a proper removal from the
                // scene graph by calling InvActiveNode::~InvActiveNode()
                bool del(false);
                vector<InvAnnoFlag *>::iterator it, remPos;
                // search flag with instance nr = objIndex;
                for (it = mee->flags_.begin(); it != mee->flags_.end(); ++it)
                {
                    if ((*it)->getInstance() == objIndex)
                    {
                        del = true;
                        remPos = it;
                    }
                }
                // delete flag and remove it from flags_
                if (del)
                {
                    delete *remPos;
                    mee->flags_.erase(remPos);
                    mee->trueNumFlags_--;
                    mee->deactivate();
                    mee->sendParameterData();
                }
            }
        }
    }
    // we create a new flag if anything else is selected
    else
    {
        if (mode != InvAnnoManager::MAKE)
            return;

        InvAnnoManager *mee = static_cast<InvAnnoManager *>(me);

        mee->add();

        InvAnnoFlag *af = mee->getActiveFlag();

        if (!af)
            return;

        SbVec3f camPos = mee->viewer_->getCamera()->position.getValue();

        af->setPickedPoint(mee->actPickedPoint_, camPos);

        InvAnnoFlag::selectionCB(af, selectedObject);

        mee->setKbActive();

        mee->deactivate();
    }
}
Beispiel #29
0
int
main(int argc, char ** argv)
{
  fprintf(stderr, "ivcp v0.1\n");

  SoDB::init();
  SoNodeKit::init();
  SoInteraction::init();

  if (argc != 3 ) {
    fprintf(stdout, "Usage: %s infile outfile\n", argv[0]);
    return 0;
  }

  SoInput * in = new SoInput;
  if (!in->openFile(argv[1])) {
    fprintf(stderr, "error: could not open file '%s'\n", argv[1]);
    delete in;
    SoDB::cleanup();
    return -1;
  }

  SoNode * scene = SoDB::readAll(in);

  if (!scene) {
    fprintf(stderr, "error: could not read file '%s'\n", argv[1]);
    delete in;
    SoDB::cleanup();
    return -1;
  }
  FileType inputFileType;
  if (in->isFileVRML1())
    inputFileType = VRML1;
  else if (in->isFileVRML2())
    inputFileType = VRML2;
  else
    inputFileType = INVENTOR;

  delete in;
  scene->ref();

  SoNode * firstChild = static_cast<SoSeparator*>(scene)->getNumChildren()?
    static_cast<SoSeparator*>(scene)->getChild(0)
    :NULL;

  if (firstChild && firstChild->isOfType(SoForeignFileKit::getClassTypeId())) {
    SoForeignFileKit * kit = (SoForeignFileKit *) firstChild;
    if (kit->canWriteScene() ) {
      SoNode * subscene = NULL;
      kit->writeScene(subscene);
      if (!subscene ) {
        return -1;
      }
      subscene->ref();
      scene->unref();
      scene = subscene;
    }
  }

  SoOutput * out = new SoOutput;
  if (!out->openFile(argv[2])) {
    fprintf(stderr, "error: could not open file '%s' for writing\n");
    scene->unref();
    delete out;
    SoDB::cleanup();
    return -1;
  }
  switch (inputFileType) {
  case VRML1:
    out->setHeaderString("#VRML V1.0 ascii");
    break;
  case VRML2:
    out->setHeaderString("#VRML V2.0 utf8");
  }

  SoWriteAction wa(out);
  wa.apply(scene);

  out->closeFile();
  delete out;

  scene->unref();

  // with actions on the stack, cleanup can't be called...
  // SoDB::cleanup();
  return 0;
}
void ViewProviderRobotObject::updateData(const App::Property* prop)
{
    Robot::RobotObject* robObj = static_cast<Robot::RobotObject*>(pcObject);
    if (prop == &robObj->RobotVrmlFile) {
        // read also from file
        const char* filename = robObj->RobotVrmlFile.getValue();
        QString fn = QString::fromUtf8(filename);
        QFile file(fn);
        SoInput in;
        pcRobotRoot->removeAllChildren();
        if (!fn.isEmpty() && file.open(QFile::ReadOnly)) {
            QByteArray buffer = file.readAll();
            in.setBuffer((void *)buffer.constData(), buffer.length());
            SoSeparator * node = SoDB::readAll(&in);
            if (node) pcRobotRoot->addChild(node);
            pcRobotRoot->addChild(pcTcpRoot);
        }
		// search for the conection points +++++++++++++++++++++++++++++++++++++++++++++++++
		Axis1Node = Axis2Node = Axis3Node = Axis4Node = Axis5Node = Axis6Node = 0;
		SoSearchAction searchAction;
		SoPath * path;

		// Axis 1
		searchAction.setName("FREECAD_AXIS1");
		searchAction.setInterest(SoSearchAction::FIRST);
		searchAction.setSearchingAll(FALSE);
		searchAction.apply(pcRobotRoot);
		path = searchAction.getPath();
		if(path){
			SoNode* node = path->getTail();
			std::string typeName = (const char*)node->getTypeId().getName();
			if (!node || node->getTypeId() != SoVRMLTransform::getClassTypeId())
				throw; // should not happen
			Axis1Node = static_cast<SoVRMLTransform *>(node);
		}
		// Axis 2
		searchAction.setName("FREECAD_AXIS2");
		searchAction.setInterest(SoSearchAction::FIRST);
		searchAction.setSearchingAll(FALSE);
		searchAction.apply(pcRobotRoot);
		path = searchAction.getPath();
		if(path){
			SoNode* node = path->getTail();
			std::string typeName = (const char*)node->getTypeId().getName();
			if (!node || node->getTypeId() != SoVRMLTransform::getClassTypeId())
				throw; // should not happen
			Axis2Node = static_cast<SoVRMLTransform *>(node);
		}
		// Axis 3
		searchAction.setName("FREECAD_AXIS3");
		searchAction.setInterest(SoSearchAction::FIRST);
		searchAction.setSearchingAll(FALSE);
		searchAction.apply(pcRobotRoot);
		path = searchAction.getPath();
		if(path){
			SoNode* node = path->getTail();
			std::string typeName = (const char*)node->getTypeId().getName();
			if (!node || node->getTypeId() != SoVRMLTransform::getClassTypeId())
				throw; // should not happen
			Axis3Node = static_cast<SoVRMLTransform *>(node);
		}
		// Axis 4
		searchAction.setName("FREECAD_AXIS4");
		searchAction.setInterest(SoSearchAction::FIRST);
		searchAction.setSearchingAll(FALSE);
		searchAction.apply(pcRobotRoot);
		path = searchAction.getPath();
		if(path){
			SoNode* node = path->getTail();
			std::string typeName = (const char*)node->getTypeId().getName();
			if (!node || node->getTypeId() != SoVRMLTransform::getClassTypeId())
				throw; // should not happen
			Axis4Node = static_cast<SoVRMLTransform *>(node);
		}
		// Axis 5
		searchAction.setName("FREECAD_AXIS5");
		searchAction.setInterest(SoSearchAction::FIRST);
		searchAction.setSearchingAll(FALSE);
		searchAction.apply(pcRobotRoot);
		path = searchAction.getPath();
		if(path){
			SoNode* node = path->getTail();
			std::string typeName = (const char*)node->getTypeId().getName();
			if (!node || node->getTypeId() != SoVRMLTransform::getClassTypeId())
				throw; // should not happen
			Axis5Node = static_cast<SoVRMLTransform *>(node);
		}
		// Axis 6
		searchAction.setName("FREECAD_AXIS6");
		searchAction.setInterest(SoSearchAction::FIRST);
		searchAction.setSearchingAll(FALSE);
		searchAction.apply(pcRobotRoot);
		path = searchAction.getPath();
		if(path){
			SoNode* node = path->getTail();
			std::string typeName = (const char*)node->getTypeId().getName();
			if (!node || node->getTypeId() != SoVRMLTransform::getClassTypeId())
				throw; // should not happen
			Axis6Node = static_cast<SoVRMLTransform *>(node);
		}
		if(Axis1Node)
			Axis1Node->rotation.setValue(SbVec3f(0.0,1.0,0.0),robObj->Axis1.getValue()*(M_PI/180));
		if(Axis2Node)
			Axis2Node->rotation.setValue(SbVec3f(0.0,1.0,0.0),robObj->Axis2.getValue()*(M_PI/180));
		if(Axis3Node)
			Axis3Node->rotation.setValue(SbVec3f(0.0,1.0,0.0),robObj->Axis3.getValue()*(M_PI/180));
		if(Axis4Node)
			Axis4Node->rotation.setValue(SbVec3f(0.0,1.0,0.0),robObj->Axis4.getValue()*(M_PI/180));
		if(Axis5Node)
			Axis5Node->rotation.setValue(SbVec3f(0.0,1.0,0.0),robObj->Axis5.getValue()*(M_PI/180));
		if(Axis6Node)
			Axis6Node->rotation.setValue(SbVec3f(0.0,1.0,0.0),robObj->Axis6.getValue()*(M_PI/180));
    }else if (prop == &robObj->Axis1) {
        if(Axis1Node){
			Axis1Node->rotation.setValue(SbVec3f(0.0,1.0,0.0),robObj->Axis1.getValue()*(M_PI/180));
            if(toolShape)
                toolShape->setTransformation((robObj->Tcp.getValue() * (robObj->ToolBase.getValue().inverse())).toMatrix());
        }
    }else if (prop == &robObj->Axis2) {
        if(Axis2Node){
			Axis2Node->rotation.setValue(SbVec3f(0.0,1.0,0.0),robObj->Axis2.getValue()*(M_PI/180));
            if(toolShape)
                toolShape->setTransformation((robObj->Tcp.getValue() * (robObj->ToolBase.getValue().inverse())).toMatrix());
        }
    }else if (prop == &robObj->Axis3) {
        if(Axis3Node){
			Axis3Node->rotation.setValue(SbVec3f(0.0,1.0,0.0),robObj->Axis3.getValue()*(M_PI/180));
            if(toolShape)
                toolShape->setTransformation((robObj->Tcp.getValue() * (robObj->ToolBase.getValue().inverse())).toMatrix());
        }
    }else if (prop == &robObj->Axis4) {
        if(Axis4Node){
			Axis4Node->rotation.setValue(SbVec3f(0.0,1.0,0.0),robObj->Axis4.getValue()*(M_PI/180));
            if(toolShape)
                toolShape->setTransformation((robObj->Tcp.getValue() * (robObj->ToolBase.getValue().inverse())).toMatrix());
        }
    }else if (prop == &robObj->Axis5) {
        if(Axis5Node){
			Axis5Node->rotation.setValue(SbVec3f(0.0,1.0,0.0),robObj->Axis5.getValue()*(M_PI/180));
            if(toolShape)
                toolShape->setTransformation((robObj->Tcp.getValue() * (robObj->ToolBase.getValue().inverse())).toMatrix());
        }
    }else if (prop == &robObj->Axis6) {
        if(Axis6Node){
			Axis6Node->rotation.setValue(SbVec3f(0.0,1.0,0.0),robObj->Axis6.getValue()*(M_PI/180));
            if(toolShape)
                toolShape->setTransformation((robObj->Tcp.getValue() * (robObj->ToolBase.getValue().inverse())).toMatrix());
        }
	}else if (prop == &robObj->Tcp) {
        Base::Placement loc = robObj->Tcp.getValue();
        SbMatrix  M;
        M.setTransform(SbVec3f(loc.getPosition().x,loc.getPosition().y,loc.getPosition().z),
                       SbRotation(loc.getRotation()[0],loc.getRotation()[1],loc.getRotation()[2],loc.getRotation()[3]),
                       SbVec3f(150,150,150)
                       );
        if(pcDragger)
            pcDragger->setMotionMatrix(M);
        if(toolShape)
            toolShape->setTransformation((robObj->Tcp.getValue() * (robObj->ToolBase.getValue().inverse())).toMatrix());
		//pcTcpTransform->translation = SbVec3f(loc.getPosition().x,loc.getPosition().y,loc.getPosition().z);
		//pcTcpTransform->rotation = SbRotation(loc.getRotation()[0],loc.getRotation()[1],loc.getRotation()[2],loc.getRotation()[3]);
	}else if (prop == &robObj->ToolShape) {
        App::DocumentObject* o = robObj->ToolShape.getValue<App::DocumentObject*>();

        if(o && (o->isDerivedFrom(Part::Feature::getClassTypeId()) || o->isDerivedFrom(App::VRMLObject::getClassTypeId())) ){
            //Part::Feature *p = dynamic_cast<Part::Feature *>(o);
            toolShape = Gui::Application::Instance->getViewProvider(o);
            toolShape->setTransformation((robObj->Tcp.getValue() * (robObj->ToolBase.getValue().inverse())).toMatrix());
        }else
            toolShape = 0;
 	}

}