Unity 3D - Hide vertices inside chunks - c#

I am making a Minecraft-like terrain, therefor I need to combine thousands of blocks into chunks. The chunks I generate look like this:
This all looks fine. Except for the fact it still has the vertices in the middle of the chunk, like this:
I once saw a Youtube video with explanation on how to hide these vertices, since you can't actually see them while playing the game and they will take up a lot of memory when playing the game. Plus, I want to make the chunks bigger, prefered 16*16*64. If I do that right now, I will get an error:
count <= std::numeric_limits<UInt16>::max()
UnityEngine.Mesh:CombineMeshes(CombineInstance[])
However, I can't seem to find the video I talked about anymore, which is why I am here.
How can I update the chunk so it only shows the vertices which are actually visible?

Related

How to apply pixel perfect collision to rotated sprites?

I'm having difficulty of knowing how to approach or how to tackle this problem. I've looked at some tutorials but they are meant for programmers that already know what they're doing. I followed a video on how to perform a form of pixel collision that applies to regular bounding boxes, where if the bounding boxes collide it checks if any non-transparent pixel in both intersecting boxes are overlapping. If they do, then a boolean will return a true value. Where and how could I start to implement the changing of the bounding box's axis in a rotating object to compliment the texture's appreance? I wouldn't prefer being pointed to an external tutorial because most of the ones I've read assumes the programmer knows everything the writer is talking about.
I've also looked at some source code that perfectly demonstrates what I'm looking for, but it seems I need a very in depth explanation to make any use of reading code as well.
First off, I don't really recommend doing this, as it's gonna be either computing- or resource-intensive (or both).
That said, one idea is to still do your aforementioned AABB method of straight-up pixel on pixel. This requires you to maintain your own pixel data in memory to only be used for collision, as opposed to relying strictly on the texture's data.
To be more specific, using this method you will have to generate what is essentially an "image", or 2 dimensional matrix of some kind, one that represents/follows your rotated image's pixels. But you will not be storing color information in it, as you would with a normal image. Instead, each "pixel" or entry in the structure shall be collision data: "block" or "not block". You could easily use a bitmask to represent this, with 1 meaning "block" and 0 meaning "not block", and you'd need one bit per pixel. (NOTE: Usually you don't need more than just a boolean "on" & "off" for this, but it's possible you may want different types of collision per pixel; if so, bitmasks won't work, instead encode whatever you need per pixel, regardless the overall idea remains the same)
Generating a bitmask (or other such structure) for your sprite will enable you to just use the AABB method; all you'd have to do is use the generated bitmask instead of the texture data directly, and everything else is the same as before. But how do we generate this? That's the true difficulty of this method, because you generating your own image is basically replicating the work of your graphics card when you tell it to do rotations.
You would essentially "draw" out the rotated image yourself. This could be done by stepping through your base texture image data pixel by pixel, and applying a rotational transformation matrix to each pixel to get it to the correct destination in your bitmask/buffer. Once you have the correct destination, you then would test the image data for "block" or "not block" (using transparency as you mentioned) and write a 1 or 0 there accordingly.
While you're generating, you should also keep track of local minima and maxima; that is, how far left, right, up, and down your rotated image goes, just to give it an actual true AABB to live inside for quick checks (i.e. "Do I even need to check per-pixel collision?")
To be fully accurate, you will probably need to know which interpolation/rounding algorithm you're using (bilinear, nearest neighbor, etc.), which can get ugly. Graphics systems often do very complicated things, so taking ALL of this into account just for collision is pretty extreme. At the end of the day, even applying this method, it may not truly be "pixel perfect" as far as "perfectly synchronized with the rendered image output", unless you really go far in replicating exactly what XNA / DirectX is doing.
Finally, when does this generation occur? The answer is every time anything rotates! Otherwise you'll be checking stale data. Obviously you could just keep one buffer per sprite and just keep changing that, to not hog so much memory. But this does mean potentially once per frame if you're rotating consistently. Which means multiple times per frame if multiple sprites are all rotating a lot. Might not be the most computationally friendly.

Finding a Path through a Multidimensional Array

I started work on a dungeon crawler in C# and I've already coded the level generation.
However, I've run into a problem. My level map is stored in a 32x32 multidimensional array, and each tile is stored as a string. All the tiles except for the following (all of these names are the variable names that represent that tile) (mongroveplant, tree, hjalaplant, vnosplant, barraplant, weedplant, naroplant, deathweedplant, venustrap, strangulator, statue, emptiness and stonewall) cannot be walked over.
These tiles (which can be walked over), which constitute a much longer list, are found here: Walkable Tiles. In each entry in the 32x32 multidimensional array, every entry is a string.
How do I create a pathfinding algorithm that avoids all the tiles listed above, but can go through all the tiles listed in the link? I am trying to go from the "start" tile to the "exitlevel" tile.
The first thing I would remove is the notion of string. Parsing string isn't quick in term of a video game. What you want, is to have flags for each tiles (bitfields). In the end, you will love flags because you can combine them!
[Flags]
public enum TileDescription
{
Walkable,
Trap,
Altar,
Door
}
They can also be stored at a int, which take far less space. Speed and space, two amazing notions.
As for the path-finding algo, there's plenty of them out-there. But basically, you have a start point, a end point, and you must find the quickest way between both. The idea is to check the nearest "nodes" and see if you get closer or not of your goal. Each time, you repeat the check with the new node. If you get trapped, you rewind to the nodes that still had available paths.
You have some nice basic algo :
http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm
http://en.wikipedia.org/wiki/A*_search_algorithm
However, long range pathfinding is ALWAYS extremely costly. You will have to limit the pathfinding to a specific range around the origin. Parsing a whole 32x32 maze could take a lot of time to find the quickest route. In most case, when you are beyond a specific range, you move your NPC up to the closest point, then repeat the pathfinding when it reaches it, or while reaching it. The trick to pathfinding is to do it over many frames and never to try to process it all at once.

XNA clears textures mid-render?

We're prerendering large sets of textures to RenderTexture2D and this is the issue we're having:
It seems that randomly during the render of a chunk, the textures for each cell (the top and sides) will corrupt and disappear. The weird things is that they come back when the next chunk is rendered though, so it seems to be something that is occurring on a per-frame basis.
Does anyone know why this occurs (and randomly it seems; note the white rectangle is where a side texture corrupts and you can see from there on out the texture contains just transparent)?
EDIT: The sides of the cubes are being saved to Texture2D but they are still disappearing in the middle of a chunk render and then coming back on the next one. So I don't understand why graphics that are in Texture2D are disappearing and coming back, without reinitialization (and that's the weird part).
RenderTexture2D is only a temporary memory construct, and gets flushed quite quickly and regularly. It is because it is reused in an effort to save memory and to a lesser extent to speed things up. As such you should only treat it as a very temporary place to store your texture. You will want to shift it to a proper Texture2D which will be stored for longer. As just doing a simple:
Texture2D YourPic = (RenderTexture2D)SomeRenderedPic;
Will not do it. This just passes the pointer to the memory space of the rendered image. When the graphics card discards it, then it will still just vanish. What you want to do is something more like:
Color[] MyColorArray = new Color[SomeRenderedPic.Width * SomeRenderedPic.Height];
SomeRendeerPic.GetData<Color>(MyColorArray);
Texture2D YourPic = new Texture2D(
GraphicsDevice,
SomeRenderedPic.Width,
SomeRenderedPic.Height);
YourPic.SetData<Color>(MyColorArray);
Now if I have whipped up that code right then it should store the data and not the pointer into the new texture. This makes the new texture its own unique memory space that won't get flushed the same way a Render Target space would.
There is a down side to this method. It cannot be done at the full refresh rate of XNA. (Something like 60 frames a second... I think... maybe 30... I forget.) At any rate, this may not be fast enough if you need a very constant refreshing. However if you are creating a static texture that doesn't really change much if ever, then this may do the trick for you.
Hopefully this made sense as I am writing this on the fly and late at night. If this doesn't work I apologize. Feel free to write me at jareth_gk#hotmail.com if need be. If I am able to answer your questions I will be happy to.
Otherwise good luck, and be inventive. I am sure there is a solution.
x Jeremy M.
I can't say that we ever solved this issue for sure, but it appears to have been something caused by either threading or splitting the task across multiple cycles. It wasn't an issue with the RenderTarget2D since we were already doing that at the time.

