void mitk::MicroBirdTrackingDevice::TrackTools()
{
  if (this->GetState() != Tracking)
    return;

  /* Frequency configuration */
  double updateRate = 1000.0 / m_SystemConfig.measurementRate;
  double measurementDuration = 0.0;


  // lock the TrackingFinishedMutex to signal that the execution rights
  //   are now transfered to the tracking thread
  MutexLockHolder trackingFinishedLockHolder(*m_TrackingFinishedMutex); // keep lock until end of scope

  // Because m_StopTracking is used by two threads, access has to be guarded
  //   by a mutex. To minimize thread locking, a local copy is used here 
  bool localStopTracking;

  /* update the local copy of m_StopTracking */
  this->m_StopTrackingMutex->Lock();
  localStopTracking = this->m_StopTracking;
  this->m_StopTrackingMutex->Unlock();

  /* Tracking loop */
  while ((this->GetState() == Tracking) && (localStopTracking == false))
  {
    int errorCode;
    unsigned int nOfAttachedSensors = 0;
    double timeStamp = 0.0;   
    int toolNumber = 0; // Numbers for attached sensors only

    for (int sensorID = 0; sensorID < m_SystemConfig.numberSensors; sensorID++) // for each sensor grep data
    {
      if (!m_SensorConfig[sensorID].attached)
        continue;

      // sensor attached so get record
      errorCode = GetAsynchronousRecord(sensorID, pRecord, sizeof(record));
      if (CompareError(errorCode, BIRD_ERROR_SUCCESS))      
      { // On SUCCESS, parse sensor information
        nOfAttachedSensors++;       
        timeStamp += record.time; // Get timestamp from record
        ToolType* tool = GetMicroBirdTool(toolNumber); /// Get tool (current sensor)
        if (tool != NULL)
        {
          tool->SetTrackingError(record.quality); // Set tracking error (quality) from record
          mitk::Point3D position;
          position[0] = record.x;
          position[1] = record.y;
          position[2] = record.z;
          tool->SetPosition(position);  // Set position
          mitk::Quaternion orientation(record.q[1], record.q[2], record.q[3],record.q[0]);
          tool->SetOrientation(orientation); // Set orientation as quaternion \todo : verify quaternion order q(r,x,y,z)
          tool->SetDataValid(true); // Set data state to valid
        }        
        toolNumber++; // Increment tool number
      }  
      else
      { // ERROR while reading sensor information
        HandleError(errorCode);
      }      
    }

    /// @todo : is there any synchronisation?
    // Average timestamp: timeStamp/nOfAttachedSensors

    // Compute sleep time
    double sleepTime = updateRate - measurementDuration;
    // Sleep
    if (sleepTime > 0.0 && sleepTime < 500.0)
    {
      // Note: we only have to approximately sleep one measurement cycle,
      //    since the tracker keeps track of the measurement rate itself
      itksys::SystemTools::Delay(sleepTime)
      //Sleep(static_cast<DWORD>(sleepTime));
    }

    // Update the local copy of m_StopTracking
    this->m_StopTrackingMutex->Lock();  
    localStopTracking = m_StopTracking;
    this->m_StopTrackingMutex->Unlock();
  }

  // @bug (#1813) : maybe we need to check for localStopTracking=true here?
  //    m_StopTracking should only ever be updated by StopTracking(), so
  //    maybe we should not unlock a mutex that nobody is waiting for?

  return; // returning from this function (and ThreadStartTracking()) this will end the thread
}
示例#2
0
文件: Camera.cpp 项目: jheise/grid
glm::vec3 Camera::forward() const {
    glm::vec4 forward = glm::inverse(orientation()) * glm::vec4(0,0,-1,1);
    return glm::vec3(forward);
}
示例#3
0
文件: Camera.cpp 项目: jheise/grid
glm::vec3 Camera::up() const {
    glm::vec4 up = glm::inverse(orientation()) * glm::vec4(0,1,0,1);
    return glm::vec3(up);
}
示例#4
0
文件: q3dockarea.cpp 项目: Suneal/qt
int Q3DockAreaLayout::layoutItems(const QRect &rect, bool testonly)
{
    if (dockWindows->isEmpty())
        return 0;

    dirty = false;

    // some corrections
    QRect r = rect;
    if (orientation() == Qt::Vertical)
        r.setHeight(r.height() - 3);

    // init
    lines.clear();
    ls.clear();
    int start = start_pos(r, orientation());
    int pos = start;
    int sectionpos = 0;
    int linestrut = 0;
    QList<Q3DockData> lastLine;
    int tbstrut = -1;
    int maxsize = size_extent(rect.size(), orientation());
    int visibleWindows = 0;

    // go through all widgets in the dock
    for (int i = 0; i < dockWindows->size(); ++i) {
        Q3DockWindow *dw = dockWindows->at(i);
        if (dw->isHidden())
            continue;
        ++visibleWindows;
        // find position for the widget: This is the maximum of the
        // end of the previous widget and the offset of the widget. If
        // the position + the width of the widget dosn't fit into the
        // dock, try moving it a bit back, if possible.
        int op = pos;
        int dockExtend = dock_extent(dw, orientation(), maxsize);
        if (!dw->isStretchable()) {
            pos = qMax(pos, dw->offset());
            if (pos + dockExtend > size_extent(r.size(), orientation()) - 1)
                pos = qMax(op, size_extent(r.size(), orientation()) - 1 - dockExtend);
        }
        if (!lastLine.isEmpty() && !dw->newLine() && space_left(rect, pos, orientation()) < dockExtend)
            shrink_extend(dw, dockExtend, space_left(rect, pos, orientation()), orientation());
        // if the current widget doesn't fit into the line anymore and it is not the first widget of the line
        if (!lastLine.isEmpty() &&
             (space_left(rect, pos, orientation()) < dockExtend || dw->newLine())) {
            if (!testonly) // place the last line, if not in test mode
                place_line(lastLine, orientation(), linestrut, size_extent(r.size(), orientation()), tbstrut, maxsize, this);
            // remember the line coordinats of the last line
            if (orientation() == Qt::Horizontal)
                lines.append(QRect(0, sectionpos, r.width(), linestrut));
            else
                lines.append(QRect(sectionpos, 0, linestrut, r.height()));
            // do some clearing for the next line
            lastLine.clear();
            sectionpos += linestrut;
            linestrut = 0;
            pos = start;
            tbstrut = -1;
        }

        // remember first widget of a line
        if (lastLine.isEmpty()) {
            ls.append(dw);
            // try to make the best position
            int op = pos;
            if (!dw->isStretchable())
                pos = qMax(pos, dw->offset());
            if (pos + dockExtend > size_extent(r.size(), orientation()) - 1)
                pos = qMax(op, size_extent(r.size(), orientation()) - 1 - dockExtend);
        }
        // do some calculations and add the remember the rect which the docking widget requires for the placing
        QRect dwRect(pos, sectionpos, dockExtend, dock_strut(dw, orientation() ));
        lastLine.append(Q3DockData(dw, dwRect));
        if (qobject_cast<Q3ToolBar*>(dw))
            tbstrut = qMax(tbstrut, dock_strut(dw, orientation()));
        linestrut = qMax(dock_strut(dw, orientation()), linestrut);
        add_size(dockExtend, pos, orientation());
    }

    // if some stuff was not placed/stored yet, do it now
    if (!testonly)
        place_line(lastLine, orientation(), linestrut, size_extent(r.size(), orientation()), tbstrut, maxsize, this);
    if (orientation() == Qt::Horizontal)
        lines.append(QRect(0, sectionpos, r.width(), linestrut));
    else
        lines.append(QRect(sectionpos, 0, linestrut, r.height()));
    if (lines.size() >= 2 && *(--lines.end()) == *(--(--lines.end())))
        lines.removeLast();

    bool hadResizable = false;
    for (int i = 0; i < dockWindows->size(); ++i) {
        Q3DockWindow *dw = dockWindows->at(i);
        if (!dw->isVisibleTo(parentWidget))
            continue;
        hadResizable = hadResizable || dw->isResizeEnabled();
        dw->updateSplitterVisibility(visibleWindows > 1); //!dw->area()->isLastDockWindow(dw));
        if (Q3ToolBar *tb = qobject_cast<Q3ToolBar *>(dw))
            tb->checkForExtension(dw->size());
    }
    return sectionpos + linestrut;
}
void mitk::NavigationDataRecorderDeprecated::Update()
{
  if (m_Recording)
  {
    DataObjectPointerArray inputs = this->GetInputs(); //get all inputs
    mitk::NavigationData::TimeStampType timestamp=0.0; // timestamp for mitk time
    timestamp = mitk::IGTTimeStamp::GetInstance()->GetElapsed();


    mitk::NavigationData::TimeStampType sysTimestamp = 0.0; // timestamp for system time
    sysTimestamp = m_SystemTimeClock->GetCurrentStamp();

    // cast system time double value to stringstream to avoid low precision rounding
    std::ostringstream strs;
    strs.precision(15); // rounding precision for system time double value
    strs << sysTimestamp;
    std::string sysTimeStr = strs.str();

    //if csv-mode: write csv header and timestamp at beginning
    if (m_OutputFormat == mitk::NavigationDataRecorderDeprecated::csv)
      {
      //write header only when it's the first line
      if (m_firstLine)
        {
        m_firstLine = false;
        *m_Stream << "TimeStamp";
        for (unsigned int index = 0; index < inputs.size(); index++){ *m_Stream << ";Valid_Tool" << index <<
                                                                                ";X_Tool" << index <<
                                                                                ";Y_Tool" << index <<
                                                                                ";Z_Tool" << index <<
                                                                                ";QX_Tool" << index <<
                                                                                ";QY_Tool" << index <<
                                                                                ";QZ_Tool" << index <<
                                                                                ";QR_Tool" << index;}
        *m_Stream << "\n";
        }
      //write timestamp (always)
      *m_Stream << timestamp;
      }

    //write tool data for every tool
    for (unsigned int index = 0; index < inputs.size(); index++)
    {
      mitk::NavigationData* nd = dynamic_cast<mitk::NavigationData*>(inputs[index].GetPointer());
      nd->Update(); // call update to propagate update to previous filters

      mitk::NavigationData::PositionType position;
      mitk::NavigationData::OrientationType orientation(0.0, 0.0, 0.0, 0.0);
      mitk::NavigationData::CovarianceMatrixType matrix;

      bool hasPosition = true;
      bool hasOrientation = true;
      bool dataValid = false;

      position.Fill(0.0);
      matrix.SetIdentity();

      position = nd->GetPosition();
      orientation = nd->GetOrientation();
      matrix = nd->GetCovErrorMatrix();

      hasPosition = nd->GetHasPosition();
      hasOrientation = nd->GetHasOrientation();
      dataValid = nd->IsDataValid();

      //use this one if you want the timestamps of the source
      //timestamp = nd->GetIGTTimeStamp();

      //a timestamp is never < 0! this case happens only if you are using the timestamp of the nd object instead of getting a new one
      if (timestamp >= 0)
      {
        if (this->m_OutputFormat == mitk::NavigationDataRecorderDeprecated::xml)
          {
          TiXmlElement* elem = new TiXmlElement("NavigationData");

          elem->SetDoubleAttribute("Time", timestamp);
          elem->SetAttribute("SystemTime", sysTimeStr); // tag for system time
          elem->SetDoubleAttribute("Tool", index);
          elem->SetDoubleAttribute("X", position[0]);
          elem->SetDoubleAttribute("Y", position[1]);
          elem->SetDoubleAttribute("Z", position[2]);

          elem->SetDoubleAttribute("QX", orientation[0]);
          elem->SetDoubleAttribute("QY", orientation[1]);
          elem->SetDoubleAttribute("QZ", orientation[2]);
          elem->SetDoubleAttribute("QR", orientation[3]);

          elem->SetDoubleAttribute("C00", matrix[0][0]);
          elem->SetDoubleAttribute("C01", matrix[0][1]);
          elem->SetDoubleAttribute("C02", matrix[0][2]);
          elem->SetDoubleAttribute("C03", matrix[0][3]);
          elem->SetDoubleAttribute("C04", matrix[0][4]);
          elem->SetDoubleAttribute("C05", matrix[0][5]);
          elem->SetDoubleAttribute("C10", matrix[1][0]);
          elem->SetDoubleAttribute("C11", matrix[1][1]);
          elem->SetDoubleAttribute("C12", matrix[1][2]);
          elem->SetDoubleAttribute("C13", matrix[1][3]);
          elem->SetDoubleAttribute("C14", matrix[1][4]);
          elem->SetDoubleAttribute("C15", matrix[1][5]);

          if (dataValid)
            elem->SetAttribute("Valid",1);
          else
            elem->SetAttribute("Valid",0);

          if (hasOrientation)
            elem->SetAttribute("hO",1);
          else
            elem->SetAttribute("hO",0);

          if (hasPosition)
            elem->SetAttribute("hP",1);
          else
            elem->SetAttribute("hP",0);

          // set additional attribute?
          std::map<const mitk::NavigationData*, std::pair<std::string, std::string> >::iterator
              it = m_AdditionalAttributes.find( nd );
          if( it != m_AdditionalAttributes.end() )
          {
            elem->SetAttribute(it->second.first, it->second.second);
          }

          *m_Stream << "        " << *elem << std::endl;

          delete elem;
          }
        else if (this->m_OutputFormat == mitk::NavigationDataRecorderDeprecated::csv)
          {
          *m_Stream << ";" << dataValid << ";" << position[0] << ";" << position[1] << ";" << position[2] << ";" << orientation[0] << ";" << orientation[1] << ";" << orientation[2] << ";" << orientation[3];
          }
      }
    }
    if (this->m_OutputFormat == mitk::NavigationDataRecorderDeprecated::csv)
    {
      *m_Stream << "\n";
    }
  }
  m_RecordCounter++;
  if ((m_RecordCountLimit<=m_RecordCounter)&&(m_RecordCountLimit != -1)) {StopRecording();}
}
示例#6
0
void ScaleDraw::drawBreak(QPainter *painter) const
{
	ScaleEngine *sc_engine = (ScaleEngine *)d_plot->axisScaleEngine(axis());
	/*const QwtScaleEngine * qwtsc_engine=d_plot->axisScaleEngine(axis());
	const ScaleEngine *sc_engine =dynamic_cast<const ScaleEngine*>(qwtsc_engine);
	if(sc_engine!=NULL)
	{*/
		if (!sc_engine->hasBreak() || !sc_engine->hasBreakDecoration())
			return;

		painter->save();
		painter->setRenderHint(QPainter::Antialiasing);

		int len = majTickLength();

		QwtScaleMap scaleMap = map();
		const QwtMetricsMap metricsMap = QwtPainter::metricsMap();
		QPoint pos = this->pos();

		if ( !metricsMap.isIdentity() ){
			QwtPainter::resetMetricsMap();
			pos = metricsMap.layoutToDevice(pos);

			if ( orientation() == Qt::Vertical ){
				scaleMap.setPaintInterval(
					metricsMap.layoutToDeviceY((int)scaleMap.p1()),
					metricsMap.layoutToDeviceY((int)scaleMap.p2()));
				len = metricsMap.layoutToDeviceX(len);
			} else {
				scaleMap.setPaintInterval(
					metricsMap.layoutToDeviceX((int)scaleMap.p1()),
					metricsMap.layoutToDeviceX((int)scaleMap.p2()));
				len = metricsMap.layoutToDeviceY(len);
			}
		}

		int lval = scaleMap.transform(sc_engine->axisBreakLeft());
		int rval = scaleMap.transform(sc_engine->axisBreakRight());
		switch(alignment()){
		case LeftScale:
			QwtPainter::drawLine(painter, pos.x(), lval, pos.x() - len, lval + len);
			QwtPainter::drawLine(painter, pos.x(), rval, pos.x() - len, rval + len);
			break;
		case RightScale:
			QwtPainter::drawLine(painter, pos.x(), lval, pos.x() + len, lval - len);
			QwtPainter::drawLine(painter, pos.x(), rval, pos.x() + len, rval - len);
			break;
		case BottomScale:
			QwtPainter::drawLine(painter, lval, pos.y(), lval - len, pos.y() + len);
			QwtPainter::drawLine(painter, rval, pos.y(), rval - len, pos.y() + len);
			break;
		case TopScale:
			QwtPainter::drawLine(painter, lval, pos.y(), lval + len, pos.y() - len);
			QwtPainter::drawLine(painter, rval, pos.y(), rval + len, pos.y() - len);
			break;
		}

		QwtPainter::setMetricsMap(metricsMap); // restore metrics map
		painter->restore();
	//}
}
示例#7
0
Actor*
Parser::parseBox(xml_node_iterator sceneElement)
{
	vec3 center(0, 0, 0);
	quat orientation(vec3(0, 0, 0));
	vec3 scale(1, 1, 1);

	// opt values
	xml_node op;
	op = sceneElement->child("center");
	REAL x, y, z;
	if (op != NULL)
	{
		const char* center_vector = op.text().as_string();

		sscanf(center_vector, "%f %f %f", &x, &y, &z);
		center.set(x, y, z);
	}
	op = sceneElement->child("orientation");
	if (op != NULL){
		const char* orientation_vec = op.text().as_string();

		sscanf(orientation_vec, "%f %f %f", &x, &y, &z);
		orientation.eulerAngles(vec3(x, y, z));
	}
	op = sceneElement->child("scale");
	if (op != NULL){
		const char* scale_vec = op.text().as_string();

		sscanf(scale_vec, "%f %f %f", &x, &y, &z);
		scale.set(vec3(x, y, z));
	}

	// now, lets make the mesh of Sphere
	TriangleMesh* boxMesh = MeshSweeper::makeBox(center, orientation, scale);

	Primitive* primitive = new TriangleMeshShape(boxMesh);

	if ((op = sceneElement->child("transform")) != NULL) {
		vec3 position(0, 0, 0);
		quat q(vec3(0, 0, 0));
		vec3 scale(1, 1, 1);
		float x, y, z;

		xml_object_range<xml_node_iterator> transformations = op.children();

		for (xml_node_iterator transformation = transformations.begin(); transformation != transformations.end(); ++transformation)
		{
			if (strcmp(transformation->name(), "position") == 0)
			{
				const char * stringTranslation = transformation->text().as_string();

				sscanf(stringTranslation, "%f %f %f", &x, &y, &z);
				vec3 translationVec(x, y, z);
				position = translationVec;
			}
			else if (strcmp(transformation->name(), "scale") == 0)
			{
				float s_ = transformation->text().as_float();
				vec3 newS(s_, s_, s_);
				scale = newS;
			}
			else if (strcmp(transformation->name(), "rotation") == 0)
			{
				float angle = transformation->child("angle").text().as_float();

				const char * _Axis = transformation->child("axis").text().as_string();
				sscanf(_Axis, "%f %f %f", &x, &y, &z);
				vec3 axis(x, y, z);
				q = quat(axis, angle);
			}

			boxMesh->transform(mat4::TRS(position, q, scale));
		}
	}
	if ((op = sceneElement->child("material")) != NULL) {
		Material * material = parseMaterial(op);
		primitive->setMaterial(material);
	}
	else
	{
		Material * material = MaterialFactory::New();
		primitive->setMaterial(material->getDefault());

	}

	Actor* act = new Actor(*primitive);
	act->setName("box");

	return act;
}
示例#8
0
void RDHeaderView::paintSection(QPainter *painter, const QRect &rect, int section) const
{
  if(!m_customSizing)
    return QHeaderView::paintSection(painter, rect, section);

  if(!rect.isValid())
    return;

  QStyleOptionHeader opt;
  initStyleOption(&opt);

  QAbstractItemModel *m = this->model();

  if(hasFocus())
    opt.state |= (QStyle::State_Active | QStyle::State_HasFocus);
  else
    opt.state &= ~(QStyle::State_Active | QStyle::State_HasFocus);

  QVariant textAlignment = m->headerData(section, orientation(), Qt::TextAlignmentRole);
  opt.rect = rect;
  opt.section = section;
  opt.textAlignment = defaultAlignment();
  opt.iconAlignment = Qt::AlignVCenter;

  QVariant variant;

  if(m_columnGroupRole)
  {
    variant = m->headerData(section, orientation(), m_columnGroupRole);
    if(variant.isValid() && variant.canConvert<QString>())
      opt.text = variant.toString();
  }

  if(opt.text.isEmpty())
    opt.text = m->headerData(section, orientation(), Qt::DisplayRole).toString();

  int margin = 2 * style()->pixelMetric(QStyle::PM_HeaderMargin, 0, this);

  if(textElideMode() != Qt::ElideNone)
    opt.text = opt.fontMetrics.elidedText(opt.text, textElideMode(), rect.width() - margin);

  if(section == 0 && section == m_sections.count() - 1)
    opt.position = QStyleOptionHeader::OnlyOneSection;
  else if(section == 0)
    opt.position = QStyleOptionHeader::Beginning;
  else if(section == m_sections.count() - 1)
    opt.position = QStyleOptionHeader::End;
  else
    opt.position = QStyleOptionHeader::Middle;

  opt.orientation = orientation();

  bool prevSel = section > 0 && selectionModel()->isColumnSelected(section - 1, QModelIndex());
  bool nextSel = section + 1 < m_sections.count() &&
                 selectionModel()->isColumnSelected(section + 1, QModelIndex());

  if(prevSel && nextSel)
    opt.selectedPosition = QStyleOptionHeader::NextAndPreviousAreSelected;
  else if(prevSel)
    opt.selectedPosition = QStyleOptionHeader::PreviousIsSelected;
  else if(nextSel)
    opt.selectedPosition = QStyleOptionHeader::NextIsSelected;
  else
    opt.selectedPosition = QStyleOptionHeader::NotAdjacent;

  style()->drawControl(QStyle::CE_Header, &opt, painter, this);
}
示例#9
0
void RDHeaderView::cacheSections()
{
  if(m_suppressSectionCache)
    return;

  QAbstractItemModel *m = this->model();

  int oldCount = m_sections.count();
  m_sections.resize(m->columnCount());

  // give new sections a default minimum size
  for(int col = oldCount; col < m_sections.count(); col++)
    m_sections[col].size = 10;

  for(int col = 0; col < m_sections.count(); col++)
  {
    if(m_columnGroupRole > 0)
    {
      QVariant v = m->data(m->index(0, col), m_columnGroupRole);
      if(v.isValid())
        m_sections[col].group = v.toInt();
      else
        m_sections[col].group = -m_columnGroupRole - col;

      if(col > 0)
      {
        m_sections[col - 1].groupGap =
            (m_sections[col].group != m_sections[col - 1].group) && m_sections[col].group >= 0;
      }
    }
    else
    {
      m_sections[col].group = col;
      m_sections[col].groupGap = true;
    }
  }

  int accum = 0;

  for(int col = 0; col < m_sections.count(); col++)
  {
    if(col == m_pinnedColumns)
      m_pinnedWidth = accum;

    m_sections[col].offset = accum;
    accum += m_sections[col].size;

    if(hasGroupGap(col))
      accum += groupGapSize();
  }

  if(m_pinnedColumns >= m_sections.count())
    m_pinnedWidth = m_pinnedColumns;

  QStyleOptionHeader opt;
  initStyleOption(&opt);

  QFont f = font();
  f.setBold(true);

  opt.section = 0;
  opt.fontMetrics = QFontMetrics(f);
  opt.text = m->headerData(0, orientation(), Qt::DisplayRole).toString();

  m_sizeHint = style()->sizeFromContents(QStyle::CT_HeaderSection, &opt, QSize(), this);
  m_sizeHint.setWidth(accum);

  viewport()->update(viewport()->rect());
}
示例#10
0
QStyleOptionHeader HierarchicalHeaderView::styleOptionForCell(int logicalInd) const
{
	QStyleOptionHeader opt;
	initStyleOption(&opt);
	if (window()->isActiveWindow())
		opt.state |= QStyle::State_Active;
	opt.textAlignment = Qt::AlignCenter;
	opt.iconAlignment = Qt::AlignVCenter;
	opt.section = logicalInd;

	int visual = visualIndex(logicalInd);

	if (count() == 1)
		opt.position = QStyleOptionHeader::OnlyOneSection;
	else
	{
		if (visual == 0)
			opt.position = QStyleOptionHeader::Beginning;
		else
			opt.position=(visual==count()-1 ? QStyleOptionHeader::End : QStyleOptionHeader::Middle);
	}

    if(isClickable())
	{
/*
        if (logicalIndex == d->hover)
            state |= QStyle::State_MouseOver;
        if (logicalIndex == d->pressed)
		{
            state |= QStyle::State_Sunken;
		}
        else*/
		{
			if(highlightSections() && selectionModel()) 
			{
                if(orientation()==Qt::Horizontal)
                {
				    if(selectionModel()->columnIntersectsSelection(logicalInd, rootIndex()))
					    opt.state |= QStyle::State_On;
                    if(selectionModel()->isColumnSelected(logicalInd, rootIndex()))
                        opt.state |= QStyle::State_Sunken;
                }
                else
                {
				    if(selectionModel()->rowIntersectsSelection(logicalInd, rootIndex()))
					    opt.state |= QStyle::State_On;
                    if(selectionModel()->isRowSelected(logicalInd, rootIndex()))
                        opt.state |= QStyle::State_Sunken;
                }
			}
        }
    }
	if(selectionModel())
	{
	    bool previousSelected=false;
        if(orientation()==Qt::Horizontal)
            previousSelected = selectionModel()->isColumnSelected(logicalIndex(visual - 1), rootIndex());
        else
            previousSelected = selectionModel()->isRowSelected(logicalIndex(visual - 1), rootIndex());
		bool nextSelected=false;
        if(orientation()==Qt::Horizontal)
            nextSelected = selectionModel()->isColumnSelected(logicalIndex(visual + 1), rootIndex());
        else
            nextSelected = selectionModel()->isRowSelected(logicalIndex(visual + 1), rootIndex());
		if (previousSelected && nextSelected)
			opt.selectedPosition = QStyleOptionHeader::NextAndPreviousAreSelected;
		else 
		{
			if (previousSelected)
				opt.selectedPosition = QStyleOptionHeader::PreviousIsSelected;
			else
			{
				if (nextSelected)
					opt.selectedPosition = QStyleOptionHeader::NextIsSelected;
				else
					opt.selectedPosition = QStyleOptionHeader::NotAdjacent;
			}
		}
	}
	return opt;
}
示例#11
0
void RDHeaderView::resizeSectionsWithHints()
{
  if(m_sectionMinSizes.count() == 0)
    return;

  QVector<int> sizes = m_sectionMinSizes;

  int available = 0;

  if(orientation() == Qt::Horizontal)
    available = rect().width();
  else
    available = rect().height();

  // see if we even have any extra space to allocate
  if(available > m_sectionMinSizesTotal)
  {
    // this is how much space we can allocate to stretch sections
    available -= m_sectionMinSizesTotal;

    // distribute the available space between the sections. Dividing by the total stretch tells us
    // how many 'whole' multiples we can allocate:
    int wholeMultiples = available / m_sectionStretchHintTotal;

    if(wholeMultiples > 0)
    {
      for(int i = 0; i < sizes.count() && i < m_sectionStretchHints.count(); i++)
      {
        int hint = m_sectionStretchHints[i];
        if(hint > 0)
          sizes[i] += wholeMultiples * hint;
      }
    }

    available -= wholeMultiples * m_sectionStretchHintTotal;

    // we now have a small amount (less than m_sectionStretchHintTotal) of extra space to allocate.
    // we still want to assign this leftover proportional to the hints, otherwise we'd end up with a
    // stair-stepping effect.
    // To do this we calculate hint/total for each section then loop around adding on fractional
    // components to the sizes until one is above 1, then it gets a pixel, and we keep going until
    // all the remainder is allocated
    QVector<float> fractions, increment;
    fractions.resize(sizes.count());
    increment.resize(sizes.count());

    // set up increments
    for(int i = 0; i < sizes.count(); i++)
    {
      // don't assign any space to sections with negative hints, or sections without hints
      if(i >= m_sectionStretchHints.count() || m_sectionStretchHints[i] <= 0)
      {
        increment[i] = 0.0f;
        continue;
      }

      increment[i] = float(m_sectionStretchHints[i]) / float(m_sectionStretchHintTotal);
    }

    while(available > 0)
    {
      // loop along each section incrementing it.
      for(int i = 0; i < fractions.count(); i++)
      {
        fractions[i] += increment[i];

        // if we have a whole pixel now, assign it
        if(fractions[i] > 1.0f)
        {
          fractions[i] -= 1.0f;
          sizes[i]++;
          available--;

          // if we've assigned all pixels, stop
          if(available == 0)
            break;
        }
      }
    }

    for(int pix = 0; pix < available; pix++)
    {
      int minSection = 0;
      for(int i = 1; i < sizes.count(); i++)
      {
        // don't assign any space to sections with negative hints
        if(i < m_sectionStretchHints.count() && m_sectionStretchHints[i] <= 0)
          continue;

        if(sizes[i] < sizes[minSection])
          minSection = i;
      }

      sizes[minSection]++;
    }
  }

  resizeSections(sizes.toList());
}
示例#12
0
void PointCloudDisplay::transformCloud()
{
  if ( message_.header.frame_id.empty() )
  {
    message_.header.frame_id = fixed_frame_;
  }

  tf::Stamped<tf::Pose> pose( btTransform( btQuaternion( 0, 0, 0 ), btVector3( 0, 0, 0 ) ), message_.header.stamp, message_.header.frame_id );

  try
  {
    tf_->transformPose( fixed_frame_, pose, pose );
  }
  catch(tf::TransformException& e)
  {
    ROS_ERROR( "Error transforming point cloud '%s' from frame '%s' to frame '%s'\n", name_.c_str(), message_.header.frame_id.c_str(), fixed_frame_.c_str() );
  }

  Ogre::Vector3 position( pose.getOrigin().x(), pose.getOrigin().y(), pose.getOrigin().z() );
  robotToOgre( position );

  btScalar yaw, pitch, roll;
  pose.getBasis().getEulerZYX( yaw, pitch, roll );

  Ogre::Matrix3 orientation( ogreMatrixFromRobotEulers( yaw, pitch, roll ) );

  // First find the min/max intensity values
  float min_intensity = 999999.0f;
  float max_intensity = -999999.0f;

  typedef std::vector<std_msgs::ChannelFloat32> V_Chan;
  typedef std::vector<bool> V_bool;

  V_bool valid_channels(message_.chan.size());
  uint32_t point_count = message_.get_pts_size();
  V_Chan::iterator chan_it = message_.chan.begin();
  V_Chan::iterator chan_end = message_.chan.end();
  uint32_t index = 0;
  for ( ; chan_it != chan_end; ++chan_it, ++index )
  {
    std_msgs::ChannelFloat32& chan = *chan_it;
    uint32_t val_count = chan.vals.size();
    bool channel_size_correct = val_count == point_count;
    ROS_ERROR_COND(!channel_size_correct, "Point cloud '%s' on topic '%s' has channel 0 with fewer values than points (%d values, %d points)", name_.c_str(), topic_.c_str(), val_count, point_count);

    valid_channels[index] = channel_size_correct;

    if ( channel_size_correct && ( chan.name.empty() || chan.name == "intensity" || chan.name == "intensities" ) )
    {
      for(uint32_t i = 0; i < point_count; i++)
      {
        float& intensity = chan.vals[i];
        // arbitrarily cap to 4096 for now
        intensity = std::min( intensity, 4096.0f );
        min_intensity = std::min( min_intensity, intensity );
        max_intensity = std::max( max_intensity, intensity );
      }
    }
  }

  float diff_intensity = max_intensity - min_intensity;

  typedef std::vector< ogre_tools::PointCloud::Point > V_Point;
  V_Point points;
  points.resize( point_count );
  for(uint32_t i = 0; i < point_count; i++)
  {
    Ogre::Vector3 color( color_.r_, color_.g_, color_.b_ );
    ogre_tools::PointCloud::Point& current_point = points[ i ];

    current_point.x_ = message_.pts[i].x;
    current_point.y_ = message_.pts[i].y;
    current_point.z_ = message_.pts[i].z;
    current_point.r_ = color.x;
    current_point.g_ = color.y;
    current_point.b_ = color.z;
  }

  chan_it = message_.chan.begin();
  index = 0;
  for ( ; chan_it != chan_end; ++chan_it, ++index )
  {
    if ( !valid_channels[index] )
    {
      continue;
    }

    std_msgs::ChannelFloat32& chan = *chan_it;
    enum ChannelType
    {
      CT_INTENSITY,
      CT_RGB,
      CT_R,
      CT_G,
      CT_B,

      CT_COUNT
    };

    ChannelType type = CT_INTENSITY;
    if ( chan.name == "rgb" )
    {
      type = CT_RGB;
    }
    else if ( chan.name == "r" )
    {
      type = CT_R;
    }
    else if ( chan.name == "g" )
    {
      type = CT_G;
    }
    else if ( chan.name == "b" )
    {
      type = CT_B;
    }

    typedef void (*TransformFunc)(float, ogre_tools::PointCloud::Point&, float, float, float);
    TransformFunc funcs[CT_COUNT] =
    {
      transformIntensity,
      transformRGB,
      transformR,
      transformG,
      transformB
    };

    for(uint32_t i = 0; i < point_count; i++)
    {
      ogre_tools::PointCloud::Point& current_point = points[ i ];
      funcs[type]( chan.vals[i], current_point, min_intensity, max_intensity, diff_intensity );
    }
  }

  {
    RenderAutoLock renderLock( this );

    scene_node_->setPosition( position );
    scene_node_->setOrientation( orientation );

    cloud_->clear();

    if ( !points.empty() )
    {
      cloud_->addPoints( &points.front(), points.size() );
    }
  }

  causeRender();

}
示例#13
0
QSize SplitterHandle::sizeHint() const
{
    return (orientation() == Qt::Horizontal) ? QSize( 1, height() ) : QSize( width(), 1 );
}
示例#14
0
QSplitterHandle *PlaylistSplitter::createHandle()
{
    return new SplitterHandle( orientation(), this );
}
示例#15
0
int Scrollbar::scrollbarThickness() const {
  int thickness = orientation() == HorizontalScrollbar ? height() : width();
  if (!thickness || !m_hostWindow)
    return thickness;
  return m_hostWindow->windowToViewportScalar(m_themeScrollbarThickness);
}
示例#16
0
/*!
  Draw a tube

  Builds 2 curves from the upper and lower limits of the intervals
  and draws them with the pen(). The area between the curves is
  filled with the brush().

  \param painter Painter
  \param xMap Maps x-values into pixel coordinates.
  \param yMap Maps y-values into pixel coordinates.
  \param canvasRect Contents rect of the canvas
  \param from Index of the first sample to be painted
  \param to Index of the last sample to be painted. If to < 0 the
         series will be painted to its last sample.

  \sa drawSeries(), drawSymbols()
*/
void QwtPlotIntervalCurve::drawTube( QPainter *painter,
    const QwtScaleMap &xMap, const QwtScaleMap &yMap,
    const QRectF &canvasRect, int from, int to ) const
{
    const bool doAlign = QwtPainter::roundingAlignment( painter );

    painter->save();

    const size_t size = to - from + 1;
    QPolygonF polygon( 2 * size );
    QPointF *points = polygon.data();

    for ( uint i = 0; i < size; i++ )
    {
        QPointF &minValue = points[i];
        QPointF &maxValue = points[2 * size - 1 - i];

        const QwtIntervalSample intervalSample = sample( from + i );
        if ( orientation() == Qt::Vertical )
        {
            double x = xMap.transform( intervalSample.value );
            double y1 = yMap.transform( intervalSample.interval.minValue() );
            double y2 = yMap.transform( intervalSample.interval.maxValue() );
            if ( doAlign )
            {
                x = qRound( x );
                y1 = qRound( y1 );
                y2 = qRound( y2 );
            }

            minValue.rx() = x;
            minValue.ry() = y1;
            maxValue.rx() = x;
            maxValue.ry() = y2;
        }
        else
        {
            double y = yMap.transform( intervalSample.value );
            double x1 = xMap.transform( intervalSample.interval.minValue() );
            double x2 = xMap.transform( intervalSample.interval.maxValue() );
            if ( doAlign )
            {
                y = qRound( y );
                x1 = qRound( x1 );
                x2 = qRound( x2 );
            }

            minValue.rx() = x1;
            minValue.ry() = y;
            maxValue.rx() = x2;
            maxValue.ry() = y;
        }
    }

    if ( d_data->brush.style() != Qt::NoBrush )
    {
        painter->setPen( QPen( Qt::NoPen ) );
        painter->setBrush( d_data->brush );

        if ( d_data->paintAttributes & ClipPolygons )
        {
            const qreal m = 1.0;
            const QPolygonF p = QwtClipper::clipPolygonF( 
                canvasRect.adjusted(-m, -m, m, m), polygon, true );

            QwtPainter::drawPolygon( painter, p );
        }
        else
        {
            QwtPainter::drawPolygon( painter, polygon );
        }
    }

    if ( d_data->pen.style() != Qt::NoPen )
    {
        painter->setPen( d_data->pen );
        painter->setBrush( Qt::NoBrush );

        if ( d_data->paintAttributes & ClipPolygons )
        {
            qreal pw = qMax( qreal( 1.0 ), painter->pen().widthF());
            const QRectF clipRect = canvasRect.adjusted(-pw, -pw, pw, pw);

            QPolygonF p;

            p.resize( size );
            qMemCopy( p.data(), points, size * sizeof( QPointF ) );
            p = QwtClipper::clipPolygonF( canvasRect, p );
            QwtPainter::drawPolyline( painter, p );

            p.resize( size );
            qMemCopy( p.data(), points + size, size * sizeof( QPointF ) );
            p = QwtClipper::clipPolygonF( canvasRect, p );
            QwtPainter::drawPolyline( painter, p );
        }
        else
        {
            QwtPainter::drawPolyline( painter, points, size );
            QwtPainter::drawPolyline( painter, points + size, size );
        }
    }

    painter->restore();
}
示例#17
0
/* ==================================== */
int32_t lattribute(
        struct xvimage *img, /* image de depart */
        int32_t connex,          /* 4, 8  */
        int32_t typregion,       /* = <LABMIN | LABMAX | LABPLATEAU> */
        int32_t attrib,          /* 0: surface, 1: perimetre, 2: circularite, 3: nb. trous, 
                                4: excentricite, 5: orientation, 6: diamètre vertical, 7: diamètre horizontal */
        int32_t seuil,           /* en dessous (<=) de seuil, l'attribut est mis a 0 */
        struct xvimage *lab, /* resultat: image d'attributs */
        int32_t *nlabels)        /* resultat: nombre de regions traitees */
