Click or drag to resize
Ab4d.SharpEngine logo

SceneViewGetWorldToViewMatrix Method

Gets Matrix4x4 that can be used to convert 3D coordinates to 2D view (screen) coordinates. If the method returns true, than the worldToViewMatrix was set; if false is returned than the matrix cannot be calculated.

Namespace: Ab4d.SharpEngine
Assembly: Ab4d.SharpEngine (in Ab4d.SharpEngine.dll) Version: 2.0.8956+4c7684e186ca1be74e7a284fbe739d9a1b843d3c
Syntax
C#
public bool GetWorldToViewMatrix(
	out Matrix4x4? worldToViewMatrix,
	bool updateIfDirty = true
)

Parameters

worldToViewMatrix  Matrix4x4
reference to Matrix4x4
updateIfDirty  Boolean  (Optional)
when true (by default) then the Update(Boolean) method is called if the camera was changed after the last matrices were calculated; when false the current values are returned (may be outdated)

Return Value

Boolean
true if worldToViewMatrix was set; false if the matrix cannot be calculated
Remarks

GetWorldToViewMatrix gets Matrix4x4 that can be used to convert 3D coordinates to 2D viewport coordinates.

If the method returns true, than the worldToViewMatrix was set; if false is returned than the matrix cannot be calculated (for example when MatrixCamera is used and the matrix cannot be inverted).

Important:
To calculate the view (screen) coordinates of a 3D point you need to convert the Point3D to Point4D, multiply it with worldToViewportMatrix and than divide the X and Y coordinate with W value from Point4D struct. The following code shows that:

C#
Vector2 screenPoint;
bool isWorldToViewMatrixValid = sceneView.GetWorldToViewMatrix(out var worldToViewMatrix, updateIfDirty: true);

if (isWorldToViewMatrixValid)
{
    var screenPoint4 = Vector4.Transform(new Vector4(point3D.X, point3D.Y, point3D.Z, 1), worldToViewMatrix);

    // Get screen position - perform perspective division (divide by W)
    if (screenPoint4.W > 0 || (screenPoint4.W != 0 && myCamera.ProjectionType == ProjectionTypes.Orthographic)) // if W < 0 then point is behind the camera; this is only allowed for Orthographic camera
    {
        if (adjustByDpiScale)
            screenPoint = new Vector2(screenPoint4.X / (screenPoint4.W * sceneView.DpiScaleX), screenPoint4.Y / (screenPoint4.W * sceneView.DpiScaleY));
        else
            screenPoint = new Vector2(screenPoint4.X / screenPoint4.W, screenPoint4.Y / screenPoint4.W);
    }
    else
    {
        screenPoint = new Vector2(float.NaN, float.NaN);
    }
}
else
{
    screenPoint = new Vector2(float.NaN, float.NaN);
}
See Also