3D Solved - D3D9 - Use Pixel Shader to copy texture to texture

Recommended Posts

// SOLVED: code working properly now

Hey guys,

having read a lot here in the forums before, I decided to sign up and ask for help with my problem. And I would really appreciate any help!

I need to copy the contents of a D3D9 texture (1024 x 1024) of format INTZ to system memory to be able to use it in a different application. By the way, I am stuck with D3D9, the INTZ texture is part of a closed application and I get its handle via intercepting the D3D calls (proxy dll).

As far as I know (at least my attempts trying to do so failed) it is not possible to just use GetRenderDataTarget. The texture resides in the default pool and its usage is set to Depth/Stencil (2), thus the other methods like StretchRect, UpdateTexture, etc. also cannot be used.

Now I would like to use a pixel shader to sample this texture and write/copy the contents to a texture of a different format like R32F. I suppose, I can then use GetRenderTargetData to copy the contents to a third texture in system memory and lock this texture afterwards (probably with a delay so that the GPU has enough time to copy the data from video to system memory).

What I have so far is the following:

------ Vertex shader -----

struct VS_IN
    float4 pos : POSITION;
    float2 texcoord : TEXCOORD0;    

struct VS_OUT
    float4 pos : POSITION;
    float2 texcoord : TEXCOORD0;        

VS_OUT main(VS_IN input)
    VS_OUT output;
    output.pos = input.pos;
    output.texcoord = input.texcoord;
    return output;

------ Pixel shader: ------

sampler2D s2d : register(s0);

struct PS_IN

    float2 pos : VPOS; //screen position
    float2 texcoord : TEXCOORD0;    

float4 main(PS_IN input)
    float depth = tex2D(s2d,input.texcoord).r;
    return float4(depth, depth, depth, 1.0);


Application code:


struct CPYVTX_t {
    float x, y, z, rhw;
    float tu, tv;

#define D3D9CHECKANDTHROW(cmd,msg)        \
if (FAILED(cmd))                        \
{                                        \
    throw std::runtime_error(msg);        \


void Init()

D3D9CHECKANDTHROW(apDev->CreateOffscreenPlainSurface(gcR32Width, gcR32Height, D3DFMT_R32F, D3DPOOL_SYSTEMMEM, &gpSysMemSurface, 0),
        "Failed to create offscreen plain surface in system memory.")    

    D3D9CHECKANDTHROW(apDev->CreateRenderTarget(gcR32Width, gcR32Height, D3DFMT_R32F, D3DMULTISAMPLE_NONE, 0, false, &gpCopyRenderTarget, 0),
        "Failed to create render target as destination for copy pass.")

    D3D9CHECKANDTHROW(apDev->CreateDepthStencilSurface(gcR32Width, gcR32Height, D3DFMT_D24S8, D3DMULTISAMPLE_NONE, 0, true, &gpCopyDepthStencil, 0),
        "Failed to create depth stencil surface.")

    D3D9CHECKANDTHROW(apDev->CreateVertexDeclaration(CPYVTX_DECL, &gpVertexDeclaration),
        "Failed to create vertex declaration")

    // initialize vertices to be used for texture access    
    D3D9CHECKANDTHROW(apDev->CreateVertexBuffer(sizeof(CPYVTX_t) * 4, NULL, 0, D3DPOOL_DEFAULT, &gpVtxBuf, NULL),
        "Failed to create vertex buffer required for copy pass.")


        CPYVTX_t* lpVertices;
        gpVtxBuf->Lock(0, 0, (void**)&lpVertices, NULL);
        //Coordinates system, in general:   https://msdn.microsoft.com/en-us/library/windows/desktop/bb204853(v=vs.85).aspx
        //D3D9 vs D3D10 / NDC:                  https://msdn.microsoft.com/en-us/library/windows/desktop/cc308049(v=vs.85).aspx  
        //Triangle strips example:                https://msdn.microsoft.com/de-de/library/windows/desktop/bb206274(v=vs.85).aspx
        lpVertices[0].tu = 0.0f;
        lpVertices[0].tv = 0.0f;
        lpVertices[0].x = -1.0f;
        lpVertices[0].y = 1.0f;
        lpVertices[0].z = 0.0f;
        lpVertices[0].rhw = 1.0f;

        lpVertices[1].tu = 1.0f;
        lpVertices[1].tv = 0.0f;
        lpVertices[1].x = 1.0f;
        lpVertices[1].y = 1.0f;
        lpVertices[1].z = 0.0f;
        lpVertices[1].rhw = 1.0f;

        lpVertices[2].tu = 0.0f;
        lpVertices[2].tv = 1.0f;
        lpVertices[2].x = -1.0f;
        lpVertices[2].y = -1.0f;
        lpVertices[2].z = 0.0f;
        lpVertices[2].rhw = 1.0f;

        lpVertices[3].tu = 1.0f;
        lpVertices[3].tv = 1.0f;
        lpVertices[3].x = 1.0f;
        lpVertices[3].y = -1.0f;
        lpVertices[3].z = 0.0f;
        lpVertices[3].rhw = 1.0f;


LPD3DXBUFFER lpCPSO = nullptr, lpCVSO = nullptr, lpErrBuf = nullptr;
        NULL, NULL, "main", "vs_3_0", 0, &lpCVSO, &lpErrBuf, NULL),
        "Failed to compile vertex shader file.")

            NULL, NULL, "main", "ps_3_0", 0, &lpCPSO, &lpErrBuf, NULL),
            "Failed to compile pixel shader file.")

        if (gpCopyPixelShader)
        if (gpCopyVertexShader)
        D3D9CHECKANDTHROW(apDev->CreatePixelShader((DWORD*)lpCPSO->GetBufferPointer(), &gpCopyPixelShader),
            "Failed to create pixel shader from compiled object.")

        D3D9CHECKANDTHROW(apDev->CreateVertexShader((DWORD*)lpCVSO->GetBufferPointer(), &gpCopyVertexShader),
            "Failed to create vertex shader from compiled object.")


