Skip to content
Permalink
Browse files

Add some useful QgsVector methods

  • Loading branch information
nyalldawson committed Apr 23, 2018
1 parent d5647bc commit 01f036cf52050054f074383f256ee3ff68e3ec05
Showing with 47 additions and 0 deletions.
  1. +19 −0 python/core/qgsvector.sip.in
  2. +5 −0 src/core/qgsvector.cpp
  3. +19 −0 src/core/qgsvector.h
  4. +4 −0 tests/src/core/testqgspoint.cpp
@@ -52,6 +52,17 @@ Constructor for QgsVector taking x and y component values.
double length() const;
%Docstring
Returns the length of the vector.

.. seealso:: :py:func:`lengthSquared`
%End

double lengthSquared() const;
%Docstring
Returns the length of the vector.

.. versionadded:: 3.2

.. seealso:: :py:func:`length`
%End

double x() const;
@@ -81,6 +92,14 @@ Returns the angle of the vector in radians.
double angle( QgsVector v ) const;
%Docstring
Returns the angle between this vector and another vector in radians.
%End

double crossProduct( QgsVector v ) const;
%Docstring
Returns the 2D cross product of this vector and another vector ``v``. (This is sometimes
referred to as a "perpendicular dot product", and equals x1 * y1 - y1 * x2).

.. versionadded:: 3.2
%End

QgsVector rotateBy( double rot ) const;
@@ -99,6 +99,11 @@ double QgsVector::angle( QgsVector v ) const
return v.angle() - angle();
}

double QgsVector::crossProduct( QgsVector v ) const
{
return mX * v.y() - mY * v.x();
}

QgsVector QgsVector::rotateBy( double rot ) const
{
double angle = std::atan2( mY, mX ) + rot;
@@ -89,9 +89,20 @@ class CORE_EXPORT QgsVector

/**
* Returns the length of the vector.
* \see lengthSquared()
*/
double length() const;

/**
* Returns the length of the vector.
* \since QGIS 3.2
* \see length()
*/
double lengthSquared() const
{
return mX * mX + mY * mY;
}

/**
* Returns the vector's x-component.
* \see y()
@@ -119,6 +130,14 @@ class CORE_EXPORT QgsVector
*/
double angle( QgsVector v ) const;

/**
* Returns the 2D cross product of this vector and another vector \a v. (This is sometimes
* referred to as a "perpendicular dot product", and equals x1 * y1 - y1 * x2).
*
* \since QGIS 3.2
*/
double crossProduct( QgsVector v ) const;

/**
* Rotates the vector by a specified angle.
* \param rot angle in radians
@@ -274,6 +274,7 @@ void TestQgsPointXY::vector()
// length
QCOMPARE( v1.length(), 0.0 );
QGSCOMPARENEAR( v2.length(), std::sqrt( 5.0 ), 0.000000001 );
QCOMPARE( v2.lengthSquared(), 5.0 );

// perpVector
QCOMPARE( QgsVector( 2, 3 ).perpVector().x(), -3.0 );
@@ -320,6 +321,9 @@ void TestQgsPointXY::vector()
v1 -= v2;
QCOMPARE( v1.x(), 1.0 );
QCOMPARE( v1.y(), 3.0 );

// 2d cross product
QCOMPARE( QgsVector( 1, 3 ).crossProduct( QgsVector( 6, 9 ) ), -9.0 );
}

void TestQgsPointXY::asVariant()

0 comments on commit 01f036c

Please sign in to comment.
You can’t perform that action at this time.