## Recommended Posts

Today has been a painful introduction to Direct3D 11 for me. I have successfully got a device initiated and displaying a blank screen (no geometry). I'm now trying to load and apply an effect to get some geometry showing. Unfortunately, the loading and usage of an effect is tripping me up. I think the problem is down to the fact that I'm targetting 'FeatureLevel.Level_9_1' but I'm not sure. Here is my fx file, as simple as can be:
struct VS_IN
{
float4 pos : POSITION;
};

struct PS_IN
{
float4 pos : SV_POSITION;
};

PS_IN vs_main(VS_IN input)
{
PS_IN output = (PS_IN)0;
output.pos = input.pos;
return output;
}

float4 ps_main(PS_IN input) : SV_Target
{
return float4(1, 0, 0, 1);
}

technique Render
{
pass P0
{
}
}


Note that it's simple vertex / pixel shader. And this is me trying to load the effect:
ShaderBytecode effectByteCode = ShaderBytecode.CompileFromFile("Default.fx", "Render", "fx_5_0", /*"vs_4_0_level_9_1", */ShaderFlags.EnableStrictness, EffectFlags.None);
Effect effect = new Effect(this.device, this.effectByteCode, EffectFlags.None);


The loads succeeds (although I'm unsure if it's 'safe' to use the "fx_5_0" profile when targetting Direct3D 9, and vertex / pixel shaders 2.0)? The 'vs_4_0_level_9_1' comment was an alternative profile that I tried, with no success. The problem occurs when I try to use the effect:
EffectTechnique tech = effect.GetTechniqueByIndex(0);
EffectPass pass = tech.GetPassByIndex(0);

InputLayout input = new InputLayout(this.device, pass.Description.Signature, new InputElement[]
{
new InputElement("POSITION0", 0, Format.R32G32B32_Float, 0, 0)
});


GetTechniqueByIndex fails with 'ID3DX11Effect::GetTechniqueByIndex: Invalid technique index (0)', which doesn't cause SlimDX to except until the InputLayout instance is created. I've tried the same with the following:
EffectTechnique tech = effect.GetTechniqueByName("Render");
EffectPass pass = tech.GetPassByIndex(0);

InputLayout input = new InputLayout(this.device, pass.Description.Signature, new InputElement[]
{
new InputElement("POSITION0", 0, Format.R32G32B32_Float, 0, 0)
});


But then the GetTechniqueByName method excepts with 'Attempted to read or write protected memory. This is often an indication that other memory is corrupt.' I'm not sure where I'm going wrong - if my shader code is wrong, if it's compiled incorrectly for Direct3D 9, etc. Hopefully someone can help me? Thanks.

##### Share on other sites
I don't think you can use the 4.0 and up profiles without using technique10 or technique11. I also don't think you can use them in the 9 feature level.

##### Share on other sites
I tried 'fx_2_0', and got the exception '[7860] Effects11: Effect version is unrecognized. This runtime supports fx_5_0 to fx_5_0.'. It may just be a weird error message, but that suggests to me that ONLY the fx_5_0 is supported.

I also tried 'vs_4_0_level_9_1', but I get the exception 'error X3501: 'Render': entrypoint not found'. I'm not sure what an entry point in terms of an effect file, but I assumed 'Render' would be it..!

##### Share on other sites
Leave the entry point null or blank (I forget which is valid). Use technique10.

##### Share on other sites
As far as I can tell, neither is valid - if it's null I get the exception:

"String reference not set to an instance of a String.
Parameter name: s"

If set it to be empty string, I get another exception

"Index was outside the bounds of the array."

I thought I couldn't use 'technique10' when using the 'FeatureLevel.Level_9_1' feature level?

Thanks for your help so far.

##### Share on other sites
Dunno. I'm just guessing. I hadn't ever been able to get effects in D3D11 working properly, although I didn't try very hard. It's the main reason we don't have D3D11 samples in SlimDX yet.

##### Share on other sites
I did wonder why there weren't any. I also wondered why Effect.FromFile was missing - is the effects framework unfinished in SlimDX perhaps?

In fact, should I even be loading effect files with ShaderBytecode.CompileFromFile I wonder? It looks to me like a shader compilation function, and not an effects one...

##### Share on other sites
Effects11 (the underlying native library) is rather different than the previous versions of the effect framework. You're supposed to compile the effect to bytecode and load that, there isn't a 'from file' method any longer.

##### Share on other sites
I got a bit further! Not necessarily in the right direction. I made file a plain vertex shader (no techniques, passes, etc).
struct VS_IN{	float4 pos : POSITION;};struct PS_IN{	float4 pos : SV_POSITION;};PS_IN vs_main(VS_IN input){	PS_IN output = (PS_IN)0;	output.pos = input.pos;	return output;}

