Jump to content
  • Advertisement
Sign in to follow this  
Medium99

DX11 [SlimDX] I fail at a simple triangle!?

This topic is 2429 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi!

I've been fiddling around with SlimDX a few (many) months ago, and currently try to freshen up on it. I did some GPGPU mini projects and stuff, nothing proper or serious so far, thus the knowledge from then was not free from (major) gaps, and now seems to consist only of them :(

I have a darn simple wish: Draw a triangle using DX10 (I did DX9 back then, so there's changed quite a bit for me). Is stitched stuff from various tutorials together, and had this working with just compute shaders under DX11 quite well. I now wanted to downgrade my code to DX10, and do actual 3D stuff. Well, not even that: I want a simplistic 2D particle system in the end, but all I see from the following is the light blue cleared render target, but no triangle whatsoever. I'm almost sure it's something stupidly simple, but I seem unable to find it. Any hints are thus highly appreciated :)

The following would be my Form class, where I do pretty much everything so far while learning to at least get something on the screen.



public partial class MainForm : Form
{
private D3DDevice device;
private SwapChain swapChain;

private Particles Parts;
private SlimDX.Direct3D10.Buffer Vertices;
private PixelShader PShader;
private VertexShader VShader;
private InputElement[] InputElements;
private InputLayout ILayout;

private Texture2D DisplayTexture;
private RenderTargetView DisplayRenderTarget;


public MainForm()
{
//
// The InitializeComponent() call is required for Windows Forms designer support.
//
InitializeComponent();

SwapChainDescription swapChainDesc = new SwapChainDescription()
{
BufferCount = 1,
Flags = SwapChainFlags.None,
IsWindowed = true,
ModeDescription = new ModeDescription(ClientSize.Width, ClientSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm),
OutputHandle = Handle,
SampleDescription = new SampleDescription(1, 0),
SwapEffect = SwapEffect.Discard,
Usage = Usage.RenderTargetOutput | (Usage)1024
};

D3DDevice.CreateWithSwapChain(null, DriverType.Hardware, DeviceCreationFlags.Debug, swapChainDesc, out device, out swapChain);

ShaderBytecode vs = ShaderBytecode.CompileFromFile("Shaders.fx", "VShader", "vs_4_0", ShaderFlags.None, EffectFlags.None);
ShaderBytecode ps = ShaderBytecode.CompileFromFile("Shaders.fx", "PShader", "ps_4_0", ShaderFlags.None, EffectFlags.None);
VShader = new VertexShader(device, vs);
PShader = new PixelShader(device, ps);

InputElements = new[] {new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0)};
ILayout = new InputLayout(device, ShaderSignature.GetInputSignature(vs), InputElements);

DisplayTexture = Texture2D.FromSwapChain<Texture2D>(swapChain, 0);
DisplayRenderTarget = new RenderTargetView(device, DisplayTexture);

Parts = new Particles(); // simply holds a DataStream with 3 vertices. Constructor shown at the end of this code
Vertices = new SlimDX.Direct3D10.Buffer(device, Parts.Points, 12*3, ResourceUsage.Default, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None);

device.InputAssembler.SetInputLayout(ILayout);
device.InputAssembler.SetPrimitiveTopology(PrimitiveTopology.TriangleList);
device.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(Vertices, 12, 0));
device.VertexShader.Set(VShader);
device.PixelShader.Set(PShader);
}

void MainFormShown(object sender, EventArgs e)
{
while (true)
{
device.ClearRenderTargetView(DisplayRenderTarget, Color.LightBlue);
device.Draw(3, 0);
swapChain.Present(0, PresentFlags.None);
}
}
}




// The particle class that hold my vertices (not particles for now though, until I got it running with a tri...)
public class Particles
{
public DataStream Points;

public Particles()
{
Points = new DataStream(12*3, true, true);
Points.Write(new Vector3(0.0f, 0.5f, 0.5f));
Points.Write(new Vector3(0.5f, -0.5f, 0.5f));
Points.Write(new Vector3(-0.5f, -0.5f, 0.5f));
Points.Position = 0;
}
}





And finally my rather simplistic shaders:



struct VS_OUTPUT
{
float4 pos : SV_POSITION;
};

struct PS_INPUT
{
float4 pos : SV_POSITION;
};

VS_OUTPUT VShader(float4 position : POSITION)
{
VS_OUTPUT vo;
vo.pos = position;
return vo;
}

float4 PShader(PS_INPUT pos) : SV_Target
{
return float4(1.0f, 1.0f, 0.0f, 1.0f);
}



I'd expect a neat yellow triangle on a light blue ground. The latter I have, but no yellow in my sky :( What am I doing wrong?

Thanks in advance!

Share this post


Link to post
Share on other sites
Advertisement
Your vertex data doesn't match what you've declared in the shader. You're sending three floats for position, but the shader is expecting four. Also, I don't see you setting a viewport anywhere.