void RunCopy(){
    IDirect3DVertexDeclaration9 *lpDecl = nullptr;
    IDirect3DSurface9 *lpRenderTargetSfc = nullptr, *lpDepthStencilSfc = nullptr;
    IDirect3DVertexBuffer9 *lpVtxBuf = nullptr;
    IDirect3DVertexShader9 *lpVSShader = nullptr;
    IDirect3DPixelShader9 *lpPSShader = nullptr;
    IDirect3DBaseTexture9 *lpCurrentTex = nullptr;
    UINT lVtxBufOffset = 0, lVtxBufStride = 0;
    DWORD lFVF = 0;
// --- get current state

D3D9CHECKANDTHROW(apDev->GetVertexDeclaration(&lpDecl), "GetVertexDeclaration failed")
D3D9CHECKANDTHROW(apDev->GetStreamSource(0, &lpVtxBuf, &lVtxBufOffset, &lVtxBufStride), "")
D3D9CHECKANDTHROW(apDev->GetRenderTarget(0, &lpRenderTargetSfc), "GetRenderTarget failed.")
D3D9CHECKANDTHROW(apDev->GetDepthStencilSurface(&lpDepthStencilSfc), "GetDepthStencil failed.")
D3D9CHECKANDTHROW(apDev->GetVertexShader(&lpVSShader), "GetVertexShader")
D3D9CHECKANDTHROW(apDev->GetPixelShader(&lpPSShader), "GetPixelShader")
D3D9CHECKANDTHROW(apDev->GetTexture(0, &lpCurrentTex), "GetTexture failed")

// --- set new states required for copy pass

D3D9CHECKANDTHROW(apDev->SetVertexDeclaration(gpVertexDeclaration), "SetVertexDeclaration failed.")
D3D9CHECKANDTHROW(apDev->SetStreamSource(0, gpVtxBuf, 0, sizeof(CPYVTX_t)), "SetStreamSource failed.")
D3D9CHECKANDTHROW(apDev->SetRenderTarget(0, gpCopyRenderTarget), "SetRenderTarget failed.")
D3D9CHECKANDTHROW(apDev->SetDepthStencilSurface(gpCopyDepthStencil), "SetDepthStencilSurface failed.")
D3D9CHECKANDTHROW(apDev->SetVertexShader(gpCopyVertexShader), "SetVertexShader failed.")
D3D9CHECKANDTHROW(apDev->SetPixelShader(gpCopyPixelShader), "SetPixelShader failed.")

D3D9CHECKANDTHROW(apDev->SetTexture(0, gpR32Tex), "SetTexture failed")
D3D9CHECKANDTHROW(apDev->SetPixelShaderConstantF(0, &lFrustum.far_plane, 1), "SetPixelShaderConstantF failed.")
D3D9CHECKANDTHROW(apDev->SetPixelShaderConstantF(1, &lFrustum.near_plane, 1), "SetPixelShaderConstantF failed.")
D3D9CHECKANDTHROW(apDev->SetPixelShaderConstantF(2, lInvProjMat, 4), "SetPixelShaderConstantF failed.")

D3D9CHECKANDTHROW(apDev->BeginScene(), "BeginScene failed.")
D3D9CHECKANDTHROW(apDev->DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, 2), "DrawPrimitive failed.")
D3D9CHECKANDTHROW(apDev->EndScene(), "EndScene failed.")

