Jump to content

  • Log In with Google      Sign In   
  • Create Account

How to fill triangle with different colors on front and back sides?


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
12 replies to this topic

#1 Yura   Members   -  Reputation: 263

Like
0Likes
Like

Posted 19 December 2012 - 05:41 AM

I have primitive triangles (triangle list) and have back culling off
[source lang="csharp"] d3dDevice.SetRenderState(RenderState.CullMode, Cull.None);[/source]

And now I want to fill this triangle with colour in such way, so front side had one colour and when I rotate it to back side, it had another colour.
Is it possible to do that?
Each point of triangle can have it's colour

Sponsor:

#2 Gavin Williams   Members   -  Reputation: 776

Like
3Likes
Like

Posted 19 December 2012 - 06:48 AM

if you pass the camera position to your vertex shader, then you can check facing with the following ..

output.faceShear = dot(input.normal,gEyePosition - input.position);

Then you can select front and back face with

if (input.faceShear >= 0.0)
  return float4(input.colorA,1);
else
  return float4(input.colorB,1);


#3 unbird   Crossbones+   -  Reputation: 6012

Like
6Likes
Like

Posted 19 December 2012 - 12:52 PM

For shader model 3 there's also the VFACE semantic, automatically available in the pixel shader (just define a float face : VFACE parameter in your shader function).

Or are you using the fixed function pipeline ?

@Gavin: Hmmm, does this really work ? E.g. normals don't need to coincide with the face normals.

#4 Gavin Williams   Members   -  Reputation: 776

Like
3Likes
Like

Posted 19 December 2012 - 03:11 PM

It really works, as long as the 3 normals are perpendicular to the face and forward facing. But no, the normals don't have to coincide with the face normals, and if they were non-perpendicular then you would get color flipping across the face. But I didn't think the OP was interested in the general case, just a specific requirement. I thought there was something in DX11 to give the front/back face, like the semantic you've mentioned, but I couldn't say about DX9. So I just gave him the first solution that came to mind.

But, Yura, definitely follow unbirds suggestion if that works.

#5 Yura   Members   -  Reputation: 263

Like
0Likes
Like

Posted 20 December 2012 - 07:20 AM

For shader model 3 there's also the VFACE semantic, automatically available in the pixel shader (just define a float face : VFACE parameter in your shader function).

Or are you using the fixed function pipeline ?

@Gavin: Hmmm, does this really work ? E.g. normals don't need to coincide with the face normals.


I do not use any shaders, so can you explain in details, what and where shoud I fix in my code

