Issue with transparent texture on 3D primitive, XNA 4.0 - c#

I need to draw a large set of cubes, all with (possibly) unique textures on each side. Some of the textures also have parts of transparency. The cubes that are behind ones with transparent textures should show through the transparent texture. However, it seems that the order in which I draw the cubes decides if the transparency works or not, which is something I want to avoid. Look here:
cubeEffect.CurrentTechnique = cubeEffect.Techniques["Textured"];
Block[] cubes = new Block[4];
cubes[0] = new Block(BlockType.leaves, new Vector3(0, 0, 3));
cubes[1] = new Block(BlockType.dirt, new Vector3(0, 1, 3));
cubes[2] = new Block(BlockType.log, new Vector3(0, 0, 4));
cubes[3] = new Block(BlockType.gold, new Vector3(0, 1, 4));
foreach(Block b in cubes) {
b.shape.RenderShape(GraphicsDevice, cubeEffect);
}
This is the code in the Draw method. It produces this result:
As you can see, the textures behind the leaf cube are not visible on the other side. When i reverse index 3 and 0 on in the array, I get this:
It is clear that the order of drawing is affecting the cubes. I suspect it may have to do with the blend mode, but I have no idea where to start with that.

You are relying on depth buffering to achieve occlusion. This technique only works for opaque objects.
To achieve correct occlusion for a scene containing transparent objects:
Set DepthBufferEnable and
DepthBufferWriteEnable to true
Draw all opaque geometry
Leave DepthBufferEnable set to true,
but change DepthBufferWriteEnable to
false
Sort alpha blended objects by
distance from the camera, then draw
them in order from back to front
Extract from Depth sorting alpha blended objects by Shawn Hargreaves

Drawing transparent objects properly is harder than regular ones. The reason is when face is rendered by default it marks all pixels as drawn at certain depth and as result pixels that are behind will not be drawn at all. I'd recommend getting a book on 3d rendering and look through for more details.
The easiest approach you already found - draw transparent objects AFTER non-transparent ones. Works for transpreant and semi-transparent objects. Note that transparent objects need to be sorted to be drawn correctly (unlike non-transparent ones).
In your particular case (non-semitransparent) you can change texture renreding to NOT render anything for transparent parts.

You may be able to use this if you don't have semi-transparent pixels on the objects. It'll either render completely solid or won't write to the Z-Buffer.
As in Riemers Alpha Testing.

XNA (and DirectX and all major 3D libraries) take in consideration something called culling. Although from your code I cannot tell for sure, from the images I think this is your problem. The polygons that you don't see have the vertices in the wrong order. If this is the problem, you have two solutions:
either turn culling off (device.RenderState.CullMode = CullMode.None; if I remember correctly)
apply your texture twice, with the points of the polygon both in clockwise order and counter clockwise

Related

Draw a one pixel line around square sprite

I have a 15 x 15 pixel box, that I draw several off in different colours using:
spriteBatch.Draw(texture, position, colour);
What I'd like to do is draw a one pixel line around the outside, in different colours, thus making it a 17 x 17 box, with (for example), a blue outline one pixel wide and a grey middle.
The only way I can think of doing it is to draw two boxes, one 17x17 in the outline colour, one 15x15 with the box colour, and layer them to give the appearance of an outline:
spriteBatch.Draw(texture17by17, position, outlineColour);
spriteBatch.Draw(texture15by15, position, boxColour);
Obviously the position vector would need to be modified but I think that gives a clear picture of the idea.
The question is: is there a better way?
You can draw lines and triangles using DrawUserIndexedPrimitives, see Drawing 3D Primitives using Lists or Strips on MSDN for more details. Other figures like rectangles and circles are constructed from lines, but you'll need to implement them yourself.
To render lines in 2D, just use orthographic projection which mirrors transformation matrix from SpriteBatch.
You can find a more complete example with the PrimitiveBatch class which encapsulates the logic of drawing in the example Primitives from XBox Live Indie Games.
Considering XNA can't draw "lines" like OpenGL immediate mode can, it is far more efficient to draw a spite with a pre-generated texture quad (2 triangles) than to draw additional geometry with dynamic texturing particularly when a single "line" each requiring 1 triangle; 2 triangles vs 4 respectfully. Less triangles and vertices in the former too.
So I would not try to draw a "thin" line using additional geometry that is trying to mimic lines around the outside of the other, instead continue with what you are doing - drawing 2 different sprites (each is a quad anyway)
Every object drawn in 3D is drawn using triangles. - Would you like to know more?

