Jump to content

  • Log In with Google      Sign In   
  • Create Account


Porting from OpenGL to Directx


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
30 replies to this topic

#1 xDarkice   Members   -  Reputation: 112

Like
0Likes
Like

Posted 07 January 2012 - 07:23 AM

Hello,

recently I have been trying to port over the OpenGL interface due to some problems with Intel Graphic chips which have a bad OpenGL driver in Windows. I need help to port a Quad in OpenGL to DirectX. Heres what i have done in OpenGL:

GL.Begin(BeginMode.Quads);
					GL.TexCoord2(x1, y1);
					GL.Vertex3(rx1, ry1, rect.Z + CGraphics.ZOffset);
				  
					GL.TexCoord2(x1, y2);
					GL.Vertex3(rx1, ry2, rect.Z + CGraphics.ZOffset);
					GL.TexCoord2(x2, y2);
					GL.Vertex3(rx2, ry2, rect.Z + CGraphics.ZOffset);
					GL.TexCoord2(x2, y1);
					GL.Vertex3(rx2, ry1, rect.Z + CGraphics.ZOffset);
					GL.End();

And here is what I am doing for DirectX
rx1 = ((rx1 * 2) / ClientSize.Width)  -1f;
				rx2 = ((rx2 * 2) / ClientSize.Width) - 1f;
				ry1 = ((ry1 * 2) / ClientSize.Height) - 1f;
				ry2 = ((ry2 * 2) / ClientSize.Height) - 1f;

				DataStream stream = _VertexBuffer.Lock(0, 0, LockFlags.None);
				stream.WriteRange(new[] {
   				 new TexturedVertex(new Vector3(rx1, ry1, 0), new Vector2(x1, y1)),
   				 new TexturedVertex(new Vector3(rx1, ry2, 0), new Vector2(x1, y2)),
   				 new TexturedVertex(new Vector3(rx2, ry2, 0), new Vector2(x2, y2)),
					new TexturedVertex(new Vector3(rx2, ry1, 0), new Vector2(x2, y1)),
   			 });
				_VertexBuffer.Unlock();
				m_Device.SetTexture(0, _D3DTextures[Texture.index]);
				m_Device.SetStreamSource(0, _VertexBuffer, 0, Marshal.SizeOf(typeof(TexturedVertex)));
				m_Device.DrawPrimitives(PrimitiveType.TriangleFan, 0, 2);

Unfortunetely the Textures are mirrored and the alpha Channel is displayed in black. I hope you can help me, I have been trying to get this working for 2 days now =/

Best regards xDarkice

Attached Thumbnails

  • mirrored.PNG


Sponsor:

#2 Nik02   Crossbones+   -  Reputation: 2641

Like
1Likes
Like

Posted 07 January 2012 - 08:40 AM

To mirror the texture, negate the v component of the texture coordinate. D3D and OpenGL consider the "up" direction differently in this case.

To blend with alpha channel, you need to enable the alphablend render state, and set the blend source and destination states accordingly.

As a side note, you don't want to be locking the vertex buffer at each frame if you don't need to. If you have a genuine need to do so, use a vertex buffer with dynamic usage flag specified. Excessive locking can cause stalling because the hardware can't use the buffer for rendering while it is locked to you. Requesting dynamic usage hints the driver to allocate the buffer to a physical memory resource that allows fast write usage at the expense of rendering performance (though choosing the actual allocation strategy is still up to the driver).

Niko Suni


#3 xDarkice   Members   -  Reputation: 112

Like
0Likes
Like

Posted 07 January 2012 - 09:38 AM

Thanks for your answer! After setting
m_Device.SetRenderState(RenderState.AlphaBlendEnable, true);
			m_Device.SetRenderState(RenderState.DestinationBlend, Blend.InverseSourceAlpha);
			m_Device.SetRenderState(RenderState.SourceBlend, Blend.SourceAlpha);
Alpha textures seem to render almost properly. But there are still some black blocks left.

Negating the y cords seems to work for the mirror part but the image is still some of sort of upset down. The main menu texture should be top. The ry1 and ry2 coordinates seem to be incorrect. Am I calculating them wrong? On top of that my Textures seem to be blurry and there might be a part missing
ry1 = ((ry1 * 2) / CSettings.iRenderH) - 1f;
				ry2 = ((ry2 * 2) / CSettings.iRenderH) - 1f;
I am multiplicating my coordinates by 2 and dividing them by the heigth and substracting 1.

I think I do not need to lock the buffer each frame. What should i initialize my DataStream with? Right now I am using
DataStream stream = _VertexBuffer.Lock(0, 0, LockFlags.None);

The second picture shows how it is rendering in OpenGL. I disabled the background video in DirectX for testing purposes.

Now I just need to find a way to color the textures. But I think I can just add a new Color in my TexturedVertex struct.

Thanks for your help!

EDIT: I got the upside down fixed! I didnt had to negate y1 and y2, but ry1 and y2. But the blurry textures and texts arent fixed yet
EDIT2: The Black Bars seem to appear for a whitespace in a text

Attached Thumbnails

  • problem.PNG
  • right.PNG
  • D3D.PNG


#4 hupsilardee   Members   -  Reputation: 486

Like
0Likes
Like

Posted 07 January 2012 - 08:19 PM

OpenGL interprets screen-space positions as the centre of the pixel
DirectX interprets screen-space positions as the top-left corner of the pixel
(Or is it the other way round?)

Either way, to stop your textures from blurring, you need to subtract 0.5 from your screen-space positions when changing between OpenGL and DX. This is like shifting them up-left by 0.5 pixels. So they will still fill the same pixels, but it will affect how the texture coordinates are interpolated, and should stop the blurring

#5 Nik02   Crossbones+   -  Reputation: 2641

Like
0Likes
Like

Posted 08 January 2012 - 05:45 AM

I believe the black bars appear because your text rendering logic actually generates black rectangles with alpha of 1.0 to fill whitespace. Check your code that generates the triangles for the glyphs.

Niko Suni


#6 Nik02   Crossbones+   -  Reputation: 2641

Like
0Likes
Like

Posted 08 January 2012 - 05:53 AM

Regarding locking, only do so when you actually change the text contents. You can't get the DataStream any other way than locking the buffer, nor can you keep the reference to it between frames (because it would keep the resource locked).

You can change the text color by modulating the rgb of the texture with a constant color factor, instead of locking the buffer. In fixed function pipeline, this is achieved by setting appropriate texture stage states, and in a pixel shader the operation is a single multiplication.

Niko Suni


#7 xDarkice   Members   -  Reputation: 112

Like
0Likes
Like

Posted 08 January 2012 - 07:05 AM

I think the black bars appear because texture transparency is not drawn properly. For example my main menu bar should be drawn a little bit transparent like in the openGL pickture I included above.
My DrawGlyph function does render a transparent texture at whitespaces. This shouldnt be the problem because it is working in OpenGL aswell.

EDIT: I am providing my AddTexture and DrawTexture function:

public STexture AddTexture(Bitmap bmp, string TexturePath)
	    {
		    STexture texture = new STexture(-1);
		    if (bmp.Height == 0 || bmp.Width == 0)
			    return texture;
		    int MaxSize;
		    switch (CConfig.TextureQuality)
		    {
			    case ETextureQuality.TR_CONFIG_TEXTURE_LOWEST:
				    MaxSize = 128;
				    break;
			    case ETextureQuality.TR_CONFIG_TEXTURE_LOW:
				    MaxSize = 256;
				    break;
			    case ETextureQuality.TR_CONFIG_TEXTURE_MEDIUM:
				    MaxSize = 512;
				    break;
			    case ETextureQuality.TR_CONFIG_TEXTURE_HIGH:
				    MaxSize = 1024;
				    break;
			    case ETextureQuality.TR_CONFIG_TEXTURE_HIGHEST:
				    MaxSize = 2048;
				    break;
			    default:
				    MaxSize = 512;
				    break;
		    }

		    int w = bmp.Width;
		    int h = bmp.Height;

		    if (h >= w && w > MaxSize)
		    {
			    h = (int)Math.Round((float)MaxSize / bmp.Width * bmp.Height);
			    w = MaxSize;
		    }

		    if (w >= h && h > MaxSize)
		    {
			    w = (int)Math.Round((float)MaxSize / bmp.Height * bmp.Width);
			    h = MaxSize;
		    }

		    Bitmap bmp2 = new Bitmap(w, h);
		    Graphics g = Graphics.FromImage(bmp2);
		    g.DrawImage(bmp, new Rectangle(0, 0, w, h));
		    g.Dispose();


		    texture.width = bmp2.Width;
		    texture.height = bmp2.Height;
		    texture.w2 = texture.width;
		    texture.h2 = texture.height;

		    texture.width_ratio = texture.width / texture.width;
		    texture.height_ratio = texture.height / texture.height;

		    BitmapData bmp_data = bmp2.LockBits(new Rectangle(0, 0, bmp2.Width, bmp2.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
		    using (MemoryStream stream = new MemoryStream())
		    {
			    bmp2.Save(stream, ImageFormat.Bmp);
			    stream.Position = 0;
			    //Texture t = Texture.FromStream(m_Device, stream);
			    Texture t = Texture.FromStream(m_Device, stream, 0, w, h, 0, Usage.None, Format.A8R8G8B8, Pool.Managed, Filter.Default, Filter.Linear, 0);
			    t.AutoMipGenerationFilter = TextureFilter.Linear;
			    t.GenerateMipSublevels();
			    //t = Texture.FromStream(m_Device, stream);
			    _D3DTextures.Add(t);
		    }
		    bmp2.UnlockBits(bmp_data);
		    bmp2.Dispose();

		    // Add to Texture List
		    texture.index = _D3DTextures.Count - 1;
		    texture.color = new SColorF(1f, 1f, 1f, 1f);
		    texture.rect = new SRectF(0f, 0f, texture.width, texture.height, 0f);
		    texture.TexturePath = String.Empty;
		    _Textures.Add(texture);

		    return texture;
	    }

public void DrawTexture(STexture Texture, SRectF rect, SColorF color, SRectF bounds, bool mirrored)
		    {
			    if ((Texture.index >= 0) && (_Textures.Count > 0) && (_D3DTextures.Count > Texture.index))
			    {
				    float x1 = (bounds.X - rect.X) / rect.W * Texture.width_ratio;
				    float x2 = (bounds.X + bounds.W - rect.X) / rect.W * Texture.width_ratio;
				    float y1 = (bounds.Y - rect.Y) / rect.H * Texture.height_ratio;
				    float y2 = (bounds.Y + bounds.H - rect.Y) / rect.H * Texture.height_ratio;

				    if (x1 < 0)
					    x1 = 0f;

				    if (x2 > Texture.width_ratio)
					    x2 = Texture.width_ratio;

				    if (y1 < 0)
					    y1 = 0f;

				    if (y2 > Texture.height_ratio)
					    y2 = Texture.height_ratio;

				    float rx1 = rect.X;
				    float rx2 = rect.X + rect.W;
				    float ry1 = rect.Y;
				    float ry2 = rect.Y + rect.H;

				    if (rx1 < bounds.X)
					    rx1 = bounds.X;

				    if (rx2 > bounds.X + bounds.W)
					    rx2 = bounds.X + bounds.W;

				    if (ry1 < bounds.Y)
					    ry1 = bounds.Y;

				    if (ry2 > bounds.Y + bounds.H)
					    ry2 = bounds.Y + bounds.H;
				    rect.Z = 1f;
				    //y1 = y1*-1;

				    rx1 = (((rx1-0.5f) * 2) / 1280) - 1f;
				    rx2 = (((rx2 -0.5f) * 2) / 1280) - 1f;
				    ry1 = (((ry1-0.5f) * 2) / 720) - 1f;
				    ry2 = (((ry2-0.5f) * 2) / 720) - 1f;

				    DataStream stream = _VertexBuffer.Lock(0, 0, LockFlags.None);
				    Color c = Color.FromArgb((int)(color.A*255), (int)(color.R*255), (int)(color.G*255), (int)(color.B*255));
				    stream.WriteRange(new[] {
   					 new TexturedColoredVertex(new Vector3(rx1, ry1*-1f, rect.Z + CGraphics.ZOffset), new Vector2(x1, y1), c.ToArgb()),
   					 new TexturedColoredVertex(new Vector3(rx1, ry2*-1f, rect.Z + CGraphics.ZOffset), new Vector2(x1, y2), c.ToArgb()),
   					 new TexturedColoredVertex(new Vector3(rx2, ry2*-1f, rect.Z + CGraphics.ZOffset), new Vector2(x2, y2), c.ToArgb()),
					    new TexturedColoredVertex(new Vector3(rx2, ry1*-1f, rect.Z + CGraphics.ZOffset), new Vector2(x2, y1), c.ToArgb()),
   				 });
				    _VertexBuffer.Unlock();
				    m_Device.VertexDeclaration= TexturedColoredVertex.GetDeclaration(m_Device);
				    m_Device.SetTexture(0, _D3DTextures[Texture.index]);
				    m_Device.SetStreamSource(0, _VertexBuffer, 0, Marshal.SizeOf(typeof(TexturedColoredVertex)));
				    m_Device.DrawPrimitives(PrimitiveType.TriangleFan, 0, 2);
			    }
		    }

I am looking for a way to make textures a bit transparent.

#8 Nik02   Crossbones+   -  Reputation: 2641

Like
1Likes
Like

Posted 08 January 2012 - 09:10 AM

The bmp format does not support alpha channels (universally). Png would be a better choice.

Niko Suni


#9 Nik02   Crossbones+   -  Reputation: 2641

Like
1Likes
Like

Posted 08 January 2012 - 09:12 AM

...and you still lock the vertex buffer each time you draw it (which effectively means at least once per frame).

Niko Suni


#10 xDarkice   Members   -  Reputation: 112

Like
0Likes
Like

Posted 08 January 2012 - 09:37 AM

Ok, thanks for your tip changing from BMP to PNG. This removed the black bars Posted Image. Could you please provide a snippet how to not lock the Vertex buffer each frame, because I am not getting it? And i still need the textures to be a bit translucent.

#11 Nik02   Crossbones+   -  Reputation: 2641

Like
0Likes
Like

Posted 08 January 2012 - 10:46 AM

Simply don't do the lock->write->unlock in the same place where you draw. The buffer update should only be done when you actually want to change its contents, which is usually far more seldom than drawing it.

Niko Suni


#12 Nik02   Crossbones+   -  Reputation: 2641

Like
1Likes
Like

Posted 08 January 2012 - 10:48 AM

And if you want "bit more translucent", you can adjust the alpha levels on the PNG files, or modulate the alpha of the texture by using texture stage states or (again) simple maths in the pixel shader.

Niko Suni


#13 xDarkice   Members   -  Reputation: 112

Like
0Likes
Like

Posted 08 January 2012 - 11:58 AM

I do not need to adjust the alpha levels, because they should already be in the PNG. In OpenGL those textures are rendered translucent, but in DirectX they arent. Just compare the OpenGL and the DirectX one: In OpenGL you can see the snow falling behind the texture where "Main Menu" is drawn on. In DirectX you cant.
I think I am missing some parameters for alpha Blending, am I?

Attached Thumbnails

  • D3Dnottranslucent.PNG
  • OpenGLtranslucend.PNG


#14 Nik02   Crossbones+   -  Reputation: 2641

Like
1Likes
Like

Posted 09 January 2012 - 02:20 AM

If you have alpha blending on, the alpha factor comes from the texture stage setup or the pixel shader. If either outputs alpha of 1.0 (independent of any source textures), the drawn geometry is opaque even though blending is enabled.

Niko Suni


#15 xDarkice   Members   -  Reputation: 112

Like
0Likes
Like

Posted 09 January 2012 - 06:15 AM

Ok i got alpha working now. Now I am stuck at creating a texture out of a byte[], height and width is given. I am doing this:

Texture t = new Texture(m_Device, W, H, 0, Usage.Dynamic, Format.A8R8G8B8, Pool.Default);
			DataRectangle rect = t.LockRectangle(0, LockFlags.None);
			rect.Data.WriteRange(Data);
			t.UnlockRectangle(0);
But i am not getting the result I want on screen. I need this to play a video, decoded by Acinerella, so creating a Bitmap out of the byte[] would not be a good idea due to the bad performance.

Attached Thumbnails

  • video.PNG


#16 Nik02   Crossbones+   -  Reputation: 2641

Like
1Likes
Like

Posted 09 January 2012 - 07:03 AM

It looks like the pitch of the data is incorrect.

D3D textures have a "pitch" that is the number of bytes per line. It may or may not be equal to width * bytes per pixel, and you should not assume that it is.

The actual visible pixels are guaranteed to be at the beginning of the scanline (regardless of the pitch) so the most robust way to copy an image to a texture is to copy the data one line at a time, and shift the destination pointer by the pitch after each line until all the lines are copied. I don't know how to do this in SlimDX, though - I'm a native D3D user.

Also check that the source and destination formats are same (or at least have the same bit count per pixel).

Niko Suni


#17 Nik02   Crossbones+   -  Reputation: 2641

Like
0Likes
Like

Posted 09 January 2012 - 07:16 AM

Also, do not create the texture each frame. This is very detrimental to performance. Instead, keep the texture reference in your code after you've created it, and merely update it when you want to change the contents.

Niko Suni


#18 xDarkice   Members   -  Reputation: 112

Like
0Likes
Like

Posted 09 January 2012 - 09:31 AM

I am not recreating the texture each frame. I keep all textures stored in a List and they can be updated using my UpdateTexture methods. The textures are drawn in my DrawTexture methods.

Your post really helped me out. Instead of writing the data directly into the stream i am now doing this which works like a charm:

DataRectangle rect = t.LockRectangle(0, LockFlags.None);
			for(int i = 0; i < Data.Length;) {
				rect.Data.Write(Data, i, 4 * W);
				i+= 4*W;
				rect.Data.Position = rect.Data.Position - 4 * W;
				rect.Data.Position += rect.Pitch;
			}
			t.UnlockRectangle(0);

The hopefully last minor bugs are that my z-position isnt applied correctly and the textures are still a bit blurry.
The small album art should be rendered over the big one. It is working fine in OpenGL, but z-Positions can go beyond 1.0f in OpenGL. If I draw my z-Positions with values over 1f they wont show up. I am currently setting any positions over 1f to 1f which creates this bug i think.
The other thing is that the textures are not that good as in OpenGL. I experimented with some TextureFilters ending up using a linear filter, which is still not too fine. In OpenGL i am using MipMaps to have smooth textures. Can I do the same in DirectX?

EDIT: Fixed z-Positions, still need to examine why the textures are a bit blurry though I am shifting the Pixels by 0.5

Attached Thumbnails

  • zposition.PNG


#19 Nik02   Crossbones+   -  Reputation: 2641

Like
0Likes
Like

Posted 10 January 2012 - 04:57 AM

You can use mipmaps in D3D too.

In the image attached to your last post, it seems that there is not a 1:1 size correspondence between the source and target. If this is intented, be sure to enable minification, magnification and mip filtering. For mip mapping, you need to allocate and fill the mip levels (I believe there is a D3DX helper function for filling them).

Niko Suni


#20 xDarkice   Members   -  Reputation: 112

Like
0Likes
Like

Posted 10 January 2012 - 06:47 AM

Could this issue also be caused because I am not using textures with sizes of a power of two? The Sizes are not the same, they need to get scaled. For instance covers of any size can be used and they need to get scaled to fit. Could my calculation of the positions be too inaccurate? I need to scale the positions down to values from 0 to 1. In OpenGL I was able to specify screen positions. Is there a setting to do this in D3D aswell?

Edit: I got it smooth now. But I am now getting small bars. After setting
m_Device.SetSamplerState(0, SamplerState.MinFilter, TextureFilter.Linear);
			m_Device.SetSamplerState(0, SamplerState.MagFilter, TextureFilter.Linear);
			m_Device.SetSamplerState(0, SamplerState.MipFilter, TextureFilter.Linear);
I do not get the Previewvideo anymore and these small bars are appearing. Any ideas?

Edit2:
m_Device.SetSamplerState(0, SamplerState.MipFilter, TextureFilter.Linear);
is definetely the line which is breaking the video. Could this be due to I am not filling the video's mipmaps? This is how I am adding a new texture for a video:

public STexture AddTexture(int W, int H, ref byte[] Data)
	    {
		    STexture texture = new STexture(-1);
		    texture.width = W;
		    texture.height = H;
		    texture.w2 = texture.width;
		    texture.h2 = texture.height;
		    texture.width_ratio = texture.width / texture.w2;
		    texture.height_ratio = texture.height / texture.h2;
		    Texture t = new Texture(m_Device, W, H, 0, Usage.Dynamic, Format.A8R8G8B8, Pool.Default);
		    DataRectangle rect = t.LockRectangle(0, LockFlags.None);
		    for(int i = 0; i < Data.Length;) {
			    rect.Data.Write(Data, i, 4 * W);
			    i+= 4*W;
			    rect.Data.Position = rect.Data.Position - 4 * W;
			    rect.Data.Position += rect.Pitch;
		    }
		    t.UnlockRectangle(0);
		    _D3DTextures.Add(t);
		    texture.index = _D3DTextures.Count - 1;
		    texture.color = new SColorF(1f, 1f, 1f, 1f);
		    texture.rect = new SRectF(0f, 0f, texture.width, texture.height, 0f);
		    texture.TexturePath = String.Empty;
		    _Textures.Add(texture);
		    return texture;
	    }

And this is how I am updating this:

public bool UpdateTexture(ref STexture Texture, ref byte[] Data)
	    {
		    if ((Texture.index >= 0) && (_Textures.Count > 0) && (_D3DTextures.Count > Texture.index))
		    {
			    DataRectangle rect = _D3DTextures[Texture.index].LockRectangle(0, LockFlags.None);
			    for (int i = 0; i < rect.Data.Length; )
			    {
				    if (rect.Data.Length - rect.Data.Position > 4 * (int)Texture.width)
				    {
					    rect.Data.Write(Data, i, 4 * (int)Texture.width);
					    i += 4 * (int)Texture.width;
					    rect.Data.Position = rect.Data.Position - 4 * (int)Texture.width;
					    rect.Data.Position += rect.Pitch;
				    }
				    else
					    break;
			    }
			    rect.Data.Position = 0;
			    _D3DTextures[Texture.index].UnlockRectangle(0);
		    }
		    return true;
	    }

I do not need to use MipMaps for videos due to performance reasons, can I disable MipMaps for single textures only?

Attached Thumbnails

  • NoPreview.PNG
  • preview.PNG
  • smallbars.PNG





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