Example #1
1
Qgs3DMapScene::Qgs3DMapScene( const Qgs3DMapSettings &map, QgsAbstract3DEngine *engine )
  : mMap( map )
  , mEngine( engine )
{

  connect( &map, &Qgs3DMapSettings::backgroundColorChanged, this, &Qgs3DMapScene::onBackgroundColorChanged );
  onBackgroundColorChanged();

  // TODO: strange - setting OnDemand render policy still keeps QGIS busy (Qt 5.9.0)
  // actually it is more busy than with the default "Always" policy although there are no changes in the scene.
  //mRenderer->renderSettings()->setRenderPolicy( Qt3DRender::QRenderSettings::OnDemand );

#if QT_VERSION >= 0x050900
  // we want precise picking of terrain (also bounding volume picking does not seem to work - not sure why)
  mEngine->renderSettings()->pickingSettings()->setPickMethod( Qt3DRender::QPickingSettings::TrianglePicking );
#endif

  QRect viewportRect( QPoint( 0, 0 ), mEngine->size() );

  // Camera
  float aspectRatio = ( float )viewportRect.width() / viewportRect.height();
  mEngine->camera()->lens()->setPerspectiveProjection( mMap.fieldOfView(), aspectRatio, 10.f, 10000.0f );

  mFrameAction = new Qt3DLogic::QFrameAction();
  connect( mFrameAction, &Qt3DLogic::QFrameAction::triggered,
           this, &Qgs3DMapScene::onFrameTriggered );
  addComponent( mFrameAction ); // takes ownership

  // Camera controlling
  mCameraController = new QgsCameraController( this ); // attaches to the scene
  mCameraController->setViewport( viewportRect );
  mCameraController->setCamera( mEngine->camera() );
  mCameraController->resetView( 1000 );

  addCameraViewCenterEntity( mEngine->camera() );

  // create terrain entity

  createTerrainDeferred();
  connect( &map, &Qgs3DMapSettings::terrainGeneratorChanged, this, &Qgs3DMapScene::createTerrain );
  connect( &map, &Qgs3DMapSettings::terrainVerticalScaleChanged, this, &Qgs3DMapScene::createTerrain );
  connect( &map, &Qgs3DMapSettings::mapTileResolutionChanged, this, &Qgs3DMapScene::createTerrain );
  connect( &map, &Qgs3DMapSettings::maxTerrainScreenErrorChanged, this, &Qgs3DMapScene::createTerrain );
  connect( &map, &Qgs3DMapSettings::maxTerrainGroundErrorChanged, this, &Qgs3DMapScene::createTerrain );
  connect( &map, &Qgs3DMapSettings::terrainShadingChanged, this, &Qgs3DMapScene::createTerrain );
  connect( &map, &Qgs3DMapSettings::pointLightsChanged, this, &Qgs3DMapScene::updateLights );
  connect( &map, &Qgs3DMapSettings::fieldOfViewChanged, this, &Qgs3DMapScene::updateCameraLens );

  // create entities of renderers

  Q_FOREACH ( const QgsAbstract3DRenderer *renderer, map.renderers() )
  {
    Qt3DCore::QEntity *newEntity = renderer->createEntity( map );
    newEntity->setParent( this );
  }

  // listen to changes of layers in order to add/remove 3D renderer entities
  connect( &map, &Qgs3DMapSettings::layersChanged, this, &Qgs3DMapScene::onLayersChanged );

  updateLights();

#if 0
  ChunkedEntity *testChunkEntity = new ChunkedEntity( AABB( -500, 0, -500, 500, 100, 500 ), 2.f, 3.f, 7, new TestChunkLoaderFactory );
  testChunkEntity->setEnabled( false );
  testChunkEntity->setParent( this );
  chunkEntities << testChunkEntity;
#endif

  connect( mCameraController, &QgsCameraController::cameraChanged, this, &Qgs3DMapScene::onCameraChanged );
  connect( mCameraController, &QgsCameraController::viewportChanged, this, &Qgs3DMapScene::onCameraChanged );

#if 0
  // experiments with loading of existing 3D models.

  // scene loader only gets loaded only when added to a scene...
  // it loads everything: geometries, materials, transforms, lights, cameras (if any)
  Qt3DCore::QEntity *loaderEntity = new Qt3DCore::QEntity;
  Qt3DRender::QSceneLoader *loader = new Qt3DRender::QSceneLoader;
  loader->setSource( QUrl( "file:///home/martin/Downloads/LowPolyModels/tree.dae" ) );
  loaderEntity->addComponent( loader );
  loaderEntity->setParent( this );

  // mesh loads just geometry as one geometry...
  // so if there are different materials (e.g. colors) used in the model, this information is lost
  Qt3DCore::QEntity *meshEntity = new Qt3DCore::QEntity;
  Qt3DRender::QMesh *mesh = new Qt3DRender::QMesh;
  mesh->setSource( QUrl( "file:///home/martin/Downloads/LowPolyModels/tree.obj" ) );
  meshEntity->addComponent( mesh );
  Qt3DExtras::QPhongMaterial *material = new Qt3DExtras::QPhongMaterial;
  material->setAmbient( Qt::red );
  meshEntity->addComponent( material );
  Qt3DCore::QTransform *meshTransform = new Qt3DCore::QTransform;
  meshTransform->setScale( 1 );
  meshEntity->addComponent( meshTransform );
  meshEntity->setParent( this );
#endif

  if ( map.hasSkyboxEnabled() )
  {
    Qt3DExtras::QSkyboxEntity *skybox = new Qt3DExtras::QSkyboxEntity;
    skybox->setBaseName( map.skyboxFileBase() );
    skybox->setExtension( map.skyboxFileExtension() );
    skybox->setParent( this );

    // docs say frustum culling must be disabled for skybox.
    // it _somehow_ works even when frustum culling is enabled with some camera positions,
    // but then when zoomed in more it would disappear - so let's keep frustum culling disabled
    mEngine->setFrustumCullingEnabled( false );
  }

  // force initial update of chunked entities
  onCameraChanged();
}
Example #2
0
void ShapeTool::mouseMoveEvent(QMouseEvent* e)
{
    if (m_mousePressed) {
        m_polyline[0] = e->pos();
        QPainter painter;
        painter.begin(m_pDrawPadCanvas->currentPage()->pixmap());
        drawTemporaryShape(painter);
        painter.end();

        QRect r = m_polyline.boundingRect();
        r = r.normalize();
        r.setLeft(r.left() - m_pDrawPad->pen().width());
        r.setTop(r.top() - m_pDrawPad->pen().width());
        r.setRight(r.right() + m_pDrawPad->pen().width());
        r.setBottom(r.bottom() + m_pDrawPad->pen().width());

        QRect viewportRect(m_pDrawPadCanvas->contentsToViewport(r.topLeft()),
                           m_pDrawPadCanvas->contentsToViewport(r.bottomRight()));

        bitBlt(m_pDrawPadCanvas->viewport(), viewportRect.x(), viewportRect.y(),
               m_pDrawPadCanvas->currentPage()->pixmap(), r.x(), r.y(), r.width(), r.height());

        m_pDrawPadCanvas->viewport()->update(viewportRect);

        m_polyline[1] = m_polyline[0];
    }
}
void BakedOpRenderer::endFrame(const Rect& repaintRect) {
    if (CC_UNLIKELY(Properties::debugOverdraw)) {
        ClipRect overdrawClip(repaintRect);
        Rect viewportRect(mRenderTarget.viewportWidth, mRenderTarget.viewportHeight);
        // overdraw visualization
        for (int i = 1; i <= 4; i++) {
            if (i < 4) {
                // nth level of overdraw tests for n+1 draws per pixel
                mRenderState.stencil().enableDebugTest(i + 1, false);
            } else {
                // 4th level tests for 4 or higher draws per pixel
                mRenderState.stencil().enableDebugTest(4, true);
            }

            SkPaint paint;
            paint.setColor(mCaches.getOverdrawColor(i));
            Glop glop;
            GlopBuilder(mRenderState, mCaches, &glop)
                    .setRoundRectClipState(nullptr)
                    .setMeshUnitQuad()
                    .setFillPaint(paint, 1.0f)
                    .setTransform(Matrix4::identity(), TransformFlags::None)
                    .setModelViewMapUnitToRect(viewportRect)
                    .build();
            renderGlop(nullptr, &overdrawClip, glop);
        }
        mRenderState.stencil().disable();
    }

    // Note: we leave FBO 0 renderable here, for post-frame-content decoration
}
Example #4
0
float ChromeClientImpl::windowToViewportScalar(const float scalarValue) const {
  if (!m_webView->client())
    return scalarValue;
  WebFloatRect viewportRect(0, 0, scalarValue, 0);
  m_webView->client()->convertWindowToViewport(&viewportRect);
  return viewportRect.width;
}
Example #5
0
void Qgs3DMapCanvas::resizeEvent( QResizeEvent *ev )
{
  QWidget::resizeEvent( ev );

  QRect viewportRect( QPoint( 0, 0 ), size() );
  mScene->cameraController()->setViewport( viewportRect );
}
Example #6
0
void QgsLayoutView::viewChanged()
{
  if ( mHorizontalRuler )
  {
    mHorizontalRuler->setSceneTransform( viewportTransform() );
  }
  if ( mVerticalRuler )
  {
    mVerticalRuler->setSceneTransform( viewportTransform() );
  }

  // determine page at center of view
  QRect viewportRect( 0, 0, viewport()->width(), viewport()->height() );
  QRectF visibleRect = mapToScene( viewportRect ).boundingRect();
  QPointF centerVisible = visibleRect.center();

  if ( currentLayout() && currentLayout()->pageCollection() )
  {
    int newPage = currentLayout()->pageCollection()->pageNumberForPoint( centerVisible );
    if ( newPage != mCurrentPage )
    {
      mCurrentPage = newPage;
      emit pageChanged( mCurrentPage );
    }
  }
}
Example #7
0
QList<int> QgsLayoutView::visiblePageNumbers() const
{
  //get current visible part of scene
  QRect viewportRect( 0, 0, viewport()->width(), viewport()->height() );
  QRectF visibleRect = mapToScene( viewportRect ).boundingRect();
  return currentLayout()->pageCollection()->visiblePageNumbers( visibleRect );
}
Example #8
0
void QgsLayoutViewToolZoom::layoutReleaseEvent( QgsLayoutViewMouseEvent *event )
{
  if ( !mMarqueeZoom || event->button() != Qt::LeftButton )
  {
    event->ignore();
    return;
  }

  mMarqueeZoom = false;
  QRectF newBoundsRect = mRubberBand->finish( event->layoutPoint() );

  // click? or click-and-drag?
  if ( !isClickAndDrag( mMousePressStartPos, event->pos() ) )
  {
    //just a click, so zoom to clicked point and recenter
    double scaleFactor = 0.5;
    //get current visible part of scene
    QRect viewportRect( 0, 0, view()->viewport()->width(), view()->viewport()->height() );
    QgsRectangle visibleRect = QgsRectangle( view()->mapToScene( viewportRect ).boundingRect() );

    visibleRect.scale( scaleFactor, event->layoutPoint().x(), event->layoutPoint().y() );
    newBoundsRect = visibleRect.toRectF();
  }

  //zoom view to fit desired bounds
  view()->fitInView( newBoundsRect, Qt::KeepAspectRatio );
  view()->emitZoomLevelChanged();
  view()->updateRulers();
}
Example #9
0
void QgsLayoutViewToolZoom::layoutPressEvent( QgsLayoutViewMouseEvent *event )
{
  if ( event->button() != Qt::LeftButton )
  {
    event->ignore();
    return;
  }

  mMousePressStartPos = event->pos();
  if ( event->modifiers() & Qt::AltModifier )
  {
    //zoom out action, so zoom out and recenter on clicked point
    double scaleFactor = 2;
    //get current visible part of scene
    QRect viewportRect( 0, 0, view()->viewport()->width(), view()->viewport()->height() );
    QgsRectangle visibleRect = QgsRectangle( view()->mapToScene( viewportRect ).boundingRect() );

    visibleRect.scale( scaleFactor, event->layoutPoint().x(), event->layoutPoint().y() );
    QRectF boundsRect = visibleRect.toRectF();

    //zoom view to fit desired bounds
    view()->fitInView( boundsRect, Qt::KeepAspectRatio );
    view()->emitZoomLevelChanged();
    view()->updateRulers();
  }
  else
  {
    //zoom in action
    startMarqueeZoom( event->layoutPoint() );
  }
}
//-----------------------------------------------------------------------------
QRegion vktraceviewer_QTimelineView::itemRegion(const QModelIndex &index) const
{
    if (!index.isValid())
        return QRegion();

    return QRegion(viewportRect(index).toRect());
}
Example #11
0
void ShapeTool::mouseReleaseEvent(QMouseEvent* e)
{
    Q_UNUSED(e)

    QPainter painter;
    painter.begin(m_pDrawPadCanvas->currentPage()->pixmap());
    drawFinalShape(painter);
    painter.end();

    QRect r = m_polyline.boundingRect();
    r = r.normalize();
    r.setLeft(r.left() - m_pDrawPad->pen().width());
    r.setTop(r.top() - m_pDrawPad->pen().width());
    r.setRight(r.right() + m_pDrawPad->pen().width());
    r.setBottom(r.bottom() + m_pDrawPad->pen().width());

    QRect viewportRect(m_pDrawPadCanvas->contentsToViewport(r.topLeft()),
                       m_pDrawPadCanvas->contentsToViewport(r.bottomRight()));

    bitBlt(m_pDrawPadCanvas->viewport(), viewportRect.x(), viewportRect.y(),
           m_pDrawPadCanvas->currentPage()->pixmap(), r.x(), r.y(), r.width(), r.height());

    m_pDrawPadCanvas->viewport()->update(viewportRect);

    m_mousePressed = false;
}
Example #12
0
void gxCamera::perspectiveChanged()
{
	if(getProjectionType()==gxCamera::PERSPECTIVE_PROJECTION)
		m_cDummyProjMatrix.setPerspective(m_FOV, 1.0f, m_fNear, m_fFar);
	else
	{
		gxRectf viewportRect(0, 0, 200, 200);
		vector2f centerAlignedPos(viewportRect.m_pos-viewportRect.m_size*0.5f);
		m_cDummyProjMatrix.setOrtho(centerAlignedPos.x, centerAlignedPos.x+viewportRect.m_size.x, centerAlignedPos.y, centerAlignedPos.y+viewportRect.m_size.y, m_fNear, m_fFar);
	}

	extractFrustumPlanes();
}
Example #13
0
void PageView::calculateCurrentPageNumber(int x, int y)
{
  // Safety check
  if (widgetList == 0)
    return;

  QRect viewportRect(x, y, visibleWidth(), visibleHeight());

  //kdDebug() << "viewportRect(" << viewportRect.x() << ", " << viewportRect.y() << ", "
  //          << viewportRect.width() << ", " << viewportRect.height() << ")" << endl;

  int maxVisiblePixels = 0;
  DocumentWidget* _currentWidget = 0;

  for (Q_UINT16 i = 0; i < widgetList->size(); i++)
  {
    DocumentWidget* documentWidget = widgetList->at(i);
    // Safety check
    if (documentWidget == 0)
      continue;

    // Check if the Widget is visible
    int cx = childX(documentWidget);
    int cy = childY(documentWidget);
    QRect widgetRect(cx, cy, documentWidget->width(), documentWidget->height());
    bool isVisible = widgetRect.intersects(viewportRect);

    if (!isVisible)
      continue;

    // Calculate the number of visible pixels of the widget
    QRect visibleRect = widgetRect.intersect(viewportRect);
    int visiblePixels = visibleRect.width() * visibleRect.height();

    //kdDebug() << visiblePixels << " pixels are visible of page " << documentWidget->getPageNumber() << endl;

    // If a bigger part of this widget as of the previous widgets is visible make it the current widget.
    if (maxVisiblePixels < visiblePixels)
    {
      maxVisiblePixels = visiblePixels;
      _currentWidget = documentWidget;
    }
  }

  // No page is visible
  if (_currentWidget == 0)
    return;

  // Return the number of the current page
  emit currentPageChanged(_currentWidget->getPageNumber());
}
Example #14
0
// This function needs to be reentrant.
void LayerTreeHostProxy::paintToCurrentGLContext(const TransformationMatrix& matrix, float opacity)
{
    if (!m_textureMapper)
        m_textureMapper = TextureMapperGL::create();

    syncRemoteContent();
    GraphicsLayer* currentRootLayer = rootLayer();
    if (!currentRootLayer)
        return;

    TextureMapperNode* node = toTextureMapperNode(currentRootLayer);

    if (!node)
        return;

    GLint viewport[4];
    glGetIntegerv(GL_VIEWPORT, viewport);
    IntRect viewportRect(viewport[0], viewport[1], viewport[2], viewport[3]);
    m_textureMapper->setViewportSize(IntSize(viewport[2], viewport[3]));
    node->setTextureMapper(m_textureMapper.get());
    m_textureMapper->beginPainting();
    m_textureMapper->bindSurface(0);

    if (currentRootLayer->opacity() != opacity || currentRootLayer->transform() != matrix) {
        currentRootLayer->setOpacity(opacity);
        currentRootLayer->setTransform(matrix);
        currentRootLayer->syncCompositingStateForThisLayerOnly();
    }

    TextureMapperNode::NodeRectMap nodeVisualContentsRectMap;
    if (node->collectVisibleContentsRects(nodeVisualContentsRectMap, viewportRect)) {
        TextureMapperNode::NodeRectMap::iterator endIterator = nodeVisualContentsRectMap.end();
        for (TextureMapperNode::NodeRectMap::iterator it = nodeVisualContentsRectMap.begin(); it != endIterator; ++it) {
            WebLayerID layerID = it->first->id();
            // avoid updating non-synced root layer
            if (!layerID)
                continue;
            IntRect visibleRect = IntRect(it->second);
            setVisibleContentsRectForLayer(layerID, visibleRect);
        }
    }
    node->paint();

    m_textureMapper->endPainting();

    if (node->descendantsOrSelfHaveRunningAnimations()) {
        node->syncAnimationsRecursively();
        m_viewportUpdateTimer.startOneShot(0);
    }
}
void ThumbnailList::updateWidgets()
{
    // find all widgets that intersects the viewport and update them
    QRect viewportRect( contentsX(), contentsY(), visibleWidth(), visibleHeight() );
    QValueList<ThumbnailWidget *>::iterator vIt = m_visibleThumbnails.begin(), vEnd = m_visibleThumbnails.end();
    for ( ; vIt != vEnd; ++vIt )
    {
        ThumbnailWidget * t = *vIt;
        QRect widgetRect( childX( t ), childY( t ), t->width(), t->height() );
        // update only the exposed area of the widget (saves pixels..)
        QRect relativeRect = viewportRect.intersect( widgetRect );
        if ( !relativeRect.isValid() )
            continue;
        relativeRect.moveBy( -widgetRect.left(), -widgetRect.top() );
        t->update( relativeRect );
    }
}
Example #16
0
void RealPaintWidget::paintEvent( QPaintEvent * event )
{
	QPainter p( this );
	QRect viewportRect( rect() );

	if( fixedSize )
	{
		QSize sz = viewportRect.size() - size;
		p.translate( QPoint( sz.width() / 2, sz.height() / 2 ) );
		viewportRect.setSize( size );
	}

    p.setRenderHints( QPainter::Antialiasing | QPainter::TextAntialiasing | QPainter::SmoothPixmapTransform );

	viewportRect.setWidth( viewportRect.width() - 1 );
	viewportRect.setHeight( viewportRect.height() - 1 );

	FILL( background, p, viewportRect );

	p.setPen( QColor( 0, 0, 0 ) );
	p.drawRect( viewportRect );

	for(int i = 0; i<layers.size(); i++)
	{
		layers[i]->paintLayer( p );
	}
	selection.paint( p );


	if( inSelectionMode )
	{
		QPen selectionRectPen( Qt::DashLine );
		selectionRectPen.setColor( QColor( 50, 50, 50, 200 ) );

		p.setBrush( QBrush() );
		p.setPen( selectionRectPen );

		p.drawRect( selectionRect.x(), selectionRect.y(),
			selectionRect.width() - 1, selectionRect.height() - 1 );
	}




}
Example #17
0
void QgsLayoutView::wheelZoom( QWheelEvent *event )
{
  //get mouse wheel zoom behavior settings
  QgsSettings settings;
  double zoomFactor = settings.value( QStringLiteral( "qgis/zoom_factor" ), 2 ).toDouble();

  // "Normal" mouse have an angle delta of 120, precision mouses provide data faster, in smaller steps
  zoomFactor = 1.0 + ( zoomFactor - 1.0 ) / 120.0 * qAbs( event->angleDelta().y() );

  if ( event->modifiers() & Qt::ControlModifier )
  {
    //holding ctrl while wheel zooming results in a finer zoom
    zoomFactor = 1.0 + ( zoomFactor - 1.0 ) / 20.0;
  }

  //calculate zoom scale factor
  bool zoomIn = event->angleDelta().y() > 0;
  double scaleFactor = ( zoomIn ? 1 / zoomFactor : zoomFactor );

  //get current visible part of scene
  QRect viewportRect( 0, 0, viewport()->width(), viewport()->height() );
  QgsRectangle visibleRect = QgsRectangle( mapToScene( viewportRect ).boundingRect() );

  //transform the mouse pos to scene coordinates
  QPointF scenePoint = mapToScene( event->pos() );

  //adjust view center
  QgsPointXY oldCenter( visibleRect.center() );
  QgsPointXY newCenter( scenePoint.x() + ( ( oldCenter.x() - scenePoint.x() ) * scaleFactor ),
                        scenePoint.y() + ( ( oldCenter.y() - scenePoint.y() ) * scaleFactor ) );
  centerOn( newCenter.x(), newCenter.y() );

  //zoom layout
  if ( zoomIn )
  {
    scaleSafe( zoomFactor );
  }
  else
  {
    scaleSafe( 1 / zoomFactor );
  }
}
//-----------------------------------------------------------------------------
void vktraceviewer_QTimelineView::drawTimelineItem(QPainter* painter, const QModelIndex &index)
{
    QRectF rect = viewportRect(index);

    // don't draw if the rect is outside the viewport
    if (!rect.isValid() ||
        rect.bottom() < 0 ||
        rect.y() > viewport()->height() ||
        rect.x() > viewport()->width() ||
        rect.right() < 0)
    {
        return;
    }

    QStyleOptionViewItem option = viewOptions();
    option.rect = rect.toRect();
    if (selectionModel()->isSelected(index))
        option.state |= QStyle::State_Selected;
    if (currentIndex() == index)
        option.state |= QStyle::State_HasFocus;

    // check mask to determine if this item should be drawn, or if something has already covered it's pixels
    vktrace_trace_packet_header* pHeader = (vktrace_trace_packet_header*)index.internalPointer();
    QVector<int>& mask = m_threadMask[pHeader->thread_id];
    bool drawItem = false;
    int x = option.rect.x();
    int right = qMin( qMax(x, option.rect.right()), viewport()->width()-1);
    for (int pixel = qMax(0, x); pixel <= right; pixel++)
    {
        if (mask[pixel] == 0)
        {
            drawItem = true;
            mask[pixel] = 1;
        }
    }

    // draw item if it should be visible
    if (drawItem)
    {
        itemDelegate()->paint(painter, option, index);
    }
}
Example #19
0
void Qgs3DMapCanvas::setMap( Qgs3DMapSettings *map )
{
  // TODO: eventually we want to get rid of this
  Q_ASSERT( !mMap );
  Q_ASSERT( !mScene );

  QRect viewportRect( QPoint( 0, 0 ), size() );
  Qgs3DMapScene *newScene = new Qgs3DMapScene( *map, mWindow3D->defaultFrameGraph(), mWindow3D->renderSettings(), mWindow3D->camera(), viewportRect );

  mWindow3D->setRootEntity( newScene );

  if ( mScene )
    mScene->deleteLater();
  mScene = newScene;

  delete mMap;
  mMap = map;

  resetView();
}
Example #20
0
void QgsLayoutView::zoomWidth()
{
  //get current visible part of scene
  QRect viewportRect( 0, 0, viewport()->width(), viewport()->height() );
  QRectF visibleRect = mapToScene( viewportRect ).boundingRect();

  double verticalCenter = ( visibleRect.top() + visibleRect.bottom() ) / 2.0;
  // expand out visible rect to include left/right edges of scene
  // centered on current visible vertical center
  // note that we can't have a 0 height rect - fitInView doesn't handle that
  // so we just set a very small height instead.
  const double tinyHeight = 0.01;
  QRectF targetRect( scene()->sceneRect().left(),
                     verticalCenter - tinyHeight,
                     scene()->sceneRect().width(),
                     tinyHeight * 2 );

  fitInView( targetRect, Qt::KeepAspectRatio );
  emit zoomLevelChanged();
  updateRulers();
}
Example #21
0
void QgsComposerView::endMarqueeZoom( QMouseEvent* e )
{
  mMarqueeZoom = false;

  QRectF boundsRect;

  if ( !mRubberBandItem || ( mRubberBandItem->rect().width() < 0.1 && mRubberBandItem->rect().height() < 0.1 ) )
  {
    //just a click, so zoom to clicked point and recenter
    double scaleFactor = 0.5;
    //get current visible part of scene
    QRect viewportRect( 0, 0, viewport()->width(), viewport()->height() );
    QgsRectangle visibleRect = QgsRectangle( mapToScene( viewportRect ).boundingRect() );

    //transform the mouse pos to scene coordinates
    QPointF scenePoint = mapToScene( e->pos() );

    visibleRect.scale( scaleFactor, scenePoint.x(), scenePoint.y() );
    boundsRect = visibleRect.toRectF();
  }
  else
  {
    //marquee zoom
    //zoom bounds are size marquee object
    boundsRect = QRectF( mRubberBandItem->transform().dx(), mRubberBandItem->transform().dy(),
                         mRubberBandItem->rect().width(), mRubberBandItem->rect().height() );
  }

  removeRubberBand();
  //zoom view to fit desired bounds
  fitInView( boundsRect, Qt::KeepAspectRatio );

  if ( mTemporaryZoomStatus == QgsComposerView::ActiveUntilMouseRelease )
  {
    //user was using the temporary keyboard activated zoom tool
    //and the control or space key was released before mouse button, so end temporary zoom
    mTemporaryZoomStatus = QgsComposerView::Inactive;
    setCurrentTool( mPreviousTool );
  }
}
Example #22
0
void QgsComposerView::mouseReleaseEvent( QMouseEvent* e )
{
  if ( !composition() )
  {
    return;
  }

  QPoint mousePressStopPoint = e->pos();
  int diffX = mousePressStopPoint.x() - mMousePressStartPos.x();
  int diffY = mousePressStopPoint.y() - mMousePressStartPos.y();

  //was this just a click? or a click and drag?
  bool clickOnly = false;
  if ( qAbs( diffX ) < 2 && qAbs( diffY ) < 2 )
  {
    clickOnly = true;
  }

  QPointF scenePoint = mapToScene( e->pos() );

  if ( mPanning )
  {
    mPanning = false;

    if ( clickOnly && e->button() == Qt::MidButton )
    {
      //middle mouse button click = recenter on point

      //get current visible part of scene
      QRect viewportRect( 0, 0, viewport()->width(), viewport()->height() );
      QgsRectangle visibleRect = QgsRectangle( mapToScene( viewportRect ).boundingRect() );
      visibleRect.scale( 1, scenePoint.x(), scenePoint.y() );
      QRectF boundsRect = visibleRect.toRectF();

      //zoom view to fit desired bounds
      fitInView( boundsRect, Qt::KeepAspectRatio );
    }

    //set new cursor
    if ( mCurrentTool == Pan )
    {
      viewport()->setCursor( Qt::OpenHandCursor );
    }
    else
    {
      if ( composition() )
      {
        //allow composer items to change cursor
        composition()->setPreventCursorChange( false );
      }
      viewport()->setCursor( Qt::ArrowCursor );
    }
  }

  if ( mMarqueeSelect )
  {
    endMarqueeSelect( e );
    return;
  }

  switch ( mCurrentTool )
  {
    case Select:
    {
      QGraphicsView::mouseReleaseEvent( e );
      break;
    }

    case Zoom:
    {
      if ( mMarqueeZoom )
      {
        endMarqueeZoom( e );
      }
      break;
    }

    case MoveItemContent:
    {
      if ( mMoveContentItem )
      {
        //update map preview if composer map
        QgsComposerMap* composerMap = dynamic_cast<QgsComposerMap *>( mMoveContentItem );
        if ( composerMap )
        {
          composerMap->setOffset( 0, 0 );
        }

        double moveX = scenePoint.x() - mMoveContentStartPos.x();
        double moveY = scenePoint.y() - mMoveContentStartPos.y();

        composition()->beginCommand( mMoveContentItem, tr( "Move item content" ) );
        mMoveContentItem->moveContent( -moveX, -moveY );
        composition()->endCommand();
        mMoveContentItem = 0;
      }
      break;
    }
    case AddArrow:
      if ( composition() )
      {
        QPointF scenePoint = mapToScene( e->pos() );
        QPointF snappedScenePoint = composition()->snapPointToGrid( scenePoint );
        QgsComposerArrow* composerArrow = new QgsComposerArrow( mRubberBandStartPos, QPointF( snappedScenePoint.x(), snappedScenePoint.y() ), composition() );
        composition()->addComposerArrow( composerArrow );

        composition()->clearSelection();
        composerArrow->setSelected( true );
        emit selectedItemChanged( composerArrow );

        scene()->removeItem( mRubberBandLineItem );
        delete mRubberBandLineItem;
        mRubberBandLineItem = 0;
        emit actionFinished();
        composition()->pushAddRemoveCommand( composerArrow, tr( "Arrow added" ) );
      }
      break;

    case AddRectangle:
    case AddTriangle:
    case AddEllipse:
      addShape( mCurrentTool );
      break;

    case AddMap:
      if ( !mRubberBandItem || ( mRubberBandItem->rect().width() < 0.1 && mRubberBandItem->rect().height() < 0.1 ) )
      {
        removeRubberBand();
        return;
      }
      if ( composition() )
      {
        QgsComposerMap* composerMap = new QgsComposerMap( composition(), mRubberBandItem->transform().dx(), mRubberBandItem->transform().dy(), mRubberBandItem->rect().width(), mRubberBandItem->rect().height() );
        composition()->addComposerMap( composerMap );

        composition()->clearSelection();
        composerMap->setSelected( true );
        emit selectedItemChanged( composerMap );

        removeRubberBand();
        emit actionFinished();
        composition()->pushAddRemoveCommand( composerMap, tr( "Map added" ) );
      }
      break;

    case AddHtml:
      if ( composition() )
      {
        QgsComposerHtml* composerHtml = new QgsComposerHtml( composition(), true );
        QgsAddRemoveMultiFrameCommand* command = new QgsAddRemoveMultiFrameCommand( QgsAddRemoveMultiFrameCommand::Added,
            composerHtml, composition(), tr( "Html item added" ) );
        composition()->undoStack()->push( command );
        QgsComposerFrame* frame = new QgsComposerFrame( composition(), composerHtml, mRubberBandItem->transform().dx(),
            mRubberBandItem->transform().dy(), mRubberBandItem->rect().width(),
            mRubberBandItem->rect().height() );
        composition()->beginMultiFrameCommand( composerHtml, tr( "Html frame added" ) );
        composerHtml->addFrame( frame );
        composition()->endMultiFrameCommand();

        composition()->clearSelection();
        frame->setSelected( true );
        emit selectedItemChanged( frame );

        removeRubberBand();
        emit actionFinished();
      }
    default:
      break;
  }
}
Example #23
0
void QgsComposerView::wheelZoom( QWheelEvent * event )
{
  //get mouse wheel zoom behaviour settings
  QSettings mySettings;
  int wheelAction = mySettings.value( "/qgis/wheel_action", 2 ).toInt();
  double zoomFactor = mySettings.value( "/qgis/zoom_factor", 2 ).toDouble();

  if (( QgsMapCanvas::WheelAction )wheelAction == QgsMapCanvas::WheelNothing )
  {
    return;
  }

  if ( event->modifiers() & Qt::ControlModifier )
  {
    //holding ctrl while wheel zooming results in a finer zoom
    zoomFactor = 1.0 + ( zoomFactor - 1.0 ) / 10.0;
  }

  //caculate zoom scale factor
  bool zoomIn = event->delta() > 0;
  double scaleFactor = ( zoomIn ? 1 / zoomFactor : zoomFactor );

  //get current visible part of scene
  QRect viewportRect( 0, 0, viewport()->width(), viewport()->height() );
  QgsRectangle visibleRect = QgsRectangle( mapToScene( viewportRect ).boundingRect() );

  //transform the mouse pos to scene coordinates
  QPointF scenePoint = mapToScene( event->pos() );

  //adjust view center according to wheel action setting
  switch (( QgsMapCanvas::WheelAction )wheelAction )
  {
    case QgsMapCanvas::WheelZoomAndRecenter:
    {
      centerOn( scenePoint.x(), scenePoint.y() );
      break;
    }

    case QgsMapCanvas::WheelZoomToMouseCursor:
    {
      QgsPoint oldCenter( visibleRect.center() );
      QgsPoint newCenter( scenePoint.x() + (( oldCenter.x() - scenePoint.x() ) * scaleFactor ),
                          scenePoint.y() + (( oldCenter.y() - scenePoint.y() ) * scaleFactor ) );
      centerOn( newCenter.x(), newCenter.y() );
      break;
    }

    default:
      break;
  }

  //zoom composition
  if ( zoomIn )
  {
    scale( zoomFactor, zoomFactor );
  }
  else
  {
    scale( 1 / zoomFactor, 1 / zoomFactor );
  }

  //update composition for new zoom
  emit zoomLevelChanged();
  updateRulers();
  update();
  //redraw cached map items
  QList<QGraphicsItem *> itemList = composition()->items();
  QList<QGraphicsItem *>::iterator itemIt = itemList.begin();
  for ( ; itemIt != itemList.end(); ++itemIt )
  {
    QgsComposerMap* mypItem = dynamic_cast<QgsComposerMap *>( *itemIt );
    if (( mypItem ) && ( mypItem->previewMode() == QgsComposerMap::Render ) )
    {
      mypItem->updateCachedImage();
    }
  }
}
Example #24
0
void QgsComposerView::mousePressEvent( QMouseEvent* e )
{
  if ( !composition() )
  {
    return;
  }

  QPointF scenePoint = mapToScene( e->pos() );
  QPointF snappedScenePoint = composition()->snapPointToGrid( scenePoint );
  mMousePressStartPos = e->pos();

  //lock/unlock position of item with right click
  if ( e->button() == Qt::RightButton )
  {
    QgsComposerItem* selectedItem = composition()->composerItemAt( scenePoint );
    if ( selectedItem )
    {
      bool lock = selectedItem->positionLock() ? false : true;
      selectedItem->setPositionLock( lock );
      selectedItem->update();
    }
    return;
  }
  else if ( e->button() == Qt::MidButton )
  {
    //pan composer with middle button
    mPanning = true;
    mMouseLastXY = e->pos();
    if ( composition() )
    {
      //lock cursor to closed hand cursor
      composition()->setPreventCursorChange( true );
    }
    viewport()->setCursor( Qt::ClosedHandCursor );
    return;
  }

  switch ( mCurrentTool )
  {
      //select/deselect items and pass mouse event further
    case Select:
    {
      //check if we are clicking on a selection handle
      if ( composition()->selectionHandles()->isVisible() )
      {
        //selection handles are being shown, get mouse action for current cursor position
        QgsComposerMouseHandles::MouseAction mouseAction = composition()->selectionHandles()->mouseActionForScenePos( scenePoint );

        if ( mouseAction != QgsComposerMouseHandles::MoveItem && mouseAction != QgsComposerMouseHandles::NoAction && mouseAction != QgsComposerMouseHandles::SelectItem )
        {
          //mouse is over a resize handle, so propagate event onward
          QGraphicsView::mousePressEvent( e );
          return;
        }
      }

      QgsComposerItem* selectedItem = 0;
      QgsComposerItem* previousSelectedItem = 0;

      if ( e->modifiers() & Qt::ControlModifier )
      {
        //CTRL modifier, so we are trying to select the next item below the current one
        //first, find currently selected item
        QList<QgsComposerItem*> selectedItems = composition()->selectedComposerItems();
        if ( selectedItems.size() > 0 )
        {
          previousSelectedItem = selectedItems.at( 0 );
        }
      }

      if ( previousSelectedItem )
      {
        //select highest item just below previously selected item at position of event
        selectedItem = composition()->composerItemAt( scenePoint, previousSelectedItem );

        //if we didn't find a lower item we'll use the top-most as fall-back
        //this duplicates mapinfo/illustrator/etc behaviour where ctrl-clicks are "cyclic"
        if ( !selectedItem )
        {
          selectedItem = composition()->composerItemAt( scenePoint );
        }
      }
      else
      {
        //select topmost item at position of event
        selectedItem = composition()->composerItemAt( scenePoint );
      }

      if ( !selectedItem )
      {
        //not clicking over an item, so start marquee selection
        startMarqueeSelect( scenePoint );
        break;
      }

      if (( !selectedItem->selected() ) &&        //keep selection if an already selected item pressed
          !( e->modifiers() & Qt::ShiftModifier ) ) //keep selection if shift key pressed
      {
        composition()->clearSelection();
      }

      if (( e->modifiers() & Qt::ShiftModifier ) && ( selectedItem->selected() ) )
      {
        //SHIFT-clicking a selected item deselects it
        selectedItem->setSelected( false );

        //Check if we have any remaining selected items, and if so, update the item panel
        QList<QgsComposerItem*> selectedItems = composition()->selectedComposerItems();
        if ( selectedItems.size() > 0 )
        {
          emit selectedItemChanged( selectedItems.at( 0 ) );
        }
      }
      else
      {
        selectedItem->setSelected( true );
        QGraphicsView::mousePressEvent( e );
        emit selectedItemChanged( selectedItem );
      }
      break;
    }

    case Zoom:
    {
      if ( !( e->modifiers() & Qt::ShiftModifier ) )
      {
        //zoom in action
        startMarqueeZoom( scenePoint );
      }
      else
      {
        //zoom out action, so zoom out and recenter on clicked point
        double scaleFactor = 2;
        //get current visible part of scene
        QRect viewportRect( 0, 0, viewport()->width(), viewport()->height() );
        QgsRectangle visibleRect = QgsRectangle( mapToScene( viewportRect ).boundingRect() );

        //transform the mouse pos to scene coordinates
        QPointF scenePoint = mapToScene( e->pos() );

        visibleRect.scale( scaleFactor, scenePoint.x(), scenePoint.y() );
        QRectF boundsRect = visibleRect.toRectF();

        //zoom view to fit desired bounds
        fitInView( boundsRect, Qt::KeepAspectRatio );
      }
      break;
    }

    case Pan:
    {
      //pan action
      mPanning = true;
      mMouseLastXY = e->pos();
      viewport()->setCursor( Qt::ClosedHandCursor );
      break;
    }

    case MoveItemContent:
    {
      //get a list of items at clicked position
      QList<QGraphicsItem *> itemsAtCursorPos = items( e->pos() );
      if ( itemsAtCursorPos.size() == 0 )
      {
        //no items at clicked position
        return;
      }

      //find highest QgsComposerItem at clicked position
      //(other graphics items may be higher, eg selection handles)
      QList<QGraphicsItem*>::iterator itemIter = itemsAtCursorPos.begin();
      for ( ; itemIter != itemsAtCursorPos.end(); ++itemIter )
      {
        QgsComposerItem* item = dynamic_cast<QgsComposerItem *>(( *itemIter ) );
        if ( item )
        {
          //we've found the highest QgsComposerItem
          mMoveContentStartPos = scenePoint;
          mMoveContentItem = item;
          break;
        }
      }

      //no QgsComposerItem at clicked position
      return;
    }

    case AddArrow:
    {
      mRubberBandStartPos = QPointF( snappedScenePoint.x(), snappedScenePoint.y() );
      mRubberBandLineItem = new QGraphicsLineItem( snappedScenePoint.x(), snappedScenePoint.y(), snappedScenePoint.x(), snappedScenePoint.y() );
      mRubberBandLineItem->setZValue( 1000 );
      scene()->addItem( mRubberBandLineItem );
      scene()->update();
      break;
    }

    //create rubber band for map and ellipse items
    case AddMap:
    case AddRectangle:
    case AddTriangle:
    case AddEllipse:
    case AddHtml:
    {
      QTransform t;
      mRubberBandItem = new QGraphicsRectItem( 0, 0, 0, 0 );
      mRubberBandStartPos = QPointF( snappedScenePoint.x(), snappedScenePoint.y() );
      t.translate( snappedScenePoint.x(), snappedScenePoint.y() );
      mRubberBandItem->setTransform( t );
      mRubberBandItem->setZValue( 1000 );
      scene()->addItem( mRubberBandItem );
      scene()->update();
    }
    break;

    case AddLabel:
      if ( composition() )
      {
        QgsComposerLabel* newLabelItem = new QgsComposerLabel( composition() );
        newLabelItem->setText( tr( "QGIS" ) );
        newLabelItem->adjustSizeToText();
        newLabelItem->setSceneRect( QRectF( snappedScenePoint.x(), snappedScenePoint.y(), newLabelItem->rect().width(), newLabelItem->rect().height() ) );
        composition()->addComposerLabel( newLabelItem );

        composition()->clearSelection();
        newLabelItem->setSelected( true );
        emit selectedItemChanged( newLabelItem );

        emit actionFinished();
        composition()->pushAddRemoveCommand( newLabelItem, tr( "Label added" ) );
      }
      break;

    case AddScalebar:
      if ( composition() )
      {
        QgsComposerScaleBar* newScaleBar = new QgsComposerScaleBar( composition() );
        newScaleBar->setSceneRect( QRectF( snappedScenePoint.x(), snappedScenePoint.y(), 20, 20 ) );
        composition()->addComposerScaleBar( newScaleBar );
        QList<const QgsComposerMap*> mapItemList = composition()->composerMapItems();
        if ( mapItemList.size() > 0 )
        {
          newScaleBar->setComposerMap( mapItemList.at( 0 ) );
        }
        newScaleBar->applyDefaultSize(); //4 segments, 1/5 of composer map width

        composition()->clearSelection();
        newScaleBar->setSelected( true );
        emit selectedItemChanged( newScaleBar );

        emit actionFinished();
        composition()->pushAddRemoveCommand( newScaleBar, tr( "Scale bar added" ) );
      }
      break;

    case AddLegend:
    {
      if ( composition() )
      {
        QgsComposerLegend* newLegend = new QgsComposerLegend( composition() );
        newLegend->setSceneRect( QRectF( snappedScenePoint.x(), snappedScenePoint.y(), newLegend->rect().width(), newLegend->rect().height() ) );
        composition()->addComposerLegend( newLegend );
        newLegend->updateLegend();

        composition()->clearSelection();
        newLegend->setSelected( true );
        emit selectedItemChanged( newLegend );

        emit actionFinished();
        composition()->pushAddRemoveCommand( newLegend, tr( "Legend added" ) );
      }
      break;
    }
    case AddPicture:
      if ( composition() )
      {
        QgsComposerPicture* newPicture = new QgsComposerPicture( composition() );
        newPicture->setSceneRect( QRectF( snappedScenePoint.x(), snappedScenePoint.y(), 30, 30 ) );
        composition()->addComposerPicture( newPicture );

        composition()->clearSelection();
        newPicture->setSelected( true );
        emit selectedItemChanged( newPicture );

        emit actionFinished();
        composition()->pushAddRemoveCommand( newPicture, tr( "Picture added" ) );
      }
      break;
    case AddTable:
      if ( composition() )
      {
        QgsComposerAttributeTable* newTable = new QgsComposerAttributeTable( composition() );
        newTable->setSceneRect( QRectF( snappedScenePoint.x(), snappedScenePoint.y(), 50, 50 ) );
        composition()->addComposerTable( newTable );

        composition()->clearSelection();
        newTable->setSelected( true );
        emit selectedItemChanged( newTable );

        emit actionFinished();
        composition()->pushAddRemoveCommand( newTable, tr( "Table added" ) );
      }
      break;
    default:
      break;
  }
}
void ossimPlanetLandCullCallback::applyOrthoCull(ossimPlanetPagedLandLod* n,
                                                 osg::NodeVisitor* nv)
{
   //OpenThreads::ScopedLock<OpenThreads::Mutex> lock(n->theMutex);

   osgUtil::CullVisitor* cullVisitor = dynamic_cast<osgUtil::CullVisitor*>(nv);
   if(n->theRefreshType == ossimPlanetLandRefreshType_PRUNE)
   {
      if(n->getNumChildren() > 0)
      {
         if(n->getChild(0))
         {
            n->getChild(0)->accept(*nv);
         }
      }
      cullVisitor->getDatabaseRequestHandler()->requestNodeFile(n->theRequestNameList[0]+"_GEOM",
                                                                n,
                                                                99999999,
                                                                nv->getFrameStamp());
      return;
   }
   if(!cullVisitor) return;
   n->theCulledFlag = false;
   bool addChildrenFlag = false;
   n->theRemoveChildrenFlag = false;
   double distance=0.0;
   osg::Matrix wm = cullVisitor->getWindowMatrix();

   const osg::RefMatrix& m = *(cullVisitor->getMVPW());
   double x = cullVisitor->getViewport()->x();
   double y = cullVisitor->getViewport()->y();
   double w = cullVisitor->getViewport()->width();
   double h = cullVisitor->getViewport()->height();
   if(w < 1) w = 1;
   if(h < 1) h = 1;
   ossimDrect viewportRect(x,
                           y,
                           x + (w-1),
                           y + (h-1));
   wm = osg::Matrixd::inverse(*cullVisitor->getProjectionMatrix());

   osg::Vec3d center = (osg::Vec3d(0.0,0.0, 1.0)*wm);
   osg::Vec3d projectedCenter = (n->theCenterPoint*m);
   distance = (center-n->getBound().center()).length();
//    distance = (center-n->getBound().center()).length()/(sqrt(180.0*180.0 + 90.0*90.0));
//    
//    distance = (osg::Vec2d(projectedCenter[0],
//                           projectedCenter[1]) -
//                osg::Vec2d(w/2.0,
//                           h/2.0)).length();
   
   osg::Vec3d ulView = n->theUlPoint*m;
   osg::Vec3d urView = n->theUrPoint*m;
   osg::Vec3d lrView = n->theLrPoint*m;
   osg::Vec3d llView = n->theLlPoint*m;
   ossimDpt ulViewDpt(ulView[0], ulView[1]);
   ossimDpt urViewDpt(urView[0], urView[1]);
   ossimDpt lrViewDpt(lrView[0], lrView[1]);
   ossimDpt llViewDpt(llView[0], llView[1]);
   ossimDrect rect(ulViewDpt,
                   urViewDpt,
                   lrViewDpt,
                   llViewDpt);
   
   n->theCulledFlag = !rect.intersects(viewportRect);
   
   float pixelSize = ossim::max(rect.width(), rect.height());
   if(pixelSize >= 512)
   {
      if(n->isLeaf())
      {
         addChildrenFlag = true;
      }
   }
   else if(pixelSize < 256)
   {
//       if(!n->isLeaf())
      {
         n->theRemoveChildrenFlag = true;
      }
   }
   
   distance *= 1<<n->theLevel;
   double priority = 0.0;
   if(distance > 0.0)
   {
      priority = 1.0/distance;
   }
   else
   {
      priority = 1.0/FLT_EPSILON;
   }
   if((n->theRefreshType == ossimPlanetLandRefreshType_GEOM)&&(!n->theCulledFlag))
   {
      cullVisitor->getDatabaseRequestHandler()->requestNodeFile(n->theRequestNameList[0]+"_GEOM",
                                                                n,
                                                                priority,
                                                                nv->getFrameStamp());
   }
   else if((n->theRefreshType == ossimPlanetLandRefreshType_TEXTURE)&&(!n->theCulledFlag))
   {
      cullVisitor->getDatabaseRequestHandler()->requestNodeFile(n->theRequestNameList[0]+"_TEXTURE",
                                                                n,
                                                                priority,
                                                                nv->getFrameStamp());
   }
   std::string requestString = ((n->getNumChildren() < 5)&&(n->thePagedLodList.size()<4))?n->theRequestNameList[n->thePagedLodList.size()+1]:"";
//   std::string requestString = (n->getNumChildren() < 5)?n->getRequestName(n->getNumChildren()):"";
   if((requestString!= "")&&
      cullVisitor->getDatabaseRequestHandler())
   {
      if((n->theRefreshType == ossimPlanetLandRefreshType_GEOM)&&(!n->theCulledFlag))
      {
         cullVisitor->getDatabaseRequestHandler()->requestNodeFile(n->theRequestNameList[0]+"_GEOM",
                                                                   n,
                                                                   priority,
                                                                   nv->getFrameStamp());
      }
      else if((n->theRefreshType == ossimPlanetLandRefreshType_TEXTURE)&&(!n->theCulledFlag))
      {
         cullVisitor->getDatabaseRequestHandler()->requestNodeFile(n->theRequestNameList[0]+"_TEXTURE",
                                                                   n,
                                                                   priority,
                                                                   nv->getFrameStamp());
      }
      if(!n->theRemoveChildrenFlag &&
         addChildrenFlag&&
         !n->theCulledFlag&&
         (n->getNumChildren() < 5))
      {
         cullVisitor->getDatabaseRequestHandler()->requestNodeFile(requestString,
                                                                   n,
                                                                   priority,
                                                                   nv->getFrameStamp());
      }
      else if((n->theCulledFlag)&&
              (n->isLeaf())&&
              (n->getNumChildren()>1))
      {
			ossimPlanetDatabasePager* pager = dynamic_cast<ossimPlanetDatabasePager*>(cullVisitor->getDatabaseRequestHandler());
          if(pager)
          {
             pager->invalidateRequest(requestString);
          }
      }
   }
   if(!n->theCulledFlag)
   {
      if(n->getNumChildren() >4)
      {
         ossim_uint32 idx = 0;
         for(idx = 1; idx < n->getNumChildren(); ++idx)
         {
            if(n->getChild(idx))
            {
               n->getChild(idx)->accept(*nv);
            }
         }
      }
      else
      {
         if(n->getNumChildren() > 0)
         {
            if(n->getChild(0))
            {
               n->getChild(0)->accept(*nv);
            }
         }
      }
   }
}
Example #26
0
void RealPaintWidget::paintFrameTo( QPainter &to, const QRect &r, qreal frame )
{
	/*qreal currentFrame = layers[currentLayer]->frame();
		QRect viewportRect( rect() );

		if( fixedSize )
		{
			QSize sz = viewportRect.size() - size;
			viewportRect.setSize( size );
		}

		to.setRenderHints( QPainter::Antialiasing |
							QPainter::TextAntialiasing |
							QPainter::SmoothPixmapTransform );

		to.save();
		to.scale( qreal( r.width() ) / qreal( viewportRect.width() ),
					qreal( r.height() ) / qreal( viewportRect.height() ) );

		to.translate( r.x(), r.y() );

		viewportRect.setWidth( viewportRect.width() - 1 );
		viewportRect.setHeight( viewportRect.height() - 1 );

		FILL( background, to, viewportRect );

		to.setPen( QColor( 0, 0, 0 ) );
		to.drawRect( viewportRect );

		int size = layers.size();
		for (int i = 0; i < size; i++) {
			layers[i]->setFrame( frame );
			layers[i]->paint( to );
			layers[i]->setFrame( currentFrame );
		}

		to.restore();*/
	qreal currentFrame = layers[currentLayer]->frame();
	layers[currentLayer]->setFrame( frame );
	QRect viewportRect( rect() );

	if( fixedSize )
	{
		QSize sz = viewportRect.size() - size;
		viewportRect.setSize( size );
	}

	to.setRenderHints( QPainter::Antialiasing |
						QPainter::TextAntialiasing |
						QPainter::SmoothPixmapTransform );

	to.save();
	to.scale( qreal( r.width() ) / qreal( viewportRect.width() ),
				qreal( r.height() ) / qreal( viewportRect.height() ) );

	to.translate( r.x(), r.y() );

	viewportRect.setWidth( viewportRect.width() - 1 );
	viewportRect.setHeight( viewportRect.height() - 1 );

	//FILL( background, to, viewportRect );

	to.setPen( QColor( 0, 0, 0 ) );
	to.drawRect( viewportRect );
	layers[currentLayer]->paint( to );

	layers[currentLayer]->setFrame( currentFrame);
	to.restore();
}
void QSGDefaultRenderer::render()
{
#if defined (QML_RUNTIME_TESTING)
    static bool dumpTree = qApp->arguments().contains(QLatin1String("--dump-tree"));
    if (dumpTree) {
        printf("\n\n");
        QSGNodeDumper::dump(rootNode());
    }
#endif

#ifdef RENDERER_DEBUG
    debugTimer.invalidate();
    debugTimer.start();
    geometryNodesDrawn = 0;
    materialChanges = 0;
#endif

    glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
    glDisable(GL_BLEND);

    glFrontFace(isMirrored() ? GL_CW : GL_CCW);
    glDisable(GL_CULL_FACE);

    glEnable(GL_DEPTH_TEST);
    glDepthMask(true);
    glDepthFunc(GL_GREATER);
#if defined(QT_OPENGL_ES)
    glClearDepthf(0);
#else
    glClearDepth(0);
#endif

    glDisable(GL_SCISSOR_TEST);
    glClearColor(m_clear_color.redF(), m_clear_color.greenF(), m_clear_color.blueF(), m_clear_color.alphaF());

#ifdef RENDERER_DEBUG
    int debugtimeSetup = debugTimer.elapsed();
#endif

    bindable()->clear(clearMode());

#ifdef RENDERER_DEBUG
    int debugtimeClear = debugTimer.elapsed();
#endif

    QRect r = viewportRect();
    glViewport(r.x(), deviceRect().bottom() - r.bottom(), r.width(), r.height());
    m_current_projection_matrix = projectionMatrix();
    m_current_model_view_matrix.setToIdentity();

    m_currentClip = 0;
    glDisable(GL_STENCIL_TEST);

    m_currentMaterial = 0;
    m_currentProgram = 0;
    m_currentMatrix = 0;

    if (m_rebuild_lists) {
        m_opaqueNodes.reset();
        m_transparentNodes.reset();
        m_currentRenderOrder = 1;
        buildLists(rootNode());
        m_rebuild_lists = false;
    }

#ifdef RENDERER_DEBUG
    int debugtimeLists = debugTimer.elapsed();
#endif


    if (m_needs_sorting) {
        if (!m_opaqueNodes.isEmpty()) {
            qSort(&m_opaqueNodes.first(), &m_opaqueNodes.first() + m_opaqueNodes.size(),
                  m_sort_front_to_back
                  ? nodeLessThanWithRenderOrder
                  : nodeLessThan);
        }
        m_needs_sorting = false;
    }

#ifdef RENDERER_DEBUG
    int debugtimeSorting = debugTimer.elapsed();
#endif

    m_renderOrderMatrix.setToIdentity();
    m_renderOrderMatrix.scale(1, 1, qreal(1) / m_currentRenderOrder);

    glDisable(GL_BLEND);
    glDepthMask(true);
#ifdef QML_RUNTIME_TESTING
    if (m_render_opaque_nodes)
#endif
    {
#if defined (QML_RUNTIME_TESTING)
        if (dumpTree)
            qDebug() << "Opaque Nodes:";
#endif
        renderNodes(m_opaqueNodes);
    }

#ifdef RENDERER_DEBUG
    int debugtimeOpaque = debugTimer.elapsed();
    int opaqueNodes = geometryNodesDrawn;
    int opaqueMaterialChanges = materialChanges;
#endif

    glEnable(GL_BLEND);
    glDepthMask(false);
#ifdef QML_RUNTIME_TESTING
    if (m_render_alpha_nodes)
#endif
    {
#if defined (QML_RUNTIME_TESTING)
        if (dumpTree)
            qDebug() << "Alpha Nodes:";
#endif
        renderNodes(m_transparentNodes);
    }

#ifdef RENDERER_DEBUG
    int debugtimeAlpha = debugTimer.elapsed();
#endif


    if (m_currentProgram)
        m_currentProgram->deactivate();

#ifdef RENDERER_DEBUG
    if (debugTimer.elapsed() > DEBUG_THRESHOLD) {
        printf(" --- Renderer breakdown:\n"
               "     - setup=%d, clear=%d, building=%d, sorting=%d, opaque=%d, alpha=%d\n"
               "     - material changes: opaque=%d, alpha=%d, total=%d\n"
               "     - geometry ndoes: opaque=%d, alpha=%d, total=%d\n",
               debugtimeSetup,
               debugtimeClear - debugtimeSetup,
               debugtimeLists - debugtimeClear,
               debugtimeSorting - debugtimeLists,
               debugtimeOpaque - debugtimeSorting,
               debugtimeAlpha - debugtimeOpaque,
               opaqueMaterialChanges, materialChanges - opaqueMaterialChanges, materialChanges,
               opaqueNodes, geometryNodesDrawn - opaqueNodes, geometryNodesDrawn);
    }
#endif

}
Example #28
0
void QgsComposerView::wheelZoom( QWheelEvent * event )
{
  //get mouse wheel zoom behaviour settings
  QSettings mySettings;
  int wheelAction = mySettings.value( "/qgis/wheel_action", 2 ).toInt();
  double zoomFactor = mySettings.value( "/qgis/zoom_factor", 2 ).toDouble();

  //caculate zoom scale factor
  bool zoomIn = event->delta() > 0;
  double scaleFactor = ( zoomIn ? 1 / zoomFactor : zoomFactor );

  //get current visible part of scene
  QRect viewportRect( 0, 0, viewport()->width(), viewport()->height() );
  QgsRectangle visibleRect = QgsRectangle( mapToScene( viewportRect ).boundingRect() );

  //transform the mouse pos to scene coordinates
  QPointF scenePoint = mapToScene( event->pos() );

  //zoom composition, respecting wheel action setting
  switch (( QgsMapCanvas::WheelAction )wheelAction )
  {
    case QgsMapCanvas::WheelZoom:
      // zoom without changing extent
      if ( zoomIn )
      {
        scale( zoomFactor, zoomFactor );
      }
      else
      {
        scale( 1 / zoomFactor, 1 / zoomFactor );
      }
      break;

    case QgsMapCanvas::WheelZoomAndRecenter:
    {
      visibleRect.scale( scaleFactor, scenePoint.x(), scenePoint.y() );
      fitInView( visibleRect.toRectF(), Qt::KeepAspectRatio );
      break;
    }

    case QgsMapCanvas::WheelZoomToMouseCursor:
    {
      QgsPoint oldCenter( visibleRect.center() );
      QgsPoint newCenter( scenePoint.x() + (( oldCenter.x() - scenePoint.x() ) * scaleFactor ),
                          scenePoint.y() + (( oldCenter.y() - scenePoint.y() ) * scaleFactor ) );

      visibleRect.scale( scaleFactor, newCenter.x(), newCenter.y() );
      fitInView( visibleRect.toRectF(), Qt::KeepAspectRatio );
      break;
    }

    case QgsMapCanvas::WheelNothing:
      return;
  }

  //update composition for new zoom
  updateRulers();
  update();
  //redraw cached map items
  QList<QGraphicsItem *> itemList = composition()->items();
  QList<QGraphicsItem *>::iterator itemIt = itemList.begin();
  for ( ; itemIt != itemList.end(); ++itemIt )
  {
    QgsComposerMap* mypItem = dynamic_cast<QgsComposerMap *>( *itemIt );
    if (( mypItem ) && ( mypItem->previewMode() == QgsComposerMap::Render ) )
    {
      mypItem->updateCachedImage();
    }
  }
}
Example #29
0
void QgsComposerView::mouseReleaseEvent( QMouseEvent* e )
{
  if ( !composition() )
  {
    return;
  }

  if ( e->button() != Qt::LeftButton &&
       ( composition()->selectionHandles()->isDragging() || composition()->selectionHandles()->isResizing() ) )
  {
    //ignore clicks while dragging/resizing items
    return;
  }

  QPoint mousePressStopPoint = e->pos();
  int diffX = mousePressStopPoint.x() - mMousePressStartPos.x();
  int diffY = mousePressStopPoint.y() - mMousePressStartPos.y();

  //was this just a click? or a click and drag?
  bool clickOnly = false;
  if ( qAbs( diffX ) < 2 && qAbs( diffY ) < 2 )
  {
    clickOnly = true;
  }

  QPointF scenePoint = mapToScene( e->pos() );

  if ( mMousePanning || mToolPanning )
  {
    mMousePanning = false;
    mToolPanning = false;

    if ( clickOnly && e->button() == Qt::MidButton )
    {
      //middle mouse button click = recenter on point

      //get current visible part of scene
      QRect viewportRect( 0, 0, viewport()->width(), viewport()->height() );
      QgsRectangle visibleRect = QgsRectangle( mapToScene( viewportRect ).boundingRect() );
      visibleRect.scale( 1, scenePoint.x(), scenePoint.y() );
      QRectF boundsRect = visibleRect.toRectF();

      //zoom view to fit desired bounds
      fitInView( boundsRect, Qt::KeepAspectRatio );
    }

    //set new cursor
    if ( mCurrentTool != Pan )
    {
      if ( composition() )
      {
        //allow composer items to change cursor
        composition()->setPreventCursorChange( false );
      }
    }
    viewport()->setCursor( defaultCursorForTool( mCurrentTool ) );
  }

  //for every other tool, ignore clicks of non-left button
  if ( e->button() != Qt::LeftButton )
  {
    return;
  }

  if ( mMarqueeSelect )
  {
    endMarqueeSelect( e );
    return;
  }

  switch ( mCurrentTool )
  {
    case Select:
    {
      QGraphicsView::mouseReleaseEvent( e );
      break;
    }

    case Zoom:
    {
      if ( mMarqueeZoom )
      {
        endMarqueeZoom( e );
      }
      break;
    }

    case MoveItemContent:
    {
      if ( mMoveContentItem )
      {
        //update map preview if composer map
        QgsComposerMap* composerMap = dynamic_cast<QgsComposerMap *>( mMoveContentItem );
        if ( composerMap )
        {
          composerMap->setOffset( 0, 0 );
        }

        double moveX = scenePoint.x() - mMoveContentStartPos.x();
        double moveY = scenePoint.y() - mMoveContentStartPos.y();

        composition()->beginCommand( mMoveContentItem, tr( "Move item content" ) );
        mMoveContentItem->moveContent( -moveX, -moveY );
        composition()->endCommand();
        mMoveContentItem = 0;
        mMovingItemContent = false;
      }
      break;
    }
    case AddArrow:
      if ( !composition() || !mRubberBandLineItem )
      {
        scene()->removeItem( mRubberBandLineItem );
        delete mRubberBandLineItem;
        mRubberBandLineItem = 0;
        return;
      }
      else
      {
        QgsComposerArrow* composerArrow = new QgsComposerArrow( mRubberBandLineItem->line().p1(), mRubberBandLineItem->line().p2(), composition() );
        composition()->addComposerArrow( composerArrow );

        composition()->clearSelection();
        composerArrow->setSelected( true );
        emit selectedItemChanged( composerArrow );

        scene()->removeItem( mRubberBandLineItem );
        delete mRubberBandLineItem;
        mRubberBandLineItem = 0;
        emit actionFinished();
        composition()->pushAddRemoveCommand( composerArrow, tr( "Arrow added" ) );
      }
      break;

    case AddRectangle:
    case AddTriangle:
    case AddEllipse:
      addShape( mCurrentTool );
      break;

    case AddMap:
      if ( !composition() || !mRubberBandItem || ( mRubberBandItem->rect().width() < 0.1 && mRubberBandItem->rect().height() < 0.1 ) )
      {
        removeRubberBand();
        return;
      }
      else
      {
        QgsComposerMap* composerMap = new QgsComposerMap( composition(), mRubberBandItem->transform().dx(), mRubberBandItem->transform().dy(), mRubberBandItem->rect().width(), mRubberBandItem->rect().height() );
        composition()->addComposerMap( composerMap );

        composition()->clearSelection();
        composerMap->setSelected( true );
        emit selectedItemChanged( composerMap );

        removeRubberBand();
        emit actionFinished();
        composition()->pushAddRemoveCommand( composerMap, tr( "Map added" ) );
      }
      break;

    case AddPicture:
      if ( !composition() || !mRubberBandItem || ( mRubberBandItem->rect().width() < 0.1 && mRubberBandItem->rect().height() < 0.1 ) )
      {
        removeRubberBand();
        return;
      }
      else
      {
        QgsComposerPicture* newPicture = new QgsComposerPicture( composition() );
        newPicture->setSceneRect( QRectF( mRubberBandItem->transform().dx(), mRubberBandItem->transform().dy(), mRubberBandItem->rect().width(), mRubberBandItem->rect().height() ) );
        composition()->addComposerPicture( newPicture );

        composition()->clearSelection();
        newPicture->setSelected( true );
        emit selectedItemChanged( newPicture );

        removeRubberBand();
        emit actionFinished();
        composition()->pushAddRemoveCommand( newPicture, tr( "Picture added" ) );
      }
      break;

    case AddLabel:
      if ( !composition() || !mRubberBandItem )
      {
        removeRubberBand();
        return;
      }
      else
      {
        QgsComposerLabel* newLabelItem = new QgsComposerLabel( composition() );
        newLabelItem->setText( tr( "QGIS" ) );
        newLabelItem->adjustSizeToText();

        //make sure label size is sufficient to fit text
        double labelWidth = qMax( mRubberBandItem->rect().width(), newLabelItem->rect().width() );
        double labelHeight = qMax( mRubberBandItem->rect().height(), newLabelItem->rect().height() );
        newLabelItem->setSceneRect( QRectF( mRubberBandItem->transform().dx(), mRubberBandItem->transform().dy(), labelWidth, labelHeight ) );

        composition()->addComposerLabel( newLabelItem );

        composition()->clearSelection();
        newLabelItem->setSelected( true );
        emit selectedItemChanged( newLabelItem );

        removeRubberBand();
        emit actionFinished();
        composition()->pushAddRemoveCommand( newLabelItem, tr( "Label added" ) );
      }
      break;

    case AddLegend:
      if ( !composition() || !mRubberBandItem )
      {
        removeRubberBand();
        return;
      }
      else
      {
        QgsComposerLegend* newLegend = new QgsComposerLegend( composition() );
        newLegend->setSceneRect( QRectF( mRubberBandItem->transform().dx(), mRubberBandItem->transform().dy(), mRubberBandItem->rect().width(), mRubberBandItem->rect().height() ) );
        composition()->addComposerLegend( newLegend );
        newLegend->updateLegend();

        composition()->clearSelection();
        newLegend->setSelected( true );
        emit selectedItemChanged( newLegend );

        removeRubberBand();
        emit actionFinished();
        composition()->pushAddRemoveCommand( newLegend, tr( "Legend added" ) );
      }
      break;

    case AddTable:
      if ( !composition() || !mRubberBandItem )
      {
        removeRubberBand();
        return;
      }
      else
      {
        QgsComposerAttributeTable* newTable = new QgsComposerAttributeTable( composition() );
        newTable->setSceneRect( QRectF( mRubberBandItem->transform().dx(), mRubberBandItem->transform().dy(), mRubberBandItem->rect().width(), qMax( mRubberBandItem->rect().height(), 15.0 ) ) );
        QList<const QgsComposerMap*> mapItemList = composition()->composerMapItems();
        if ( mapItemList.size() > 0 )
        {
          newTable->setComposerMap( mapItemList.at( 0 ) );
        }
        composition()->addComposerTable( newTable );

        composition()->clearSelection();
        newTable->setSelected( true );
        emit selectedItemChanged( newTable );

        removeRubberBand();
        emit actionFinished();
        composition()->pushAddRemoveCommand( newTable, tr( "Table added" ) );
      }
      break;

    case AddHtml:
      if ( !composition() || !mRubberBandItem || ( mRubberBandItem->rect().width() < 0.1 && mRubberBandItem->rect().height() < 0.1 ) )
      {
        removeRubberBand();
        return;
      }
      else
      {
        QgsComposerHtml* composerHtml = new QgsComposerHtml( composition(), true );
        QgsAddRemoveMultiFrameCommand* command = new QgsAddRemoveMultiFrameCommand( QgsAddRemoveMultiFrameCommand::Added,
            composerHtml, composition(), tr( "Html item added" ) );
        composition()->undoStack()->push( command );
        QgsComposerFrame* frame = new QgsComposerFrame( composition(), composerHtml, mRubberBandItem->transform().dx(),
            mRubberBandItem->transform().dy(), mRubberBandItem->rect().width(),
            mRubberBandItem->rect().height() );
        composition()->beginMultiFrameCommand( composerHtml, tr( "Html frame added" ) );
        composerHtml->addFrame( frame );
        composition()->endMultiFrameCommand();

        composition()->clearSelection();
        frame->setSelected( true );
        emit selectedItemChanged( frame );

        removeRubberBand();
        emit actionFinished();
      }
    default:
      break;
  }
}
//-----------------------------------------------------------------------------
QRect vktraceviewer_QTimelineView::visualRect(const QModelIndex &index) const
{
    QRectF rectf = viewportRect(index);
    return rectf.toRect();
}