Scrolling texture in cycle

I'm using C# and XNA and I would like to make a scrolling background in my game.
I'm trying to figure out what the best way to implement a scrolling texture that moves in some direction indefinitely. Let's say a space background with stars. So, when ship moves do does the texture, but in opposite direction. Kinda like in "tiling" mode.
My only guess so far is to render two textures which are, let's say moving left, and then just make the most left one jump to right when it's beyond visibility or something similar to this.
So, I was wondering is there some simple way to do it in XNA, maybe some render mode, or is the way I described it is good enough? I just don't want to overcomplicate things. I obviously tried to google first, but found pretty much nothing, but it is strange considering that many games use similar techniques too.
Theory
A scrolling background image is easy to implement with the XNA SpriteBatch class. There are several overloads of the Draw method which let the caller specify a source rectangle. This source rectangle defines the section of the texture that is drawn to the specified destination rectangle on screen:
Changing the position of the source rectangle will change the section of the texture displayed in the destination rectangle.
In order to have the sprite cover the whole screen use the following destination rectangle:
var destination = new Rectangle(0, 0, screenWidth, screenHeight);
If the whole texture should be displayed use the following destination rectangle:
var source = new Rectangle(0, 0, textureWidth, textureHeight);
Than all you have to do is animate the source rectangle's X and Y coordinates and you are done.
Well, almost done. The texture should start again even if the source rectangle moves out of the texture area. To do that you have to set a SamplerState that uses texture wrap. Fortunately the Begin method of the SpriteBatch allows the usage of a custom SamplerState. You can use one of the following:
// Either one of the three is fine, the only difference is the filter quality
SamplerState sampler;
sampler = SamplerState.PointWrap;
sampler = SamplerState.LinearWrap;
sampler = SamplerState.AnisotropicWrap;
Example
// Begin drawing with the default states
// Except the SamplerState should be set to PointWrap, LinearWrap or AnisotropicWrap
spriteBatch.Begin(
SpriteSortMode.Deferred,
BlendState.Opaque,
SamplerState.AnisotropicWrap, // Make the texture wrap
DepthStencilState.Default,
RasterizerState.CullCounterClockwise
);
// Rectangle over the whole game screen
var screenArea = new Rectangle(0, 0, 800, 600);
// Calculate the current offset of the texture
// For this example I use the game time
var offset = (int)gameTime.TotalGameTime.TotalMilliseconds;
// Offset increases over time, so the texture moves from the bottom to the top of the screen
var destination = new Rectangle(0, offset, texture.Width, texture.Height);
// Draw the texture
spriteBatch.Draw(
texture,
screenArea,
destination,
Color.White
);
Microsoft has a XNA tutorial that does exactly this, you can grab the source code and read up on the actual programming logic behind a scrolling background. Bonus points they do parallax scrolling for a nice effect.
Link: http://xbox.create.msdn.com/en-US/education/tutorial/2dgame/getting_started

texture transparency