[source lang="csharp"][StructLayout(LayoutKind.Sequential)] struct Vertex { public Vector4 Position; public Color Color; //public Vector3 Normal; }private void InitGeometryTriangles() { FormList(); List<Vertex> points = new List<Vertex>(); for (int i = 0; i < elements.Length; i++) { List<Node> list = elements[i].Nodes; int listCount = list.Count; for (int j = 0; j < listCount; j++) { points.Add(new Vertex() { Color = SharpDX.Color.Gray, Position = new Vector4(list[j].X, list[j].Y, list[j].Z, 1.0f) }); if (j == 2) { points.Add(new Vertex() { Color = SharpDX.Color.Gray, Position = new Vector4(list[j].X, list[j].Y, list[j].Z, 1.0f) }); } } points.Add(new Vertex() { Color = SharpDX.Color.Gray, Position = new Vector4(list[0].X, list[0].Y, list[0].Z, 1.0f) }); } totalPointsCount = points.Count; vertices = new VertexBuffer(d3dDevice, Marshal.SizeOf(typeof(Vertex)) * totalPointsCount, SharpDX.Direct3D9.Usage.WriteOnly, myVertexFormat, Pool.Managed); vertices.Lock(0, 0, LockFlags.None).WriteRange(points.ToArray()); vertices.Unlock(); var vertexElems = new[] { new VertexElement(0, 0, DeclarationType.Float4, DeclarationMethod.Default, DeclarationUsage.Position, 0), new VertexElement(0, 16, DeclarationType.Color, DeclarationMethod.Default, DeclarationUsage.Color, 0), VertexElement.VertexDeclarationEnd }; vertexDecl = new VertexDeclaration(d3dDevice, vertexElems);}private void RedrawPrimitives() { d3dDevice.VertexFormat = myVertexFormat; d3dDevice.VertexDeclaration = vertexDecl; d3dDevice.Clear(ClearFlags.Target, SharpDX.Color.White, 1.0f, 0); d3dDevice.BeginScene(); d3dDevice.SetStreamSource(0, vertices, 0, Marshal.SizeOf(typeof(Vertex))); d3dDevice.DrawPrimitives(PrimitiveType.TriangleList, 0, totalPointsCount / 3); d3dDevice.EndScene(); d3dDevice.Present(); }[/source]

Thanks for reply!

#6 Gavin Williams   Members   -  Reputation: 776

Like
2Likes
Like

Posted 20 December 2012 - 07:40 AM

If you're not using shaders then neither of our suggestions are going to be of any use. Instead you will have to provide two triangles, one for each side, and turn back-face culling on, so that they don't interfere with each other when rendering.

#7 Yura   Members   -  Reputation: 263

Like
0Likes
Like

Posted 20 December 2012 - 08:31 AM

If you're not using shaders then neither of our suggestions are going to be of any use. Instead you will have to provide two triangles, one for each side, and turn back-face culling on, so that they don't interfere with each other when rendering.


Can you post here some example of shader, similar to my problem
and provide guidance on the application of this shader in my code?

#8 Yura   Members   -  Reputation: 263

Like
0Likes
Like

Posted 20 December 2012 - 09:35 AM

One more question: how to make my triangles not permeable (opaque)?

#9 BornToCode   Members   -  Reputation: 948

Like
3Likes
Like

Posted 20 December 2012 - 06:27 PM

You can do it in two pass. The first pass just set cull mode to back face so it cull back face polygons and draw the front frace with the color you want. For the second pass just set cull mode to front face and draw all the back faces with the color you want.

Edited by BornToCode, 20 December 2012 - 06:29 PM.


#10 unbird   Crossbones+   -  Reputation: 6012

Like
3Likes
Like

Posted 21 December 2012 - 07:03 AM

@Gavins: Thanks for the clarification about the normals.

@BornToCode: +1. That's what I approximately had in mind for a FFP setup.

I also find Gavin's idea with doubling the triangles quite nice. Just add the vertices twice (with different color), once as before, once in reverse order, that should do it. With an index buffer this is even easier and less wasteful.

Transparency - or any other special/custom form of final color mixing with the background - is called blending. You enable it through
device.SetRenderState(RenderState.AlphaBlendEnable, true);

There are a couple of render states for configuration.
E.g. the usual (nonpremultiplied) alpha blending is setup through:
 
device.SetRenderState(RenderState.SourceBlend, Blend.SourceAlpha);
device.SetRenderState(RenderState.DestinationBlend, Blend.InverseSourceAlpha);
device.SetRenderState(RenderState.BlendOperation, BlendOperation.Add);

Now you need to provide a sensible alpha channel, in your case through vertex color. An alpha of 255 (or 1.0 normalized) will give you full opacity, 128 will blend the color about halfway with the background.

This is relatively easy to setup, but can be hard to get right. Depending on your blending mode, you may also need to draw your objects/primitives ordered (farthest first). As a workaround: Use additive blending, this is order-independant.

Hmmmm, writing a shader mini-tutorial here ? Sorry, not in the mood smile.png. You should actually find quite plenty, just not especially for SlimDX.

Still: Highly advised in the long run, since it's the way to do real-time graphics for probably a decade now. It's really fun, since you are now programming the graphics hardware, which gives higher flexibility. But it's also harder to debug and sometimes cumbersome to get things right.

If time allows start now. I advise to use the effect framework, not raw shaders. I also advise to learn about index buffer and custom vertex format, aka VertexDeclaration (since the flexible vertex format is not really flexibel. The D3DX functions D3DXDeclaratorFromFVF, D3DXFVFFromDeclarator, D3DXGetDeclVertexSize will come in handy here, they are available in SlimDX.Direct3D9.D3DX).

Edit: Ah, sorry, you already are using a declaration.

Edited by unbird, 21 December 2012 - 07:08 AM.


#11 Yura   Members   -  Reputation: 263

Like
0Likes
Like

Posted 21 December 2012 - 09:50 AM

I don't think doubling each point is a good idea because my polygon is quite big. In better way vertex buffer contain 50 000 points, in worst - 10 000 000 and more (sometimes it just can't be drawn). Now I'm trying to reduce number of vertices by using Indexes, unfortinutly without success. There is other topic with more information about my project http://www.gamedev.net/topic/635625-fastest-way-to-draw-rectangles-with-slimdx-sharpdx/

