Exemple #1
0
    Ray Camera::ScreenPointToRay(const Vector2 point) const {
        Matrix4x4 view = GetTransformation()->GetAccumulatedMatrix();
        Vector3 camPos = Vector3(view.Get(3,0), view.Get(3,1), view.Get(3,2));
            
        Matrix4x4 vp = GetProjectionMatrix() * view;
        if (!Invert(vp)) Debug::LogError("Failed to invert view projection matrix");

        // Convert from screen space to viewport space and to [-1;1] range.
        float viewportX = (point.Get(0) - rect.x) * 2.0f / float(rect.width) - 1.0f;
        float viewportY = (point.Get(1) - rect.y) * 2.0f / float(rect.height) - 1.0f;

        Vector4 viewportPoint = Vector4(viewportX, viewportY, 1.0f, 1.0f);
            
        Vector4 worldPos = vp * viewportPoint;

        Vector3 rayEnd = Vector3(worldPos.Get(0) / worldPos.Get(3), 
                                 worldPos.Get(1) / worldPos.Get(3), 
                                 worldPos.Get(2) / worldPos.Get(3));
            
        return Ray(camPos, Normalize(rayEnd - camPos));
    }