// --- reset previous state
D3D9CHECKANDTHROW(apDev->SetVertexDeclaration(lpDecl), "SetVertexDeclaration failed.")
D3D9CHECKANDTHROW(apDev->SetStreamSource(0, lpVtxBuf, lVtxBufOffset, lVtxBufStride), "SetStreamSource failed.")
D3D9CHECKANDTHROW(apDev->SetRenderTarget(0, lpRenderTargetSfc), "SetRenderTarget failed.")
D3D9CHECKANDTHROW(apDev->SetDepthStencilSurface(lpDepthStencilSfc), "SetDepthStencilSurface failed.")
D3D9CHECKANDTHROW(apDev->SetVertexShader(lpVSShader), "SetVertexShader failed.")
D3D9CHECKANDTHROW(apDev->SetPixelShader(lpPSShader), "SetPixelShader failed.")
D3D9CHECKANDTHROW(apDev->SetTexture(0, lpCurrentTex), "SetTexture failed.")



I believe the vertex definition (CPYVTX) needs to be extended to contain D3DFVF_XYZRHW and the float members respectively, otherwise the pixel shader does not know of which pixel it should set the value. But to be honest, I don't know what the  XYZRHW variables should contain. X and Y equal to the dimensions in pixels?(0|0), (0|1023), (1023|0),(1023|1023)?

How do I access an INTZ texture (which internally should be equal to D24S8) in the pixel shader and write its output to a R32F texture - is my shader syntax correct?

As I said initially, I am really grateful for every answer.

Edited by Apollo13
// SOLVED: new code working properly now

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Forum Statistics

    • Total Topics
    • Total Posts
  • Similar Content

    • By DavidMT
      A team has a position open for a 3D artist and/or modeler.
      Excellent opportunity to gain experience working with a team remotely. Great chance to extend your portfolio Candidates, if successful have the chance to join the team permanently with entry-level financial benefits. Revenue Share What they expect
      Excellent communication skills Portfolio of previous work If you are interested please attach a CV and/or relevant works to jobs@iamdavidmt.com
    • By ForgedInteractive
      Who We Are
      We are Forged Interactive, a small team of like-minded game developers with the sole purpose of making games we love! Currently, we're progressing very quickly with our first project and there are plenty of opportunities and work for new interested programmers. With this project, our development platform is Unity 5.5.2 and C# as our behavioral language. Since this project is our first release, the game itself is a smaller project though progress is moving quickly. We are looking to finalize the current project and get started on future projects in the near future and are expanding our team to do so.
      Who We Are Looking For:
      Programmer Level Designer  
      About the Game
      Ours is the tale of two siblings, thrown into a world of chaos. Living in the shadow of their parents' heroic deeds and their Uncle's colorful military career, Finn and Atia are about to become the next force to shape our world. How will you rise through the ranks of Hereilla and what will be your legacy? Once defeated your enemies turn coat and join you in your adventures. Players can enjoy a range of troops and abilities based on their gameplay style which become more important as maps introduce more challenging terrain, enemies and bosses. Strong orc knights, dangerous shamans, and even a dragon are out on the prowl. Knowing when to fight and when to run, and how to manage your army is essential. Your actions alone decide the fate of this world.
      Previous Work by Team
      Although we are working towards our first game as Forged Interactive, our team members themselves have worked on titles including and not limited to:
      Final Fantasy Kingsglaive FIFA 2017 Xcom 2 Civilization  
      What do we expect?
      Reference work or portfolio. Examples what have you already done and what projects you have worked on academic or otherwise. The ability to commit to the project on a regular basis. If you are going on a two-week trip, we don't mind, but it would be good if you could commit 10+ hours to the project each week. Willingness to work with a royalty based compensation model, you will be paid when the game launches. Openness to learning new tools and techniques
      What can we offer?
      Continuous support and availability from our side. You have the ability to give design input, and creative say in the development of the game. Shown in credits on websites, in-game and more. Insight and contacts from within the Industry.
      If you are interested in knowing more or joining, please email or PM us on Skype. A member of our management team will reply to you within 48 hours.
      E-mail: Recruitment@ForgedInteractive.com
      Skype: ForgedInteractive
      David, Colin and Joseph
      Follow us on:
      Facebook: https://www.facebook.com/ForgedInteractive/
      Twitter: @ForgedInteract
      Youtube: https://www.youtube.com/channel/UCpK3zhq5ToOeDpdI0Eik-Ug?view_as=subscriber
      Reddit: www.reddit.com/user/Forged_Interactive

    • By Michael Pearson
      Hello all!   I'm currently in my third year on my 3D Animation & Games Development course, and I am in the process of doing some basic primary research for my dissertation project, which is to create a high quality 3D Environment for use in video games and potentially VR.   I have a questionnaire (targeting other artists in the field), and I would really appreciate it if you took some time to have a look and fill it out:   https://docs.google.com/forms/d/e/1FAIpQLScW12nFI8-fMlAUMNSQvOInxhnIfXpG91iRCm25TVlZufrvbQ/viewform?usp=sf_link   Thank you in advance!   Mike.
    • By i3DTutorials

      Game School Online™ Announces Winter Enrollment Open Through December
      Los Angeles, CA - December 2017
      Free Winter Term Enrollment!
      Free Winter Enrollment:
      Game School Online™, the first and only free online game development school of its kind, has opened enrollment for the winter term, which begins in January of 2018. GSO™ currently offers curricula in environment art and lighting for games, focusing specifically on Unreal Engine 4. GSO™ will be adding two new courses for the winter term, “Advanced Lighting Concepts with Unreal Engine 4” and “Advanced Hard Surface Modeling.”

      Free Workshop!

      December Free Workshop:
      In addition to winter enrollment, GSO™ will have a free online workshop, “Animating For Games and Movies”, with Veara Suon, Senior Animator at Double Negative. Veara has worked in the AAA games industry, working on franchises like Destiny and Bioshock. Veara also works in the film industry, having worked for famed studios like Weta, ILM, and Sony, contributing to films like Pacific Rim 2, Spiderman, and Avengers. In this month’s free GSO™ workshop, Veara will be discussing topics such as:
      Sharing techniques on how he animates for games and film
      Advice on how students can get a job in games or film
      Advice on how working professionals can switch from games to film, and vice versa
      Job relocation
      The workshop will last for an hour, with allocated time for Q & A from the audience. The workshop will take place on December 14 at 8pm PST. As usual, our monthly workshops are absolutely free and anyone is welcomed to join us. To RSVP, please visit our Facebook page here: https://www.facebook.com/events/139461393377301/?active_tab=about

      Scholars Available For Mentoring!
      Scholar Lineup:
      Scholars are our mentors, working industry professionals currently working on your favorite games and franchises- here to help you learn to be a professional game dev, with one on one live private sessions. Our current lineup of scholars includes:
      Brian Yam - Director of Visual Development @ Section Studios
      Olaf Piesche - Senior Engineer @ Epic Games
      Kevin DeBolt - World Artist @ 343 Industries
      Rosie Katz - Senior Game Designer @ EA, Visceral, Sledgehammer Games
      Leo Gonzalez - Senior Artist @ Certain Affinity
      Brandon Pham - Lead Environment Artist

      We believe that education should be free for everyone! Come join us at Game School Online™ and see what the future of game development education looks like today! For more information about Game School Online™, available courses, scholars, and events, please visit http://gameschoolonline.com/

      Facebook: https://www.facebook.com/gameschoolonline/
      Twitter: @GSOscholar
      Discord: https://discordapp.com/invite/BzU5Fq2
      Patreon: https://www.patreon.com/gameschoolonline

      About Game School Online™ (GSO™)
      Game School Online™ is the first ever, completely free game development training program. GSO™ was founded by veteran developers working in the AAA games and entertainment industries. Featuring courses authored by working industry professionals, students are able to learn production techniques and workflows used to ship some of the biggest IPs and AAA franchises. Industry pros known as “scholars”, work with students providing private live sessions to help you become “industry” ready. All courses are available for free, no trials or demos- it’s completely free for anyone that wants to learn how to become a skilled game developer. For more information, please visit our website: http://gameschoolonline.com/
      Game School Online™ and GSO™ are registered trademarks Game School Online, LLC. All other brand names, product names or trademarks belong to their respective holders.
      Game School Online, LLC.

      View full story
  • Popular Now