And tried to load and it as follows:

effectByteCode = ShaderBytecode.CompileFromFile("Default2.fx", "vs_main", "vs_4_0_level_9_1", ShaderFlags.None, EffectFlags.None);vertexShader = new VertexShader(this.device, effectByteCode);[...]InputLayout input = new InputLayout(this.device, ShaderSignature.GetInputSignature(this.effectByteCode), new InputElement[]    {         new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0)    });context.VertexShader.Set(this.vertexShader);

The shader appears to be loaded, but falls on creating the InputLayout with this error:

'[7560] D3D11: ERROR: ID3D11Device::CreateInputLayout: Input Signature in bytecode could not be parsed. Data may be corrupt or in an unrecognizable format. [ STATE_CREATION ERROR #161: CREATEINPUTLAYOUT_UNPARSEABLEINPUTSIGNATURE ]'

##### Share on other sites
You have to use technique11, the others will not work when using Effects11 API.

You have to compile with "fx_5_0", nothing else will work when using Effects11 API.

In your effect file, you have to compile for your target: which is 9_1, not 2_0 when using feature levels.

SetVertexShader(CompileShader(vs_4_0_level_9_1, vs_main()));

##### Share on other sites
A-ha! That seems to have done the trick.

I'm not getting any output but the effect is loaded. I'm getting another message in DebugView:

[7808] D3D11: WARNING: ID3D11DeviceContext::Draw: Vertex Buffer at the input vertex slot 0 is not big enough for what the Draw*() call expects to traverse. This is OK, as reading off the end of the Buffer is defined to return 0. However the developer probably did not intend to make use of this behavior. [ EXECUTION WARNING #356: DEVICE_DRAW_VERTEX_BUFFER_TOO_SMALL ]

But I think I might have an idea what the problem is.

Thank you both.

@ DieterVW - So this effect, despite having a 'technique11' will work on the Level_9_1 feature level? And will render correctly to Direct3D9 hardware? The 'vs_4_0_level_9_1' string suggests to me that it'll only work on Direct3D9 hardware that supports Vertex Shaders 4.0. Is that right?

Thanks again. :D

##### Share on other sites
There's a problem with the Get*Signature methods of the ShaderSignature class. The source in the SVN repository has an additional constructor for InputLayout that takes a full shader bytecode, but we're still working on fixing the shader signature methods.

##### Share on other sites
Quote:
 Original post by Mike.PopoloskiThere's a problem with the Get*Signature methods of the ShaderSignature class. The source in the SVN repository has an additional constructor for InputLayout that takes a full shader bytecode, but we're still working on fixing the shader signature methods.

The InputLayout methods work when using effect.GetTechniqueByIndex(...).GetPassByIndex(...).Description.Signature, but not when using a ShaderSignature obtained using the ShaderSignature.Get*Signature() methods currently, although the fix in the SVN solves that.

As for feature levels, I've never managed to get the effects system to work properly with anything under Level_9_3. Is there any reason you can't target this instead of 9_1? I could give you some pointers then.

Quote:
 Original post by jpetrieDunno. I'm just guessing. I hadn't ever been able to get effects in D3D11 working properly, although I didn't try very hard. It's the main reason we don't have D3D11 samples in SlimDX yet.

It's not as easy as it could be, but it does work with the Feb release. If you want a hand with producing samples I can provide code.

##### Share on other sites
The feature level targets are a bit confusing, but here is what happens. When running a feature 10Level9, the entire runtime will start making only DX9 DDI driver calls. So you are constrained to using features that exist only in DX9 and having to use shaders that are compiled to be used with the DX10 runtime, but target the DX9 driver.

These 10Level9 shaders contain 2 shader blobs, one is 9_x and one is 4_0, depending on the device, the runtime will make use of the correct shader blob for you.

##### Share on other sites
Quote:
 Original post by adt7It's not as easy as it could be, but it does work with the Feb release. If you want a hand with producing samples I can provide code.

This my entire test project (which still isn't work properly - it should render a triangle using WARP... but doesn't). I at least got around the effect loading problems though..!

If anyone can spot the problem, please let me know. I'll persevere and update if I solve it.

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using SlimDX.Direct3D11;using SlimDX.DXGI;using SlimDX;using Device = SlimDX.Direct3D11.Device;using Buffer = SlimDX.Direct3D11.Buffer;using System.Runtime.InteropServices;namespace TestDirect3D11{    public partial class Form1 : Form    {        private Device device;        private SwapChain swapChain;        private RenderTargetView renderTargetView;        private Texture2D texture;        private Buffer vertexBuffer;        private ShaderBytecode effectByteCode;        private Effect defaultEffect;        public Form1()        {            InitializeComponent();            // Create the swap chain description            SwapChainDescription swapChainDescription = new SwapChainDescription()            {                BufferCount = 2,                IsWindowed = true,                Flags = SwapChainFlags.None,                ModeDescription = new ModeDescription(this.Width, this.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm),                OutputHandle = this.Handle,                SampleDescription = new SampleDescription(1, 0),                SwapEffect = SwapEffect.Discard,                Usage = Usage.RenderTargetOutput            };            // Create the Direct3D11 device, using the WARP driver, and targetting Direct3D 9            Device.CreateWithSwapChain(null, DriverType.Warp, DeviceCreationFlags.None, new FeatureLevel[] { FeatureLevel.Level_9_1 }, swapChainDescription, out this.device, out this.swapChain);            this.ResizeBackBuffer();            // Load the vertex buffer               Vector4[] vertices =                {                    new Vector4(50F, 0F, 1F, 1F),                    new Vector4(100F, 100F, 1F, 1F),                    new Vector4(0F, 100F, 1F, 1F)                };            int stride = Marshal.SizeOf(typeof(Vector4));            int length = stride * vertices.Length;            using (DataStream vertexDataStream = new DataStream(vertices, true, true))            {                this.vertexBuffer = new Buffer(this.device, vertexDataStream,                    new BufferDescription(length, ResourceUsage.Default, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, stride));            }            string errors;            this.effectByteCode = ShaderBytecode.CompileFromFile("Default.fx", "vs_main", "fx_5_0", ShaderFlags.None, EffectFlags.None, null, null, out errors);            this.defaultEffect = new Effect(this.device, this.effectByteCode, EffectFlags.None);        }        private void ResizeBackBuffer()        {            // Dispose of the previous render target view            if (this.renderTargetView != null)                this.renderTargetView.Dispose();            // Resize the swap chain buffers            this.swapChain.ResizeBuffers(2, this.Width, this.Height, Format.R8G8B8A8_UNorm, SwapChainFlags.None);            // Create the new render target view            using (Texture2D backBuffer = Texture2D.FromSwapChain<Texture2D>(this.swapChain, 0))            {                this.renderTargetView = new RenderTargetView(this.device, backBuffer);            }        }        protected override void OnPaint(PaintEventArgs e)        {            if (swapChain != null)            {                try                {                    DeviceContext context = this.device.ImmediateContext;                    context.ClearRenderTargetView(this.renderTargetView, new Color4(0F, 0F, 0F));                    EffectTechnique tech = this.defaultEffect.GetTechniqueByIndex(0);                    EffectPass pass = tech.GetPassByIndex(0);                                        ShaderSignature shaderSignature = pass.Description.Signature;                    InputLayout input = new InputLayout(this.device, shaderSignature, new InputElement[]                    {                        new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0)                    });                    this.defaultEffect.GetVariableByName("worldViewProjection").AsMatrix().SetMatrix(Matrix.OrthoOffCenterLH(0F, this.Width, this.Height, 0F, 0F, 100F));                    context.InputAssembler.InputLayout = input;                    context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;                    context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(this.vertexBuffer, Marshal.SizeOf(typeof(Vector4)), 0));                    for (int i = 0; i < tech.Description.PassCount; ++i)                    {                        tech.GetPassByIndex(i).Apply(context);                        context.Draw(3, 0);                    }                    this.swapChain.Present(0, PresentFlags.None);                }                catch (Exception ex)                {                    System.Windows.Forms.MessageBox.Show(ex.ToString());                }            }                        base.OnPaint(e);        }        protected override void OnResize(EventArgs e)        {            this.ResizeBackBuffer();            base.OnResize(e);        }        protected override void OnPaintBackground(PaintEventArgs e)        {            //base.OnPaintBackground(e);        }        protected override void OnFormClosed(FormClosedEventArgs e)        {            // Dispose of the Direct3D resources            this.effectByteCode.Dispose();            this.defaultEffect.Dispose();            this.vertexBuffer.Dispose();            this.renderTargetView.Dispose();            this.swapChain.Dispose();            this.device.Dispose();            base.OnFormClosed(e);        }    }}

Default.fx
float4x4 worldViewProjection;struct VS_IN{	float4 Position : POSITION0;};struct PS_IN{	float4 Position : SV_POSITION;};// -------------// Vertex Shader// -------------PS_IN vs_main(VS_IN input) : SV_POSITION{   PS_IN output;   output.Position = mul(input.Position, worldViewProjection);   return output;}// ------------// Pixel Shader// ------------float4 ps_main(PS_IN input) : SV_TARGET{	return float4(1, 1, 1, 1);}// ----------// Techniques// ----------technique11 Render{   pass Pass_0   {      SetVertexShader(CompileShader(vs_4_0_level_9_1, vs_main()));      SetPixelShader(CompileShader(ps_4_0_level_9_1, ps_main()));   }}

I know it doesn't clean things up and is generally horribly written. I'll tidy it up once it works! :p

##### Share on other sites
First of all, don't use OnPaint as a real-time rendering mechanism. It's not designed for that. Reasoning.

As for your problem, you're missing two crucial steps:
1. You need to actual set your render target to the output merger.
2. You need to set a viewport.

For example:
device.ImmediateContext.OutputMerger.SetTargets(renderTargetView);device.ImmediateContext.Rasterizer.SetViewports(new Viewport(0, 0, ClientSize.Width, ClientSize.Height));

##### Share on other sites
Hurray! It works! Thanks for the tip about using OnPaint, this was only a test app, but it's good information to know as it probably would've crept into an actual project.

EDIT: How do I stop the MessagePump? My application excepts when the form is closed when I use it. Specifically:

ObjectDisposedException at Application.Run(new Form1());

Cannot access a disposed object.
Object name: 'Form1'.

##### Share on other sites
Don't use Application.Run if you're using MessagePump.Run. It's designed to replace it.

## Create an account

Register a new account

• ### Forum Statistics

• Total Topics
627701
• Total Posts
2978711
• ### Similar Content

• By Baemz
Hello,
I've been working on some culling-techniques for a project. We've built our own engine so pretty much everything is built from scratch. I've set up a frustum with the following code, assuming that the FOV is 90 degrees.
float angle = CU::ToRadians(45.f); Plane<float> nearPlane(Vector3<float>(0, 0, aNear), Vector3<float>(0, 0, -1)); Plane<float> farPlane(Vector3<float>(0, 0, aFar), Vector3<float>(0, 0, 1)); Plane<float> right(Vector3<float>(0, 0, 0), Vector3<float>(angle, 0, -angle)); Plane<float> left(Vector3<float>(0, 0, 0), Vector3<float>(-angle, 0, -angle)); Plane<float> up(Vector3<float>(0, 0, 0), Vector3<float>(0, angle, -angle)); Plane<float> down(Vector3<float>(0, 0, 0), Vector3<float>(0, -angle, -angle)); myVolume.AddPlane(nearPlane); myVolume.AddPlane(farPlane); myVolume.AddPlane(right); myVolume.AddPlane(left); myVolume.AddPlane(up); myVolume.AddPlane(down); When checking the intersections I am using a BoundingSphere of my models, which is calculated by taking the average position of all vertices and then choosing the furthest distance to a vertex for radius. The actual intersection test looks like this, where the "myFrustum90" is the actual frustum described above.
The orientationInverse is actually the viewMatrix-inverse in this case.
bool CFrustum::Intersects(const SFrustumCollider& aCollider) { CU::Vector4<float> position = CU::Vector4<float>(aCollider.myCenter.x, aCollider.myCenter.y, aCollider.myCenter.z, 1.f) * myOrientationInverse; return myFrustum90.Inside({ position.x, position.y, position.z }, aCollider.myRadius); } The Inside() function looks like this.
template <typename T> bool PlaneVolume<T>::Inside(Vector3<T> aPosition, T aRadius) const { for (unsigned short i = 0; i < myPlaneList.size(); ++i) { if (myPlaneList[i].ClassifySpherePlane(aPosition, aRadius) > 0) { return false; } } return true; } And this is the ClassifySpherePlane() function. (The plane is defined as a Vector4 called myABCD, where ABC is the normal)
template <typename T> inline int Plane<T>::ClassifySpherePlane(Vector3<T> aSpherePosition, float aSphereRadius) const { float distance = (aSpherePosition.Dot(myNormal)) - myABCD.w; // completely on the front side if (distance >= aSphereRadius) { return 1; } // completely on the backside (aka "inside") if (distance <= -aSphereRadius) { return -1; } //sphere intersects the plane return 0; }
Please bare in mind that this code is not optimized nor well-written by any means. I am just looking to get it working.
The result of this culling is that the models seem to be culled a bit "too early", so that the culling is visible and the models pops away.
How do I get the culling to work properly?
I have tried different techniques but haven't gotten any of them to work.
If you need more code or explanations feel free to ask for it.

Thanks.

• hi,
i have read very much about the binding of a constantbuffer to a shader but something is still unclear to me.
e.g. when performing :   vertexshader.setConstantbuffer ( buffer,  slot )
is the buffer bound
or
b. to the VertexShader that is currently set as the active VertexShader
Is it possible to bind a constantBuffer to a VertexShader e.g. VS_A and keep this binding even after the active VertexShader has changed ?
I mean i want to bind constantbuffer_A  to VS_A, an Constantbuffer_B to VS_B  and  only use updateSubresource without using setConstantBuffer command every time.

Look at this example:
perform drawcall       ( buffer_A is used )

perform drawcall   ( buffer_B is used )
perform drawcall   (now which buffer is used ??? )

I ask this question because i have made a custom render engine an want to optimize to
the minimum  updateSubresource, and setConstantbuffer  calls

• I got a quick question about buffers when it comes to DirectX 11. If I bind a buffer using a command like:
IASetVertexBuffers IASetIndexBuffer VSSetConstantBuffers PSSetConstantBuffers  and then later on I update that bound buffer's data using commands like Map/Unmap or any of the other update commands.
Do I need to rebind the buffer again in order for my update to take effect? If I dont rebind is that really bad as in I get a performance hit? My thought process behind this is that if the buffer is already bound why do I need to rebind it? I'm using that same buffer it is just different data

• I am really stuck with something that should be very simple in DirectX 11.
1. I can draw lines using a PC (position, colored) vertices and a simple shader just fine.
2. I can draw 3D triangles using PCN (position, colored, normal) vertices just fine (even transparency and SpecularBlinnPhong shaders).

However, if I'm using my 3D shader, and I want to draw my PC lines in the same scene how can I do that?

If I change my lines to PCN and pass them to the 3D shader with my triangles, then the lighting screws them all up.  I only want the lighting for the 3D triangles, but no SpecularBlinnPhong/Lighting for the lines (just PC).
I am sure this is because if I change the lines to PNC there is not really a correct "normal" for the lines.
I assume I somehow need to draw the 3D triangles using one shader, and then "switch" to another shader and draw the lines?  But I have no clue how to use two different shaders in the same scene.  And then are the lines just drawn on top of the triangles, or vice versa (maybe draw order dependent)?
I must be missing something really basic, so if anyone can just point me in the right direction (or link to an example showing the implementation of multiple shaders) that would be REALLY appreciated.

I'm also more than happy to post my simple test code if that helps as well!

• By Reitano
Hi,
I am writing a linear allocator of per-frame constants using the DirectX 11.1 API. My plan is to replace the traditional constant allocation strategy, where most of the work is done by the driver behind my back, with a manual one inspired by the DirectX 12 and Vulkan APIs.
In brief, the allocator maintains a list of 64K pages, each page owns a constant buffer managed as a ring buffer. Each page has a history of the N previous frames. At the beginning of a new frame, the allocator retires the frames that have been processed by the GPU and frees up the corresponding space in each page. I use DirectX 11 queries for detecting when a frame is complete and the ID3D11DeviceContext1::VS/PSSetConstantBuffers1 methods for binding constant buffers with an offset.
The new allocator appears to be working but I am not 100% confident it is actually correct. In particular:
1) it relies on queries which I am not too familiar with. Are they 100% reliable ?
2) it maps/unmaps the constant buffer of each page at the beginning of a new frame and then writes the mapped memory as the frame is built. In pseudo code:
BeginFrame:
page.data = device.Map(page.buffer)
device.Unmap(page.buffer)
RenderFrame
Alloc(size, initData)
...
memcpy(page.data + page.start, initData, size)
Alloc(size, initData)
...
memcpy(page.data + page.start, initData, size)
(Note: calling Unmap at the end of a frame prevents binding the mapped constant buffers and triggers an error in the debug layer)
Is this valid ?
3) I don't fully understand how many frames I should keep in the history. My intuition says it should be equal to the maximum latency reported by IDXGIDevice1::GetMaximumFrameLatency, which is 3 on my machine. But, this value works fine in an unit test while on a more complex demo I need to manually set it to 5, otherwise the allocator starts overwriting previous frames that have not completed yet. Shouldn't the swap chain Present method block the CPU in this case ?
4) Should I expect this approach to be more efficient than the one managed by the driver ? I don't have meaningful profile data yet.
Is anybody familiar with the approach described above and can answer my questions and discuss the pros and cons of this technique based on his experience ?
For reference, I've uploaded the (WIP) allocator code at https://paste.ofcode.org/Bq98ujP6zaAuKyjv4X7HSv.  Feel free to adapt it in your engine and please let me know if you spot any mistakes
Thanks
Stefano Lanza

• 21
• 14
• 12
• 10
• 12