I got some problem with texture transparency, I hope ya can help.
Details:
XNA 4.0
Texture source is BMP, what I make transparent by code:
public void Feketealapú(string Azonosító)
{
//textúra megállapítása
Texture2D Textúra = Textúrák[TextúraSzáma(Azonosító)];
//adatok lekérése
Color[] buffer = new Color[Textúra.Width * Textúra.Height];
Textúra.GetData<Color>(buffer);
//adatok módosítása
for (int i = 0; i < buffer.Length; i++)
{
Color szín = buffer[i];
szín.A = ((byte)((szín.R + szín.B + szín.G) / 3));
buffer[i] = szín;
}
//adatok visszaírása
Textúra.SetData<Color>(buffer);
}
I use the following before I start drawing 3d stuff:
public void Rajzolj()
{
GStatic.Játék.GrafikaiCsatorna.BlendState = BlendState.AlphaBlend;
GStatic.Játék.GrafikaiCsatorna.DepthStencilState = DepthStencilState.Default;
GStatic.Játék.GrafikaiCsatorna.RasterizerState = RasterizerState.CullCounterClockwise;
GStatic.Játék.GrafikaiCsatorna.SamplerStates[0] = SamplerState.LinearWrap;
..etc.
If I use BlendState.Opaque I get no transparent textures.
I get into the following trouble: http://youtu.be/ZiPzyk7AWu8
Edit: Bit more detail about the problem is: the problem is with the transparent texture, what simulates a fire effect. The fire is from several rectangles with these transparent textures. If I see the fire from an angle, I should see another fire effect's rectangle through the transparent texture, what is also transparent. The problem is that instead of this, I see the floor's texture behind the model instead.
So could someone help me out a bit?
Thanks in advance:
Péter
Never mind I don't think the transparency is the issue. I think that whats happening is the first thing in the Z-Buffer is being draw and nothing else behind it.
http://blogs.msdn.com/b/shawnhar/archive/2009/02/18/depth-sorting-alpha-blended-objects.aspx
The most import part being the where he specifies how best to order your scene and manipulate the DepthBuffer.
Set DepthBufferEnable and DepthBufferWriteEnable to true
Draw all opaque geometry
Leave DepthBufferEnable set to true, but change DepthBufferWriteEnable to false
Sort alpha blended objects by distance from the camera, then draw them in order from back to front
This is neither a transparency issue or an ordering issue that you can solve.
The nature of your layout has all 4 quads overlapping each other so that each quad needs to be both in front of and behind another quad at the same time.
So setting draw order won't help because half of quad A needs to be drawn before quad B and the other half of quad A needs to be drawn after quad B.
It may get a little bit better if you divide it into 8 quads that all meet in the middle and sort/draw by depth from the camera. But if you go this route, 3 quads may be sufficient.

XNA stretching and filling 2D and 3D content

I've written out a detailed description of my problem here:
http://www.codebot.org/articles/?doc=9574
The basic gist of my question is what is the best way to get XNA to behave like my OpenGL apps, in that I want content stretched to fill a window based on my designed proportions rather than the actual window size.
Further information, this problem relates to varying window or viewport size. In my previous OpenGL apps I would allow uses to switch between windowed and fullscreen mode, and I'd also allow windows to be resized. The problem I am running into with XNA is handling different fullscreen and windowed sizes. In OpenGL I'd detect a when window was resized and adjust the viewport so that the field of view was always fixed to a resolution aspect ratio. I would also create a 2D projection drawing, using the glOrtho function, to a fixed resolution.
The XNA examples I've worked through using SpriteBatch and SpriteFont, text and sprites seem to render in screen pixels. That is, all 2D output is rendered with square pixels and no stretching. In my XNA apps I'd rather they stretch to fill a window in the proportions I've designed. My question is, how can 2D and 3D stretching and filling, like I've done in OpenGL, best be done in XNA?
For 3D content using BasicEffect (and other effects that implement IEffectMatrices as explained here) you can use the appropriate members to set your World, View and Projection matrices as you like.
So where in your OpenGL code you have this:
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(FieldOfView, Width / Height, 1, 1000);
The equivalent in XNA is to set a projection matrix on the effect, like so:
effect.Projection = Matrix.CreatePerspectiveFieldOfView(
FieldOfView, Width / Height, 1, 1000);
Now, for 2D. Here's what you might have in OpenGL:
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, width, height, 0, 0, 1);
If you're using an effect (even with SpriteBatch, as explained here), the basic idea is the same as with 3D:
effect.Projection = Matrix.CreateOrthographicOffCenter(
0, width, height, 0, 0, 1);
Now, if you're using SpriteBatch without a custom effect (and I would recommend this, if you don't actually need a custom effect), you have to bare in mind that, by default, SpriteBatch uses an projection equivalent to:
effect.Projection = Matrix.CreateTranslation(-0.5f, -0.5f, 0)
* Matrix.CreateOrthographicOffCenter(0,
GraphicsDevice.Viewport.Width,
GraphicsDevice.Viewport.Height, 0, 0, 1);
Which gives a "client space" (top left is (0,0)) coordinate system, aligned to pixel centres.
If you want to adjust that space, you may pass in a transformation matrix to SpriteBatch.Begin (this overload).
So to get the effect you are after (where a fixed number of world units appear on screen, no matter the screen size), you can to counter-act the built-in projection from client-space with this transformation:
Matrix.CreateScale(GraphicsDevice.Viewport.Width / 640f,
GraphicsDevice.Viewport.Height / 480f, 1f);
(Assuming you want your visible world space to be 640 by 480.)
I recommend having a look through the documentation for XNA's Matrix on MSDN, to see what kind of matrices you can create.
For 2D drawing I added this to my LoadContent() method, where effect is private field in my Game class ...
effect = new BasicEffect(GraphicsDevice)
{
TextureEnabled = true,
VertexColorEnabled = true
};
And then added this inside my Draw() method ...
effect.Projection = Matrix.CreateTranslation(-0.5f, -0.5f, 0) *
Matrix.CreateOrthographicOffCenter(0, 640, 480, 0, 0, 1);
batch.Begin(0, null, null, null, RasterizerState.CullNone, effect);
It seems to work fine. Now 2D images and fonts are scaled correctly when the window is resized. You recommended not using a custom effect. Is creating an instance of BasicEffect what you meant, or did you mean something else? That is I don't see how to create a custom project matrix without using an effect instance.

