Reproduce WorldToViewportPoint function

Hello. I am trying to reproduce native camera.WorldToViewportPoint function, for projecting mesh vertices to viewport. I write colors to texture for visualisation. So, here is what i’ve tried:

  1. Transform vertex position to worldspace using TransformPoint, then use WorldToViewport

    Vector3 v = goTransform.TransformPoint(vertices*);*
    Vector3 pos = mCamera.WorldToViewportPoint(v);
    texture.SetPixel((int)(pos.xtextureSizeW), (int)(pos.ytextureSizeH), Color.white);
    And as result, everithing is fine:
    2) Calculate ModelViewProjection matrix and multiply it with vertex position.
    Matrix4x4 M = goTransform.localToWorldMatrix;
    Matrix4x4 V = mCamera.worldToCameraMatrix;
    Matrix4x4 P = mCamera.projectionMatrix;
    Matrix4x4 MVP = PVM;

Vector3 pos = MVP.MultiplyPoint(vertices[j]);
texture.SetPixel((int)(pos.xtextureSizeW), (int)(pos.ytextureSizeH), Color.white);
But result is wrong:
3) After reading [this][3] answer, I’ve added this part to my code:
if (d3d) {
// Invert Y for rendering to a render texture
for (int i = 0; i < 4; i++) {
P[1,i] = -P[1,i];
// Scale and bias from OpenGL → D3D depth range
for (int i = 0; i < 4; i++) {
P[2,i] = P[2,i]*0.5f + P[3,i]*0.5f;
But result are still wrong. Could you help me to understand what am I missing? Thanks
[3]: How do I reproduce the MVP matrix? - Unity Answers

Maybe you need pos /= pos.z, i.e. applying projection?

When you use Multiplypoint it converts it to clipping space
so too correct:

screenpos.x being your (Projection matrix* View matrix)*Multiplypoint(vector)
//clipping to 1,1
Vector3 scPos= new Vector3(screenPos.x + 1f, screenPos.y + 1f, screenPos.z + 1f) / 2f;
// viewport into screen
scPos = new Vector3(screenPos.x * Screen.width, screenPos.y * Screen.height, screenPos.z);