A* pathfinder obstacle collision problem

I am working on a project with a robot that has to find its way to an object and avoid some obstacles when going to that object it has to pick up.
The problem lies in that the robot and the object the robot needs to pick up are both one pixel wide in the pathfinder. In reality they are a lot bigger. Often the A* pathfinder chooses to place the route along the edges of the obstacles, sometimes making it collide with them, which we do not wish to have to do.
I have tried to add some more non-walkable fields to the obstacles, but it does not always work out very well. It still collides with the obstacles, also adding too many points where it is not allowed to walk, results in that there is no path it can run on.
Do you have any suggestions on what to do about this problem?
Edit:
So I did as Justin L suggested by adding a lot of cost around the obstacles which results in the folling:
Grid with no path http://sogaard.us/uploades/1_grid_no_path.png
Here you can see the cost around the obstacles, initially the middle two obstacles should look just like the ones in the corners, but after running our pathfinder it seems like the costs are overridden:
Grid with path http://sogaard.us/uploades/1_map_grid.png
Picture that shows things found on the picture http://sogaard.us/uploades/2_complete_map.png
Picture above shows what things are found on the picture.
Path found http://sogaard.us/uploades/3_path.png
This is the path found which as our problem also was before is hugging the obstacle.
The grid from before with the path on http://sogaard.us/uploades/4_mg_path.png
And another picture with the cost map with the path on.
So what I find strange is why the A* pathfinder is overriding these field costs, which are VERY high.
Would it be when it evaluates the nodes inside the open list with the current field to see whether the current fields path is shorter than the one inside the open list?
And here is the code I am using for the pathfinder:
Pathfinder.cs: http://pastebin.org/343774
Field.cs and Grid.cs: http://pastebin.org/343775
Have you considered adding a gradient cost to pixels near objects?
Perhaps one as simple as a linear gradient:
C = -mx + b
Where x is the distance to the nearest object, b is the cost right outside the boundary, and m is the rate at which the cost dies off. Of course, if C is negative, it should be set to 0.
Perhaps a simple hyperbolic decay
C = b/x
where b is the desired cost right outside the boundary, again. Have a cut-off to 0 once it reaches a certain low point.
Alternatively, you could use exponential decay
C = k e^(-hx)
Where k is a scaling constant, and h is the rate of decay. Again, having a cut-off is smart.
Second suggestion
I've never applied A* to a pixel-mapped map; nearly always, tiles.
You could try massively decreasing the "resolution" of your tiles? Maybe one tile per ten-by-ten or twenty-by-twenty set of pixels; the tile's cost being the highest cost of a pixel in the tile.
Also, you could try de-valuing the shortest-distance heuristic you are using for A*.
You might try to enlarge the obstacles taking size of the robot into account. You could round the corners of the obstacles to address the blocking problem. Then the gaps that are filled are too small for the robot to squeeze through anyway.
I've done one such physical robot. My solution was to move one step backward whenever there is a left and right turn to do.
The red line is as I understand your problem. The Black line is what I did to resolve the issue. The robot can move straight backward for a step then turn right.