/* ==================================== */
#undef F_NAME
#define F_NAME "lattribute"
{
  int32_t k, l;
  index_t w, x, y, z;
  uint8_t *SOURCE = UCHARDATA(img);
  int32_t *LABEL = SLONGDATA(lab);
  index_t rs = rowsize(img);
  index_t cs = colsize(img);
  index_t d = depth(img);
  index_t N = rs * cs;          /* taille image */
  Lifo * LIFO;
  int32_t label;
  int32_t area;
  int32_t perim;
  int32_t min, max;
  int32_t val_attrib;
  double mx1, my1; // cumuls des variables x et y
  double mx2, my2, mxy2; // cumuls des x^2, y^2 et xy
  int32_t incr_vois;

  if (datatype(lab) != VFF_TYP_4_BYTE) 
  {
    fprintf(stderr, "%s: le resultat doit etre de type VFF_TYP_4_BYTE\n", F_NAME);
    return 0;
  }

  if ((rowsize(lab) != rs) || (colsize(lab) != cs) || (depth(lab) != d))
  {
    fprintf(stderr, "%s: tailles images incompatibles\n", F_NAME);
    return 0;
  }

  if (depth(img) != 1) 
  {
    fprintf(stderr, "%s: cette version ne traite pas les images volumiques\n", F_NAME);
    exit(0);
  }

  switch (connex)
  {
    case 4: incr_vois = 2; break;
    case 8: incr_vois = 1; break;
    default: 
      fprintf(stderr, "%s: mauvaise connexite: %d\n", F_NAME, connex);
      return 0;
  } /* switch (connex) */

  /* le LABEL initialement est mis a NONMARQUE */
  for (x = 0; x < N; x++) LABEL[x] = NONMARQUE;

  LIFO = CreeLifoVide(N);
  if (LIFO == NULL)
    {   fprintf(stderr, "%s: CreeLifoVide failed\n", F_NAME);
      return(0);
  }

  *nlabels = 0;

if ((typregion == LABMIN) || (typregion == LABMAX))
{
  for (x = 0; x < N; x++)
  {
    if (LABEL[x] == NONMARQUE)   /* on trouve un point x non etiquete */
    {
      *nlabels += 1;
      LABEL[x] = MARQUE;
#ifdef DEBUGTROU
printf("AMORCE p=%d,%d h=%d set LABEL = %d\n", x%rs, x/rs, SOURCE[x], LABEL[x]);
#endif
      switch (attrib)            /* on initialise les attributs de cette composante */
      {
	case AREA: val_attrib = 0; break;
	case PERIM: val_attrib = 0; break;
	case TROUS: val_attrib = 0; break;
	case CIRC: area = perim = 0; break;
	case EXCEN: 
	case ORIEN: area = 0; mx1 = my1 = mx2 = my2 = mxy2 = 0.0; break;
        case VDIAM: min = cs-1; max = 0; break;
        case HDIAM: min = rs-1; max = 0; break;
        default: 
          fprintf(stderr, "%s: mauvais attribut: %d\n", F_NAME, attrib);
          return 0;
      } /* switch (attrib) */
      LifoPush(LIFO, x);         /* on va parcourir le plateau auquel appartient x */
      while (! LifoVide(LIFO))
      {
        w = LifoPop(LIFO);
        label = LABEL[w];
        if (label == MARQUE)     /* c'est une propagation de "marquage" : pour l'instant, */
	{                        /* on croit qu'on est dans un extremum */         
          switch (attrib)
          {
  	    case AREA: val_attrib++; break;
  	    case VDIAM: if (w/rs < min) min = w/rs; else if (w/rs > max) max = w/rs; break;
  	    case HDIAM: if (w%rs < min) min = w%rs; else if (w%rs > max) max = w%rs; break;
  	    case EXCEN:
  	    case ORIEN: area++; mx1 += w%rs; my1 += w/rs; mxy2 += (w%rs) * (w/rs);
                        mx2 += (w%rs) * (w%rs); my2 += (w/rs) * (w/rs); break;
  	    case PERIM: 
              if (w%rs==rs-1) val_attrib++; /* point de bord */
              if (w<rs)       val_attrib++; /* point de bord */
              if (w%rs==0)    val_attrib++; /* point de bord */
              if (w>=N-rs)    val_attrib++; /* point de bord */
              for (k = 0; k < 8; k += 2) /* 4-connexite obligatoire */
              {
                y = voisin(w, k, rs, N);
                if ((y != -1) && (SOURCE[y] != SOURCE[w])) val_attrib++;
              } /* for k */
            break;
            case CIRC:
              area++;
              if (w%rs==rs-1) perim++; /* point de bord */
              if (w<rs)       perim++; /* point de bord */
              if (w%rs==0)    perim++; /* point de bord */
              if (w>=N-rs)    perim++; /* point de bord */
              for (k = 0; k < 8; k += 2) /* 4-connexite obligatoire */
              {
                y = voisin(w, k, rs, N);
                if ((y != -1) && (SOURCE[y] != SOURCE[w])) perim++;
              } /* for k */
              break;
	  } /* switch (attrib) */
          for (k = 0; k < 8; k += incr_vois)
          {
            y = voisin(w, k, rs, N);
            if (y != -1)
            {
              if (((typregion == LABMIN) && (SOURCE[y] < SOURCE[w])) || 
                  ((typregion == LABMAX) && (SOURCE[y] > SOURCE[w])))
              {   /* w non dans un minimum (resp. maximum) */
                if (label == MARQUE)
		{
                  label = NONEXTREM;
                  *nlabels -= 1;
                  LABEL[w] = label;
                  LifoPush(LIFO, w);
		}
              } 
              else
              if ((SOURCE[y] == SOURCE[w]) && (LABEL[y] == NONMARQUE))
              {
                LABEL[y] = label;
#ifdef DEBUGTROU
printf(" p=%d,%d h=%d set LABEL = %d\n", y%rs, y/rs, SOURCE[y], LABEL[y]);
#endif
                LifoPush(LIFO, y);
                if (attrib == TROUS)
	        {
                  int32_t masque = 0, imasque = 1;
                  /* fabrique le masque des voisins de y MARQUES */
                  for (l = 0; l < 8; l += 1)
                  {
                    z = voisin(y, l, rs, N);
                    if ((z != -1) && (LABEL[z] == MARQUE))
                      masque |= imasque; 
                    imasque = imasque << 1;
                  } /* for k ... */
#ifdef DEBUGTROU
printf(" p=%d,%d h=%d masque=%x t4m=%d t8b=%d\n", y%rs, y/rs, SOURCE[y], masque, t4(masque), t8b(masque));
#endif
                  if (connex == 4) 
                    { val_attrib += (t4(masque) - 1); if (t8b(masque) == 0) val_attrib--; }
                  else
                    { val_attrib += (t8(masque) - 1); if (t4b(masque) == 0) val_attrib--; }
	        } /* if (attrib == TROUS) */
              } /* if ((SOURCE[y] == SOURCE[w]) && (LABEL[y] == NONMARQUE)) */
            } /* if (y != -1) */
          } /* for k ... */
	} /* if (label == MARQUE) */
        else                           /* propagation de "demarquage" */
	{
          for (k = 0; k < 8; k += incr_vois)
          {
            y = voisin(w, k, rs, N);
            if (y != -1)
            {
              if ((SOURCE[y] == SOURCE[w]) && (LABEL[y] != NONEXTREM))
              {
                LABEL[y] = NONEXTREM;
                LifoPush(LIFO, y);
              } /* if .. */
            } /* if (y != -1) */
          } /* for k ... */
	} /* else if (label == MARQUE) */
      } /* while (! LifoVide(LIFO)) */

      if (label == MARQUE)
      {
        if (attrib == CIRC) 
	{
          val_attrib = (int32_t)(256 * 4 * M_PI * (double)area / (double)(perim * perim));
          if (val_attrib > 255)
	  {
            fprintf(stderr, "WARNING: indice de circularite > 255 : %d, a=%d, p=%d\n", 
                            val_attrib, area, perim);
            val_attrib = 255;
	  }
	}
        if (attrib == EXCEN) val_attrib = excentricity(mx1, my1, mx2, my2, mxy2, area);
        if (attrib == ORIEN) val_attrib = orientation(mx1, my1, mx2, my2, mxy2, area);
        if (attrib == VDIAM) val_attrib = max - min + 1;
        if (attrib == HDIAM) val_attrib = max - min + 1;
        if (val_attrib <= seuil) val_attrib = 0;
#ifdef VERBOSE
printf("valeur attribut = %d\n", val_attrib);
#endif
        LifoPush(LIFO, x);         /* on re-parcourt le plateau pour propager l'attribut */
        LABEL[x] = val_attrib;
        while (! LifoVide(LIFO))
        {
          w = LifoPop(LIFO);
          for (k = 0; k < 8; k += incr_vois)
          {
            y = voisin(w, k, rs, N);
            if ((y != -1) && (LABEL[y] == MARQUE)) 
            {
              LABEL[y] = val_attrib;
              LifoPush(LIFO, y);
	    }
          } /* for k ... */
	} /* while (! LifoVide(LIFO)) */
      } /* if (label == MARQUE) */

    } /* if (LABEL[x] != -1) */
  } /* for (x = 0; x < N; x++) */
} /* if ((typregion == LABMIN) || (typregion == LABMAX)) */
else
{
  if (attrib == TROUS)
  {
    fprintf(stderr, "%s: attribut TROUS non compatible avec typreg = PLA\n", F_NAME);
    return 0;
  }
  for (x = 0; x < N; x++)
  {
    if (LABEL[x] == NONMARQUE)
    {
      *nlabels += 1;
      LABEL[x] = *nlabels;
      switch (attrib)            /* on initialise les attributs de cette composante */
      {
	case AREA: val_attrib = 0; break;
        case VDIAM: min = cs-1; max = 0; break;
        case HDIAM: min = rs-1; max = 0; break;
	case PERIM: val_attrib = 0; break;
	case CIRC: area = perim = 0; break;
	case EXCEN: 
	case ORIEN: area = 0; mx1 = my1 = mx2 = my2 = mxy2 = 0.0; break;
        default: 
          fprintf(stderr, "%s: mauvais attribut: %d\n", F_NAME, attrib);
          return 0;
      } /* switch (attrib) */
      LifoPush(LIFO, x);
      while (! LifoVide(LIFO))
      {
        w = LifoPop(LIFO);
        switch (attrib)
        {
	  case AREA: val_attrib++; break;
  	  case VDIAM: if (w/rs < min) min = w/rs; else if (w/rs > max) max = w/rs; break;
  	  case HDIAM: if (w%rs < min) min = w%rs; else if (w%rs > max) max = w%rs; break;
	  case EXCEN:
	  case ORIEN: area++; mx1 += w%rs; my1 += w/rs; mxy2 += (w%rs) * (w/rs);
                      mx2 += (w%rs) * (w%rs); my2 += (w/rs) * (w/rs); break;
  	  case PERIM: 
            if (w%rs==rs-1) val_attrib++; /* point de bord */
            if (w<rs)       val_attrib++; /* point de bord */
            if (w%rs==0)    val_attrib++; /* point de bord */
            if (w>=N-rs)    val_attrib++; /* point de bord */
            for (k = 0; k < 8; k += 2) /* 4-connexite obligatoire */
            {
              y = voisin(w, k, rs, N);
              if ((y != -1) && (SOURCE[y] != SOURCE[w])) val_attrib++;
            } /* for k */
          break;
          case CIRC:
            area++;
            if (w%rs==rs-1) perim++; /* point de bord */
            if (w<rs)       perim++; /* point de bord */
            if (w%rs==0)    perim++; /* point de bord */
            if (w>=N-rs)    perim++; /* point de bord */
            for (k = 0; k < 8; k += 2) /* 4-connexite obligatoire */
            {
              y = voisin(w, k, rs, N);
              if ((y != -1) && (SOURCE[y] != SOURCE[w])) perim++;
            } /* for k */
            break;
	} /* switch (attrib) */

        for (k = 0; k < 8; k += incr_vois)
        {
          y = voisin(w, k, rs, N);
          if ((y != -1) && (LABEL[y] == NONMARQUE) && (SOURCE[y] == SOURCE[w]))
          {
            LABEL[y] = MARQUE;
            LifoPush(LIFO, y);
          } /* if y ... */
        } /* for k ... */
      } /* while (! LifoVide(LIFO)) */

      if (attrib == CIRC) 
      {
        val_attrib = (int32_t)(256 * 4 * M_PI * (double)area / (double)(perim * perim));
        if (val_attrib > 255)
	{
          fprintf(stderr, "WARNING: indice de circularite > 255 : %d, a=%d, p=%d\n", 
                          val_attrib, area, perim);
          val_attrib = 255;
	}
      }
      if (attrib == EXCEN) val_attrib = excentricity(mx1, my1, mx2, my2, mxy2, area);
      if (attrib == ORIEN) val_attrib = orientation(mx1, my1, mx2, my2, mxy2, area);
      if (attrib == VDIAM) val_attrib = max - min + 1;
      if (attrib == HDIAM) val_attrib = max - min + 1;
      if (val_attrib <= seuil) val_attrib = 0;

      LifoPush(LIFO, x);         /* on re-parcourt le plateau pour propager l'attribut */
      LABEL[x] = val_attrib;
      while (! LifoVide(LIFO))
      {
        w = LifoPop(LIFO);
        for (k = 0; k < 8; k += incr_vois)
        {
          y = voisin(w, k, rs, N);
          if ((y != -1) && (LABEL[y] == MARQUE)) 
          {
            LABEL[y] = val_attrib;
            LifoPush(LIFO, y);
	  }
        } /* for k ... */
      } /* while (! LifoVide(LIFO)) */
    } /* if (LABEL[x] == NONMARQUE) */
  } /* for (x = 0; x < N; x++) */
} /* else if ((typregion == LABMIN) || (typregion == LABMAX)) */

  LifoTermine(LIFO);

  *nlabels += 1; /* pour le niveau 0 */
  return(1);
} // lattribute()
示例#18
0
void mitk::ClaronTrackingDevice::TrackTools()
{
  try
  {
    /* lock the TrackingFinishedMutex to signal that the execution rights are now transfered to the tracking thread */
    MutexLockHolder trackingFinishedLockHolder(*m_TrackingFinishedMutex); // keep lock until end of scope

    bool localStopTracking;       // Because m_StopTracking is used by two threads, access has to be guarded by a mutex. To minimize thread locking, a local copy is used here
    this->m_StopTrackingMutex->Lock();  // update the local copy of m_StopTracking
    localStopTracking = this->m_StopTracking;
    this->m_StopTrackingMutex->Unlock();

    while ((this->GetState() == Tracking) && (localStopTracking == false))
    {
      this->GetDevice()->GrabFrame();

      std::vector<mitk::ClaronTool::Pointer> detectedTools = this->DetectTools();
      std::vector<mitk::ClaronTool::Pointer> allTools = this->GetAllTools();
      std::vector<mitk::ClaronTool::Pointer>::iterator itAllTools;
      for(itAllTools = allTools.begin(); itAllTools != allTools.end(); itAllTools++)
      {
        mitk::ClaronTool::Pointer currentTool = *itAllTools;
        //test if current tool was detected
        std::vector<mitk::ClaronTool::Pointer>::iterator itDetectedTools;
        bool foundTool = false;
        for(itDetectedTools = detectedTools.begin(); itDetectedTools != detectedTools.end(); itDetectedTools++)
        {
          mitk::ClaronTool::Pointer aktuDet = *itDetectedTools;
          std::string tempString(currentTool->GetCalibrationName());
          if (tempString.compare(aktuDet->GetCalibrationName())==0)
          {
            currentTool->SetToolHandle(aktuDet->GetToolHandle());
            foundTool = true;
          }
        }
        if (!foundTool)
        {
          currentTool->SetToolHandle(0);
        }

        if (currentTool->GetToolHandle() != 0)
        {
          currentTool->SetDataValid(true);
          //get tip position of tool:
          std::vector<double> pos_vector = this->GetDevice()->GetTipPosition(currentTool->GetToolHandle());
          //write tip position into tool:
          mitk::Point3D pos;
          pos[0] = pos_vector[0];
          pos[1] = pos_vector[1];
          pos[2] = pos_vector[2];
          currentTool->SetPosition(pos);
          //get tip quaternion of tool
          std::vector<double> quat = this->GetDevice()->GetTipQuaternions(currentTool->GetToolHandle());
          //write tip quaternion into tool
          mitk::Quaternion orientation(quat[1], quat[2], quat[3], quat[0]);
          currentTool->SetOrientation(orientation);
        }
        else
        {
          mitk::Point3D origin;
          origin.Fill(0);
          currentTool->SetPosition(origin);
          currentTool->SetOrientation(mitk::Quaternion(0,0,0,0));
          currentTool->SetDataValid(false);
        }
      }
      /* Update the local copy of m_StopTracking */
      this->m_StopTrackingMutex->Lock();
      localStopTracking = m_StopTracking;
      this->m_StopTrackingMutex->Unlock();
    }
  }
  catch(...)
  {
    this->StopTracking();
    this->SetErrorMessage("Error while trying to track tools. Thread stopped.");
  }
}
示例#19
0
void ScaleDraw::drawBackbone(QPainter *painter) const
{
    ScaleEngine *sc_engine = (ScaleEngine *)d_plot->axisScaleEngine(axis());
	/*QwtScaleEngine *qwtsc_engine=d_plot->axisScaleEngine(axis());
	ScaleEngine *sc_engine =dynamic_cast<ScaleEngine*>(qwtsc_engine);
	if(sc_engine!=NULL)
	{*/
		if (!sc_engine->hasBreak()){
			const int len = length();
			const int bw = painter->pen().width();
			const int bw2 = bw / 2;
			QPoint pos = this->pos();
			switch(alignment()){
			case LeftScale:
				QwtPainter::drawLine(painter, pos.x() - bw2,
					pos.y(), pos.x() - bw2, pos.y() + len );
				break;
			case RightScale:
				QwtPainter::drawLine(painter, pos.x() + bw2,
					pos.y(), pos.x() + bw2, pos.y() + len);
				break;
			case TopScale:
				QwtPainter::drawLine(painter, pos.x(), pos.y() - bw2,
					pos.x() + len, pos.y() - bw2);
				break;
			case BottomScale:
				QwtPainter::drawLine(painter, pos.x(), pos.y() + bw2,
					pos.x() + len, pos.y() + bw2);
				break;
			}
			return;
		}

		QwtScaleMap scaleMap = map();
		const QwtMetricsMap metricsMap = QwtPainter::metricsMap();
		QPoint pos = this->pos();

		if ( !metricsMap.isIdentity() ){
			QwtPainter::resetMetricsMap();
			pos = metricsMap.layoutToDevice(pos);

			if ( orientation() == Qt::Vertical ){
				scaleMap.setPaintInterval(
					metricsMap.layoutToDeviceY((int)scaleMap.p1()),
					metricsMap.layoutToDeviceY((int)scaleMap.p2()));
			} else {
				scaleMap.setPaintInterval(
					metricsMap.layoutToDeviceX((int)scaleMap.p1()),
					metricsMap.layoutToDeviceX((int)scaleMap.p2()));
			}
		}

		const int start = scaleMap.transform(sc_engine->axisBreakLeft());
		const int end = scaleMap.transform(sc_engine->axisBreakRight());
		int lb = start, rb = end;
		if (sc_engine->testAttribute(QwtScaleEngine::Inverted)){
			lb = end;
			rb = start;
		}

		const int bw = painter->pen().width();
		const int bw2 = bw / 2;
		const int len = length() - 1;
		int aux;
		switch(alignment())
		{
		case LeftScale:
			aux = pos.x() - bw2;
			QwtPainter::drawLine(painter, aux, pos.y(), aux, rb);
			QwtPainter::drawLine(painter, aux, lb + bw, aux, pos.y() + len);
			break;
		case RightScale:
			aux = pos.x() + bw2;
			QwtPainter::drawLine(painter, aux, pos.y(), aux, rb - bw - 1);
			QwtPainter::drawLine(painter, aux, lb - bw2, aux, pos.y() + len);
			break;
		case TopScale:
			aux = pos.y() - bw2;
			QwtPainter::drawLine(painter, pos.x(), aux, lb - bw2, aux);
			QwtPainter::drawLine(painter, rb + bw, aux, pos.x() + len, aux);
			break;
		case BottomScale:
			aux = pos.y() + bw2;
			QwtPainter::drawLine(painter, pos.x(), aux, lb - bw, aux);
			QwtPainter::drawLine(painter, rb, aux, pos.x() + len, aux);
			break;
		}
	//}
}
示例#20
0
// update updates the position and orientation of the Sound Instance
//
void Sound::update() {

	if (apiSound && local) 
	    apiSound->update(position(), orientation('z'));
}
/*! @brief Updates the held information ready for a new frame.
*   Gets copies of the actions and sensors pointers from the blackboard and
*   gets a new image from the blackboard. Updates framecounts.
*   @return Whether the fetched data is valid.
*/
bool DataWrapper::updateFrame()
{
    digitalWrite (17, LOW);
    digitalWrite (18, LOW);
    digitalWrite (22, LOW);
    digitalWrite (23, LOW);

    if(m_ok) {
        if(!imagestrm.is_open()) {
            errorlog << "No image stream - " << streamname << std::endl;
            return false;
        }
        if(using_sensors && !sensorstrm.is_open()) {
            errorlog << "No sensor stream - " << sensorstreamname << std::endl;
            return false;
        }
        try {
            imagestrm >> current_frame;
        }
        catch(std::exception& e) {
            return false;
        }
        if(using_sensors) {
            try {
                sensorstrm >> sensor_data;
            }
            catch(std::exception& e){
                errorlog << "Sensor stream error: " << e.what() << std::endl;
                return false;
            }
        }

        //overwrite sensor horizon if using sensors
        std::vector<float> hor_data;
        if(using_sensors && sensor_data.getHorizon(hor_data)) {
            kinematics_horizon.setLine(hor_data.at(0), hor_data.at(1), hor_data.at(2));
        }

        //update kinematics snapshot
        if(using_sensors) {

            vector<float> orientation(3, 0);

            if(!sensor_data.getCameraHeight(camera_height))
                errorlog << "DataWrapperQt - updateFrame() - failed to get camera height from NUSensorsData" << std::endl;
            if(!sensor_data.getPosition(NUSensorsData::HeadPitch, head_pitch))
                errorlog << "DataWrapperQt - updateFrame() - failed to get head pitch from NUSensorsData" << std::endl;
            if(!sensor_data.getPosition(NUSensorsData::HeadYaw, head_yaw))
                errorlog << "DataWrapperQt - updateFrame() - failed to get head yaw from NUSensorsData" << std::endl;
            if(!sensor_data.getOrientation(orientation))
                errorlog << "DataWrapperQt - updateFrame() - failed to get orientation from NUSensorsData" << std::endl;
            orientation = Vector3<float>(orientation.at(0), orientation.at(1), orientation.at(2));

            vector<float> left, right;
            if(sensor_data.get(NUSensorsData::LLegTransform, left) and sensor_data.get(NUSensorsData::RLegTransform, right))
            {
                neck_position = Kinematics::CalculateNeckPosition(Matrix4x4fromVector(left), Matrix4x4fromVector(right), sensor_calibration.m_neck_position_offset);
            }
            else
            {
                errorlog << "DataWrapperRPi - updateFrame() - failed to get left or right leg transforms from NUSensorsData" << std::endl;
                // Default in case kinemtaics not available. Base height of darwin.
                neck_position = Vector3<double>(0.0, 0.0, 39.22);
            }
        }
        else {
            camera_height = head_pitch = head_yaw = 0;
            orientation = Vector3<float>(0,0,0);
            neck_position = Vector3<double>(0.0, 0.0, 39.22);
        }

        numFramesProcessed++;

        return current_frame.getHeight() > 0 && current_frame.getWidth() > 0;
    }
    return false;
}
示例#22
0
    // Just override the mandatory create scene method
    void createScene(void)
    {
		RenderSystem *rs = Root::getSingleton().getRenderSystem();
		const RenderSystemCapabilities* caps = rs->getCapabilities();
        if (!caps->hasCapability(RSC_VERTEX_PROGRAM) || !(caps->hasCapability(RSC_FRAGMENT_PROGRAM)))
        {
            OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "Your card does not support vertex and fragment programs, so cannot "
                "run this demo. Sorry!", 
                "DeferredShading::createScene");
        }
		if (caps->getNumMultiRenderTargets()<2)
        {
            OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "Your card does not support at least two simultaneous render targets, so cannot "
                "run this demo. Sorry!", 
                "DeferredShading::createScene");
        }

		// Prepare athene mesh for normalmapping
        MeshPtr pAthene = MeshManager::getSingleton().load("athene.mesh", 
            ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
        unsigned short src, dest;
        if (!pAthene->suggestTangentVectorBuildParams(VES_TANGENT, src, dest))
            pAthene->buildTangentVectors(VES_TANGENT, src, dest);
		// Prepare knot mesh for normal mapping
		pAthene = MeshManager::getSingleton().load("knot.mesh", 
            ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
        if (!pAthene->suggestTangentVectorBuildParams(VES_TANGENT, src, dest))
            pAthene->buildTangentVectors(VES_TANGENT, src, dest);

        // Set ambient light
        mSceneMgr->setAmbientLight(ColourValue(0.2, 0.2, 0.15));
        // Skybox
        mSceneMgr->setSkyBox(true, "DeferredDemo/SkyBox");

		// Create "root" node
		SceneNode* rootNode = mSceneMgr->getRootSceneNode()->createChildSceneNode();

		Entity* athena = mSceneMgr->createEntity("Athena", "athene.mesh");
		athena->setMaterialName("DeferredDemo/DeferredAthena");
		SceneNode *aNode = rootNode->createChildSceneNode();
		aNode->attachObject( athena );
		aNode->setPosition(-100, 40, 100);

		// Create a prefab plane
		mPlane = new MovablePlane("ReflectPlane");
		mPlane->d = 0;
		mPlane->normal = Vector3::UNIT_Y;
		MeshManager::getSingleton().createCurvedPlane("ReflectionPlane", 
			ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, 
			*mPlane,
			2000, 2000, -1000,
			20, 20, 
			true, 1, 10, 10, Vector3::UNIT_Z);
		mPlaneEnt = mSceneMgr->createEntity( "Plane", "ReflectionPlane" );
		mPlaneNode = rootNode->createChildSceneNode();
		mPlaneNode->attachObject(mPlaneEnt);
		mPlaneNode->translate(-5, -30, 0);
		//mPlaneNode->roll(Degree(5));
		mPlaneEnt->setMaterialName("DeferredDemo/Ground");

		// Create an entity from a model (will be loaded automatically)
		Entity* knotEnt = mSceneMgr->createEntity("Knot", "knot.mesh");
		knotEnt->setMaterialName("DeferredDemo/RockWall");
		knotEnt->setMeshLodBias(0.25f);

		// Create an entity from a model (will be loaded automatically)
		Entity* ogreHead = mSceneMgr->createEntity("Head", "ogrehead.mesh");
		ogreHead->getSubEntity(0)->setMaterialName("DeferredDemo/Ogre/Eyes");// eyes
		ogreHead->getSubEntity(1)->setMaterialName("DeferredDemo/Ogre/Skin"); 
		ogreHead->getSubEntity(2)->setMaterialName("DeferredDemo/Ogre/EarRing"); // earrings
		ogreHead->getSubEntity(3)->setMaterialName("DeferredDemo/Ogre/Tusks"); // tusks
		rootNode->createChildSceneNode( "Head" )->attachObject( ogreHead );

		// Add a whole bunch of extra entities to fill the scene a bit
		Entity *cloneEnt;
		int N=4;
		for (int n = 0; n < N; ++n)
		{
			float theta = 2.0f*Math::PI*(float)n/(float)N;
			// Create a new node under the root
			SceneNode* node = mSceneMgr->createSceneNode();
			// Random translate
			Vector3 nodePos;
			nodePos.x = Math::SymmetricRandom() * 40.0 + Math::Sin(theta) * 500.0;
			nodePos.y = Math::SymmetricRandom() * 20.0 - 40.0;
			nodePos.z = Math::SymmetricRandom() * 40.0 + Math::Cos(theta) * 500.0;
			node->setPosition(nodePos);
			Quaternion orientation(Math::SymmetricRandom(),Math::SymmetricRandom(),Math::SymmetricRandom(),Math::SymmetricRandom());
			orientation.normalise();
			node->setOrientation(orientation);
			rootNode->addChild(node);
			// Clone knot
			char cloneName[12];
			sprintf(cloneName, "Knot%d", n);
			cloneEnt = knotEnt->clone(cloneName);
			// Attach to new node
			node->attachObject(cloneEnt);

		}

        mCamera->setPosition(-50, 100, 500);
        mCamera->lookAt(0,0,0);

		// show overlay
		Overlay* overlay = OverlayManager::getSingleton().getByName("Example/ShadowsOverlay");    
		overlay->show();

		mSystem = new DeferredShadingSystem(mWindow->getViewport(0), mSceneMgr, mCamera);

		// Create main, moving light
		MLight* l1 = mSystem->createMLight();//"MainLight");
        l1->setDiffuseColour(0.75f, 0.7f, 0.8f);
		l1->setSpecularColour(0.85f, 0.9f, 1.0f);
		
		SceneNode *lightNode = mSceneMgr->getRootSceneNode()->createChildSceneNode();
		lightNode->attachObject(l1);

		// Create a track for the light
        Animation* anim = mSceneMgr->createAnimation("LightTrack", 16);
        // Spline it for nice curves
        anim->setInterpolationMode(Animation::IM_SPLINE);
        // Create a track to animate the camera's node
        NodeAnimationTrack* track = anim->createNodeTrack(0, lightNode);
        // Setup keyframes
        TransformKeyFrame* key = track->createNodeKeyFrame(0); // A start position
        key->setTranslate(Vector3(300,300,-300));
        key = track->createNodeKeyFrame(4);//B
        key->setTranslate(Vector3(300,300,300));
        key = track->createNodeKeyFrame(8);//C
        key->setTranslate(Vector3(-300,300,300));
        key = track->createNodeKeyFrame(12);//D
        key->setTranslate(Vector3(-300,300,-300));
		key = track->createNodeKeyFrame(16);//D
        key->setTranslate(Vector3(300,300,-300));
        // Create a new animation state to track this
        SharedData::getSingleton().mAnimState = mSceneMgr->createAnimationState("LightTrack");
        SharedData::getSingleton().mAnimState->setEnabled(true);

		// Create some happy little lights
		createSampleLights();

		// safely setup application's (not postfilter!) shared data
		SharedData::getSingleton().iCamera = mCamera;
		SharedData::getSingleton().iRoot = mRoot;
		SharedData::getSingleton().iWindow = mWindow;
		SharedData::getSingleton().iActivate = true;
		SharedData::getSingleton().iGlobalActivate = true;
		SharedData::getSingleton().iSystem = mSystem;
		SharedData::getSingleton().iMainLight = l1;
	}
示例#23
0
文件: q3dockarea.cpp 项目: Suneal/qt
void Q3DockArea::moveDockWindow(Q3DockWindow *w, const QPoint &p, const QRect &r, bool swap)
{
    invalidateFixedSizes();
    int mse = -10;
    bool hasResizable = false;
    for (int i = 0; i < dockWindows.size(); ++i) {
        Q3DockWindow *dw = dockWindows.at(i);
        if (dw->isHidden())
            continue;
        if (dw->isResizeEnabled())
            hasResizable = true;
        if (orientation() != Qt::Horizontal)
            mse = qMax(qMax(dw->fixedExtent().width(), dw->width()), mse);
        else
            mse = qMax(qMax(dw->fixedExtent().height(), dw->height()), mse);
    }
    if (!hasResizable && w->isResizeEnabled()) {
        if (orientation() != Qt::Horizontal)
            mse = qMax(w->fixedExtent().width(), mse);
        else
            mse = qMax(w->fixedExtent().height(), mse);
    }

    Q3DockWindow *dockWindow = 0;
    int dockWindowIndex = findDockWindow(w);
    QList<Q3DockWindow *> lineStarts = layout->lineStarts();
    QList<QRect> lines = layout->lineList();
    bool wasAloneInLine = false;
    QPoint pos = mapFromGlobal(p);
    int line = lineOf(dockWindowIndex);
    QRect lr;
    if (line < lines.size())
        lr = lines.at(line);
    if (dockWindowIndex != -1) {
        if (lineStarts.contains(w)
            && ((dockWindowIndex < dockWindows.count() - 1
                 && lineStarts.contains(dockWindows.at(dockWindowIndex + 1)))
                || dockWindowIndex == dockWindows.count() - 1))
            wasAloneInLine = true;
        dockWindow = dockWindows.takeAt(dockWindowIndex);
        if (!wasAloneInLine) { // only do the pre-layout if the widget isn't the only one in its line
            if (lineStarts.contains(dockWindow) && dockWindowIndex < dockWindows.count())
                dockWindows.at(dockWindowIndex)->setNewLine(true);
            layout->layoutItems(QRect(0, 0, width(), height()), true);
        }
    } else {
        dockWindow = w;
        bool vis = dockWindow->isVisible();
        dockWindow->setParent(this);
        dockWindow->move(0, 0);
        if(vis)
            dockWindow->show();
        if (swap)
            dockWindow->resize(dockWindow->height(), dockWindow->width());
        w->installEventFilter(this);
    }

    lineStarts = layout->lineStarts();
    lines = layout->lineList();

    QRect rect = QRect(mapFromGlobal(r.topLeft()), r.size());
    if (orientation() == Qt::Horizontal && QApplication::reverseLayout()) {
        rect = QRect(width() - rect.x() - rect.width(), rect.y(), rect.width(), rect.height());
        pos.rx() = width() - pos.x();
    }
    dockWindow->setOffset(point_pos(rect.topLeft(), orientation()));
    if (orientation() == Qt::Horizontal) {
        int offs = dockWindow->offset();
        if (width() - offs < dockWindow->minimumWidth())
            dockWindow->setOffset(width() - dockWindow->minimumWidth());
    } else {
        int offs = dockWindow->offset();
        if (height() - offs < dockWindow->minimumHeight())
            dockWindow->setOffset(height() - dockWindow->minimumHeight());
    }

    if (dockWindows.isEmpty()) {
        dockWindows.append(dockWindow);
    } else {
        int dockLine = -1;
        bool insertLine = false;
        int i = 0;
        QRect lineRect;
        // find the line which we touched with the mouse
        for (QList<QRect>::Iterator it = lines.begin(); it != lines.end(); ++it, ++i) {
            if (point_pos(pos, orientation(), true) >= point_pos((*it).topLeft(), orientation(), true) &&
                 point_pos(pos, orientation(), true) <= point_pos((*it).topLeft(), orientation(), true) +
                 size_extent((*it).size(), orientation(), true)) {
                dockLine = i;
                lineRect = *it;
                break;
            }
        }
        if (dockLine == -1) { // outside the dock...
            insertLine = true;
            if (point_pos(pos, orientation(), true) < 0) // insert as first line
                dockLine = 0;
            else
                dockLine = (int)lines.count(); // insert after the last line ### size_t/int cast
        } else { // inside the dock (we have found a dockLine)
            if (point_pos(pos, orientation(), true) <
                 point_pos(lineRect.topLeft(), orientation(), true) + 4) {        // mouse was at the very beginning of the line
                insertLine = true;                                        // insert a new line before that with the docking widget
            } else if (point_pos(pos, orientation(), true) >
                        point_pos(lineRect.topLeft(), orientation(), true) +
                        size_extent(lineRect.size(), orientation(), true) - 4) {        // mouse was at the very and of the line
                insertLine = true;                                                // insert a line after that with the docking widget
                dockLine++;
            }
        }

        if (!insertLine && wasAloneInLine && lr.contains(pos)) // if we are alone in a line and just moved in there, re-insert it
            insertLine = true;

#if defined(QDOCKAREA_DEBUG)
        qDebug("insert in line %d, and insert that line: %d", dockLine, insertLine);
        qDebug("     (btw, we have %d lines)", lines.count());
#endif
        Q3DockWindow *dw = 0;
        if (dockLine >= (int)lines.count()) { // insert after last line
            dockWindows.append(dockWindow);
            dockWindow->setNewLine(true);
#if defined(QDOCKAREA_DEBUG)
            qDebug("insert at the end");
#endif
        } else if (dockLine == 0 && insertLine) { // insert before first line
            dockWindows.insert(0, dockWindow);
            dockWindows.at(1)->setNewLine(true);
#if defined(QDOCKAREA_DEBUG)
            qDebug("insert at the begin");
#endif
        } else { // insert somewhere in between
            // make sure each line start has a new line
            for (int i = 0; i < lineStarts.size(); ++i) {
                dw = lineStarts.at(i);
                dw->setNewLine(true);
            }

            // find the index of the first widget in the search line
            int searchLine = dockLine;
#if defined(QDOCKAREA_DEBUG)
            qDebug("search line start of %d", searchLine);
#endif
            Q3DockWindow *lsw = lineStarts.at(searchLine);
            int index = dockWindows.indexOf(lsw);
            if (index == -1) { // the linestart widget hasn't been found, try to find it harder
                if (lsw == w && dockWindowIndex <= dockWindows.count())
                    index = dockWindowIndex;
                else
                    index = 0;
            }
#if defined(QDOCKAREA_DEBUG)
            qDebug("     which starts at %d", index);
#endif
            if (!insertLine) { // if we insert the docking widget in the existing line
                // find the index for the widget
                bool inc = true;
                bool firstTime = true;
                for (int i = index; i < dockWindows.size(); ++i) {
                    dw = dockWindows.at(i);
                    if (orientation() == Qt::Horizontal)
                        dw->setFixedExtentWidth(-1);
                    else
                        dw->setFixedExtentHeight(-1);
                    if (!firstTime && lineStarts.contains(dw)) // we are in the next line, so break
                        break;
                    if (point_pos(pos, orientation()) <
                         point_pos(fix_pos(dw), orientation()) + size_extent(dw->size(), orientation()) / 2) {
                        inc = false;
                    }
                    if (inc)
                        index++;
                    firstTime = false;
                }
#if defined(QDOCKAREA_DEBUG)
                qDebug("insert at index: %d", index);
#endif
                // if we insert it just before a widget which has a new line, transfer the newline to the docking widget
                // but not if we didn't only mave a widget in its line which was alone in the line before
                if (!(wasAloneInLine && lr.contains(pos))
                     && index >= 0 && index < dockWindows.count() &&
                     dockWindows.at(index)->newLine() && lineOf(index) == dockLine) {
#if defined(QDOCKAREA_DEBUG)
                    qDebug("get rid of the old newline and get me one");
#endif
                    dockWindows.at(index)->setNewLine(false);
                    dockWindow->setNewLine(true);
                } else if (wasAloneInLine && lr.contains(pos)) {
                    dockWindow->setNewLine(true);
                } else { // if we are somewhere in a line, get rid of the newline
                    dockWindow->setNewLine(false);
                }
            } else { // insert in a new line, so make sure the dock widget and the widget which will be after it have a newline
#if defined(QDOCKAREA_DEBUG)
                qDebug("insert a new line");
#endif
                if (index < dockWindows.count()) {
#if defined(QDOCKAREA_DEBUG)
                    qDebug("give the widget at %d a newline", index);
#endif
                    Q3DockWindow* nldw = dockWindows.at(index);
                    if (nldw)
                        nldw->setNewLine(true);
                }
#if defined(QDOCKAREA_DEBUG)
                qDebug("give me a newline");
#endif
                dockWindow->setNewLine(true);
            }
            // finally insert the widget
            dockWindows.insert(index, dockWindow);
        }
    }

    if (mse != -10 && w->isResizeEnabled()) {
        if (orientation() != Qt::Horizontal)
            w->setFixedExtentWidth(qMin(qMax(w->minimumWidth(), mse), w->sizeHint().width()));
        else
            w->setFixedExtentHeight(qMin(qMax(w->minimumHeight(), mse), w->sizeHint().height()));
    }

    updateLayout();
    setSizePolicy(QSizePolicy(orientation() == Qt::Horizontal ? QSizePolicy::Expanding : QSizePolicy::Minimum,
                                orientation() == Qt::Vertical ? QSizePolicy::Expanding : QSizePolicy::Minimum));
}
示例#24
0
/*!
  Draw step function

  The direction of the steps depends on Inverted attribute.

  \param painter Painter
  \param xMap x map
  \param yMap y map
  \param canvasRect Contents rect of the canvas
  \param from index of the first point to be painted
  \param to index of the last point to be painted

  \sa CurveAttribute, setCurveAttribute(),
      draw(), drawCurve(), drawDots(), drawLines(), drawSticks()
*/
void QwtPlotCurve::drawSteps( QPainter *painter,
    const QwtScaleMap &xMap, const QwtScaleMap &yMap,
    const QRectF &canvasRect, int from, int to ) const
{
    const bool doAlign = QwtPainter::roundingAlignment( painter );

    QPolygonF polygon( 2 * ( to - from ) + 1 );
    QPointF *points = polygon.data();

    bool inverted = orientation() == Qt::Vertical;
    if ( d_data->attributes & Inverted )
        inverted = !inverted;

    int i, ip;
    for ( i = from, ip = 0; i <= to; i++, ip += 2 )
    {
        const QPointF sample = d_series->sample( i );
        double xi = xMap.transform( sample.x() );
        double yi = yMap.transform( sample.y() );
        if ( doAlign )
        {
            xi = qRound( xi );
            yi = qRound( yi );
        }

        if ( ip > 0 )
        {
            const QPointF &p0 = points[ip - 2];
            QPointF &p = points[ip - 1];

            if ( inverted )
            {
                p.rx() = p0.x();
                p.ry() = yi;
            }
            else
            {
                p.rx() = xi;
                p.ry() = p0.y();
            }
        }

        points[ip].rx() = xi;
        points[ip].ry() = yi;
    }

    if ( d_data->paintAttributes & ClipPolygons )
    {
        const QPolygonF clipped = QwtClipper::clipPolygonF( 
            canvasRect, polygon, false );

        QwtPainter::drawPolyline( painter, clipped );
    }
    else
    {
        QwtPainter::drawPolyline( painter, polygon );
    }

    if ( d_data->brush.style() != Qt::NoBrush )
        fillCurve( painter, xMap, yMap, canvasRect, polygon );
}
void VanishingScrollBar::onOrientationChanged()
{
    resize(sizeHint());
    setSizePolicy(sizePolicyForOrientation(orientation()));
}
示例#26
0
void EC_OgreSky::CreateSky(bool show)
{
    if (renderer_.expired())
        return;
    RendererPtr renderer = renderer_.lock();  
    DisableSky();
    
    Ogre::SceneManager* scene_mgr = renderer->GetSceneManager();
    
    /*RexTypes::Vector3 v = genericSkyParameters.angleAxis;
    Ogre::Quaternion orientation(Ogre::Degree(genericSkyParameters.angle), Ogre::Vector3(v.x, v.y, v.z));*/
 
    ///\todo Get the sky type and other parameters from the config file.
    switch(type_)
    {
    case SKYTYPE_BOX:
    {
        Ogre::MaterialPtr skyMaterial = Ogre::MaterialManager::getSingleton().getByName(skyBoxParameters.material);
        skyMaterial->setReceiveShadows(false);
        try
        {
            RexTypes::Vector3 v = skyBoxParameters.angleAxis;
            Ogre::Quaternion orientation(Ogre::Degree(skyBoxParameters.angle), Ogre::Vector3(v.x, v.y, v.z));

            scene_mgr->setSkyBox(show, skyBoxParameters.material, skyBoxParameters.distance, skyBoxParameters.drawFirst, orientation);
        }
        catch (Ogre::Exception& e)
        {
            OgreRenderingModule::LogError("Could not set SkyBox: " + std::string(e.what()));
            return;
        }
        
        skyEnabled_ = true;
        break;
    }
    case SKYTYPE_DOME:
        try
        {
            RexTypes::Vector3 v = skyDomeParameters.angleAxis;
            Ogre::Quaternion orientation(Ogre::Degree(skyDomeParameters.angle), Ogre::Vector3(v.x, v.y, v.z));

            scene_mgr->setSkyDome(show, skyDomeParameters.material, skyDomeParameters.curvature, skyDomeParameters.tiling,
                skyDomeParameters.distance, skyDomeParameters.drawFirst, orientation, skyDomeParameters.xSegments,
                skyDomeParameters.ySegments, skyDomeParameters.ySegmentsKeep);
        }
        catch (Ogre::Exception& e)
        {
            OgreRenderingModule::LogError("Could not set SkyDome: " + std::string(e.what()));
            return;
        }

        skyEnabled_ = true;
        break;
    case SKYTYPE_PLANE:
        try
        {
            ///\todo
            Ogre::Plane plane;
            plane.d = skyPlaneParameters.distance;
            plane.normal = Ogre::Vector3::NEGATIVE_UNIT_Z;
            scene_mgr->setSkyPlane(true, plane, skyPlaneParameters.material, skyPlaneParameters.scale, skyPlaneParameters.tiling, true, 
                                    skyPlaneParameters.bow, skyPlaneParameters.xSegments, skyPlaneParameters.ySegments);
        }
        catch (Ogre::Exception& e)
        {
            OgreRenderingModule::LogError("Could not set SkyPlane: " + std::string(e.what()));
            return;
        }
        
        skyEnabled_ = true;
        break;
    case SKYTYPE_NONE:
    default:
        skyEnabled_ = false;
        break;
    }
}
示例#27
0
文件: Camera.cpp 项目: jheise/grid
glm::vec3 Camera::right() const {
    glm::vec4 right = glm::inverse(orientation()) * glm::vec4(1,0,0,1);
    return glm::vec3(right);
}
示例#28
0
bool Scrollbar::gestureEvent(const PlatformGestureEvent& evt,
                             bool* shouldUpdateCapture) {
  DCHECK(shouldUpdateCapture);
  switch (evt.type()) {
    case PlatformEvent::GestureTapDown:
      setPressedPart(theme().hitTest(*this, evt.position()));
      m_pressedPos = orientation() == HorizontalScrollbar
                         ? convertFromRootFrame(evt.position()).x()
                         : convertFromRootFrame(evt.position()).y();
      *shouldUpdateCapture = true;
      return true;
    case PlatformEvent::GestureTapDownCancel:
      if (m_pressedPart != ThumbPart)
        return false;
      m_scrollPos = m_pressedPos;
      return true;
    case PlatformEvent::GestureScrollBegin:
      switch (evt.source()) {
        case PlatformGestureSourceTouchpad:
          // Update the state on GSB for touchpad since GestureTapDown
          // is not generated by that device. Touchscreen uses the tap down
          // gesture since the scrollbar enters a visual active state.
          *shouldUpdateCapture = true;
          setPressedPart(NoPart);
          m_pressedPos = 0;
          return true;
        case PlatformGestureSourceTouchscreen:
          if (m_pressedPart != ThumbPart)
            return false;
          m_scrollPos = m_pressedPos;
          return true;
        default:
          ASSERT_NOT_REACHED();
          return true;
      }
      break;
    case PlatformEvent::GestureScrollUpdate:
      switch (evt.source()) {
        case PlatformGestureSourceTouchpad: {
          FloatSize delta(-evt.deltaX(), -evt.deltaY());
          if (m_scrollableArea &&
              m_scrollableArea->userScroll(evt.deltaUnits(), delta)
                  .didScroll()) {
            return true;
          }
          return false;
        }
        case PlatformGestureSourceTouchscreen:
          if (m_pressedPart != ThumbPart)
            return false;
          m_scrollPos += orientation() == HorizontalScrollbar ? evt.deltaX()
                                                              : evt.deltaY();
          moveThumb(m_scrollPos, false);
          return true;
        default:
          ASSERT_NOT_REACHED();
          return true;
      }
      break;
    case PlatformEvent::GestureScrollEnd:
    case PlatformEvent::GestureLongPress:
    case PlatformEvent::GestureFlingStart:
      m_scrollPos = 0;
      m_pressedPos = 0;
      setPressedPart(NoPart);
      return false;
    case PlatformEvent::GestureTap: {
      if (m_pressedPart != ThumbPart && m_pressedPart != NoPart &&
          m_scrollableArea &&
          m_scrollableArea
              ->userScroll(
                  pressedPartScrollGranularity(),
                  toScrollDelta(pressedPartScrollDirectionPhysical(), 1))
              .didScroll()) {
        return true;
      }
      m_scrollPos = 0;
      m_pressedPos = 0;
      setPressedPart(NoPart);
      return false;
    }
    default:
      // By default, we assume that gestures don't deselect the scrollbar.
      return true;
  }
}
示例#29
0
文件: Camera.cpp 项目: jheise/grid
glm::mat4 Camera::view() const {
    return orientation() * glm::translate(glm::mat4(), -_position);
}
示例#30
0
void DockBarExtension::mouseMoveEvent(QMouseEvent *e)
{
    if(!(e->state() & LeftButton))
        return;
    if(dragging_container == 0)
    {
        // Check whether the user has moved far enough.
        int delay = QApplication::startDragDistance();
        if((mclic_pos - e->pos()).manhattanLength() > delay)
        {
            int pos = findContainerAtPoint(e->pos());
            original_container = 0;
            if(pos > -1)
            {
                original_container = containers.at(pos);
                mclic_dock_pos = e->pos() - original_container->pos();
                dragged_container_original_pos = pos;
                dragging_container =
                    new DockContainer(original_container->command(), 0, original_container->resName(), original_container->resClass(), true);
                dragging_container->show();
                dragging_container->embed(original_container->embeddedWinId());
                grabMouse();
            }
        }
    }
    if(dragging_container)
    {
        dragging_container->move(e->globalPos() - mclic_dock_pos);

        // change layout of other containers
        QPoint dragpos(dragging_container->pos()), barpos(mapToGlobal(pos()));
        int pdrag1, pdrag2, psz;
        pdrag1 = dragpos.x() - barpos.x() + DockContainer::sz() / 2;
        pdrag2 = dragpos.y() - barpos.y() + DockContainer::sz() / 2;
        if(orientation() == Vertical)
        {
            int tmp = pdrag1;
            pdrag1 = pdrag2;
            pdrag2 = tmp;
            psz = height();
        }
        else
            psz = width();
        if(pdrag2 >= 0 && pdrag2 < DockContainer::sz() && pdrag1 >= 0 && pdrag1 < psz)
            pdrag1 /= DockContainer::sz();
        else
            pdrag1 = dragged_container_original_pos;


        DockContainer::Vector::iterator it = qFind(containers.begin(), containers.end(), original_container);

        if(it == containers.end())
        {
            return;
        }

        DockContainer::Vector::iterator target = containers.begin();
        for(int i = 0; i < pdrag1 && target != containers.end(); ++i)
        {
            ++target;
        }

        containers.erase(it);
        containers.insert(target, original_container);
        layoutContainers();
    }
}