Forming bounding box only around visible sprites

this site has been really amazing for helping me with game development however I'm unable to find an answer for the following question (nor am I able to solve it on my own).
I am trying to do rectangle collision in my game. My idea is to 1) get the original collision bounding rectangle 2) Transform the texture (pos/rot/scale) 3) Factor changes of item into a matrix and then use this matrix to change the original collision bounds of the item.
However, my textures contain a lot of transparency, transparency that affect the overall height/width of the texture (I do this to maintain power of two dimensions).
My problem: How to create a rectangle that forms dimensions which ignore transparency around the object. A picture is provided below:
I guess you could step through each row of pixels in the bounding rectangle, starting from the top, checking when you first hit a pixel with colour by checking its alpha value (Color.A != 0).
That way you'll get Y coordinate of the rectangle.
Then step through each column starting from the left of the bounding rectangle, looking for the first coloured pixel.
You'll get the X this way.
Then step through each row again but starting from the bottom and you'll get the height.
Then step through each column again but starting from the right and you'll get the width.
Hope that helps
I think dois answer is the way to do it. I use the following code to find the pixel value at a specific point inside my texture. You can change this code to get line by line the pixels, check for transparency and stop when you find a line with a pixel which is not transparent.
Color[] colorData = new Color[1];
Texture2D texture = //Get your Texture2D here
texture.GetData<Color>(0, new Rectangle(targetPoint.X, targetPoint.Y, 1, 1), colorData, 0, 1);
To check if pixel is not transparent I do this :
if(colorData[0].A > 0)
I don't know how expensive can this operation be for collision detection though.
I know for my games, I use circles. If your objects are reasonably round, it can often provide a closer estimate AND collision detection is dead easy. If the distance between the centres of the objects is less than the sum of the radii, then they are colliding.
If circles are out of the question, then muku or Dois have provided decent answers.

Categories

Resources