Share this post


Link to post
Share on other sites
I tried a float3 for the POSITION semantic already, that wasn't it unfortunately. Or at least not only: The viewport thingy has a nice ring to it, I remember now. Since this wasn't necessary for just number crunching and outputting directly to the render target, I see how I missed that. I'll try! Thanks!

Share this post


Link to post
Share on other sites
Also, you forget to bind your render target:

device.OutputMerger.SetTargets(DisplayRenderTarget);
And make sure you got the right cull mode / triangle winding.

Additional "cosmetics": Dispose the resources before exit and use a proper render loop (e.g. SlimDXs message pump) or bind your drawing to the forms Paint event. Your current one is pretty blocking.

Share this post


Link to post
Share on other sites
Good thing I came here before continuing, thanks!

The loop surely isn't what I intend to use in a final program. Dirty "try to get other things working first" state. But I need to ask: If I bind it to the Paint-Event, that would only ever give me repaints whenever the form is invalidated, right? So that's not an option for a steady 60fps?

Share this post


Link to post
Share on other sites
DirectX has a way of making me feel a lot more stupid than I usually am. (It might stem from the fact, that there's not a single half decent tutorial or even book out there that gets one actually started. Especially with SlimDX. Even most references assume, that you otherwise know damn well what you're doing, and there is little comprehensive stuff. But that's another topic, which however concerns me a lot, being an avid autodidact. Meh.)

I put in the following, assuming I created a valid ViewPort with it and bound it to the device properly, and assuming this would set the RenderTarget to the right thing in the right place. My results however are unchanged. (Winding order wasn't it either, I checked that.)

DisplayTexture = Texture2D.FromSwapChain<Texture2D>(swapChain, 0);
DisplayRenderTarget = new RenderTargetView(device, DisplayTexture);
device.OutputMerger.SetTargets(DisplayRenderTarget);
Viewport vp = new Viewport(-1, -1, 2, 2);
device.Rasterizer.SetViewports(vp);


(This piece is inside my form's constructor shown above. The "DisplayTexture"-line is there already, that's where I added stuff.)

I also fixed the type mismatch for the POSITION semantic.



Another nudge? Please? :)

Share this post


Link to post
Share on other sites
Viewport dimensions are in screen pixels, e.g.


Viewport vp = new Viewport(0, 0, ClientSize.Width, ClientSize.Height);

Hint: Get familiar with PIX, the DirectX Debugger which comes with the SDK. Also: Install DebugView to grab the debug messages.


...It might stem from the fact, that there's not a single half decent tutorial or even book out there that gets one actually started....

I disagree.

Share this post


Link to post
Share on other sites
I tried pixel coords first, but since this also didn't get my tri to show up, I tried the posted version. I remembered fixing my datatype problem after the viewport addition, and tried again (with both winding orders), and still nothing. This is stuff, that frustrates me most. I had it up and running with DX9 more or less, then a few months and a version jump later it feels like I never coded before.

Then again, I really need to start using the tools you mentioned frequently. So far I didn't really get how to use them properly, the effort to try and learn however seems worth the wile.

My problem with the book you mentioned: I admit that I am a rather special case. I come from Pascal/Delphi programming (databases, PLC control, etc.), and did this long before I studied IT. During that time Java was the usually chosen language (ugh), and later on I jumped to C# (although I frequently need Delphi for work still). This was about the same time I got interested in hardware accelerated GFX. So I never ever got to work with actual C(++), don't own a copy of VS (grew fond of #Develop for .NET), and thus any tutorial stuff that is done in an actual language and/or references a particular IDE and its libraries, confuses me more than anything, especially because I then have to transfer it to SlimDX terms while reading. (Yeah, I'm a managed bitch!)
I have no use at all for how to set up a VS project for D3D, nor am I able to transfer it properly to C# without a lot of additional efforts for learning C++ and VS habits first. My current way of learning mostly consists of skimming through the code completion, looking for anything that sounds about right, and try if it actually does what I think it should do. This unfortunately does not tell me what I need to do, nor what is to be done further, or what the corresponding constructs to some structured buffer must look like in my shaders and such. Thus I mostly look for a sort of "recipe" for a bunch of usecases. Something like "Setting up a rather universal D3D environment: Create a device, there may be parameters that are roughly named X and affect Y (see more below). Then do foo and bar...".
I also often came across tuts where a later chapter that sounded interesting makes heaaaaaavy use of some custom frameworkish methods and utilities done 6 hours of reading before, in C++ which I don't use and know, and not intend to implement. To make it short: Most of the educational stuff on D3D out there comes with a considerable amount of "clutter" that has nothing to to with D3D itself, and thus is barely usable as a hybrid between reference and tutorial without spending hours on figuring out what all the unknown things I see do first, and then understand the simple solution to my problem at hand, which could have cost 10 minutes if done more focused.

If there is no other way, that's what I'll need to do, but it would get me a lot further a lot faster if I could just jump into D3D with SlimDX and learn the qiurks and quabbles from there, since there I at least feel at home in terms of the language, framework and IDE. Doing all 4 components at once is doable, but much less efficient. Certainly nothing for the meager ~3 hours I currently have between getting home and going to sleep :(
It is quite odd: I (quite successfully) wrote my bachelor thesis based on the first learning project I did for both, SlimDX (or D3D in general, but fullscreen quad and GPGPU doesn't really count I guess ;)) and C# (.NET in general), and even wrote a (DX9) pixelshader that implemented a quaternion fractal raytracer with camera, lights, shadows and stuff, but stitching together a friggin triangle in DX10 already proves to be so troublesome for me :/ (Saying: Once everything is set up and well, and all the managing stuff aside from the actual math is in my head, I am very well up to speed. I just need to get there properly once.)

But since the book you posted is of VERY reasonable price, I still will give it a shot. I hope bringing it to Germany won't be too much of a problem, but amazon usually is awesome.

But I guess my little happy birthday particle-message-minidemo is doomed, that's gonna need a miracle by now. I did not fathom such stupid problems that early on .




Umh, this got a tad more lengthy than intended, but I had to get it off my chest I guess ;) Thanks for the great help so far!!

Share this post


Link to post
Share on other sites
:lol:

I come from Delphi, too, but since I'm used to C# I never want to go back. Neither do I like C++ very much. Admittedly, when it comes down to bare DX, docs, tutorials and books are mainly C++, so it's IMHO essential to be able to read it.

I started with XNA up to the point I understood enough to delve deeper. The DX 9 shader book from Luna helped a lot. Don't get discouraged. The dreaded triangle can drive people nuts (happens here regularly) but from there it gets easier. And you actually already know the DX 9 API a bit. Good start.

Additonal hints: Checkout the SlimDX source, [strike]only this will come with the samples and the (no longer supported!) framework[/strike] Edit: Oops, no, it's there, as a self extracting archive, sorry.
It's also very convenient to find the API counterpart (and vice versa) of a function or structure.

Show your complete code, I take a look.


PS: As an aside: It's usually recommended to learn DX 11 directly (search the forum). Problem is: Even fewer books.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
  • Advertisement
  • Popular Tags

  • Popular Now

  • Advertisement
  • Similar Content

    • By chiffre
      Introduction:
      In general my questions pertain to the differences between floating- and fixed-point data. Additionally I would like to understand when it can be advantageous to prefer fixed-point representation over floating-point representation in the context of vertex data and how the hardware deals with the different data-types. I believe I should be able to reduce the amount of data (bytes) necessary per vertex by choosing the most opportune representations for my vertex attributes. Thanks ahead of time if you, the reader, are considering the effort of reading this and helping me.
      I found an old topic that shows this is possible in principal, but I am not sure I understand what the pitfalls are when using fixed-point representation and whether there are any hardware-based performance advantages/disadvantages.
      (TLDR at bottom)
      The Actual Post:
      To my understanding HLSL/D3D11 offers not just the traditional floating point model in half-,single-, and double-precision, but also the fixed-point model in form of signed/unsigned normalized integers in 8-,10-,16-,24-, and 32-bit variants. Both models offer a finite sequence of "grid-points". The obvious difference between the two models is that the fixed-point model offers a constant spacing between values in the normalized range of [0,1] or [-1,1], while the floating point model allows for smaller "deltas" as you get closer to 0, and larger "deltas" the further you are away from 0.
      To add some context, let me define a struct as an example:
      struct VertexData { float[3] position; //3x32-bits float[2] texCoord; //2x32-bits float[3] normals; //3x32-bits } //Total of 32 bytes Every vertex gets a position, a coordinate on my texture, and a normal to do some light calculations. In this case we have 8x32=256bits per vertex. Since the texture coordinates lie in the interval [0,1] and the normal vector components are in the interval [-1,1] it would seem useful to use normalized representation as suggested in the topic linked at the top of the post. The texture coordinates might as well be represented in a fixed-point model, because it seems most useful to be able to sample the texture in a uniform manner, as the pixels don't get any "denser" as we get closer to 0. In other words the "delta" does not need to become any smaller as the texture coordinates approach (0,0). A similar argument can be made for the normal-vector, as a normal vector should be normalized anyway, and we want as many points as possible on the sphere around (0,0,0) with a radius of 1, and we don't care about precision around the origin. Even if we have large textures such as 4k by 4k (or the maximum allowed by D3D11, 16k by 16k) we only need as many grid-points on one axis, as there are pixels on one axis. An unsigned normalized 14 bit integer would be ideal, but because it is both unsupported and impractical, we will stick to an unsigned normalized 16 bit integer. The same type should take care of the normal vector coordinates, and might even be a bit overkill.
      struct VertexData { float[3] position; //3x32-bits uint16_t[2] texCoord; //2x16bits uint16_t[3] normals; //3x16bits } //Total of 22 bytes Seems like a good start, and we might even be able to take it further, but before we pursue that path, here is my first question: can the GPU even work with the data in this format, or is all I have accomplished minimizing CPU-side RAM usage? Does the GPU have to convert the texture coordinates back to a floating-point model when I hand them over to the sampler in my pixel shader? I have looked up the data types for HLSL and I am not sure I even comprehend how to declare the vertex input type in HLSL. Would the following work?
      struct VertexInputType { float3 pos; //this one is obvious unorm half2 tex; //half corresponds to a 16-bit float, so I assume this is wrong, but this the only 16-bit type I found on the linked MSDN site snorm half3 normal; //same as above } I assume this is possible somehow, as I have found input element formats such as: DXGI_FORMAT_R16G16B16A16_SNORM and DXGI_FORMAT_R16G16B16A16_UNORM (also available with a different number of components, as well as different component lengths). I might have to avoid 3-component vectors because there is no 3-component 16-bit input element format, but that is the least of my worries. The next question would be: what happens with my normals if I try to do lighting calculations with them in such a normalized-fixed-point format? Is there no issue as long as I take care not to mix floating- and fixed-point data? Or would that work as well? In general this gives rise to the question: how does the GPU handle fixed-point arithmetic? Is it the same as integer-arithmetic, and/or is it faster/slower than floating-point arithmetic?
      Assuming that we still have a valid and useful VertexData format, how far could I take this while remaining on the sensible side of what could be called optimization? Theoretically I could use the an input element format such as DXGI_FORMAT_R10G10B10A2_UNORM to pack my normal coordinates into a 10-bit fixed-point format, and my verticies (in object space) might even be representable in a 16-bit unsigned normalized fixed-point format. That way I could end up with something like the following struct:
      struct VertexData { uint16_t[3] pos; //3x16bits uint16_t[2] texCoord; //2x16bits uint32_t packedNormals; //10+10+10+2bits } //Total of 14 bytes Could I use a vertex structure like this without too much performance-loss on the GPU-side? If the GPU has to execute some sort of unpacking algorithm in the background I might as well let it be. In the end I have a functioning deferred renderer, but I would like to reduce the memory footprint of the huge amount of vertecies involved in rendering my landscape. 
      TLDR: I have a lot of vertices that I need to render and I want to reduce the RAM-usage without introducing crazy compression/decompression algorithms to the CPU or GPU. I am hoping to find a solution by involving fixed-point data-types, but I am not exactly sure how how that would work.
    • By cozzie
      Hi all,
      I was wondering it it matters in which order you draw 2D and 3D items, looking at the BeginDraw/EndDraw calls on a D2D rendertarget.
      The order in which you do the actual draw calls is clear, 3D first then 2D, means the 2D (DrawText in this case) is in front of the 3D scene.
      The question is mainly about when to call the BeginDraw and EndDraw.
      Note that I'm drawing D2D stuff through a DXGI surface linked to the 3D RT.
      Option 1:
      A - Begin frame, clear D3D RT
      B - Draw 3D
      C - BeginDraw D2D RT
      D - Draw 2D
      E - EndDraw D2D RT
      F - Present
      Option 2:
      A - Begin frame, clear D3D RT + BeginDraw D2D RT
      B - Draw 3D
      C - Draw 2D
      D - EndDraw D2D RT
      E- Present
      Would there be a difference (performance/issue?) in using option 2? (versus 1)
      Any input is appreciated.
    • By Sebastian Werema
      Do you know any papers that cover custom data structures like lists or binary trees implemented in hlsl without CUDA that work perfectly fine no matter how many threads try to use them at any given time?
    • By cozzie
      Hi all,
      Last week I noticed that when I run my test application(s) in Renderdoc, it crashes when it enable my code that uses D2D/DirectWrite. In Visual Studio no issues occur (debug or release), but when I run the same executable in Renderdoc, it crashes somehow (assert of D2D rendertarget or without any information). Before I spend hours on debugging/ figuring it out, does someone have experience with this symptom and/or know if Renderdoc has known issues with D2D? (if so, that would be bad news for debugging my application in the future );
      I can also post some more information on what happens, code and which code commented out, eliminates the problems (when running in RenderDoc).
      Any input is appreciated.
    • By lonewolff
      Hi Guys,
      I understand how to create input layouts etc... But I am wondering is it at all possible to derive an input layout from a shader and create the input layout directly from this? (Rather than manually specifying the input layout format?)
      Thanks in advance :)
       
  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!