#12 unbird   Crossbones+   -  Reputation: 6012

Like
1Likes
Like

Posted 21 December 2012 - 06:58 PM

That is quite big. Let us look at the numbers:

Your current vertex size is 20 (4 floats, 4 bytes each for position, 4 bytes for the color)
10 million vertices.
This alone gives you approx 200 Mb of vertex data.

With a naive setup (add quads/tris as they come) this number will be scaled by factor of 6 or 3 respectively, so you've probably already blown the GPU memory limit of an average consumer card (or the limit the driver gives you). As you say: One draw call impossible. True, duplicating vertices further (or adding additional vertex data) is undesirable.

Sure you can now massage the API to make it work , but with these numbers I'm inclined to suggest an non-realtime approach (you could still use D3D for rendering though). Have you tried a GDI-setup (with low render quality) ?

Anyway, here some suggestions for D3D optimizations.
  • No need to use a Vector4 for position if your w is always 1. The D3D runtime will do that automatically for Vector3 (D3DDECLTYPE_FLOAT3 )
  • Reduce precision of your vertex elements. Half-floats/shorts for positions ? Scalar for the color ? With shaders you can even do sophisticated packing (custom format).
  • Why rely on big memory or insist on few draw calls ? Split your mesh into parts the API/GPU can cope with one at a time. You can still get good performance with that. It's sort of streaming.
  • Indexing, as Dynamo_Maestro suggested. To get familiar with start with something real simple (triangle, quad, two adjacent quads, grid, a sphere...).
  • Shaders: As mentioned, greater flexibility.
  • Instancing. Is a way to render "the same" geometry multiple times with different position/color/whatever. In your case this would be the quads for the geometry and the position and color for the instances. Consider this advanced D3D API, it needs SM 3.
But always know: no API-trick (or even using a "faster" API like D3D) is a silver bullet. You can setup a complex system reducing e.g. payload and the thing still renders slower.
Do some research and chose wisely which path you wanna go because I think you have a challenging problem.

#13 Yura   Members   -  Reputation: 263

Like
0Likes
Like

Posted 24 December 2012 - 08:14 AM

That is quite big. Let us look at the numbers:

Your current vertex size is 20 (4 floats, 4 bytes each for position, 4 bytes for the color)
10 million vertices.
This alone gives you approx 200 Mb of vertex data.

With a naive setup (add quads/tris as they come) this number will be scaled by factor of 6 or 3 respectively, so you've probably already blown the GPU memory limit of an average consumer card (or the limit the driver gives you). As you say: One draw call impossible. True, duplicating vertices further (or adding additional vertex data) is undesirable.

Sure you can now massage the API to make it work , but with these numbers I'm inclined to suggest an non-realtime approach (you could still use D3D for rendering though). Have you tried a GDI-setup (with low render quality) ?

Anyway, here some suggestions for D3D optimizations.

  • No need to use a Vector4 for position if your w is always 1. The D3D runtime will do that automatically for Vector3 (D3DDECLTYPE_FLOAT3 )
  • Reduce precision of your vertex elements. Half-floats/shorts for positions ? Scalar for the color ? With shaders you can even do sophisticated packing (custom format).
  • Why rely on big memory or insist on few draw calls ? Split your mesh into parts the API/GPU can cope with one at a time. You can still get good performance with that. It's sort of streaming.
  • Indexing, as Dynamo_Maestro suggested. To get familiar with start with something real simple (triangle, quad, two adjacent quads, grid, a sphere...).
  • Shaders: As mentioned, greater flexibility.
  • Instancing. Is a way to render "the same" geometry multiple times with different position/color/whatever. In your case this would be the quads for the geometry and the position and color for the instances. Consider this advanced D3D API, it needs SM 3.
But always know: no API-trick (or even using a "faster" API like D3D) is a silver bullet. You can setup a complex system reducing e.g. payload and the thing still renders slower.
Do some research and chose wisely which path you wanna go because I think you have a challenging problem.

 

Thanks for your interest to my problem! 
So, about your suggestions, I've already made changes in Vectors, now they are Vector3. It works fine. Now I'm trying to implement Indexes. It seems to be easy, with triangle list it realy is, but I can't force it to draw line list. But it is my bad, i'll do it soon.
I'm not very good in DirectX programming, so I have no idea what is SM 3, but idea with multiple geometry is very seductive. I'll try to figure out with this.
About shaders,  I read about them but I didn't find how to solve any of my problems with their help... They are too difficult for me)





Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS