# Question
Title: ConsumeStructuredBuffer, what am I doing wrong?
I'm trying to implement the 3rd exercise in chapter 12 of Introduction to 3D Game Programming with DirectX 11, that is:

* Implement a Compute Shader to calculate the length of 64 vectors.

Previous exercises ask you to do the same with typed buffers and regular structured buffers and I had no problems with them.

For what I've read, \[Consume|Append\]StructuredBuffers are bound to the pipeline using UnorderedAccessViews (as long as they use the D3D11\_BUFFER\_UAV\_FLAG\_APPEND, and the buffers have both D3D11\_BIND\_SHADER\_RESOURCE and D3D11\_BIND\_UNORDERED\_ACCESS bind flags).

Problem is: my AppendStructuredBuffer works, since I can append data to it and retrieve it from the application to write to a results file, but the ConsumeStructuredBuffer always returns zeroed data. Data is in the buffer, since if I change the UAV to a ShaderResourceView and to a StructuredBuffer in the HLSL side it works.

I don't know what I am missing:

* Should I initialize the ConsumeStructuredBuffer on the GPU, or can I do it when I create the buffer (as I amb currently doing)?.
* Is it OK to bind the buffer with a UAV as described above? Do I need to bind it as a ShaderResourceView somehow?
* Maybe I am missing some step?

This is the declaration of buffers in the Compute Shader:

```
struct Data
{
    float3 v;
};

struct Result
{
    float l;
};

ConsumeStructuredBuffer<Data> gInput;
AppendStructuredBuffer<Result> gOutput;

```

And here the creation of the buffer and UAV for input data:

```
D3D11_BUFFER_DESC inputDesc;
inputDesc.Usage = D3D11_USAGE_DEFAULT;
inputDesc.ByteWidth = sizeof(Data) * mNumElements;
inputDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_UNORDERED_ACCESS;
inputDesc.CPUAccessFlags = 0;
inputDesc.StructureByteStride = sizeof(Data);
inputDesc.MiscFlags = D3D11_RESOURCE_MISC_BUFFER_STRUCTURED;

D3D11_SUBRESOURCE_DATA vinitData;
vinitData.pSysMem = &data[0];

HR(md3dDevice->CreateBuffer(&inputDesc, &vinitData, &mInputBuffer));

D3D11_UNORDERED_ACCESS_VIEW_DESC uavDesc;
uavDesc.Format = DXGI_FORMAT_UNKNOWN;
uavDesc.ViewDimension = D3D11_UAV_DIMENSION_BUFFER;
uavDesc.Buffer.FirstElement = 0;
uavDesc.Buffer.Flags = D3D11_BUFFER_UAV_FLAG_APPEND;
uavDesc.Buffer.NumElements = mNumElements;

md3dDevice->CreateUnorderedAccessView(mInputBuffer, &uavDesc, &mInputUAV);

```

Initial data is an array of Data structs, which contain a XMFLOAT3 with random data.

I bind the UAV to the shader using the Effects framework:

`ID3DX11EffectUnorderedAccessViewVariable* Input = mFX->GetVariableByName("gInput")->AsUnorderedAccessView();`

`Input->SetUnorderedAccessView(uav); // uav is mInputUAV`

Any ideas?

Thank you.

# Answer
> 4 votes
> I started to think the problem was with the idea of "initializing a ConsumeStructuredBuffer from the CPU".

When you bind your consume buffer UAV, are you setting the count? In OMSetRenderTargetsAndUnorderedAccessViews, there is a parameter to pass the initial count for each UAV. I believe with a consume buffer that's set up on the CPU, you will need to set the initial count here as well as in the uavDesc. (The count in the uavDesc is the *maximum* count, i.e. the number of elements to allocate memory for, while the count in OMSetRenderTargetsAndUnorderedAccessViews is the current *actual* count of elements that have valid data.) Without this, it probably thinks the initial count is zero, leading it to simply return zeros when you try to read from the consume buffer.

> if I created the Shader Resource View (for input to the first shader) with the same D3D11\_BUFFER\_DESC as the original input Unordered Access View there was no loaded data.

Strange; I would expect this to work, although I haven't tried it on my own machine. I wonder if it might work to load the data after creating the buffer, either by using UpdateSubresource() or by doing Map()/Unmap() and copying the data in manually. It's also worth making sure your drivers are up to date, in case this is a driver bug that has been fixed.

# Answer
> 3 votes
Use this:

```
// Bind both, the consume buffer UAV and the append buffer UAV to the CS.
ID3D11UnorderedAccessView* UAVArray[2] = { mInputUAV, mOutputUAV };
UINT initialCounts[2] = { mNumElements, 0 };
md3dImmediateContext->CSSetUnorderedAccessViews( 0, 2, UAVArray, initialCounts );

```

just before applying the tech passes in DoComputeWork() public function.

# Answer
> 2 votes
I started to think the problem was with the idea of "initializing a ConsumeStructuredBuffer from the CPU". Since it "acts" as a stack of elements, it makes sense that the data must be "pushed" into the stack before "poping" it out.

So, this is what I did: I created a new simple shader which takes a StructuredBuffer as an input and an AppendStructuredBuffer as an output. The StructuredBuffer can be initialized from CPU. All the shader had to do was fill the AppendStructuredBuffer with the data from the StructuredBuffer.

Now, the actual calculation: After that, I bound the aforementioned AppendStructuredBuffer to a ConsumeStructuredBuffer, and the original output buffer to a new AppendStructuredBuffer HLSL variable.

And that worked as charm!

Further investigation led me to think that the presence of the D3D11\_BIND\_UNORDERED\_ACCESS bind flag in a D3D11\_BUFFER\_DESC make the CreateBuffer function discard any initial data: if I created the Shader Resource View (for input to the first shader) with the same D3D11\_BUFFER\_DESC as the original input Unordered Access View there was no loaded data. When I removed the D3D11\_BIND\_UNORDERED\_ACCESS bind flag (leaving only D3D11\_BIND\_SHADER\_RESOURCE), the data was loaded successfully.

I couldn't find this "feature" documented anywhere, though. Anybody can confirm it?

---
Tags: directx, shaders, directx11, gpgpu
---


title: How to assign texture to shader?

text:
# Question
Title: How to assign texture to shader?
In OpenGL, most shader uniform variables are easy, a float or a vec3 or whatever is associated with a shader program. But samplers are different, we associate a texture unit to the shader program, and associate a texture with a texture unit.

To change a texture on a shader program, there are two approaches:

1. reassign the texture unit, or
2. use the same texture unit with a new texture.

Codewise:

```
glUseProgram(theProgram);

// way 1 setup
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, texture1);
glActiveTexture(GL_TEXTURE2);
glBindTexture(GL_TEXTURE_2D, texture2);

// way 1 assign before each draw
glUniform1i(uniformLocation, 1);
...draw...
glUniform1i(uniformLocation, 2);
...draw...

```

or

```
// way 2 setup
glUniform1i(uniformLocation, 1);

// way 2 assign before each draw
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE2D, texture1);
...draw...
glBindTexture(GL_TEXTURE2D, texture2);
...draw...

```

I profiled both, and got inconclusive results. On desktop (mac pro), "Way 1" is much slower. On laptop (mac retina), they're about the same.

Both ways work, so neither is "wrong"... so perhaps this question is loose. Best would be to profile every video card, but I cannot.

Is there a recommended approach for managing textures & texture units?

(Or, at the risk of making the question even vaguer, is there some mental model I should have for how textures, texture units, and shader programs interact which makes it obvious why Way 2 might be faster on some platforms?)

# Answer
> 1 votes
You only have a set of 16 possible textures per-shader stage, so way 1 may get out of hand quickly. You have up to 80 possible *unique binding locations* in GL4 (16 * 5 stages = 80) and 48 in GL3 (16 * 3), but you can only use 16 of those in a single shader invocation.

In truth, bindless textures, array textures and texture atlases have all been designed to make this sort of thing more efficient. Instead of breaking up your draw calls to change something as trivial as a single texture, those each allow you a way of working around that. I listed them in order of hardware requirements, by the way - with texture atlases requiring zero special hardware and bindless textures requiring a late model GPU.

---
Tags: opengl, shaders, optimization
---


# Question
Title: Why don't game developers change game stories after launch?
Game developers have shown willing to remove and add game features, change art assets and remake parts of their games in following updates, but why don't they ever change the plot? Some times parts are added to the story, but only as attachments, never revisions.

Why is plot thought as a feature beyond editing, even if it would enhance player experience just as much as any graphical update or gameplay tweak?

P.S.: I would like to ask for a game-narrative/writing/story tag, and they are just as important part of game development as game mechanics.

P.S.²: This is as broad a question as why not to release source code. Therefore I think it is not too broad for answering.

# Answer
> 2 votes
Because stories are subjective and tied to emotion.

<sup>(The rest of this answer contains daaaangerous TV Tropes links.)</sup>

Players can become really attached to arguably awkward story or dialogue. They might feel robbed if the details were retroactively changed, without any hope of re-experiencing them that way, regerdless of whether the changes were generally seen as good or bad. This is especially true of games which hinge on story, like visual novels or dating sims.

If fans were so invested in the story that they felt it needed changes, they probably liked it enough to buy your re-release or sequel anyway (especially if you target them with it), and fill the gap with fix fic. (But don't take it too far.)

Bug-fixes are much easier to justify, as players are unlikely to have become fond of a technical flaw. Although… that happens sometimes too.

---
Tags: game-design
---


title: Material optimization in Unity3d

text:
# Question
Title: Material optimization in Unity3d
In my 2d game I need a road. And here is two ways, how can I make it.

I can make it using **a lot of quads** with size 1\*1, or for each specific area (they all have different length) I can use **big quads** with size 1\*10, 1\*5, etc.

In the **Mipmaps** view both variants doesn't looks good, because:

* in the 1st case it is a lot of poligons
* in the 2nd case texture on the material are stretched (but have only 2 polygons). Although each quad need its own material, because I can't use the same material for quad 1\*10 and quad 1\*20 - they are have different stretched settings.

What is the best way here for optimization?

Settings for second case:

# Answer
Generate your quads in "chunks" then group the chunks in to a "World" parent object. Assign a single material to the parent then pass that down to the children.

The children can then share a single material.

If your doing what I think your doing (making a tile based map for your game) you may want to build a sprite containing all the tile textures then each tile will have uv coords that map to part of the material main texture.

Effectively this results in ...

1. less mesh objects
2. less draw calls
3. more opportunity for the engine to determine if it can save on draw calls with batching on its own

experimenting with chunk sizing may help you determine some interesting answers to how your code performs.
> 2 votes

---
Tags: unity
---


# Question
Title: determining view boundaries based on z position when using a perspective projection
I'm using three.js to make an animation of a box moving around the screen in 3 dimensions.

It is moving pseudo-randomly, according to a noise function. So, I want to place an invisible wall just outside of view, so the box tends to stay in the screen.

I have accomplished this. However, it only works correctly when the box's z coordinate is 0.

I need a function that calculates the boundaries based on the z coordinate of the box. Right now, if z is negative (farther away) the boundary is too small and if z is positive the boundary gets too big.

I am not sure how to go about this. This is how I am creating the camera, I am new to three.js and this part I just copied from a tutorial:

```
var camera = new THREE.PerspectiveCamera(45, window.innerWidth/window.innerHeight, 1, 10000);
camera.position.z=1000;

```

This is the function signature from the docs:

**PerspectiveCamera( fov, aspect, near, far )**

* fov: Camera frustum vertical field of view.
* aspect: Camera frustum aspect ratio.
* near: Camera frustum near plane.
* far: Camera frustum far plane.

I'm not really sure what FOV does but I think it may be the key here.... If FOV allows me to get a relevant angle than I can probably use basic trig to find my offset value.

# Answer
FOV is field of view. Everyone likes to say that there is no camera in OpenGL, but to me that's a silly notion to hold on to even if it might be technically true. When you use the perspectiveCamera function you are essentially creating a camera. So think of the FOV as the type of lens. Is it a wide angle lens or more of a zoom lens?

The FOV is given as an angle. If it's a smaller number things that are farther away will appear larger. If it's a larger number things that are farther away will appear smaller. This is exactly like a real lens. In a way, smaller FOV's sort of *compress* the distance.

The way a lens works is that the visible plane at any farther distance is bigger than the visible plane at a shorter distance. Looking through a lens you can see the width of an entire city in the distance but only the width of a park bench in the foreground. The value you're trying to fix is this: What is the size of the visible X at a given Z. Then the Y height can be calculated using aspect ratio math.

I don't know three.js or even java. But that's not important because this is a pure math problem that you can translate into any programming language. I have a couple of links here.

First is when I tried to work this out originally. A question (and answer) that I wrote here on SE. It's fairly generic to which library you're using. It's mostly just the matrix math: In 3D camera math, calculate what Z depth is pixel unity for a given FOV

Second is a video I did on how to do it in Unity3D. That one shows the code and an example of altering the FOV and seeing an object slide to stay at a specific x/y size. It's using the same type of math. You can find it on my blog here: http://gameweasel.com/pixel-perfect-sprites-in-unity3d/

Last I'll give you the actual formula to do what you're wanting. The size of the frustum at any distance can be easily calculated:

```
frustumHeight = 2.0 * distance * tan(fov * 0.5 * (pi/180));

```

That calculates the total hight of the frustum at any `distance` from the camera. If the center of your screen is `0,0` then the Y bounds of your frustum are (+ and -) 1/2 that amount. So just remove the `2.0 *` part of the formula and then that will be the Y bounds in both the positive and negative directions.

That `distance` value in my formula might just be the z coordinate if your camera is at zero. Where your camera is in 3d space is determined by your View Matrix or your lookAt matrix. If it's not at 0 it's going to be an offset amount from your camera, or the distance from the camera. It's obviously in the bounds between your `near` and `far` values that you used.

Then to get the X bounds you'll take your `aspect` and the height result of the above formula and do:

```
frustumWidth = frustumHeight * aspect;

```

That will give you either the total width if you included the `2.0 *` or the X bounds if you didn't.
> 4 votes

---
Tags: camera, perspective, three.js
---


# Question
Title: Handling (spawning/removing) entities in SFML
I am unsure which method to use to handle my enemies in SFML.

The idea that I am trying to recreate is to spawn enemies every so many seconds. Initially I wanted to do this using a vector such as std::vector SpriteVector; The advantages of this method would be that in theory it is easy to add and remove my enemies from the vector. Using the push\_back and erase method.

However the error with this at the moment is that when I am trying to check whether the sprite or the arrows are hitting an enemy within my vector it will not work.

I know that I could possibly use an array to store the enemies then set their state when hit to false however I am not sure how this will effect spawning my enemies. The functionality of being able to add to a vector is what I think I will need. Otherwise I am sure not sure how to get around the issue of having a certain number of enemies within the array then spawning more over a series of time.

Is this the best way to go about the task I am trying to achieve?

# Answer
I think what you're looking for is an object pool. You can create such a pool with constant time (O(1) complexity) creation and deletion, which is perfect for your case, I believe.

Let's say you have an Entity class:

```
class Entity
{
public:
    Entity* getNext(void) const { return m_state.next; }
    void setNext(Entity* next) { m_state.next = next; }

private:
    // Entity data...

    // Store either entity data or the next one in the pool.
    union{
        // Entity data.
        struct{
            int x, y;
        } position;

        // Next entity pointer used by object pool.
        Entity* next;
    } m_state;
};

```

You'll need a pool class for managing all entities:

```
class EntityPool
{
public:
    explicit EntityPool(void) :
    m_entities(new Entity[MAX_ENTITIES])
    m_firstAvailable(nullptr) {
        // Assign first available entity.
        m_firstAvailable = m_entities[0];

        // Assign each entity's next pointer.
        for (int i = 0; i < MAX_ENTITIES - 1; ++i){
            m_entities[i].setNext(&m_entities[i + 1]);
        }

        // Terminate end of array.
        m_entities[MAX_ENTITIES - 1].setNext(nullptr);
    }

    ~EntityPool(void){
        delete[] m_entities;
    }

    Entity* create(void){
        // Check if pool is full.
        assert(m_firstAvailable != nullptr);

        // Pull out the next available entity.
        Entity* e = m_firstAvailable;
        m_firstAvailable = e->getNext();

        // Init entity if needed...
        // ...

        return e;
    }

    void destroy(Entity* e){
        // Reset entity data...
        // ...

        e->setNext(m_firstAvailable);
        m_firstAvailable = e;
    }

private:
    static const int MAX_ENTITIES = 256;
    Entity m_entities[MAX_ENTITIES];
    Entity* m_firstAvailable;
};

```

So then, creating and destroying entities is simple. To create one, use it, and destroy it would look something like this:

```
Entity* monster = m_entityPool.create();
// Do things with monster...
// ...
// Monster is dead, remove it.
m_entityPool.destroy(monster);

```

You can also add an update() function to the pool to iterate through all the entities. This is a very simple example of a pool, and should be expanded upon in your own implementation.
> 1 votes

---
Tags: c++, collision-detection, procedural-generation, sfml
---


# Question
Title: Creating LOS zones on a 2D grid for chase AI
I have a 2D grid, around 20x20, stored as an array. Each grid cell can contain an opaque object or not. I also already have an algorithm to calculate LOS between any two squares via Bresenham.

I want to implement an AI that chases the player in a step-time game. The current rules I have are (re-evaluated with this priority each step):

* If we can see the player go get them (a step at a time with Dijkstra/A\* pathfinding).
* If we can't see the player go to where we last saw them.
* If we can't see the player and are where we last saw them, give up and head home.

But I want to add a further rule:

* If we can't see the player and are where we last saw them, but there is only one way they could have gone to now be hidden without coming past us, go that way.

This turns out to be really hard to detect. What I have wondered about doing is to assign each grid square one or more zone numbers, such that every square that is in a given zone can see all other squares in that zone; then if there is only one neighbouring zone than the guard has not visited the guard will move into it. However, the zones overlap and a ridiculously large number of them are generated for even simple maps (due to, for example, different parts of a room gradually becoming visible as you walk down a corridor into it) which makes this awkward or difficult, and the generation algorithm seems to be at least O(n^2) or worse. Alternatively the zones could be calculated as a navigation mesh but this seems very difficult to compute from a grid map.

Is there any way to do this without manually putting hints on the map?

# Answer
This task can be surprisingly difficult in general; it is a variant of the Art gallery problem, and just like that problem, it is made dramatically harder with even slight complexities in the geometry.

But if you're willing to accept a flawed, "good enough" solution, here's one: **leave a "vision trail"**, and assess whether there is only one exit that is not next to the "vision trail".

* When you spot the target, start marking all cells that you can see as "visited"
* After you have reached the target's last known position, inspect the boundaries of your LOS
    + If there is one exit which does not lead to "visited" cells, continue on to the unvisited exit, and keep going until this splits into two (or more)
    + If there are more than two exits that do not lead to "visited" cells, stop

Example of continuing condition:

```
                 |   |
                 |   | <--- unvisited exit
                 |...|
                 |...|
                 |...| <--- LOS
-----------------+...|
vvvvvvvvvvvvv......A.| <--- AI
---------------------+
         ^
      visited cells

```

Example of stopping condition:

```
                 |   |
                 |   | <--- unvisited exits (not contiguous)
                 |...|      |
                 |...|      |
                 |...|      v
-----------------+...+------------
vvvvvvvvvvvvv......A......
----------------------------------
         ^
      visited cells

```

The reason why this solution is "good enough" is because it will run into problems with edge cases like this one:

```
---------------------------------
vvvvvvv.........
vvvvvv.........+-+
vvvvv..........+-+
vvvv.......A......
---------------------------------

```

What should the AI do, in the presence of a small obstruction that splits the exit? Stop? Or continue? Remember, technically the target could be hiding *just* behind that obstruction and avoid being seen, and double back on your AI.

Virtually all problems of this kind (LOS, navigation) will be greatly simplified by performing some preprocessing, so that the geometry is simpler. It is then possible to do as you suggest - creating LOS zones - since we can make lots of assumptions with the simplified geometry. It is up to you to decide what kind of processing you can accept.
> 1 votes

# Answer
Eric Lippert presented a tutorial (in C# of course) on calculating Line-of-Sight with Shadowcasting for a square grid.

The first five sessions define various objects used in the algorithm, with the final code

```
private static Func<int, int, T> TranslateOrigin<T>(Func<int, int, T> f, int x, int y)
{
    return (a, b) => f(a + x, b + y);being this:

}

private static Action<int, int> TranslateOrigin(Action<int, int> f, int x, int y)
{
    return (a, b) => f(a + x, b + y);
}

private static Func<int, int, T> TranslateOctant<T>(Func<int, int, T> f, int octant)
{
    switch (octant)
    {
        default: return f;
        case 1: return (x, y) => f(y, x);
        case 2: return (x, y) => f(-y, x);
        case 3: return (x, y) => f(-x, y);
        case 4: return (x, y) => f(-x, -y);
        case 5: return (x, y) => f(-y, -x);
        case 6: return (x, y) => f(y, -x);
        case 7: return (x, y) => f(x, -y);
    }
}

```

and

```
public static void ComputeFieldOfViewWithShadowCasting(
    int x, int y, int radius,
    Func<int, int, bool> isOpaque,
    Action<int, int> setFoV)
{
    Func<int, int, bool> opaque = TranslateOrigin(isOpaque, x, y);
    Action<int, int> fov = TranslateOrigin(setFoV, x, y);

    for (int octant = 0; octant < 8; ++octant)
    {
        ComputeFieldOfViewInOctantZero(
            TranslateOctant(opaque, octant),
            TranslateOctant(fov, octant),
            radius);
    }
}

```

I have adapted this code for a terrain map on a hex-grid in my Hexgrid utilities project: Open Source under MIT Licence.
> -1 votes

---
Tags: 2d, ai, grid, line-of-sight
---


# Question
Title: How to implement this collision detection function?
I would like to know how to implement this collision detection function, but I'm not even sure what it's called.

The input shapes are 2D convex polygons, with an optional "rounding radius": imagine putting a circle on each vertex of the polygon, and filling in the area between them.

I already have a function that uses SAT to tell if they intersect (and return a minimum correction vector), but I also need a function that takes two of these shapes, A and B, and a unit direction vector. It should tell whether A will ever touch B if it moves along the direction, and if so, report how far it could move and the surface normal where they would touch.

So how would that be implemented, or at least how is it called, so I could search for hints?

# Answer
If your 2D convex polygons are defined by an array of 2D Vectors then you are looking for line-line intersection or edge-edge intersection, whichever you prefer.

This stackoverflow page has an advanced and precise algorith: https://stackoverflow.com/questions/2255842/detecting-coincident-subset-of-two-coincident-line-segments/2255848#2255848
> 1 votes

---
Tags: collision-detection, mathematics, collision-resolution
---


# Question
Title: How to use friction to bring object to a stop in a simple 2D platformer?
I'm coding the physics for a little platformer I'm making but I'm not sure how to design a friction calculation that does what I expect. When running along a platform I want the player's character to pick up speed but be prevented from going too fast due to friction counteracting their movement. Then, if they stop running I want them to continue to run for a little bit proportional to their speed (if they're going slow they should stop almost instantly).

```
void Update(V2!float forces, Elapsed time){
    position += (velocity * time.deltaS);
    forces -= 0.5 * velocity^3; //friction???
    velocity += (forces * time.deltaS);
}

```

The *forces* variable contains anything accelerating the object such as gravity, or acceleration from the player hitting a directional key, etc. What keeps happening is that whatever I try to plug in as friction doesn't bring the object its moving to a nice clean stop. It will look like it's stopped but then move a pixel or two after that because its velocity, while very small, doesn't hit zero for several seconds.

I can fix this with a bunch of conditional statements, but if there's a simple solution I'd much rather do that!

# Answer
> 1 votes
Did you try using a different power for the velocity or a combination of powers? Power 3 means that for small speed the friction is almost zero, eg 0.1^3=0.001. Drag from air flow is normally ~v^2 for higher and ~v for low speed so you could use a linear combination a*v^2+b*v. Sliding friction is even independent of speed, so you could add an extra constant which will dominate the friction for low v.

---
Tags: physics, platformer
---


title: Assign each player a unique ID?

text:
# Question
Title: Assign each player a unique ID?
For my game's multiplayer matchmaking and back-end, every player is assigned a unique GlobalID and LocalID. The GlobalID is used for keeping track of all players and the LocalID is for keeping track of players in a specific room. How can I assign to each player a unique ID so that at any one time 2 players don't have the same GlobalIDs or LocalIDs? I think I can manage with assigning each player their own GlobalID and let them keep it after they log off but I definitely need to reuse LocalIDs Note: I'm using C# for my server which handles the IDs.

# Answer
> 1 votes
Okay so I played around with the ID assignments a bit and came up with this:

After every player is assigned and ID, the number gets put in a list called TakenIDs. A for loop checks which number isn't contained in TakenIDs. As soon as a viable number pops up, the for loop is broken and that number is returned then added to TakenIDs. When a player leaves, his ID is taken off the TakenIDs list.

I added in an important optimization. When a player leaves, his ID is stored in a list called CachedIDs. When generating an ID, the generator first checks if there are any IDs in CachedIDs. If there is, then that number is returned and removed from CachedIDs. If there isn't, then proceed with incrementally searching. The list of CachedIDs is self-maintaining and increases to accommodate the player base.

# Answer
> 1 votes
If you're using a server, even if only for matchmaking, just assign them one. You can use a counter as they sign up for accounts. Alternately you could use a random number and check for duplicates. Or use their screen name as a unique id.

You can use a hash of their e-mail address or some other unique data.

Microsoft came up with a system of generating Globally Unique Identifiers, GUIDs. It uses local information plus some statistics to virtually guarantee that each identifier generated will be unique. Theses probably overkill for what you want. But since you're using c# you all ready have the code: https://msdn.microsoft.com/en-us/library/system.guid.newguid(v=vs.110).aspx

# Answer
> 0 votes
You could generate a random ID, compare it to the existing used IDs ingame, and if the generated ID matches one of the existing IDs, you restart the process. You keep doing this until you have a unique id. Here is an example in C#:

```
//Lets assume you're using an array named 'idArray' filled the existing IDs
Random rand = new Random();
int generatedID = -1;
do
{
    generatedID = rand.Next(1, int.MaxValue);
    foreach (int existingID in idArray)
    {
        if(generatedID == existingID)
        {
            generatedID = -1;
            break;
        }
    }
} while (generatedID == -1);

```

If your players have names, you could use the name as the ID (since its multiplayer, I guess you'd prefer not having 2 players with the same name) or you could generate an ID with the name as the seed of the generator to make sure the you have a number generated from a unique source, a bit like how hashing works.

Here is an explaination of what hashing is if you are not familiar with it: http://mathworld.wolfram.com/HashFunction.html

# Answer
> 0 votes
If you're using a byte for Local IDs then create an ID array with 256 slots for each room. When a player enters the room assign their Global ID to the first empty slot in the array and their Local ID can be their position in the array. When they leave just set the array to a reserved Global ID that indicates it's unused. If Global IDs are 128bits a piece the entire array will take up 4kb of space on the server, and I can't think of why you'd need to transmit the whole list of IDs over the network so that's not 4kb of network traffic...

---
Tags: c#, networking, multiplayer, matchmaking
---


# Question
Title: Using Chromosomes to Go from Input to Output in Genetic Algorithms
Lately I've developed an interest in AI and genetic algorithms. Specifically, AI that learns to do something completely on its own. For example, play a video game. I've seen AIs that start out playing the game with no knowledge of what any of the buttons do, the only information they are given is their position, velocity, and the solid tiles and entities near them. Eventually the AI learns to run and jump. Later on, it learns to avoid enemies.

I mostly understand how genetic algorithms work, but there is one thing I really don't get. The chromosome is basically the instructions for the AI, right? **My question is, how do you use the chromosome of the AI to go from the inputs(the AI's position, velocity, nearby tiles/enemies) to the outputs(button presses)?** I think this is called neural networks, but after researching for an hour or so I didn't really understand the concept. Is the answer to my question just a bunch of "if" statements?

```
if(enemyNear)
{
    if(chromosomeContents[0]==1)
        jump();
    else
        keepRunning();
}

```

That seems like it would be redundant, since you would have to manually program in all of the best solutions, right? I'm not sure; I feel like I'm missing something really obvious here. If anyone could explain this to me, that would be fantastic. :D (Sorry if my explanation was confusing. I tried to explain the best I could.)

# Answer
> 2 votes
You wouldn't have to hardcode the best answers. You'd make chromosomes out of genes that indicate what to compare and how to compare them.

Comparison DNAs: \< \> == !=
Modifying DNAs: + - * /
Value DNAs: player.position.x, 9, 3.18, etc
Condition Extension DNAs: && ||

If you make a bunch of genes out of some combination of the above DNAs you can get meaningful behaviour after a number of generations. You could create rules that immediately abort any AI with a gene with a bad mutation that won't compile. You could do a lot of things, but a real bare bones example might look something like:

```
class Gene{
    DNA[] sequence;
    Output action;
    bool Evaluate(){
        //turn sequence into a true/false comparison & return
    }
}
foreach ( gene; chromosome ){
    if( gene.Evaluate ){
        AI.do(gene.action);
    }
}

```

The important factor in your DNA learning is how you select and recombine traits each generation. For example, you don't want to breed the AI that sat in the corner all level with the one that got 1/3 of the way though the level, you want to combine the one that got halfway thought the level with one that got 3/4 of the way though.

---
Tags: ai, evolution
---


title: Continuous translation in Unity

text:
# Question
Title: Continuous translation in Unity
I would like to apply a constant-speed everlasting translation to a game object (e.g a background) in Unity. Without physics.

What is the best way to achieve that?

# Answer
> 1 votes
There is no one "best way" and what is best is subjective.

The method I present is quite simple - just change the position over time. Use `Time.deltaTime` so the motion seems fluid regardless of the length of the frame. You can substitute for Vector3.forward with any other vector with the magnitude of 1 - it decides in what direction does your object move.

I dont have access to Unity right now to test it, but the script would look similar to this:

```
float speed = 1.0f;

public void Update()
{
  Vector3 newPosition = transform.position + (Vector3.forward * speed * Time.deltaTime);
  transform.position = newPosition;
}

```

---
Tags: unity
---


# Question
Title: MonoGame Point filtering movement appears Choppy/Jerky
When you move a sprite that is drawn using point filtering with a decimal number, example : 0.1 pixel or 100 * deltaTime (1.6) the movement appear choppy/jerky because it jumps from pixel to pixel. How would I go about doing to make the movement smooth?

> please don't answer : linear filtering because I get some issues with my map then

# Answer
> 1 votes
Nothing. Pixel is smallest part of image. You cannot divide it more. If you don't want smooth image then humble with it. :|

**BUT!**

Problem also can be in how you calculate draw positions. See first answer on this question. It can helps you. If not please post code of your Draw method.

---
Tags: xna, c#, monogame
---


# Question
Title: Is there a difference in the time taken to load one texture instead of many?
Is there a difference in the loading time of 16 256\*256 textures versus a single 1024\*1024 texture? Specifically for level loading time?

# Answer
*In theory*, loading many textures will be slower. In practice, the actual amount by which it is "slower" is probably negligible.

There are two main bottlenecks:

* Reading the texture file off the disk.
* Sending the texture to the GPU.

Files on disk have some small-but-non-zero overhead in terms of book-keeping information for the filesystem. Thus, 16 files storing otherwise the same data as one may be slightly larger than the single file alone. Further, files are disk are typically actually allocated at some multiple of a disk's sector size, which can exacerbate that difference slightly (given the size of typical textures these days, however, it's not really a concern until you start getting into the hundreds or thousands of texture files).

However, multiple files aren't necessarily located at the same spot on the disk. While less of a concern for SSDs, spinning-disk hard drives (and disc drives) are still commonly in use for games. To read a file off of such a drive, the read head must physically move (or the disk must move underneath it) to the appropriate location, which introduces seek time into the load operation.

Games that ship on disc media (like console games) used to aggressively arrange the physical layout of their files on the media to optimize for seek times. It's still done occasionally. These disk IO overheads are also one of the reasons why many games pack all their "files" into a single monolithic archive: to amortize the cost, in physical storage and OS overhead, of reading a file across the entire file set instead of paying it for every tiny file.

Similarly, you will have some setup and transmission overhead in sending the texture data to the GPU for use. So if you can pack things into a single / fewer textures, it will generally save you those costs (as well as the overhead of the state switch), so it's preferable if it makes sense and does not result in other compromises for performance (there is a point at which shoving everything into a single texture may save you the file IO performance hit, but cost you *more* in some performance hit elsewhere; you'll have to find that balance).

Many of these issues won't be *serious* unless you are dealing with a high volume of files and constantly hitting the disk or the GPU bus to move them about. You can also hide a lot of the problems behind multithreaded design, if you can do something else during the IO that eliminates the IO from the critical path.

But generally, if there is an overhead for some operation that you will perform *N* times, and that overhead can be paid *once* instead of *N* times, it's generally better to do so.
> 2 votes

# Answer
Don't know nothing about your level loading, but generally processing more of smaller objects (textures in your case) is a bit slower than processing just one. But processing a huge one is troublesome too.

Think of it as transporting a pile of stones from A to B. If you carry each gravel piece one by one you will loose a lot of time and effort on walking here and there almost empty-handidly. On the other side, if you decide to transport the whole pile at once you likely to be limited by amount of weight you can lift.

TL;DR. There's an optimal size and count. You need to test that for yourself, considering your target hardware.
> 0 votes

---
Tags: unity, textures, performance, optimization
---


title: Math for 2d movement with max speed?

text:
# Question
Title: Math for 2d movement with max speed?
I need some help with math in a 2d environment. I have a joystick that controls the acceleration vetor for the player figure.

Its suppose to look like the ground is slippery which makes the figure turn slowly and accelerate and decelerate slowly.

Now, I can do this without any problem if I remove the maximum speed, but Im having problem when using a speed cap.

This is my calculation:

```
func move() {
    if acceleration == CGPointZero && currentSpeed != 0 {
        direction *= 0.95
    }
    else {
        if self.currentSpeed > maxSpeed {
            // This is almost working, just a little buggy, please help here with quality mathamatics :)

            let angle = CGPointZero.angleToPoint(direction) // In Radians
            direction = CGPoint(cos(angle), sin(angle)) * maxSpeed
        }
        else {
            direction += acceleration
        }
    }

    self.center += direction
}

```

move() is getting called by a timer running at 32 fps. acceleration is a Vector pointing to the direction the user wants his figure to go. currentSpeed is calculated using Pythagorean theorem. direction is acceleration * speed. maxSpeed is a number. self.center is the centerpoint of the figure.

# Answer
I don't see any real problems with your implementation here, but I suspect your problem is buried in `angleToPoint()`. I couldn't find any mention of it in the `CGPoint` documentation, so I assume it's something you've implemented yourself. Make sure you're using `atan2()` or equivalent, not just `atan()`.

However, it'd be easier not to use any trigonometry at all:

```
if self.currentSpeed > maxSpeed {
    direction *= maxSpeed/direction.magnitude();
}

```

This scales `direction` down to `maxSpeed` while keeping the direction of the vector the same.

---

I'd suggest renaming `direction` to `velocity` \- not only is that what it is called canonically, but also `direction` doesn't just contain the direction of movement, it's also got the magnitude of that movement.
> 2 votes

---
Tags: 2d, movement
---


# Question
Title: Unity 2D - Pixel perfect movement using physics
I'm trying to make a game in the style of many NES games and I'd like object movement to do two things:

1. I want to move an exact number of pixels per update.
2. I want, for lack of a better term, absolute movement. The object should move or not move, I don't want a ramp up or down in speed.

I'm trying to do this with physics because I would like to use Unity's hitbox collision detection. Moving objects using the translation property does not allow for this, at least that is my understanding.

Any help is appreciated and if my thought process is off, I'd like any suggestions or pointers in the right direction, thanks.

Here is my move method that gets called on Update. I expect to movement to be in whole pixels, however, when I test the x and y are always fractional.

```
private void Move()
{
    VerticalMovement = 0;
    HorizontalMovement = 0;

    if (Input.GetKey(KeyCode.W))
        VerticalMovement = 1;

    if (Input.GetKey(KeyCode.S))
        VerticalMovement = -1;

    if (Input.GetKey(KeyCode.A))
        HorizontalMovement = -1;

    if (Input.GetKey(KeyCode.D))
        HorizontalMovement = 1;

    this.GetComponent<Rigidbody2D>().velocity = new Vector2(HorizontalMovement * Speed, VerticalMovement * Speed);
}

```

# Answer
> 2 votes
If you just want to "snap" from pixel to pixel, you would probably have to set the position explicitly, like `rigidbody.position = new Vector2(x, y)`. Manipulating the velocity will always yield fractional numbers.

Using a `Rigidbody2D`, you could probably use MovePosition to achieve something like this as well.

Also, you should put your code inside of `FixedUpdate()` for anything concerning physics interactions.

---
Tags: unity, physics, movement
---


title: How to occlude lights in Unity3D?

text:
# Question
Title: How to occlude lights in Unity3D?
First off, I own Unity Pro.

I've been looking in to occluding lights when they aren't being viewed for a while now to improve performance. The main methods I ran in to were using BecameVisible() and testing the camera frustum.

My main problem was that if the player is viewing an area that would be lit by the light, I still want the light to be on.

Currently I'm using a method which checks to see if the lit area is in the camera frustum, but the problem is sometimes lights are in the frustum without actually being visible by the player (e.g. a wall between them and the player). I've tried raycasting to them but you can never get detailed enough for the actual lit area (the best I could figure was using renderer.bounds.extent and renderer.bounds.center to calculate the maximum lit points from the light).

Does anyone know of an easy way in Unity Pro to occlude lights? Or could you tell me a good way to use that camera fulcrum method I was talking about?

# Answer
> 1 votes
You could write your own script to occlude lights. Something like this attached to the main camera:

```
List<Light> Lights = new List<Light>();
const float OccludeDist = 100;
void Update()
{
    foreach (Light light in Lights)
    {
        if ((transform.position - light.transform.position).sqrMagnitude > OccludeDist * OccludeDist))
        {
            light.enabled = false;
        }
        else{
            light.enabled = true;
        }
    }
}

```

You could also check if the point is within an angle on the Y axis of the camera (the other axes will just give you pain). Be a bit generous with the angle, maybe 2 times the camera's frustrum, so that lights won't turn off when they're lighting areas within the camera's view. If you choose to add this additional optimization (which probably won't be necessary), make sure you use the distance as the broadphase because it's a lot less costly.

---
Tags: unity, performance, lighting, occlusion
---


# Question
Title: What is the difference between framerate independent vs framerate dependent?
What is the difference between framerate independent vs framerate dependent? Can you please give an example.

# Answer
See the answer linked in the comments on your question for a detailed answer. Here is an undetailed answer:

Say a character is moving to the right along the x axis. You move it at 1 pixel per frame. In 60 frames, it will be 60 pixels to the right of where it started. If you are running at 60 FPS, it will arrive at its destination in 1 second. If you are running at 30 frames per second, it will take 2 seconds to reach its destination. This is generally not ideal. (Frame rate dependent)

If you multiply that pixels per frame by the duration of the frame (in milliseconds), it will arrive at its destination in the same amount of time, regardless of frame rate (FPS). (Frame rate independent)
> 3 votes

---
Tags: game-design, game-mechanics, frame-rate
---


# Question
Title: Position problems instantiating lasers at the sides of a space ship
I'm developing a demo of a 3D Space Ship game concept in Unity, just for learning purposes.

I have a cube representing my space ship in the scene, and a laser prefab that is instantiated at the 2 sides of the space ship any time the user presses the spacebar, i use this C# code (placed in the script attached to the space ship, just a cube right now) to calculate the position of the lasers and instantiate them:

```
Vector3 laser1Position =
    this.transform.position + this.transform.forward + this.transform.right;
Vector3 laser2Position =
    this.transform.position + this.transform.forward - this.transform.right;

Instantiate (laser, laser1Position, this.transform.rotation);
Instantiate (laser, laser2Position, this.transform.rotation);

```

At this point, everything worked perfect, and the lasers are instantiated correctly at the sides of the cube, exactly at the middle of the 2 sides.

The problem came yesterday, when i replaced the cube by a real space ship model, a simple design made by my brother in Blender, and attached the same script my cube had, the lasers are instantiated very above from the space ship, producing the effect seen in the next image, the lasers are spawned at the red line i drew just for showing purposes, when i need them to be instantiated at the green line:

Here you can see the space ship model vs the cube, both firing lasers:

We designed the space ship model in blender, in the origin of coordinates, without any other objects or light sources, so my doubts are:

1. Why are the lasers spawned that high if the model is not there? Is really the model bigger than i see in the editor? (The green box is a box collider i added for collisions managing)
2. Should we configure or touch something in the Blender project to stablish the real size or axis of the model when we import it?
3. Is there a better method of calculate where the lasers should be spawned that this one i am using? Imagine that i want to spawn them in the point of the wings, in front of them. Is there any marker or method i could use to easily spot the place where the lasers should be spawned at runtime? Instead of manual calculating it or by test-error.

I don't have the model here right now, if you need it please let me know and i will try to upload it to somewhere later.

Thank you so much for your help!

# Answer
> 0 votes
Verify in Blender that the center of the object is, in fact, at or near the center of the mesh. Just modeling at the origin means nothing. The center of the object will be, as I recall, an orange dot. Since your one-over and one-forward isn't spawning where you think it is, the center of your object isn't where you think it is.

There are better ways to do this, though (the two I'll suggest both boil down to the same thing). B is how I prefer to do it, though there are doubtless many ways:

A) The first is to add a rig (i.e. bones) to the model in blender. One will need to be the root. Add two more at the appropriate points, the wing tips, pointing forward with the model. When the model is imported into Unity those bones will be gameObjects. You can name them (the bones in blender) and find them using any method you care to and simply spawn at their location, with their orientation.

B) Similar but simpler, after you import the model add some empty game objects as children and position them where you want the laser bolts to spawn (correct position and facing). Then make a prefab out of this, and use it. You then find those objects and spawn on their location/orientation (by name, or by tag or any other method you choose).

As a suggestion, you'll probably want the prefab to be an empty game object with the model and laser markers as children. If you add all this under the model you may lose them if you re-import the model file. As long as they are all positioned relatively, there is no reason for anything to be an actual child of the mesh-containing objects.

Both approaches result in the same thing. The second just avoids messing around with bones in Blender, which is trickier than adding a few gameObjects in the Unity editor.

You might also consider creating a 'laser spawner prefab', an empty gameObject with a script to spawn your laser bolt at

```
GameObject.Instantiate (laser, transform.Position,transform.Rotation);

```

Then you'd apply those prefabs to your model-prefab. Then you could reuse these on any other model as well, though you'd need some method of sending fire messages to them.

# Answer
> 0 votes
I followed the answer of DrHeinous and used spawners for the lasers, and now it works just great and i can mark exactly where i want the lasers to be spawned.

These are the steps i followed:

1. Created an empty GameObject and called it laserSpawner, dragged it to my prefabs folder and attached a C# script called "LaserSpawnerBehaviour" with this code:

```
using UnityEngine;
using System.Collections;

public class LaserSpawnerBehaviour : MonoBehaviour {

    //This will referenciate the laser prefab
    public Transform laser;

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {

    }

    //Fires a laser at the Spawner position
    public void fire()
    {
        Instantiate (laser, this.transform.position, this.transform.rotation);
    }
}

```
2. Attach the laser prefab to the script public variable "laser", so it can be instantiated
3. Dragged the laserSpawner prefab i just created as my ship GameObject child, you can place it wherever you want in the designer:
4. Created a public Transform variable in my Ship script called "LaserSpawnerFront", and dragged the LaserSpawnerFront child of my ship to it:
5. In the Update() method of my Ship Script, when the spacebar is pressed and the timing allows it, i get the LaserSpawnerBehaviour Script from the Transform and i call the fire() method:

```
if (Input.GetKey (KeyCode.Space) && Time.time > nextLaserTime)
{
    //Fire lasers using Laser Spawners
    laserSpawnerFront.GetComponent<LaserSpawnerBehaviour>().fire();
}

```

Now the laser is spawned at the exact position i choosed placing the LaserSpawner:

---
Tags: c#, unity, models, blender, design-patterns
---


title: Get actual button by input name

text:
# Question
Title: Get actual button by input name
How would I get the physical button name (A, B, C) by the name set up in the Input Manager (Fire1, Reload, Jump)? For instance, if the player needs to reload his gun, I want to print "PRESS \[RELOAD BUTTON\] TO RELOAD" on screen where \[RELOAD BUTTON\] is whatever he assigned it to. I don't see anything helpful in the Input class, where else can I look?

# Answer
> 3 votes
Sadly, the only way to do it the way you want to is to get or write your own custom input manager. That would also give you the opportunity to assign representative images to each input (ie picture of button for A-button) and get better control over thumbstick deadzones. Unity's input manager is really more suited to defining names for input axes on different devices, rather than translating those inputs into gameplay terms.

However, if the platform you're targeting has a fixed set of input buttons that shouldn't be *too much* of an issue. Although it's not the best practice, you can hard code the axes to the corresponding buttons.

# Answer
> 1 votes
Manipulating the Input Manager in Script gives a solution for editor script:

```
/// <summary>
     /// Gets all the input axis defined in the project's Input manager
     /// (gets it from ProjectSettings/InputManager.asset)
     /// </summary>
     public static List<string> GetInputAxis()
     {
         var allAxis = new List<string>();

         var serializedObject = new SerializedObject(AssetDatabase.LoadAllAssetsAtPath("ProjectSettings/InputManager.asset")[0]);
         var axesProperty = serializedObject.FindProperty("m_Axes");

         axesProperty.Next(true);
         axesProperty.Next(true);
         while (axesProperty.Next(false))
         {
             SerializedProperty axis = axesProperty.Copy();
             axis.Next(true);
             allAxis.Add(axis.stringValue);
         }

         return allAxis;
     }

```

Unfortunately, *this is only safe in the editor*, and not while the game is running.

---
Tags: unity
---


# Question
Title: LibGDX problems when switching screens and disposing: AL lib: (EE) alc_cleanup: 1 device not closed
I have to classes which implements the Screen interface. I'm trying to switch between these screens. I'm able to switch one time, but when trying to switch back, I receive the error: `AL lib: (EE) alc_cleanup: 1 device not closed`

Here is the first screen class: public class GameOverScreen implements Screen { SpriteBatch batch = new SpriteBatch(); Stage stage = new Stage(); Image shipImg; Label gameOverLabel; TextButton mainMenuButton; TextButton exitButton; VerticalGroup group; Battleship battleshipGame; Skin skin; int width, height;

```
    public GameOverScreen(Battleship battleshipGame) {
        this.battleshipGame = battleshipGame;
        width = battleshipGame.width;
        height = battleshipGame.height;
    }

    @Override
    public void show() {
        Gdx.input.setInputProcessor(stage); // So that the stage can receive input-events like button-clicks
        skin = new Skin(Gdx.files.internal("android/assets/uiskin.json"),
                new TextureAtlas(Gdx.files.internal("android/assets/uiskin.atlas")));
        // Set up layout
        group = new VerticalGroup();
        group.setBounds(0, 0, width, height);
        group.space(15);
        group.pad(50);
        group.fill();

        // Create menu elements
        gameOverLabel = new Label("Game over!", skin, "default-font", Color.BLACK);
        // TODO: Show what player won the game
        gameOverLabel.setAlignment(Align.center);
        shipImg = new Image(new Texture("android/assets/battleship.jpg"));
        mainMenuButton = new TextButton("Go to Main Menu", skin);
        exitButton = new TextButton("Exit", skin);

        // Add them to menu group
        group.addActor(gameOverLabel);
        group.addActor(shipImg);
        group.addActor(mainMenuButton);
        group.addActor(exitButton);

        // Add scene to stage
        stage.addActor(group);

        // Create listeners
        mainMenuButton.addListener(new ClickListener() {
            @Override
            public void clicked(InputEvent event,
                                float x,
                                float y) {
                //hide();
                //dispose();
                battleshipGame.setMainMenuScreen();
            }
        });
        exitButton.addListener(new ClickListener() {
            @Override
            public void clicked(InputEvent event,
                                float x,
                                float y) {
                // TODO: EXIT GAME
            }
        });
    }
    @Override
    public void render(float delta) {
        Gdx.gl.glClearColor(1, 1, 1, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        batch.begin();
        stage.draw();
        batch.end();
    }

    @Override
    public void dispose() {
        stage.dispose();
        skin.dispose();
        batch.dispose();
    }

    @Override
    public void resize(int width, int height) {
    }

    @Override
    public void pause() {
    }

    @Override
    public void resume() {
    }

    @Override
    public void hide() {
        dispose();
    }
}

```

And the second:

```
public class MainMenuScreen implements Screen{
    SpriteBatch batch = new SpriteBatch();
    Stage stage = new Stage();
    Image shipImg;
    TextField nickNameField;
    String nickName;
    TextButton playButton;
    TextButton exitButton;
    Label nickNameLabel;
    VerticalGroup group;
    Battleship battleshipGame;
    Skin skin;
    int width, height;

    public MainMenuScreen(Battleship battleshipGame) {
        this.battleshipGame = battleshipGame;
        width = battleshipGame.width;
        height = battleshipGame.height;
    }

    @Override
    public void show() {
        Gdx.input.setInputProcessor(stage); // So that the stage can receive input-events like button-clicks
        skin = new Skin(Gdx.files.internal("android/assets/uiskin.json"),
                new TextureAtlas(Gdx.files.internal("android/assets/uiskin.atlas")));
        // Set up layout
        group = new VerticalGroup();
        group.setBounds(0, 0, width, height);
        group.space(15);
        group.pad(50);
        group.fill();

        // Create menu elements
        shipImg = new Image(new Texture(Gdx.files.internal("android/assets/battleship.jpg")));
        nickNameLabel = new Label("Enter nickname:", skin, "default-font", Color.BLACK);
        nickNameLabel.setAlignment(Align.center);
        nickNameField = new TextField("", skin);
        playButton = new TextButton("Find match", skin);
        exitButton = new TextButton("Exit", skin);

        // Add them to menu group
        group.addActor(shipImg);
        group.addActor(nickNameLabel);
        group.addActor(nickNameField);
        group.addActor(playButton);
        group.addActor(exitButton);

        // Add scene to stage
        stage.addActor(group);

        // Create listeners
        nickNameField.setTextFieldListener(new TextField.TextFieldListener() {
            @Override
            public void keyTyped(TextField textField, char key) {
                nickName = textField.getText();
            }
        });
        playButton.addListener(new ClickListener() {
            @Override
            public void clicked(InputEvent event,
                                float x,
                                float y) {
                // TODO: FIND MATCH
            }
        });
        exitButton.addListener(new ClickListener() {
            @Override
            public void clicked(InputEvent event,
                                float x,
                                float y) {
                // TODO: EXIT GAME
                //Gdx.app.exit();
                // For testing:
                //dispose();
                battleshipGame.setGameOverScreen();
            }
        });

    }

    @Override
    public void render(float delta) {
        Gdx.gl.glClearColor(1, 1, 1, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        batch.begin();
        stage.draw();
        batch.end();
    }

    @Override
    public void dispose() {
        stage.dispose();
        skin.dispose();
        batch.dispose();
    }

    @Override
    public void resize(int width, int height) {
    }

    @Override
    public void pause() {
    }

    @Override
    public void resume() {
    }

    @Override
    public void hide() {
        dispose();
    }
}

```

As you can see, there is a button on each screen which calls setScreen(otherScreen) in the game.

Thanks!

# Answer
Found the problem: Stage and Spritebatch needs to be initialized in the show-method (in both of the above methods).

From this:

```
public class MainMenuScreen implements Screen{
    SpriteBatch batch = new SpriteBatch();
    Stage stage = new Stage();

    public void show() {
        Gdx.input.setInputProcessor(stage);
    }

```

to this:

```
    public class MainMenuScreen implements Screen{
        SpriteBatch batch;
        Stage stage;

        public void show() {
            batch = new SpriteBatch();
            stage  = new Stage();
            Gdx.input.setInputProcessor(stage);
        }

```
> 2 votes

---
Tags: libgdx, gui
---


title: Should I ping for a TCP-based game?

text:
# Question
Title: Should I ping for a TCP-based game?
I have a head-to-head game where two players communicate through a server based on TCP.

I am planning to implement a ping/pong mechanism in order to detect network disconnection situations. For example,

A pings B every 500ms. If A receives no response from B, A shall consider B is disconnected. If A receives no response from the server, A shall consider A is disconnected itself.

Do you think this ping/pong system is needed or other method is recommended?

# Answer
> 1 votes
There is no need to ping if you are using TCP. TCP has built in mechanisms for detecting disconnects, congestion, or easily deriving latency.

To elaborate:

* the **Keep Alive** feature sends small packets during idle times to detect disconnections.
* The TCP header contains sequence numbers and ACK numbers that exactly correspond to each other, so you can measure the difference in time between the two to easily derive **RTT** (round-trip time)

# Answer
> 1 votes
It's not necessary in TCP as, as @congusbongus said, TCP can automatically detect disconnects.

But doing it your self has the extra advantage of being able to know how much lag there is on the server, as well as being able to give advanced warning of the problem while TCP is still trying to reconnect.

All in all, I'd say add pings, they're not difficult to implement and you'll be able to show how much lag players are having.

---
Tags: networking, multiplayer, protocol
---


# Question
Title: Mapping Coplanar Vertices in 3D space on to a 2D Plane
Say I have a **plane** specified by a normal vector and point on the plane.

I want to specify a **2-D co-ordinate system that lies 'across' the plane**, and then use that to find the 2-dimensional distance between any given points on that plane.

I want to do this so that I can specify scaled texture UV co-ordinates on an arbitrary plane. I will use the average centre of all points on the plane (the barycentre?) as `UV: 0,0`, and then I need a way to determine the 2-dimensional UV value for each point, subsequently.

Here's an example of what I'm trying to do:

The points in bright green are supplied as the inputs, those are the values I'm trying to work out. The dark green is the calculated mean-average centre (the image isn't exactly to scale), and should act as `UV: 0,0`.

A friend suggested that I take `(firstPoint - centrePoint).ToUnit()` as my 'x-axis' and then `xAxis.Cross(planeNormal)` as my 'y-axis'. That seems like a good place to start, but I'm unsure how to use these values to get X/Y co-ordinates for each point.

I don't care what the 'plane-local' X/Y axes are as long as they're the same for each vertex on the plane. I can rotate them in-editor later to make the right alignment manually anyway (I don't think there's any good way to programmatically select a 'default').

# Answer
> 1 votes
You're on the right track. The method you describe gives an orthonormal basis for the plane, xAxis & yAxis.

Now for any arbitrary point on (or off) the plane,

```
  offset = point - center
  uv = scale * (dot(offset, xAxis), dot(offset, yAxis))

```

You can also express this operation as a matrix multiplication if you prefer. It's an orthographic projection onto your plane.

---
Tags: mathematics, textures, geometry
---


title: Tile map optimization algorithm

text:
# Question
Title: Tile map optimization algorithm
I've read this artical on tilemap optimization https://www.scirra.com/blog/ashley/3/tech-blog-tilemap-tidbits and wondering what algorithm is used to achieve something like this.

I'm wondering how they convert an array of tiles into simplified rectangles that use the same texture. To optimize rendering

# Answer
From that picture it looks like the method to put tiles into regions like that is to check left as far as you can go for sameness, and then check for sameness below as far as you can go without a mismatch. Regions would be defined by their top left and bottom right tiles. You'd just do that, line by line, and have something in place to indicate certain tiles are already part of a region. That could just be another temporary array the same size as the tile map filled with booleans that you set when you add a tile to a region.

```
for ( int y = 0; y < tilemap.height; ++y){
    for ( int x = 0; x < tilemap.width; ++x){
        if (taken_tiles[x,y]){
            continue;
        } else {
            Region* rc = region_container.add(x, y, tilemap[x,y].tile_type);
            taken_tiles[x,y] = true;
            for ( int x2 = 0; x2 < tilemap.width - x; ++x2){
                if (tilemap[x+x2,y].tile_type == tilemap[x,y].tile_type
                    && !taken_tiles[x + x2,y]){
                    rc->last_tile(x + x2, y);
                } else {
                    for ( int y2 = 0; y2 < tilemap.height - y; ++y){
                        //check then row below the previously added row
                        //from rc->first_tile.x to rc->last_tile.x on the
                        // y + y2 line. If all are same then make each
                        // of them taken and make the y + y2 as rc->last_tile.y
                        // if there's a difference then break
                    }
                    break;
}    }    }    }    }

```
> 2 votes

---
Tags: mathematics, algorithm, tilemap, optimization
---


# Question
Title: How can I optimize per-pixel drawing in SDL?
I've been messing around with C++ the last few days and I'm trying to figure out how to draw the screen pixel by pixel each frame.

It sounded simple enough at first, but then I realized for loops during the games main loop is nothing but a slow mess. How do I safely and with speed show visual effects?

# Answer
> 5 votes
Per-pixel rendering operations are not particularly efficient on modern hardware. In the past, on classic game consoles and older PCs, they could be made usefully efficient because you had direct access to video RAM. On modern machines this is no longer the case.

Consequently, if you want to do per-pixel manipulation efficiently, you are better off constructing your own in-memory buffer of the pixel data (something as simple as a `char *` pointing at a buffer of `4 * width * height` bytes, assuming you want four-component RGBA pixels) and directly manipulating that.

At the conclusion of every frame, you then use a modern, efficient method to render this buffer to the screen. Typically, these days, that would involve updating a GPU texture with your pixel buffer and rendering a fullscreen quad with that texture mapped accordingly.

Further, when actually manipulating the pixels, it's better not to *actually* set each pixel individually, if possible. Most of the time you'll be rendering objects that consist of more than one pixel, and in those cases you should use specialized routines to blit the data. Focus on accessing the memory of the destination buffer (and source buffer, if you are copying a sprite) in a cache-coherent fashion. Copy entire rows of data when possible (for opaque sprites, for example, you can `memcpy` the rows of the sprite).

Another technique commonly used when doing this kind of thing is to use "dirty rectangles," that is, tracking which regions have changed and only re-rendering those (the previous frame bounds of a sprite, the current frame bounds of a sprite, for example -- or their union if they overlap, as they commonly will). This will generally also involve keeping a separate buffer containing all the static background imagery in a scene, so you can then (for each dirty rectangle), blit the appropriate portion of the background into the rectangle, then do the appropriate foreground drawing.

---
Tags: c++, sdl
---


# Question
Title: Can Unity 5 or Unreal Engine 4 do computationally identical physics simulation across platforms?
In order to use certain approaches to multiplayer physics, it requires that the clients calculate exactly the same values for physics simulations. That "exactly" is a very big word here and goes all the way down to the hardware.

Can Unity 5 or Unreal Engine 4 physics engines guarantee numerically exact physics simulations across platforms?

# Answer
No.

And there is *rarely* a need for exact physics replication.

You mention multiplayer in your tags.

Generally, in a multiplayer game, the physics and game logic is performed by *one* instance, which can be the server hosting the game, or one of the client that hosts the game.

Each simulation step, that authority, the *server*, performs logic update and physics update then send the resulting game state to all of the *clients*. The clients draw the scene upon reception of these events.

This way, all of the clients do not need to compute physics, they only draw. This removes a load from the clients, and it allows every one to have the same simulation. Plus it helps against cheating!

Game clients still can simulate physics for:

1. estimating and predicting game behaviour
2. non-game logic behaviour; e.g.: rag doll, objects destruction
> 4 votes

# Answer
**No.** What would be the point of that?

The physics simulation in a game engine is not a *real* simulation in the sense that everything is done with the correct real-world formulas and reproducible. Doing so would require massively more computing power.

Most of the time, you can't even exactly reproduce the same physics simulation in a game twice in a row.

**Edit:** This of course depends on the exact implementation, but I just checked in the unreal engine and this is the result of repeating the same drop of a cube on a sphere (sorry for the bad image quality):

All four screenshots were taken from the same perspective. As you can see, sometimes the cube bounces far away, sometimes it stays close.
> 1 votes

---
Tags: unity, physics, multiplayer, unreal-4
---


title: HLSL Pixel Shader for Depth Only Pass

text:
# Question
Title: HLSL Pixel Shader for Depth Only Pass
I'm using DirectX 11 and shader model 5.

There are many tutorials online for writing engines and shaders for shadow mapping. I have found an issue which seems to have a hard to find answer.

Typical shadow maps can be created by setting null render targets, assigning a depth/stencil, and setting a null pixel shader. What about the case where I want to sample a texture to determine an objects transparency and discard the pixel based on that transparency (i.e. shadow mapping a tree or chainlink fence)? In this case I need a pixel shader which samples a texture and outputs an alpha value to determine whether to write a pixel to the depth stencil. How do I output an alpha value if there are no render targets?

The regular pixel shader for an object might be:

```
struct OutputStruct
{
float4 Diffuse : SV_Target0;
float4 WorldPos : SV_Target1;
float4 Normal : SV_Target2;
}
OutputStruct PS(InputStruct Input)
{
    OutputStruct output = (OutputStruct)0;
    // perform pixel shading operations
    return output;
}

```

This seems to be what I want:

```
struct OutputStruct
{
}
OutputStruct PS(InputStruct Input)
{
    OutputStruct output = (OutputStruct)0;
    // perform pixel shading operations
    return output;
}

```

**Where do I determine whether to write to the depth stencil based on the pixel shader operations? How do I output an alpha (0 or 1 in value)?** Remember that the blend state is defined for each render target slot of which I have none.

# Answer
The proper way of doing this is to implement the alpha test yourself in a pixel shader and `clip (-1)` any pixel that fails. This will discard the pixel and no depth or stencil values will be written to the framebuffer, without having to write anything to a separate color buffer and perform an extra test afterwards.

As discussed in comments, arbitrarily deciding during pixel shader execution to discard a pixel is going to disable some hardware depth buffer optimizations. However, the complexity of your depth-only shader is such that it probably will not affect performance too much. Early Z benefits you most when you can skip complicated pixel shaders (such as those used in lighting) for occluded primitives. This shader basically amounts to a single (probably cached) texture lookup and comparison between **0.0** per-pixel; not complicated at all.
> 2 votes

---
Tags: directx11, hlsl
---


# Question
Title: Maya 2015 Collada mesh transforms not applied
I am trying to load a dae (Collada) model into my 3d engine. The problem is they export the vertices and transforms seperately. So in Maya 2015 it looks like this

In the game engine I have it simply read in vertices, normals, etc. It looks like this...

You can tell it loaded the model without any transformations. I would like it so it applies the transformations to the vertices before it exports them to the file. Does anyone know how to do this in Maya. It defaulted like that in maya on my old computer but not on my new one I just built. So now I can't make 3d geometry and load it in the engine.

NOTE: I am also using Assimp to load my models is there possibly a flag that would do this.

# Answer
I found out that when I switched computers I downloaded a more up to date version of Assimp that required me to use the "aiProcess\_PreTransformVertices" flag whereas some older versions of Assimp do this already.
> 0 votes

---
Tags: c++, directx, graphics, geometry, maya
---


title: Centering camera on player div

text:
# Question
Title: Centering camera on player div
I've been making a **roguelike-style game** in HTML5 **without using canvas (only divs)** with **pure JS** (**fiddle!**). I've been trying to **enlarge the tile size (font size) while keeping the player centered within the camera.** For some reason, when the tile size isn't equal to the map size, the camera will be slightly off.

**Note that the 3D effect is on purpose. Without it, the camera is still off center, and I believe it adds some much needed depth to the scene. :D**

When `tileScale` (line 4 in the fiddle) is `9` (very undesirable; the dots on the player's y axis should be aligned, not at a slight angle):

When `tileScale` is `25` (on point!):

Here's some relevant (trimmed) code:

```
window.onresize = function(){
    game.viewportWidth = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
    game.viewportHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
    game.windowSize = Math.min(game.viewportWidth, game.viewportHeight);
    // Droid Sans Mono has a ratio of 3:4 (width:height), conveniently.
    // This may be problematic. I'm not sure.
    game.tileWidth = game.windowSize*.6 / game.tileScale;
    game.tileHeight = game.windowSize*.8 / game.tileScale;
}

// Update the camera position (needs help?)
this.updateCamera = function(){
    // Get player coordinates (-.5 because we need to get the player tile center)
    // times the tileWidth plus the game window (inner square) size divided by two.
    var left = ((-game.player.x-.5)*game.tileWidth+game.windowSize/2)+"px";
    var top = ((-game.player.y-.5)*game.tileHeight+game.windowSize/2)+"px";
    game.planeContainer.style.left = left;
    game.planeContainer.style.top = top;
}

```

**How can I ensure that the dots in the center of the screen will be always lined up, instead of on a slight angle?** My current evidence suggests that the position of the `game.planeContainer` object isn't being established correctly.

I know this is a super-tough problem, so any help will be greatly appreciated. Thanks in advance!

*(Another fiddle link, in case you skimmed over the first one. :D)*

# Answer
> 1 votes
I found a possible solution. Simply remove the position: absolute; CSS rule on inner-text. This works on all (tileScale)'s that I thought reasonable to test.

Here's the code without that rule http://jsfiddle.net/t38k1j8w/76/

I also found some other styling things and could explain my process but wasn't sure if it was important.

---
Tags: javascript, html5, roguelikes
---


title: Pathfinding across multiple levels

text:
# Question
Title: Pathfinding across multiple levels
For a final school project, I have implemented an A\* algorithm for pathfinding across a tile graph. So far, it has worked far surpassing my expectations. However now I'm in the process of adding a bit more complexity to the level and I am not sure that tile graphs will cut it any longer.

I would like to add multiple floors, but for the sake of simplicity I will just create two floors. At the present moment, I have a 2D array of Nodes that represent the single floor in a level. I don't think this will be scalable any more to anything besides one floor. I am proposing a method to find paths across two floors using multiple clusters containing nodes for different sections of the map where some nodes are flagged as exit nodes that will lead to other clusters. Moreover exit nodes will also be marked for the ones that lead up stairs to a second floor. The heuristic cost of moving from one floor to another will be higher than if an agent was to simply move across the same level.

I'm thinking if an agent is trying to traverse from one path to the next, it first checks to see if the start node and exit node are on the same floor. If so, then the cost is simply the euclidean distance, otherwise it tries to find the path to the exit node on the cluster it's currently on, compute the path to that node, then compute the cost to the next exit node within that same cluster. Repeat ad nauseam.

So as a visual representation of this, this is a terrible representation of a floor plan. The only highlighted nodes are the exit nodes

This is what I could come up with. Is there any other way besides searching through a ton of tiles and clustering? So far on a tile of 100X100 performance seems to be ok and not an issue. I have heard of using nav meshes, but I'm not entirely sure how to implement them in my project. Since this class is an advanced game development class, if we do use nav meshes, we need to create and implement our own and not use Unity's built in navmesh

# Answer
> 4 votes
Add a meta graph that explains the route between floor entrances / exits from floor `x` to floor `y`. The vertices are entrances / exits, the edge length is the path between an entrance `A` and an exit `B` in tiles on floor `z`. Each entrance / exit is connected by such weighted edges to all entrances and exits that are accessible from it through the floor(s) it's on.

Use your existing tile-graph A\* per floor to find a path from an entrance to a desired exit. The path length will serve as the edge weight on the meta graph.

The meta graph will be used to quickly know, which entrances and exits need to be accessed but it's edges and their weights should be computed in advance. It explains through which floors you need to travel to get from floor `x` to floor `b`. The meta graph uses actual vertices and not tiles, in the sense that you need a list of neighbors for each vertex. A floor is not interesting as an object and is only used to connect it's entrances and exits with edges computed by the tile based path on each floor between them.

Remember that if an area on some floor is blocked, that floor should be logically divided to several sub-floors as entrances in one blocked sub-floor, do not allow direct access to other sub-floors.

Once you use the meta graph to figure out which floors or sub-floors you need to travel, you simply use the same tile based path-finding on each floor to get from entrance `x` to exit `y`.

---
Tags: path-finding
---


title: Fast mesh collision 3D (C# XNA)

text:
# Question
Title: Fast mesh collision 3D (C# XNA)
I'm trying to write a simple program where a 3D landscape can be walked about with a basic camera. However, I've found it very difficult to do even simple collisions with my terrain. I'm wondering if anybody has encountered a similar issue before and possibly might know how to solve it a better way?

I've seen a lot of 3D collision questions, but I noticed that a lot of the answers are to approximate the mesh objects with spheres or cubes - however I find this impractical with something as complicated as terrain. I'm using a .fbx model of terrain made with blender, grabbing its entire list of vertices, finding the one closest to the camera, and trying to set the camera Y to the vertex Y + a constant. However, I keep running into a bunch of problems such as:

* finding the closest vertex is difficult because if the model is too big, distances measured between the camera and the vertices will overflow some variable types, but if the model is too small, distances will often be indistinguishable and inaccurate.
* my method is very slow, because the terrain has a lot of detail, so I find myself only checking every 20 vertices or so.
* I end up with very bad collision detection because my method appears to be inexact and malfunctioning.

Here's some of my code, if anybody wants to see what I'm doing... (btw the d\_check array is a list of vertices of the model, and C is my camera.)

```
    private void BasicCameraCollisionTest(int radius, int offset)
    {
        float smallest_d = float.MaxValue;
        float c_d = 0;
        int i_cache = 0;
        for (int i = 0; i < d_check.Length; i+=20 )
        {
            c_d = Vector2.Distance(new Vector2(d_check[i].X, d_check[i].Z), new Vector2(C.position.X, C.position.Y));

            if (c_d < smallest_d)
            {
                smallest_d = c_d;
                i_cache = i;
            }
        }
        C.position = Vector3.Lerp(C.position, new Vector3(C.position.X, d_check[i_cache].Y + radius + offset, C.position.Z), 0.02f);
    }

```

If anybody could point me in the right direction, I'd be very grateful. Thanks!

# Answer
While it is true that approximating geometry with primitives is the general solution in collision detection, in this case that's not entirely true. What most engines do is use a triangle mesh for the terrain and a vertically oriented capsule for the character. To keep the cost of testing down the triangle mesh is partitioned with some kind of spatial structure (KD-Tree, AABB tree) to make collecting the candidate triangles a fast operation. Collision detection between a triangle and a capsule is performed using a distance-from-line-segment to triangle test. Both David Eberly's website (http://www.geometrictools.com/GTEngine/Include/GteDistLine3Triangle3.h) and Christer Ericson's book Realtime Collision Detection outline two approaches.

So to review:

* Create a vertically-oriented capsule to represent the player character
* Calculate the bounding axis aligned bounding box (AABB) of the capsule
* Use the AABB to collect a collection of candidate triangles for the triangle mesh - triangles that overlap the AABB.
* Perform distance linesegment to triangle test and if the distance is less than the radius of the capsule then a collision exists.

I hope that helps.
> 2 votes

---
Tags: xna, c#, collision-detection
---


title: Best way to handle movement input?

text:
# Question
Title: Best way to handle movement input?
I'm currently developing a RPG movement system in c++, and tried to use the State Pattern/State machine for this, but AFAIK I would have to check each movement key in every state.(right?)

Is there a better design for this?, because the states have no restriction, the player can switch to any move state at any time.

can anyone help

# Answer
> 1 votes
How about implementing a stack of states rather than a single state machine? Events and callbacks (updating, input, drawing, etc.) are sent to the topmost state. If they're unhandled, they're passed to the next state, etc.

For example, your character only has the `IdleState` on its stack. This handles movement as well.

So if the player hits a directional key, this adds another state, e.g. `MoveNorthState`. This state will handle the transition/animation and remove itself once done.

Let's assume there's a toggle to make your character take flight. So once you hit the hotkey, the state `FlightState` is added. `FlightState` won't handle movement, so input events related to movement are passed down the stack to `IdleState`, which will once again add a state, e.g. `MoveSouthState`.

If your `FlightState` notices the hotkey for state change to be hit, it will remove itself from the stack and pass control back to the state below (typically `IdleState`).

Of course this has other potential problems, like trying to modify some state in the middle. You'll have to come up with proper states and flags/status fields. Don't create a state for every tiny bit, just because you're able to.

---
Tags: c++, state
---


# Question
Title: Combine skin material to two elements without a visible seam
Software used: 3ds max 2015 and Photoshop CC 2014.

I have two elements of the head, the "FaceHead" and "UpperHead". I used unwrap UVW for both elements and used Photoshop to add a skin color (eye and lips for "FaceHead") and the same skin color for "UpperHead". I created an image for both elements in Photoshop and added the image to the elements using the Material Editor (with Bitmap option). The problem is, that there is a visible seam between the 2 elements, although I used the same color for both. Is there a solution to solve this?

What I tried:

* Used of MaterialByElement
* Used of different color
* Extend to 2 pixel from the border using Photoshop when applying Paint.

# Answer
What you see is most likely the cause of you splitting the mesh in two parts. The normals at the cut are pointing into different directions (because of triangle orientations) and thus you get a visible seam.

Usually you don't split your geometry for UV unwrapping. What you want to do is mark edges as "seams" so that the UV gets cut at these seams.

Here's a tutorial that should explain the necessary steps to mark an edge as a seam.
> 1 votes

---
Tags: models, 3dsmax, materials
---


# Question
Title: How or when to add a copyright notice in published games?
I've seen lot of videogame title screens show a copyright notice together with the company name. I'm about to publish my game and I am looking for possibilities or requirements on how or when to add such a copyright notice (including date or year published). Does it apply to both indie game makers and larger companies?

# Answer
> 5 votes
There is no requirement. Copyright is automatic the moment you produce a creative work. An explicit copyright notice is optional and not required to claim a copyright later. It is just a friendly reminder of who the copyright owner is and that they care about the copyright of their work.

When you want one, you can place it anywhere you like.

When someone violates your copyright, a copyright message can serve as a proof that you are the original author. So you should try to integrate it into your game in a way that removing it requires effort.

---
Tags: legal, copyright
---


# Question
Title: How to texture voxel terrain without triplanar texturing?
How can a voxel terrain (marching cubes) be textured without triplanar mapping ?

The goal being to have more artistic freedom.

I think, I could unwrap the mesh while extracting the isosurface then use projective painting. But I do not know how to handle terrain modifications without breaking the texture. I also guess that virtual texturing could help here.

Links for these matters would be appreciated.

# Answer
> 1 votes
**Faking it**

> "I do not know how to handle terrain modifications without breaking the texture."

This is the crux of the matter, because you'll have lost the original source of information -- the conceptual material volumes painted on by your paintbrush -- as soon as you transfer it onto the 2D texture. So you'll have no volumetric reference from which to reconstruct your 2D texture UVs. This is where 3D textures become far more useful. But you don't need 3D textures *as such*, if you're willing to opt for a simpler painting process... just a 3D dimensional backing array that you'd use as a reference for where you've painted and where you haven't i.e. where certain materials lie beneath the terrain manifold. Unless you plan to use octrees or have a fairly tiny world, you'll probably want to make your "backing" data structure used for retexturing, quite low-resolution (relatively large cells).

Perform the paint operation in 3D space, with resolution equal to that of your quantised / voxelised "backing" 3D array. The paintbrush (also quantised / voxelised) will need to snap to these backing cells as you move it through space, in order for it to paint the backing array accurately. Your paintbrush might be of uniform colour, or every voxel (as opposed to texel) might be a different colour.

When time comes to (re-)construct, project from the each vertex, outward along the appropriate world axes, until you hit the implicit "face" of the backing cell into which this vertex falls. By sampling that point within the plane, you can get the UV for your terrain vertex (may require some averaging if you need to sample on multiple axes). I guess you'll also need to handle transitions somehow, i.e. where one triangle lies in one backing array cell, and the other two lie in (a) different cell(s). As these are rectilinear raycasts, and you will only be doing them in the locale of terrain changes, the cost over time will be negligible (and the majority of your level terrain will undergo this sampling as a pre-process before play begins).

(I'd suggest keeping your subject mesh simple to start with, as it may make things easier to conceptualise.)

**The Real Deal**

Alternatively, make use of 3D textures. You don't talk much about your intended paintbrush, so I cannot tell if you intend to use a 2D texture, 3D texture, or plain / uniform colour, for painting your terrain. Irrespective, this approach will work for all of the above.

# Answer
> 0 votes
Similarly to @ArcaneEngineer, I think the way to go is to store material information (in your case just a texture id) with each voxel. Like in Minecraft, you'd have voxels of different kinds of materials. However, you'll have a much higher resolution since you're smoothing this terrain representation using Marching cubes. When adding voxels to the terrain, you can copy the material of the ground they get appended to and use that in the new voxels as well.

Now, the thing is that you can't unwrap your whole terrain geometry to a 2d texture evenly. However, if you don't plan to blend materials, it is easy to texture your smoothed terrain without stretching artifacts.

First, you have tiling 2d textures for each kind of material. With your marching cubes look-up table, you also store texture coordinates that nicely unwrap that corresponding geometry patch. Then, you have vertex buffers for each bunch of areas in your terrain that share the same material. You can now render those buffers with the same static texture of their material. There is no need to generate a new texture every time.

When you want texture blending, things get more complicated. In that case, I think you need to dynamically generate the texture of your terrain. You can consider procedural texturing for marching cubes for this.

---
Tags: textures, voxels, marching-cubes, triplanar-texturing
---