Representing a Gameworld that is Irregularly shaped

I am working on a project where the game world is irregularly shaped (Think of the shape of a lake). this shape has a grid with coordinates placed over it. The game world is only on the inside of the shape. (Once again, think Lake)
How can I efficiently represent the game world? I know that many worlds are basically square, and work well in a 2 or 3 dimension array. I feel like if I use an array that is square, then I am basically wasting space, and increasing the amount of time that I need to iterate through the array. However, I am not sure how a jagged array would work here either.
Example shape of gameworld
X
XX
XX X XX
XXX XXX
XXXXXXX
XXXXXXXX
XXXXX XX
XX X
X
Edit:
The game world will most likely need each valid location stepped through. So I would a method that makes it easy to do so.
There's computational overhead and complexity associated with sparse representations, so unless the bounding area is much larger than your actual world, it's probably most efficient to simply accept the 'wasted' space. You're essentially trading off additional memory usage for faster access to world contents. More importantly, the 'wasted-space' implementation is easier to understand and maintain, which is always preferable until the point where a more complex implementation is required. If you don't have good evidence that it's required, then it's much better to keep it simple.
You could use a quadtree to minimize the amount of wasted space in your representation. Quad trees are good for partitioning 2-dimensional space with varying granularity - in your case, the finest granularity is a game square. If you had a whole 20x20 area without any game squares, the quad tree representation would allow you to use only one node to represent that whole area, instead of 400 as in the array representation.
Use whatever structure you've come up with---you can always change it later. If you're comfortable with using an array, use it. Stop worrying about the data structure you're going to use and start coding.
As you code, build abstractions away from this underlying array, like wrapping it in a semantic model; then, if you realize (through profiling) that it's waste of space or slow for the operations you need, you can swap it out without causing problems. Don't try to optimize until you know what you need.
Use a data structure like a list or map, and only insert the valid game world coordinates. That way the only thing you are saving are valid locations, and you don't waste memory saving the non-game world locations since you can deduce those from lack of presence in your data structure.
The easiest thing is to just use the array, and just mark the non-gamespace positions with some special marker. A jagged array might work too, but I don't use those much.
You could present the world as an (undirected) graph of land (or water) patches. Each patch then has a regular form and the world is the combination of these patches. Every patch is a node in the graph and has has graph edges to all its neighbours.
That is probably also the most natural representation of any general world (but it might not be the most efficient one). From an efficiency point of view, it will probably beat an array or list for a highly irregular map but not for one that fits well into a rectangle (or other regular shape) with few deviations.
An example of a highly irregular map:
x
x x
x x x
x x
x xxx
x
x
x
x
There’s virtually no way this can be efficiently fitted (both in space ratio and access time) into a regular shape. The following, on the other hand, fits very well into a regular shape by applying basic geometric transformations (it’s a parallelogram with small bits missing):
xxxxxx x
xxxxxxxxx
xxxxxxxxx
xx xxxx
One other option that could allow you to still access game world locations in O(1) time and not waste too much space would be a hashtable, where the keys would be the coordinates.
Another way would be to store an edge list - a line vector along each straight edge. Easy to check for inclusion this way and a quad tree or even a simple location hash on each vertice can speed lookup of info. We did this with a height component per edge to model the walls of a baseball stadium and it worked beautifully.
There is a big issue that nobody here addressed: the huge difference between storing it on disk and storing it in memory.
Assuming you are talking about a game world as you said, this means it's going to be very large. You're not going to store the whole thing in memory in once, but instead you will store the immediate vicinity in memory and update it as the player walks around.
This vicinity area should be as simple, easy and quick to access as possible. It should definitely be an array (or a set of arrays which are swapped out as the player moves). It will be referenced often and by many subsystems of your game engine: graphics and physics will handle loading the models, drawing them, keeping the player on top of the terrain, collisions, etc.; sound will need to know what ground type the player is currently standing on, to play the appropriate footstep sound; and so on. Rather than broadcast and duplicate this data among all the subsystems, if you just keep it in global arrays they can access it at will and at 100% speed and efficiency. This can really simplify things (but be aware of the consequences of global variables!).
However, on disk you definitely want to compress it. Some of the given answers provide good suggestions; you can serialize a data structure such as a hash table, or a list of only filled-in locations. You could certainly store an octree as well. In any case, you don't want to store blank locations on disk; according to your statistic, that would mean 66% of the space is wasted. Sure there is a time to forget about optimization and make it Just Work, but you don't want to distribute a 66%-empty file to end users. Also keep in mind that disks are not perfect random-access machines (except for SSDs); mechanical hard drives should still be around another several years at least, and they work best sequentially. See if you can organize your data structure so that the read operations are sequential, as you stream more vicinity terrain while the player moves, and you'll probably find it to be a noticeable difference. Don't take my word for it though, I haven't actually tested this sort of thing, it just makes sense right?

Categories