title: Data flow with PhysX on a dedicated GPU

text:
# Question
Title: Data flow with PhysX on a dedicated GPU
If there are 2 GPUs in a PC, one processing only graphics and the other dedicated to PhysX, what is the flow of the physics-related data?

Let's say we're simulating an explosion and the PhysX calculates exploded elements (position, size, number, whatnot) while graphics GPU renders them. Does CPU send input to PhysX GPU, gets the results and sends (some of) them to graphics GPU? Or is something like this possible: CPU sends input data to PhysX GPU and, after performing calculations, data from PhysX GPU goes straight to graphics GPU (omitting CPU altogether) since they're just used to render stuff anyway and CPU doesn't need to do anything with them?

Edit: Actually, as a bonus question, I'd like to know the same in case of just one GPU (used for both PhysX and graphics). Does the data flow to GPU, gets calculated, returns to CPU and then goes back to GPU for rendering or can it "stay" on GPU?

# Answer
> 2 votes
It is worth noting that the render pipeline and the physics calculations are already logically separated in your application's code.

Render pipelines usually require specific data formats for the information needed to calculate a scene. The pipeline is, on top, highly customizable by using your shaders etc. .

When PhysX calculates its tasks on the gpu it DOES use the local memory but the rendering of the scene is usually logically separated clearly from physics calculations. Those are done asynchronously (with PhysX) and need to be done before starting to render a scene. So the results need to be collected at some point in time by some entity. As physx tasks are performed on both cpu and gpu and the central game logic and phsyx components run on the cpu, that "management task" can only be carried out there. The information needs to go back to the cpu, be repackaged into manageable formats and then sent to the rendering pipeline.

Maybe you can hack a graphics card to access memory that was used by a physx task before and get your data from there, but I don't know anything about that.

# Answer
> 3 votes
Even if you have a dedicated PhysX card, some of the processing is still done on the CPU, as mentioned here.

This means that all data must be sent back to the cpu, and then forwarded on to the GPU. To clarify, the PhysX calculations are not done on the GPU, they are done on the PPU (Physics Processing Unit), which happens to be part of the physical Graphics Card you put in the machine.

You used to be able to buy dedicated PPU cards, however AMD and Intel decided it was better to do these calculations on the CPU, and Nvidia/Ageia decided it would be better on a dedicated card or on the GPU. If you want to read more about the PPU/PhysX Architecture this is a really good read.

# Answer
> 0 votes
> Edit: Actually, as a bonus questions, I'd like to know the same in case of just one GPU (used for both PhysX and graphics). Does the data flow to CPU and back to GPU to can it "stay" on GPU?

Most certainly can the data remain on the GPU persistently. I don't use PhysX, instead calculate physics over HLSL shaders, so i cannot say exactly how PhysX does this. The principle should still be more or less the same. The GPU has "video memory" which is the 2,3,4, whatever GB printed on the card box. This is fast memory for the GPU, hence you can see all this nice grahics.

The big problem, as said in other replies, is the transportation of data from GPU to CPU memory. There are several issues related to this, and the retrieval of results from the GPU should be minimized in all ways, both size and density over time (= do not do anything unnecessary, ever).

If you however perform a calculation on the GPU, that has part persistent arguments and part such that change from frame to frame, you can well upload the persistent part once only. This must be possible with PhysX as well. You can also let one GPU calculation write it's results into video memory as argument for the next calculation. In both cases, it will survive from game frame to frame unless disturbed somehow.

Also to note, a hard reset will destroy whatever was written and stayed in video memory. This should happen if you change the graphics device resolution, for example resize a game that runs in windowed mode.

Timing is hugely important. The graphics pipeline is batched, meaning once you decide to render to screen, the GPU is fully occupied for some time. During that time, you should not attempt to read data from the GPU, instead focus on CPU work. That also means you will have some of the figures handy "late" in the game loop.

# Answer
> 0 votes
As far as I know, the data is transfered back to RAM even when you use one card for both rendering and PhysX.

I never worked with GPU in production environments but as far as I remember back from my university years PhysX utilizes it's own "pipeline" not completely compatable at high level with normal GPU usage.

I can be wrong though.

---
Tags: gpu, physx, cpu, dataflow
---


# Question
Title: Why should I forbid real-money trading in my MMO?
I am soon going to go public with an MMO game, and I am currently in the progress of writing the terms of use I expect players to follow (no swearing, no spamming, no cheating... you get the point).

My game allows players to trade rare items with each other.

I noticed that almost all online games which have trading, usually have a clause in their terms of use which explicitly forbids players to trade ingame items or ingame money for real-world currency.

I was wondering about the reason for this rule. Why should you ban real-money trading in an MMO?

# Answer
> 23 votes
## Gameplay reasons

Many players would like to have online games as a fair competition where the most skilled (or most determined) players are most successful. Other players buying their way to success by using money they acquired outside of the game could be seen as detrimental to their game experience.

## Economical reasons

Many games have an item mall as one or the main source of revenue. Those who don't, likely don't want to rule out the option to start this one day.

An item mall means that the game company itself sells ingame items for real-world money to make the game easier. When other parties do the same, they indirectly compete with the game company for the budget of the players which reduces the revenue of the item mall.

## Legal reasons

As soon as money is involved, the game becomes a serious business.

One problem is that when people paid good money for an item and then you make a game mechanics change which makes the item useless or removes it from the game, they might try to sue for compensation. IANAL, so I don't know how likely it would be that they are successful in court, but your legal department likely has better things to do than dealing with that.

An even more serious problem is that your game could be used for illegal money laundering. Someone could, for example, buy some items from North-American players, sell them to South-American players, and use their money to finance their drug cartel. This could attract the attention of law enforcement and cause all kinds of disturbances ranging from annoying questions, over searches and seizes of your equipment and up to prosecution as an accomplice.

# Answer
> 3 votes
While other answers are thorough in *possible* reasons, it is worth addressing the alternate:

Not *all* games forbid real-world trading.

---

World of Warcraft and Lord of the Rings Online are two examples where the economy has been changed to allow player's to acquire in-game currency with real-world currency. In these cases, the developers enforce using *game time* as the "middle currency". If you want to purchase money, you simply buy a *time card*, and sell the *time* for money.

Some might argue that this is not real-world trading, but the difference is semantic. Ultimately, you can use your real-life money to legitimately obtain in-game currency, and as a result, anything that can be traded for said currency.

---

In contrast, Diablo 3 offers a good example of a situation where real-world trading was *welcomed*; and it did not turn out very well. On release, Diablo 3 featured a real-world auction house that gave players the ability to buy and sell items for real money.

Ultimately, this mechanic was removed from the game; but not at great cost. Since the mechanic was a "day one feature", the in game economy was based on an assumption that real-world trading would always be an option. Economy is a delicate thing - even in video games - for reasons I won't go into, in this answer. As a result, the *entire* in-game economy needed to be re-balanced to accommodate for this large scale change.

This economy change took a lot of resource. In fact, at first, lead developers were quoted as *wanting* to make the change, but inevitably feeling that it was *impossible* due to the required workload. Blizzard ended up losing ***a lot*** of money, spent on a complete overhaul of the in-game economy. IIRC, this actually resulted in *low profit* for Diablo 3; despite breaking records in sales, it all went into fixing the mistakes of building in a real-world marketplace.

This is a good example of "pay heed, weary MMO developer". Not only did the inclusion of the real-world auction house lead to a lot of "free1" work and lost profit, but *content cancellation*; with the now-low profits, the second expansion was inevitably cancelled, with content already created progressively released as free DLC.

---

1 Free, in that the developer paid for it to be done, but pushed it to the game as a free update.

# Answer
> 1 votes
Are players getting items based on skill and chance, but the chance is driving outcome, which is possible to convert to back to real funds? Then it is Gambling. Forbidden in many countries (noticeably USA, except Nevada) or strongly regulated. Regulations bring noticeable cost and makes your target audience 18+ or 21+.

So totally not worthy return of investment.

Some regulation bodies allows skill games (when your skill determines outcome more than 25%, for example poker).

Recent progress in EU legal frameworks put on the radar 'buy-ins' in games as well.

# Answer
> 0 votes
Quite simply, it harms the ingame economy. The RMTs are greed money grabbing bastards with no concern for the hard work and many months of game play to attain items. RMTS bot to collect ingame money then sell it to lazy players who simply BUY rare items that normal player need to work so hard to get. Also, the RMTs bot gathers items 24/7 and sell them for ingame more (to sell). Selling any item like this kills the price down very low, and thus a normal player who gathers for say even 4 hours per day for practically worthless when bots collect 24/7. Its not hard to work out why RMTs are game killers.

# Answer
> -1 votes
I don't think forbidding real world money trading is likely to stay the norm.

The reality is if you are able to trade an item in game there is nothing a MMORPG company can do to stop it. They can maybe take down the more obvious traders where a single account/IP is moving large amounts (or spamming in game) but if its an open market place (ie the ebay or MMORPGs) where anyone can sell and anyone can buy then there is little they can do apart from set up sting operations and try to catch a small percentage of people and that means they are wasting lots of time and resources that could be better spent on improving the game. Maybe they can waste more time trying to come up with a more complex solution.

But if your economy isn't build to resist it and people can bypass it then you economy is going to suffer.

Personally I think the best solution is to either totally stop in-game trading or fully embrace real world money trading and sell it yourself (maybe it would be enough to keep the game free), keep watch on any other markets that popup and undersell them (you are making your own money after all).

Games seem to be heading in these directions. If you look at Planet Side 2, Hawken, Warframe and so on they don't have in-game money, but they do have XP that can also be earned in game or brought with real world money to speed up the process. Those aren't fantasy RPGs though, trying to wean players off GP could take a little finagling (RPGs are often about immersion in a fantasy world, if you make it impossible for characters to buy and sell then it seems very artificial). Perhaps gold still exists but can only be used to purchase 'standard' items but you have supernatural enchantment points that can turn those items into magical ones. That way GP is basically made useless provided you have enough to enchant stuff. Then there is the soul bound items like in WoW.

Other wise maybe "Your character doesn't want to give 10,000 GP to Larry the Dwarf, you don't know him that well. Maybe if you adventure together you will become friends.". You would have a small amount that characters can give to anyone. You could monitor the amount of time characters spend in proximity to each other and the activities (it not just idling). But that still leaves you with botting and complex trading networks (if I can only trade 100GP, I just need to setup 10 proxy accounts to move 1000GP. Or maybe you can only trade after reaching a specific level to prevent dummy accounts. But all that stuff will just waste resources and add odd rules.

# Answer
> -1 votes
Not *all* games forbid RMT.

As stated above there are a few reasons for game publisher to be against it:

* black market can become a competitor to in-game real money shop (smart developers often prevent this scenario by other means)
* publisher/developer may want to implement their own real money \<-\> game currency exchange
* game design permits bot usage and the developing company does not want to improve their software to block bots that come with RMT. They follow the logic: "if you can't hit the trader - hit the customer" (and if you work not in Asia that it's nearly impossible for you to stop the trader)
* the company wants to appeal to customers that believe that "fair" = "money is not involved" (no comment here)

There are plenty of MMOs that a) allow RMT or 2) do not allow it but turn a blind eye to it.

People above said that their could be some legal issues but well... I've heard about only I guess 2 cases when someone was able to sue a company for losing their items 'cause often EULA states that nothing in the game is a *property* of a customer.

---
Tags: mmo, economy, community-management, real-money-transactions
---


# Question
Title: Turn Based AI Algorithm (Small Board, Two Steps)
This is my Game-Board:

-\> The Red Balls are the AI-Controlled Actors.
-\> The Blue Balls are the Player-Controlled Actors.
-\> The Yellow Cells are the locations, from which the Red Balls can attack.
-\> Each Red Ball can do 2 actions: move-move, move-attack, attack-attack.
-\> At no time there can be 2 minions on one cell, but a minion can arrive on a cell another just left.

**Its the AI's turn. Its planning the whole turn for all minions, each of them has the two moves.<br>The objective is to maximize the number of melee attacks, which can performed in a single turn (2 actions) on the player balls.**

Problem I have in my current (brute-force) implementation:

* Sometimes it is advisable for a minion to move, although it is already in a melee position, to make space for another minion, which can then move into melee range aswell.

Example:

In this situation its more effective for the front minion to move once, so another minion can move into melee range as well.

Do you know an effective algorithm for this job? Thank you for your time!

# Answer
Alpha-Beta pruning: https://en.wikipedia.org/wiki/Alpha%E2%80%93beta\_pruning is commonly used for those scenarios. Depends how do you want to your game behave, you can choose another algorithm. Difficulty of the game (as strong the opponent is) is how deep the AI goes in tree or size of stack.
> -1 votes

---
Tags: algorithm, movement, ai, turn-based
---


# Question
Title: Getting world coordinates from mouse position
I am drawing a 2D mesh imported from CAD. The mesh vertex coordinates are in feet from some arbitrary origin and Z is always 0. I am supplying the coordinates to my shader program and using projection matrix, view matrix and model matrix to display everything. I am also using the view matrix and the model matrix to pan and zoom my 2D scene. I am trying to get the coordinates in feet from my mouse cursor coordinates. Should be a straightforward solution. A matrix multiplied by it's inverse will give you an identity matrix but something is very wrong. Here is my code (don't lough at the vb, I took over an old project):

```
Private Sub openGLControl1_MouseMove(sender As Object, e As MouseEventArgs) Handles openGLControl1.MouseMove
    Dim UnprojectMat As mat4 = glm.inverse(scene.projectionMatrix * scene.viewMatrix * scene.modelMatrix)
    Dim wCoordsVec As vec4 = UnprojectMat * New vec4(2 * e.X / openGLControl1.Width - 1, -(2 * e.Y / openGLControl1.Height - 1), 0, 1)
    wCoordsVec = wCoordsVec / wCoordsVec.w
    wCoordsLabel.Text = wCoordsVec.x.ToString + ", " + wCoordsVec.y.ToString
End Sub

```

And this is my vertex shader:

```
#version 150

in vec3 in_Position;

uniform mat4 projectionMatrix;
uniform mat4 viewMatrix;
uniform mat4 modelMatrix;

void main(void) {
    gl_Position = projectionMatrix * viewMatrix * modelMatrix * vec4(in_Position, 1.0);
//pass_Color = in_Color;

```

}

The in\_Position vector is what I'm trying to get. As you see, I normalized the mouse coordinates for the -1, 1 coordinate system. I don't have a viewport. I'm just using the entire gl control window. Please help me pinpoint what I'm doing wrong.

# Answer
> -1 votes
The problem was with the .net port of glm (OpengGl Mathematics) library. I patched up the library and the issue was resolved.

---
Tags: opengl, matrix, coordinates
---


title: Performance drawing in Pygame

text:
# Question
Title: Performance drawing in Pygame
**Relevant background information**

I'm developing a game for a high school computer science performance task in python & pygame. I'm using objects and all the code is working well for me.

The game consists of a top down (bird's eye view) 2D shooter of a player that rotates and shoots at zombies that spawn and make their way to him. Kind of like dead ops arcade from the original black ops.

Though I'm developing the levels using a list string type designer (there's probably a name for the common technique I'm unaware of), than I load it and I have an array of rects. Here is some background code.

```
            x = 0 # Start X at 0
                    y = 0 # Start Y at 0
                    for row in levelData: # run a for loop for all the rows in level data
        for col in row: # run a for loop for all the colums in the row
            if col == "1": # check if the column section is labeled 1
                self.Rects.append(pygame.Rect((x, y),(self.tileWidth, self.tileHeight))) # append a rectangle
            if col == "2": # check if the column section is labeled 2
                self.Rects.append(pygame.Rect((x, y),(self.tileWidth, self.tileHeight))) # append a rectangle
            if col == "3": # check if the column section is labeled 3
                self.zombieSpawners.append(ZombieSpawner(x, y, self.zombieManager, int(self.maxZombies / self.levelDesigns.getSpawnerAmount(self.level)), self.zombieSpawnTimeMin, self.zombieSpawnTimeMax, self.zombieVelMin, self.zombieVelMax, self.zombieHealth)) # Initalize a zombie spawner with given data
            x += 64 # adjust x
        y += 64 # adjust y
        x = 0 # reset row
    self.levelLoaded = True

            def draw(self, canvas, playerRect):
    canvas.blit(self.backgroundImage, (0, 0)) # draw background image
    for rect in range(len(self.Rects)): # for loop to run all rects
        canvas.blit(self.blockImage, (self.Rects[rect].x, self.Rects[rect].y)) # draw a block
    for spawner in range(len(self.zombieSpawners)):
        canvas.blit(self.spawnerImage, (self.zombieSpawners[spawner].getX(), self.zombieSpawners[spawner].getY()))

```

The indenting is all screwed up but you should understand what I'm doing.

**The problem**

The code above works perfectly. The game ran really smooth with just the player and zombies. Though when I run the background image above, it becomes a huge performance decrease, the fps becomes a solid 3-5. Drawing the blocks and the spawners cause some performance issue's as well, not as bad as the background image but still unplayable.

I think the background image does so much performance damage because it's an actual picture and not a little cartoon like the blocks and spawer's.

**What I'm trying to do**

Is there anything I'm doing wrong or something I should do that can get my performance back? Like some sort of spritebatch for pygame or something. I can't figure out anything online other than pygame doesn't have that good of a performance.

# Answer
> 3 votes
**I resolved the issue**

I was facing severe fps drops using my background image and blocks. Though I changed it so when I loaded them into my program, I used .convert() at the end. The .convert() made a great performance different and my fps is back up to 60.

---
Tags: 2d, performance, python, pygame
---


title: Problem Rotating z-axis openGL c++

text:
# Question
Title: Problem Rotating z-axis openGL c++
i am trying to rotate a quad at z-axis but the problem is , it is not rotating but translating towards some other direction rather than rotating at a particular point.I believe my display function is correct, and the problem exist in init() function and is related to modelView or projection matrix, i downt know the purpose of them and what will be the sequence, here is my code

```
#include<GL\freeglut.h>
#include<Windows.h>
#include <math.h>
#include"F:\BSCS VI\cg\cg\SOIL.h"
double moveX = 0.0;
double x = 0, b = 0;
int degree = 0;
void display() {

    glEnable(GL_TEXTURE_2D);

    glClear(GL_COLOR_BUFFER_BIT);

    //////////////quad to be rotated
    glPushMatrix();
    glRotatef(degree, 0.0f, 0.0f, 1.0f);
    glColor3f(0, 0, 0);
    glBegin(GL_QUADS);
    glVertex2d(30, 300);
    glVertex2d(100, 300);
    glVertex2d(100, 320);
    glVertex2d(30, 320);
    glEnd();
    glPopMatrix();
    ////////////////quad to be rotated , end

    degree++;
    glFlush();
}

void init(void) {
    glClearColor(.75, .75, .75, 0.0); /* background color select clearing color */
    //glEnable(GL_TEXTURE_2D);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluOrtho2D(0, 500, 0, 500);

}

void timer(int x){
    glutTimerFunc(100, timer, x);
    glutPostRedisplay();
}

int main(int argc, char * argv[]) {
    glutInit(&argc, argv);
    glutInitWindowPosition(100, 100);   glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
    glutInitWindowSize(800, 500);
    glutCreateWindow("simple");  // default win. 300 x 300
    glutTimerFunc(100, timer, x);
    init();
    glutDisplayFunc(display);  // set callback for display function

    glutMainLoop();
    return 0;
}

```

# Answer
> 2 votes
Actually, your code is working fine. Rotations always rotate around the origin, which based on your projection setup, is currently the lower-left corner of the screen. So the solution? Move the origin. We can do this by rotating first, then moving the rotated object to the desired rotation point, in this case I've chosen the center of the screen. (Remember in OpenGL, operations happen in reverse order from what they are in the code.) This causes the rectangle to rotate around the center in a counter-clockwise fashion, sort of like a (backwards) hand of a clock.

```
void display() {
    glEnable(GL_TEXTURE_2D);

    glClear(GL_COLOR_BUFFER_BIT);

    //////////////quad to be rotated
    glPushMatrix();
    glTranslatef(250.0f, 250.0f, 0.0f); // Point we want to rotate around
    glRotatef(degree, 0.0f, 0.0f, 1.0f);
    glColor3f(0, 0, 0);
    glBegin(GL_QUADS);
    // These coordinates adjusted to be relative to point above
    glVertex2d(-220, 50);
    glVertex2d(-150, 50);
    glVertex2d(-150, 70);
    glVertex2d(-220, 70);
    glEnd();
    glPopMatrix();
    ////////////////quad to be rotated , end

    degree++;
    glFlush();
}

```

In addition, generally I would set the mode to `GL_MODELVIEW` and load the identity at the end of `init()`, but that's up to you. If you would like information on the OpenGL matrix modes, you can see this answer

---
Tags: opengl, c++, glut
---


# Question
Title: Does the size of the image increases the game's size?
I have an image which is about 2mb in size and I want to use it as a background for my app.My question is, will this image add 2mb to the game's size (like for example the game is 20mb and after adding the image it will be 22mb) or will it get reduced when I add it to my app? I am using Unity by the way.

# Answer
This will, of course, add some data to the app. However the actual APK may not increase by exactly the size of that image. It may be compressed with other files to mean that its slightly smaller.

If you're worried about the size of images in your app, you should consider using vector images, images that are made of drawing instructions instead of raw pixel data (yes I know most image formats aren't very close to raw pixel data at all), this can mean thta many images can be much smaller file sizes, this however doesn't work for things like real world photographs, which can be larger file sizes than traditional images. Vector formats also have the advantages of scaling to fit many resolutions without looking terrible.
> 4 votes

---
Tags: unity
---


# Question
Title: Creating and Destroying OpenGl objects dynamically
I was trying to build a game like this

and i want to create and destroy these ships at runtime , I have used GL\_QUADS and used an image to plot over the QUAD, how can I dynamically create multiple Quads,paste (ship) image over them and destroy them when they collide with the canon ball, thanks

here is a chunk of code

```
ship = SOIL_load_OGL_texture(
        "ship2.png",
        SOIL_LOAD_RGBA,
        SOIL_CREATE_NEW_ID,
        SOIL_FLAG_INVERT_Y
        );
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);

    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    glColor3f(1, 1, 1);
    glBindTexture(GL_TEXTURE_2D, ship);
    glBegin(GL_QUADS);
    glTexCoord2d(0, 0);
    glVertex2d(450 - x, 0);
    glTexCoord2d(1, 0);
    glVertex2d(500 - x, 0);
    glTexCoord2d(1, 1);
    glVertex2d(500 - x, 100);
    glTexCoord2d(0, 1);
    glVertex2d(450 - x, 100);
    glEnd();

```

# Answer
> 1 votes
It's difficult to tell what's going on based on your minimal code sample, but:

* Don't reload the texture for each ship. Load it once at startup and reuse it for each ship.
* It looks like you're loading the texture every time you draw the ship. If so, don't do that.
* Since all of your ships look the same, just keep a vector of model transforms (matrices). When you destroy a ship, remove its transform from the vector. Voila, it won't be drawn on the next refresh.

In general, it's best to avoid dynamically creating and destroying objects in your update/render loop whenever possible. Allocation, asset loading and glCreate\* are expensive operations and can significantly affect performance. On a mobile device, it also impacts battery life.

Good luck!

---
Tags: opengl, c++, glut
---


# Question
Title: DirectX shader - how to spread raytracer computation over multiple frames?
I'm playing around making a shadertoy style SDF raytracer in HLSL and to make it run faster on high resolutions (1080p and up) I'd like to spread the computation over multiple frames.

Right now I have a fragment shader that does raytracing for every pixel of a screen sized quad. I've noticed that if I discard (`clip()`) the fragment for every second pixel, I get 0 framerate improvement despite effectively only rendering half the image. But if I lower the render texture resolution to half, I see improvement obviously. Also if I **clip a contiguous half** of the fragment and render the other half, I get a similar performance boost.

This must mean that the gpu thread groups are by default allocated in a tiled fashion on the screen, and that all threads of a group must be done computing before the (other) resources of the thread group can be used again.

Does anyone know of any magic that can force a fragment shader to only allocate resources for say half the pixels of the screen? (but keep the render target size)

---

Alternatively I suppose I could assign my own thread groups in a Compute shader system where I manage all this stuff myself. Is that the only way to do it? And how would I handle the render target then? (know any resources?)

I'm also pretty sure I've seen people make this kind of grainy multi-frame raytracers years ago before compute shaders were a thing.

# Answer
> 2 votes
`clip()` and `discard()` won't get you any performance increase, nor is it intended to. To understand why, consider how the GPU does things.

> This must mean that the gpu thread groups are by default allocated in a tiled fashion on the screen, ...

Correct. Not only is this the "default," it is mandated by the underlying hardware in the fixed-function rasterizer stage.

> ...and that all threads of a group must be done computing before the (other) resources of the thread group can be used again.

Shaders are executed in waves of 64 (AMD) or 32 (NVIDIA) threads. These threads execute in SIMD fashion, meaning that they execute in lock-step.

The wave will execute at the rate of the slowest thread. If some threads `clip()` or return say, halfway through the shader, they will still stall until all threads in the wave have completed. They aren't like CPU threads. (I consider the term "thread" to be something of a misnomer in this case but, hey, it's the world we live in.)

Now, with shader model 6 on the horizon, or with Vulkan right now, you can use wave ballot intrinsics to early-out and get some of that execution time back. However, even with those tools, the wave will still take as long as the the slowest thread. So, turning off every other pixel won't get you anything (as adjacent pixels are typically assigned to the same wave).

> Does anyone know of any magic that can force a fragment shader to only allocate resources for say half the pixels of the screen? (but keep the render target size)

You *may* be able to use a stencil to mask off every other pixel, but this wouldn't give you back 100% of the time you're looking to save as there's overhead for the stencil comparison. Also, that just seems like a kludge.

The best and easiest way to only draw half of the pixels is to render to a 1/4 resolution render target (1/2 on each side), then draw it scaled to match your screen-aligned quad. You can play with your sampler configuration when drawing to your screen-aligned quad to get the "grainy" pixelated image, if that's what you want.

You COULD do this in compute, but you'd be handling rasterization yourself. Then again, that may be a more appropriate place to implement raytracing. I've written raycasting code in both CUDA and HLSL compute, and it works pretty well. If you don't need the rasterizer, compute is a perfectly reasonable way to go.

---
Tags: shaders, directx11, hlsl, raytracing, compute-shader
---


# Question
Title: Collision detection problem in XNA4/Monogame
I have been trying to get 3D collision detection working for a while and I think (hope) you people can help me.

For my project I have created a 'sprite3d' kinda class which is called `ModelEntity` and there there is a function that is called `intersects`.

`intersects` gets another `ModelEntity` as a parameter.

```
 public bool intersects(ModelEntity entity)
    {
        BoundingSphere bs1 = CreateBoundingSphereForModel();
        BoundingSphere bs2 = entity.CreateBoundingSphereForModel();

        bs1.Center += position;
        bs2.Center +=entity.position;

        if (bs1.Intersects(bs2))
            return true;

        return false;
    }

public BoundingSphere CreateBoundingSphereForModel()
    {
        Matrix[] boneTransforms = new Matrix[this.model.Bones.Count];
        this.model.CopyAbsoluteBoneTransformsTo(boneTransforms);

        BoundingSphere boundingSphere = new BoundingSphere();
        BoundingSphere meshSphere;

        for (int i = 0; i < model.Meshes.Count; i++)
        {
            meshSphere = model.Meshes[i].BoundingSphere.Transform(boneTransforms[i]);
            boundingSphere = BoundingSphere.CreateMerged(boundingSphere, meshSphere);
        }
        return boundingSphere.Transform(getWorld());
    }

public Matrix getWorld()
    {
        return  Matrix.CreateTranslation(position) * Matrix.CreateRotationY(rotation.Y) * Matrix.CreateRotationZ(rotation.Z) * Matrix.CreateRotationX(rotation.X) ;
    }

```

Those are the main parts of the collision in the `ModelEntity` class and the place where I check collision is in the `PlayState` class

```
if (model.intersects(player) || player.intersects(model1))
        {
            cam.returnToLastPosition();
        }

```

`cam.returnToLastPosition()` is just returning the camera to the last place it has been so you can't pass through the model.

In the update loop, I set the player's position to the camera position (I have created a first person camera class which takes care of mouse and keyboard movement).

If you want to see the draw function:

```
public void draw(FirstPersonCamera cam)
        {
            Matrix[] transforms = new Matrix[model.Bones.Count];
            model.CopyAbsoluteBoneTransformsTo(transforms);
            foreach (ModelMesh mesh in model.Meshes)
            {
                foreach (BasicEffect effect in mesh.Effects)
                {
                    effect.EnableDefaultLighting();
                    effect.World =  transforms[mesh.ParentBone.Index] * getWorld();
                    effect.View = cam.getView();
                    effect.Projection = cam.projection;

                }
                mesh.Draw();
            }
        }

```

NOTE// in the intersects function I have tried to remove the part of

```
bs1.Center += position;
bs2.Center +=entity.position;

```

but it does not work anyways.

# Answer
> 0 votes
I know, it's a bit late but try

```
boundingSphere.Center += entityPosition;

```

before you return your sphere in `CreateBoundingSphereForModel`

# Answer
> 0 votes
Here's one problem:

```
bs1.Center += position;
bs2.Center +=entity.position;

```

But, you're also doing this in `CreateBoundingSphereForModel()`:

```
return boundingSphere.Transform(getWorld());

```

So, you're transforming the sphere - which moves it into world coordinates. Then, you're offsetting it's position based on the entity's transform. Basically, you're moving the bounding sphere twice as far from the origin as the entity. Get rid of the first block (bs\*.Center += entity.position) and see what happens.

```
public bool intersects(ModelEntity entity)
{
    BoundingSphere bs1 = CreateBoundingSphereForModel();
    BoundingSphere bs2 = entity.CreateBoundingSphereForModel();

    return bs1.Intersects(bs2))
}

```

One other note: Your `getWorld()` is doing things in the wrong order. Your approach moves the object to its world position, then rotates it around the origin. Your sphere would wind up orbiting the origin rather than spinning on its own axis.

In this framework, operations happen in SRT (scale, rotate, translate) order. (In OpenGL it would be the reverse.) So, you should have:

```
public Matrix getWorld()
{
    return  Matrix.CreateRotationY(rotation.Y) * Matrix.CreateRotationZ(rotation.Z) * Matrix.CreateRotationX(rotation.X) * Matrix.CreateTranslation(position);
}

```

Or, better yet, use `CreateFromRollPitchYaw()`:

```
public Matrix getWorld()
{
    return Matrix.CreateFromRollPitchYaw(rotation.Z,rotation.X,rotation.Y) * Matrix.CreateTranslation(position);
}

```

... assuming that you don't want to mess with quaternions which eliminate gimbal lock.

---
Tags: xna, c#, collision-detection, 3d, monogame
---


# Question
Title: Unity - Permanent force when a rigibody without gravity hit a collider
I'm actually working on a 2D game, and stumbled upon something rather strange in Unity. The issue occurs pretty specifically, so the description will be long:

In the scene, I have a flying object, controlled by the player. It has a rigidbody set as follows: Mass=1, Drag=0, Angular Drag=0.05, Gravity=false, Kinematic=false. So far, so good, the script worked flawlessly, and collide as expected in other physical objects.

Our client asked us to create platforms upon which the enemies could walk, but the player would fly through. A simple collider with IgnorePhysics(GameObject with Player tag) did the trick. The script still worked, no issue until then.

I added a cube on the platform, to test if it would fall through or not. The cube effectively collide with the platform, just as usual, and rest upon it.

But now, as soon as the player hit the cube, it get pushed back in the opposite direction until it hit another surface. It happens like when a non-gravity object is pushed by something: a force is applied and continue forever without friction. (But it does not bounce the same way on other objects. I can only suppose it comes from the force inputed to the objects during the collision, but I can't know for sure)

**Example:** if I hit the underside of the cube, my avatar will drift towards the ground until I hit it, no matter its speed in other direction. If I hit the upperside, it'll just fly out of the screen, towards the y-infinite.

The script is a classic gameobject.transform.position = Vector3.MoveTowards, so it input no forces whatsoever. Thus, I can't counter the inverse force.

**The thing bothering me is that the avatar never had this kind of drift before, even though it collided other objects.**

**My question is: How can I negate the new force input from the collision for the avatar?** (optionnaly: why does it occurs only in this case? I'm puzzled by this case)

# Answer
I think you are seeing physics in action. The flying character is not ignoring the collision with the cube -- correct? So when you touch the cube there is an **equal and opposite force** applied to the cube and the player (a law in physics), that is why the character moves down. Without friction or another object to collide into the character the motion in that downward direction will not stop. This is another law: **an object either remains at rest or continues to move at a constant velocity unless acted upon**

Your controller code `gameobject.transform.position = Vector3.MoveTowards` is moving the player directly through the use of the Transform without adding in new forces, but the previously mentioned force changed the `rigidBody` velocity thus the physics engine is still moving it too. To remove the force, do this at some point after the collision `rb.velocity = Vector3.ZERO;`

As a further note, you usually don't want to mix `RigidBody` on a non kinematic object and also have a script or animation that moves the object via the `Transform`. This leads to multiple things competing on how the object moves and you will get weird results.
> 1 votes

---
Tags: unity, unityscript
---


title: Issue with Monogame resizing

text:
# Question
Title: Issue with Monogame resizing
I've converted my XNA project into a MonoGame one.

Whenever I start the application and resize the game manually (ie - dragging the window)...

```
this.Window.AllowUserResizing = true;

```

...the game scales in a weird manner.

Namely instead of scaling as it should do, it scales to the point where it looks fuzzy and the mouse clicks aren't working correctly.

The main game map has a hard coded "component size" which means that when the screen gets larger, its supposed to show more of the game - but instead I'm getting poorly scaled components.

Part of my code looks as follows:

```
const int TILEWIDTH = 50;
const int TILEHEIGHT = 50;
//......
Rectangle rec = new Rectangle(0, 0, TILEWIDTH, TILEHEIGHT);
spriteBatch.Draw(this.game.Content.Load<Texture2D>(tileGraphic.path), rec, Color.White);

```

So theoretically the pixels are becoming larger. This was working correctly in XNA.

I am in no way handling or overriding the resize command, it was 'just working'.

I found some threads with similar problems, but no solution. Anything I could do ?

# Answer
> 1 votes
Fixing the issue was easier than expected

```
public override void Update(GameTime gameTime)
{
graphics.ApplyChanges();
}

```

It doesn't seem to impact framerate in any way (still getting 120)

# Answer
> 6 votes
I found that in order to get window resizing to work properly, you need to handle resetting the Graphics Device parameters manually, when the window is resized:

```
this.Window.AllowUserResizing = true;
this.Window.ClientSizeChanged += new EventHandler<EventArgs>(Window_ClientSizeChanged);

void Window_ClientSizeChanged(object sender, EventArgs e)
{
    graphics.PreferredBackBufferWidth = Window.ClientBounds.Width;
    graphics.PreferredBackBufferHeight = Window.ClientBounds.Height;
    graphics.ApplyChanges();
}

```

So basically, whenever your window is resized, you reset the Graphics Device with the new width/height.

# Answer
> 2 votes
## The answer by jgallant here creates a stack overflow. To fix this I did the following:

```
//add this in your initialisation

this.Window.AllowUserResizing = true;
this.Window.ClientSizeChanged += new EventHandler<EventArgs>(Window_ClientSizeChanged);

```

---

```
private bool WindowSizeIsBeingChanged = false;
void Window_ClientSizeChanged(object sender, EventArgs e)
{
    WindowSizeIsBeingChanged = !WindowSizeIsBeingChanged
    if(WindowSizeIsBeingChanged){
        graphics.PreferredBackBufferWidth = Window.ClientBounds.Width;
        graphics.PreferredBackBufferHeight = Window.ClientBounds.Height;
        graphics.ApplyChanges();
    }
}

```

---

The problem was that graphics.ApplyChanges() calls the ClientSizeChanged to be activated. With this fix, you essentially skip the code from the second call, which makes sure you don't end up with a stack overflow, without having to put any additional calls to graphics.ApplyChanges() in your main game loop.

# Answer
> 0 votes
I found that I needed to cache the resolution I had been on, and compare and if they changed, then do apply changes. This made it happen only once. Putting it in game update gave me lots of artifacts and crazy stuff.

```
void Window_ClientSizeChanged(object sender, EventArgs e)
{
    if (Resolution.currentResolution().X != Window.ClientBounds.Width || Resolution.currentResolution().Y != Window.ClientBounds.Height)
    {
         graphics.PreferredBackBufferWidth = screen.Bounds.Width;
         graphics.PreferredBackBufferHeight = screen.Bounds.Height;
         graphics.ApplyChanges();
    }
}

```

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


# Question
Title: Intersection of two limited planes (stripes)
Have two limited planes. That means just squares or stripe in 3D space (or two connected triangles on the same plane). What I want to know is exactly how (and whether) they collide.

My first approach would be to assume endless planes and calculate the collision line (which is always endless and exists unless the planes are parallel). However the resulting line just changes my problem to: "find the intersection of a line and a limited plane" and again I cannot think of a direct solution...

Anyone having a hint or an approach to a solution?

If it simplifies things, it would be safe to assume the planes to be limited in only one direction as in consisting of the area between two endless, parallel rays.

Huge thanks in advance!

# Answer
> 3 votes
For the case that someone needs this one day... I solved it by computing the intersection line of the two planes (explanation and code here: http://geomalgorithms.com/a05-\_intersect-1.html ) and then compute how this line intersects with the edge-lines of my actually limited planes. The intersection code can provide the value where on the intersection-line it hits the edge (code for that int he upper link as well). So one can use simple comparisons to detect how the two 3d-rectangles are intersecting each other exactly and whether they do at all. Ask please if needing any help :)

---
Tags: 3d, intersection, computational-geometry
---


title: Spriterenderer on top of canvases

text:
# Question
Title: Spriterenderer on top of canvases
I have two canvases. One with a background image and one with all overlaying elements like texts and such.

The background canvas has an order of 0, the overlay canvas of 1.

Now, I'd like to create an animating sprite on top of those canvases but I can't for the life of me get the sprite on top of the other images.

I can see the sprite being on top on the stage, but when I switch to gameview, it's gone! There are no scripts attached to the sprite. Only an animator(Which works fine when I play it).

Note:

* My canvases have a render mode of Screen space - Overlay.
* I've set the spriterenderer on Sorting Layer 9, order 300. Although it's the only sprite out there. layer 1 or order 1 didn't do anything different, though.
* The other elements in the canvases are either UI texts or Images
* All the elements in the canvases are on either BackgroundLayer or OverlayLayer
* The canvases themselves are on the UI layer

# Answer
> 4 votes
I'm sure there's an issue with Unity UI and the sprite renderer. UI elements tend to be drawn above everything else. One work-around is to render the UI and sprite renderer on separate cameras and then apply the depth settings to the cameras. This can negatively effect performance.

Edit: The 'best answer' here should tell you what you need to know.

# Answer
> 0 votes
Check if any of your UI elements has Transform component instead of RectTransform component. That could cause your sprites render in world space, not on UI layer.

---
Tags: unity
---


title: Unity 5.3 with C# - Toggle Sound On/Off

text:
# Question
Title: Unity 5.3 with C# - Toggle Sound On/Off
*I'm working with Unity 5.3 with C# as code editor*

**These are what I have :**

I have 2 scenes in my project : `home` and `options`. I have `bg` object on both scenes. Both `bg` objects have `Audio Source` component, which contains same background music that `play on awake`. I don't use any codes for these background musics, I only click the `Add Component` button from Unity and add `Audio Source`.

**This is what I want :**

`Options` scene can toggle the background music on/off for all scenes. Therefore, there are `btnOn` and `btnOff` in `Options` scene.

**This is my code in Audio Manager.cs :**

```
using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class AudioManager : MonoBehaviour {
    public Button btnOn;
    public Button btnOff;

    // Use this for initialization
    void Start () {
        btnOn = GetComponent<Button>();
        btnOff = GetComponent<Button>();

        btnOn.onClick.AddListener(() => PlayAudio());
        btnOff.onClick.AddListener(() => StopAudio());
    }

    void PlayAudio()
    {
        AudioSource.volume = 0.5f;
    }

    void StopAudio()
    {
        AudioSource.volume = 0f;
    }
}

```

**This is the problem :**

I have this error : `An object reference is required to access non-static member UnityEngine.AudioSource.volume`. Maybe, this is because I don't write `public AudioSource audioSource` in my code. But, if I write this, I have to add another audio in `Get Component` box, and I will have double `Audio Source` in one scene. What should I do? Thanks

# Answer
> 1 votes
The error is telling you that, you're trying to access a non-static variable ***volume*** with the class name ***AudioSource***, which is not possible. To access a non-static member, you neeed an *Instance* of the class.

Therefore, you have to define an Instance of the AudioSource class to access ***volume*** variable, and then assign it an AudioSource component either from Inspector or from code. Like this :

```
using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class AudioManager : MonoBehaviour {
    public Button btnOn;
    public Button btnOff;

    public AudioSource audioSource;

    // Use this for initialization
    void Start () {
        btnOn = GetComponent<Button>();
        btnOff = GetComponent<Button>();

        // Either use this, or assign the component from inspector
        audioSource = GetComponent<AudioSource>();

        btnOn.onClick.AddListener(() => PlayAudio());
        btnOff.onClick.AddListener(() => StopAudio());
    }

    void PlayAudio()
    {
        audioSource.volume = 0.5f;
    }

    void StopAudio()
    {
        audioSource.volume = 0f;
    }
}

```

# Answer
> 0 votes
I think you're confusing `AudioListener` with `AudioSource`. They're different things. There can be many audio sources in the scene but only one audio listener. Try using `AudioListener.volume` to set the volume instead.

You might also want to pause it.

---
Tags: unity, c#, unityscript, sound
---


# Question
Title: Photon Unity Network with Socket IO Ambiguities
When trying to use Socket.IO along with PUN I get multiple errors similar to the one below:

`The call is ambiguous between the following methods or properties: ``WebSocketSharp.Ext.SubArray<byte>(this byte[], int, int)' and ``WebSocketSharp.Ext.SubArray<byte>(this byte[], int, int)'`

I searched a lot and couldn't find any other class with the same name/namespace that could lead to this ambiguity. Please help.

# Answer
After a lot of searching I found this link: https://developer.ibm.com/answers/questions/323592/watson-sdk-photon-networking-unity-conflict.html

As per the above link, I deleted the **websocket-sharp.dll** and all the errors were gone. I checked my project to see if it was working properly and so far it seems to be working fine. Will update if I find any issue. If anybody else has a better solution. It'll be helpful.
> 2 votes

---
Tags: unity, networking, websocket, photon
---


# Question
Title: Preserve top right position and relative size to screen
I have the following circle laid out where I'd like it at 1920x1080: https://i.stack.imgur.com/zxrfE.jpg at 1280x720 it takes the same amount of relative screen space.

When the aspect ratio changes I want the circle to remain a circle and for it to always be top right aligned.

When I set the image to preserve aspect it gets pushed downwards like so: https://i.stack.imgur.com/18deg.png

How can I ensure the image stays top right aligned in all cases?

# Answer
You need to use anchors and pivot to set the position relative to screen space (also, the UI object needs to be a child of the Screen Space Canvas).

In this picture, Main Camera is the camera I'm using for the viewer. Scripter is a UI Canvas with Screen Space as the camera option. The button is relative to that canvas and will always stay relative to it. If the UI is too big for the screen, I suggest using a Canvas Scaler (can be seen in the link at the bottom).

Scripter canvas object's inspector screen.
> 1 votes

---
Tags: unity, 2d, gui
---


# Question
Title: How to make a cylindrical collider for a cylindrical mesh in UE4
When I am importing Axis Alligend cylindrical mesh in UE4 here is what I get as an automatically generated collider:

But if I rotate the mesh in Maya and again exprot FBX to improt in UE4 here is what I get:

As you can see the object is the same but the collider is much worse. How can I make the same callider in spite of the orientation of the cylinderical mesh?

BTW if I remove collider and do auto convex collider:

I get this:

Which is very good but the problem is that I want it to be generate from the beginning and not later when I edit the mesh collider. How can I achieve that?

# Answer
Here is the RuntimeMeshComponent which is free and created by Chris

You can procedurally generate a mesh and add its collider too.
> 0 votes

# Answer
Why dont you simply add a capsule collider provided by unreal instead. It is easy. Just add component on existing mesh. You can rotate your collider to match your axis.
> 0 votes

---
Tags: collision-detection, unreal, unreal-4
---


# Question
Title: Opening an executable process in background from unity
I am trying to make a chess engine run in the background from an interface i designed

```
    Process stockfish;
        stockfish = new Process {
            StartInfo = new ProcessStartInfo {
                FileName = System.IO.Directory.GetCurrentDirectory () + "\\Assets\\Scripts\\Stockfish\\stockfish.exe",
                Arguments = "",
                UseShellExecute = false,
                RedirectStandardOutput = true,
                RedirectStandardInput = true,
                RedirectStandardError = true,
                CreateNoWindow = true
            }
        };
        try{
            stockfish.Start();
        }
        catch (Exception e) {
            print (e);
        }

```

The code is throwing an exception

```
System.ComponentModel.Win32Exception: ApplicationName='E:\Narsun Projects\Ahmad's Projects\CoachChess\Narsun-CoachChess-Unity\Assets\Scripts\Stockfish\stockfish.exe', CommandLine='', CurrentDirectory=''
 at System.Diagnostics.Process.Start_noshell (System.Diagnostics.ProcessStartInfo startInfo, System.Diagnostics.Process process) [0x00000] in <filename unknown>:0
 at System.Diagnostics.Process.Start_common (System.Diagnostics.ProcessStartInfo startInfo, System.Diagnostics.Process process) [0x00000] in <filename unknown>:0
 at System.Diagnostics.Process.Start () [0x00000] in <filename unknown>:0
 at (wrapper remoting-invoke-with-check) System.Diagnostics.Process:Start ()

```

# Answer
> 0 votes
*Posting my comment as an answer as it seems to solve the problem.*

The callstack shows a problem with the application name :

```
System.ComponentModel.Win32Exception: ApplicationName='E:\Narsun Projects\Ahmad's Projects\CoachChess\Narsun-CoachChess-Unity\Assets\Scripts\Stockfish\stockfish.exe', CommandLine='', CurrentDirectory=''

```

You can see that the `\Ahmad's Projects\` quote is causing trouble as your program thinks it is the end of the string.

As John Hamilton suggested, you can parse your strings and escape the quote characters directly from your code, but I believe a best practice would be not to put any quoting mark in your directory names to begin with.

---
Tags: unity, process
---


# Question
Title: Animation playing incorrectly when controlled through player
I have a 2D simple directional blend tree with 2 inputs, X and Y, for movement.

If i move the red dot in the inspector, the animations blend nicely. Same if i move the 2 input parameters in the animator. But if i press play and move the character with arrows, i can see the 2 parameter inputs in the animator screen moving same as when i moved them with mouse, but the animation that is playing stays the same and the red dot that represents parameters in the inspector stays in the center (even though the parameters in the animator are moving).

I also tried using just 2 animations and blending between them, but turns out that doesn't work ether, even though animator shows that the correct animation should be playing. (if i press forward animator shows that forward animation is playing, but on scene the animation that is playing is like a blend at parameter value in the middle.

The animations were made in Blender as actions (if that's important).

# Answer
Turns out i had 2 problems.

1. I didn't set the Avatar under the animator.
2. I had 2 animator controllers, 1 on top level and 1 on character model. Apparently they didn't like each other.

After i set the avatar and deleted the animator on my character model, blending works perfectly.
> 0 votes

---
Tags: unity, animation
---


# Question
Title: Calculate current level and level requirements when only XP is being updated
I am trying to create a formula to calculate the players level based on his XP alone. The game currently only increments his XP after certain actions.

I have the formula for calculating the required XP to level up:

```
var baseXP = 500;
var exponent = 1.04;
var requiredXP = Math.floor(baseXP + (baseXP * Math.pow(user.level - 1, exponent)));

```

The purpose of this formula is to increment the required level as so:

```
Level 1: 0-499xp
Level 2: 500-1527
Level 3: 1528-2066
Level 4: 2067-2613
Level 5: 2614-4165
etc...

```

I'm not sure if the formula is exactly what I need to use, and the exponent value is just arbitrary (incremented/decremented to make leveling take more/less time)

How would this formula be used or reversed to calculate the players current level. As a plus, any way to limit the maximum level to 100.

Thank you

# Answer
> 1 votes
You do not need to have the inverse calculation at runtime at all. If you have "only" 100 possible levels, just store the amount of xp needed to level up and the according level in an array.

When you need to find out what level would result from a certain amount of xp at runtime, just search for the nearest lower value in your xp-level-array and there you have your result! The same goes for capping the possible levels at 100. When you need 1 Mio xp to get to level 100 and the player has 12 Mio, the nearest lower xp-value in your array is still 1 Mio, so the result is level 100.

# Answer
> 0 votes
Here is code for your question:

```
private static final double BASE_XP = 500;
private static final double EXPONENT = 1.04f;

public static void main(String args[]) {
    for (int i = 0; i < 10; i++) {
        double levelXp = calcXpForLevel(i);
        double max = calculateFullTargetXp(i);
        System.out.println(String.format("Level: %3d, xp for the next level: %10.2f, next level xp: %10.2f", i, levelXp, max));
    }
    System.out.println("====================");
    int xp = 14590;
    System.out.println("For " + xp + " xp  calculated level is " + calculateLevel(xp));
}

private static double calcXpForLevel(int level) {
    return BASE_XP + (BASE_XP * Math.pow(level, EXPONENT));
}

private static double calculateFullTargetXp(int level) {
    double requiredXP = 0;
    for (int i = 0; i <= level; i++) {
        requiredXP += calcXpForLevel(i);
    }
    return requiredXP;
}

private static int calculateLevel(double xp) {
    int level = 0;
    double maxXp = calcXpForLevel(0);
    do {
        maxXp += calcXpForLevel(++level);
    } while (maxXp < xp);
    return level;
}

```

output:

```
Level:   0, xp for the next level:     500.00, next level xp:     500.00
Level:   1, xp for the next level:    1000.00, next level xp:    1500.00
Level:   2, xp for the next level:    1528.11, next level xp:    3028.11
Level:   3, xp for the next level:    2067.39, next level xp:    5095.50
Level:   4, xp for the next level:    2614.04, next level xp:    7709.54
Level:   5, xp for the next level:    3166.24, next level xp:   10875.77
Level:   6, xp for the next level:    3722.90, next level xp:   14598.68
Level:   7, xp for the next level:    4283.31, next level xp:   18881.99
Level:   8, xp for the next level:    4846.94, next level xp:   23728.93
Level:   9, xp for the next level:    5413.40, next level xp:   29142.33
====================
For 14590 xp  calculated level is 6

```

---
Tags: java, mathematics, game-design
---


title: OpenGLES texture coordinates in shader

text:
# Question
Title: OpenGLES texture coordinates in shader
Currently I'm doing an android 2D game using **OpenGLES 2.0** and I noticed that my UVs never change in all of textures when rendering, like this in Java code:

```
    public static FloatBuffer vertexUv;

    public static void setUpUV()
    {
        float uvs[] = {0.0f, 0.0f,
                       0.0f, 1.0f,
                       1.0f, 1.0f,
                       1.0f, 0.0f
                      };
        ByteBuffer bb = ByteBuffer.allocateDirect(uvs.length*4);
        bb.order(ByteOrder.nativeOrder());
        vertexUv = bb.asFloatBuffer();
        vertexUv.put(uvs);
        vertexUv.position(0);
    }
    ...
    //UV sending in render
    int mTexCoordLoc = glGetAttribLocation(program, "a_texCoord");
    glEnableVertexAttribArray(mTexCoordLoc);
    glVertexAttribPointer(mTexCoordLoc, 2, GL_FLOAT, false, 0, vertexUv);
    ...

```

**The problem is:** even the UVs never change, I always sends via Java code to the GPU causing waste of CPU using VBOs or not(*I tested it using OpenGLES tracer*). All textures of my game is in 2D mode so I believe that I don't need send it every texture rendering.

**What I need to do?** I tried to put the UVs in the shader code *(I believe that is the way)* but without success... more or less like this: (*I tested more alternatives in the shader/fragment shader too... below is only a example of my idea to solve this problem*)

```
    //Vertex shader
    var v_texCoord= var(0.0, 0.0,
                        0.0, 1.0,
                        1.0, 1.0,
                        1.0, 0.0
                        ); //Could I init this in the first vertex processing?
    varying vec2 v_texCoord;
    attribute vec4 vPosition;
    void main()
    {
        gl_Position = vPosition;"
        v_texCoord  = v_texCoord;"   //To fragment shader
    }

```

**Question:** is possible put statically UVs in shader?

**Performance:**
Each blue region represents ONE texture rendering from a FRAME. Maybe its a minimal and unnecessary optimization...

***Thank you!!***

# Answer
Usually, the fragment shader takes the UV value for the current fragment as an input from the vertex shader:
Vertex Shader:

```
out vec2 UV;

void main(){
...

    UV = vertexUV;
}

```

Fragment Shader:

```
in vec2 UV;

uniform sampler2D myTextureSampler;

void main(){

    color = texture( myTextureSampler, UV ).rgb;
}

```

> even the UVs never change

They do not change from drawcall to drawcall. But in the end the rasterizer interpolates the UV value for the current fragment from the UV values of the vertices of the current triangle, following the information provided by the vertex shader. And those values can change from vertex to vertex .

I don't see how you would be able to deal with that in the fragment shader alone. You provide 4 UVs and look at 3 vertices for each triangle. How would you figure out what UVs to use and how would you compute the value for the current fragment?? In the end that is what the vertex shader and rasterizer combination is for, isn't it?

Also, why do you want to do that at all? The amount of data that are being transferred here seem too small to me to be worth the effort...
> 1 votes

---
Tags: opengl, android, shaders, opengl-es2, fragment-shader
---


title: Water wave simulation

text:
# Question
Title: Water wave simulation
I'm having a strange behavior simulating water waves. It works perfectly with directional waves, but point waves don't work like expected. If i do not normalize the directional vector(WoldPosition - waveCenter), it works like this:

Which would be nice if i would want to display 10 point waves, but i just added one point wave(the center one). And if i do normalize the directional vector, it looks like this:

Which is not even close of what a point wave should look like.

**Do you have any idea of what could be the problem?**

This is the formula used to calculate the heights of the waves:

```
amplitude * sin(dot(direction,vec2(x,z))*w + deltaTime*phase);

```

Vertex shader:

```
#version 330

layout (location = 0) in vec3 Position;
layout (location = 1) in vec2 TexCoord;
layout (location = 2) in vec3 Normal;

uniform mat4 gWVP;
uniform mat4 gWorld;
uniform float gMatSpecularIntensity;
uniform float gSpecularPower;
uniform vec3 eyePoint;
uniform float deltaTime;

out vec2 TexCoord0;
out vec3 Normal0;
out vec3 WorldPos0;
out vec2 Specular0;
out vec4 wvp;
out float relativeFactor;

const float w = 1.2f;
const float amplitude = 0.1f;
const float phase = 2.2f;

vec3  wavePosition = vec3(20,0,20);

float CalculateHeight(float x, float z, vec2 direction)
{
    return amplitude * sin(dot(direction,vec2(x,z))*w + deltaTime*phase);
}

vec3 CalculeNormal(float x, float z, vec2 direction)
{
    float heightR = CalculateHeight(x-1,z,direction);
    float heightL = CalculateHeight(x+1,z,direction);
    float heightU = CalculateHeight(x,z+1,direction);
    float heightD = CalculateHeight(x,z-1,direction);
    return normalize(vec3((heightR - heightL),1, (heightU - heightD)));
}

void main()
{
    wvp            = gWVP * vec4(Position, 1.0);
    gl_Position    = wvp;
    TexCoord0      = TexCoord;
    WorldPos0      = (gWorld * vec4(Position, 1.0)).xyz;

    vec2 direction = (wavePosition-WorldPos0).xz;

    gl_Position.y  += CalculateHeight(WorldPos0.x,WorldPos0.z,direction);
    Specular0      = vec2(gSpecularPower,gMatSpecularIntensity);
    relativeFactor = dot(normalize(eyePoint - WorldPos0),vec3(0,1,0));

    Normal0        = CalculeNormal(WorldPos0.x,WorldPos0.z,direction);
    relativeFactor = clamp(relativeFactor, 0.0, 1.0);
}

```

Variables:

* direction: Vector which defines the direction of the wave. It is perpendicular to the wave front.
* x: Position x in world coordinates.
* z: Position z in world coordinates.
* amplitude: The amplitude of the wave
* phase: The phase of the wave
* deltaTime: The total time passed in ms.
* gWVP: Camera perspective matrix * Camera view matrix * Water transformation matrix (position matrix * rotation matrix(no rotation) * scale matrix)
* gWorld: Water transformation matrix (position matrix * rotation matrix(no rotation) * scale matrix)

The fragment shader and the other variables do not influence in the displayed wave, it just combine the reflextion + refraction image + apply the fresnel efect.

For more info about the wave function: http://http.developer.nvidia.com/GPUGems/gpugems\_ch01.html

# Answer
This is a little over my head, but it looks super interesting. Will you bear with my while I throw out some dumb ideas?

* `... + deltaTime * phase`: Should that be a multiplication, not an addition? I've never added phase to anything, always multiplied.
* How are multiple waves combined? Apparently, something in the wave summing function compensates for a problem in the wave amplitude function.
* One thing that helps me with math-in-code debugging, is to graph out the terms of the equation, over the interesting part of their input domain. You might be able to see the problem right away, and narrow down the cause to a part of one of the wave-related functions.
> -1 votes

---
Tags: opengl, c++, water
---


title: Use Ashley with Scene2d in libGDX?

text:
# Question
Title: Use Ashley with Scene2d in libGDX?
I want to use Ashley but I also want to use actions and listeners with Scene2d. I read that it is not a good idea, but why? Ican create a system with stage.act(); and stage.draw(); in the update method or is it a bad idea? Thanks.

# Answer
> 0 votes
I don't think you can say it's always a bad idea to mix Scene2D and an ECS like Ashley. It may make a *lot* of sense to use Scene2D.UI for your user interface, and then Ashley for everything else. As you point out, there isn't a *technical* reason why you couldn't tie these two together. It's a judgment call based on your particular use case.

That being said, one reason why you typically wouldn't use Scene2D and Ashley together is that they have a lot of overlap. One of the basic principles of computer science is "Don't Repeat Yourself"- don't build the same thing twice, and when you do build something, make sure you use as few parts as possible. This includes avoiding libraries you don't need.

If you use Scene2D's actions to move your actors/entities, and you use Stage#draw() to draw everything, what's left for Ashley to add? Likely not enough to justify the complexity it adds.

---
Tags: libgdx, entity-system, entity-component, scene2d
---


# Question
Title: Opengles 2.0, Replace the black region in the image to make it transparent
I have two textures, Source image A and Overlay B, B is drawed on top of A, I want to replace the black color in B, then make the region of A visible, what should I do?

This is my shader language:

```
 varying highp vec2 textureCoordinate;
 varying highp vec2 textureCoordinate2;
 uniform sampler2D inputImageTexture;
 uniform sampler2D inputImageTexture2;
 void main()
 {
 lowp vec4 base = texture2D(inputImageTexture, textureCoordinate);
 lowp vec4 overlay = texture2D(inputImageTexture2, textureCoordinate2);

 if (overlay.r == 0.0 && overlay.g == 0.0 && overlay.b == 0.0)
 {
     gl_FragColor = base;
 }
 else
 {
     gl_FragColor = overlay;
 }
}

```

but the result is not right.

This is my overlay

when I mix the source and overlay by using the shader, I got the result like the following, What should I do to make it works right?

# Answer
> 2 votes
There is noise introduced in your texture due to compression which causes some of the pixels to not be perfectly black.

You need to add an error threshold to your comparison, fastest way is to use a distance comparison by considering the RGB color as a 3D vector and use a dot-product to calculate the squared length.

This reduces the multiple comparisons and shortcut boolean operators || which are generally very costly on GPUs.

```
varying highp vec2 textureCoordinate;
varying highp vec2 textureCoordinate2;
uniform sampler2D inputImageTexture;
uniform sampler2D inputImageTexture2;

const float squared_threshold = (0.1 * 0.1); //threshold value, squared

void main()
{
 lowp vec4 base = texture2D(inputImageTexture, textureCoordinate);
 vec4 overlay = texture2D(inputImageTexture2, textureCoordinate2);

 float squared_distance = dot(overlay.rgb, overlay.rgb);

 if (squared_distance < squared_threshold)
 {
     gl_FragColor = base;
 }
 else
 {
     gl_FragColor = overlay;
 }
}

```

if you need to compare to any other colors you can do:

```
vec3 color_diff = overlay.rgb - erase_color;
float squared_distance = dot(color_diff, color_diff);

if (squared_distance < squared_threshold)

```

Where `erase_color` is the color you want to erase, but since we're erasing black ( `vec3(0, 0, 0)` ) we can eliminate this subtraction.

Using a squared threshold allows us to skip calculating the square root to compare the distance.

# Answer
> 0 votes
Fastest solution is to change your comparison to account for JPG compression artifacts (that slightly alter pixels colors):

```
if (overlay.r <= 0.02 && overlay.g <= 0.02 && overlay.b <= 0.02)

```

Right solution would be to add Alpha to your image and use it for transparency.

---
Tags: shaders, textures, opengl-es2, cocos2d
---


# Question
Title: How can I recreate the movement of arrow in air?
Given two Particles A and B which forms the arrow itself, A.P an edge of it and the opposite one B.P. Like so A.P---------B.P.

```
const float DistArrow = 60;

```

Where I have structure Particle:

```
struct Particle
{
    struct Complex P; //Position
    struct Complex F; //Gravitational Force
    struct Complex V; //Velocity
    float m; //Mass
}

```

At the start each particle, A and B has a starting Velocity of like (40, 70). And I am adding a value of force to A.F(0, -9.21) and B.F(0, -9.81). So that the B.F has much more weight on it, so it drags the A to down kind of.

I want the arrow to move like this:

And I am tried to figure out how to make till I was stuck with this(I am trying to calibrate in a way the arrow to the initial DistArrow:

```
A = erA->B*(D(AB)-DistArrow)/2+A; where erA->B(unit vector) = (B-A)D(AB);
B = erB->A*(D(AB)-DistArrow)/2+A; where erB->A(unit vector) = (A-B)D(AB);

```

The problem is that it just rotates 180 degree, dunno why it does, if it will infinitely fall it should be A at the top of B, a line perpendicular with oX.

I am seeking a good solution not involving to much physics, any advice will be highly appreciated.

# Answer
You need a bit of physics, and a touch of calculus.

Lets assign P as the point of the arrow, L as the length of the arrow, and Q as the tail of the arrow.

You launch the arrow at an initial velocity of V, and a launch angle of A, and have gravity G as -9.81.

```
Vx = cos(A)*V
Vy = sin(A)*V

```

I is the intitial x and y locations of P at the moment the arrow was launched.

t represents the time in seconds since the arrow was launched.

```
function(t) {
  Px = t*Vx+Ix
  Py = G*t^2+Vy*t+Iy
  Sa = atan((2*G*t+Vy)/Vx)+pi
  Qx = Px+cos(Sa)*L
  Qy = Py+sin(Sa)*L
}

```
> 5 votes

---
Tags: physics, projectile-physics, trajectory
---


# Question
Title: How to get smooth parallax in a wrap-around world
I'm working on a multiplayer space shooter a-la Star Control melee. The background of the game consists of several layers of tiles sprites making up a parallax effect of clouds and stars. The player ship is always centered in the viewport.

The game world has a fixed size and implements wrap-around, so that any object that passes the game world bounds is instantly teleported to the other side.

To make the transition seamless when reaching game bounds , all objects but the player ship are also rendered outside the game bounds if they are on the other side of the screen. This makes chasing a ship, for example feel seamless.

Right now the x and y values of the background tile offsets are determined by the position of the player ship in the game world.

```
bg1.tilePosition.x = -playerShip.x * 0.01;
bg1.tilePosition.y = -playerShip.y * 0.01;

bg2.tilePosition.x = -playerShip.x * 0.02;
bg2.tilePosition.y = -playerShip.y * 0.02;

```

My problem is with the parallax background when the player reaches the game world bounds. If the ship jumps from x position 1000 to position 0, for example, then all the tile positions jump resulting in a jerky movement.

In the following gif I made a semi white transparent background for the game world so you can see exactly the parallax jump as soon as the purple ship wraps around the game world:

### How can I avoid this so that the parallax background is always smooth?

Things I've thought of:

* Not changing the position of the player when it wraps around, then use a modulo of the game world size for positioning. I can't do that because it will make the game data dirtier and harder to work with plus it increases network bandwidth which I want to avoid
* Tying the tile offset to input. The player ship can move without input from collisions/inertia so that's no help

# Answer
Use a separate position variable for each of your parallax planes.

Increment all of the planes proportionally when the ship moves.

Do the warp-around modulo for each parallax planes independently.
> 1 votes

---
Tags: animation, graphics, parallax-scrolling
---


# Question
Title: Can I make tilemaps in HTML without using Canvas?
Because of sheer experimentation, I'd like to make a game that contains a tilemap - without using the Canvas API provided for HTML5. Instead, I'd rely on CSS and Javascript (with jQuery).

Is there any chance that I can create it? If yes, how?

I have some ideas, such as placing lots of `<img>` tags and changing their sources constantly, but there might be better methods out there.

# Answer
image tags with absolute positioning via css.

better solution is canvas... but that requires canvas :)

even better solution is webgl, but again, that requires canvas.
> 1 votes

---
Tags: javascript, tiles
---


title: 3d puzzle game generating levels

text:
# Question
Title: 3d puzzle game generating levels
I want to create a puzzle game for my first year in college. I will use OpeGL and C++.

The point of the game is to create a path between squares that have the same color, without making the paths intersect each other.

This is the game I want to reproduce: http://mypuzzle.org/3d-logic-2

When I first told my teacher that I want to create this game, I told him I will generate levels, not store them internally.

Then when I actually give it a little thought, I realised I don't have a great idea, just a bad-medium idea (one that doesn't generate "good levels", levels that are actually hard, that use as much space as possible, levels that have multiple solutions).

So my question is:

Does anyone of you know a great idea, an algorithm, some math etc. to use it to generate good levels?

# Answer
Build a solver, and let it "grade" how good your random level is, and if it's good enough, present it to the user, otherwise generate another random level. That way you can place into the grading function what is required to be considered good.
> 2 votes

---
Tags: 3d, procedural-generation, logic, puzzle
---


# Question
Title: How to keep triangles from connecting across voxel mesh
I am working on a voxel engine and have just started learning webgl. I have generated a list of Vertices and Indices by using Array.concat() on a template array and adding a value based on my position in loop.

```
var verticesTemplate = [
    // Front face
    -0.5, -0.5,  0.5,
     0.5, -0.5,  0.5,
     0.5,  0.5,  0.5,
    -0.5,  0.5,  0.5,

    // Top face
    -0.5,  0.5, -0.5,
    -0.5,  0.5,  0.5,
     0.5,  0.5,  0.5,
     0.5,  0.5, -0.5,

    // Right face
    0.5, -0.5, -0.5,
    0.5,  0.5, -0.5,
    0.5,  0.5,  0.5,
    0.5, -0.5,  0.5,

    // Bottom face
    -0.5, -0.5, -0.5,
     0.5, -0.5, -0.5,
     0.5, -0.5,  0.5,
    -0.5, -0.5,  0.5,

    // Left face
    -0.5, -0.5, -0.5,
    -0.5, -0.5,  0.5,
    -0.5,  0.5,  0.5,
    -0.5,  0.5, -0.5,

    // Back face
    -0.5, -0.5, -0.5,
    -0.5,  0.5, -0.5,
     0.5,  0.5, -0.5,
     0.5, -0.5, -0.5,
];
var indicesTemplate = [
    0, 1, 2,      0, 2, 3,    // Front face
    4, 5, 6,      4, 6, 7,    // Back face
    8, 9, 10,     8, 10, 11,  // Top face
    12, 13, 14,   12, 14, 15, // Bottom face
    16, 17, 18,   16, 18, 19, // Right face
    20, 21, 22,   20, 22, 23  // Left face
];
var WorldVertices = [];
var WorldIndices = [];
var IndexLoopIndex = 0;

function generateMeshData() {
    for(var x = 0; x < 4; x++) {
        var blockVertices = [].concat(verticesTemplate);
        addToX(verticesTemplate, blockVertices, x);
        for(var y = 0; y < 4; y++) {
            addToY(verticesTemplate, blockVertices, y);
            for(var z = 0; z < 4; z++) {
                var block = blocks[x][y][z];
                if(block.isActive === true) {
                    // adds a value of 1(The blockSize) to all z coordinates in verticesTemplate and adds to end of WorldVertices
                    addToZ(verticesTemplate, blockVertices, z);
                    WorldVertices = WorldVertices.concat(blockVertices);

                    var indices = [].concat(indicesTemplate);
                    addToXYZ(indicesTemplate, indices, 24*IndexLoopIndex);
                    WorldIndices = WorldIndices.concat(indices);
                    IndexLoopIndex++;
                }
            }
        }
    }
}

```

The problem is that the triangles are skewed after the mesh is rendered using gl.drawElements. And I can't figure out why. So how can I keep triangles from being drawn that connect cubes?

# Answer
> 1 votes
I figured it out. In the end I just wrote 3 functions: CreateCube, addVertex and addTriangle. Here they are.

```
function addVertex(vertexArray) {
    WorldVertices = WorldVertices.concat(vertexArray);

    // returns a vertexId that is used to map triangles to vertices array
    return (WorldVertices.length/3)-1;
}

function addTriangle(vertexIdArray) {
    WorldIndices = WorldIndices.concat(vertexIdArray);
}

function CreateCube(x, y, z, block) {
    // 8 points on a cube are extracted using coordinates from for-loop
    var p0 = vec3.fromValues(x-1, y-1, z+1);
    var p1 = vec3.fromValues(x+1, y-1, z+1);
    var p2 = vec3.fromValues(x+1, y+1, z+1);
    var p3 = vec3.fromValues(x-1, y+1, z+1);
    var p4 = vec3.fromValues(x+1, y-1, z-1);
    var p5 = vec3.fromValues(x-1, y-1, z-1);
    var p6 = vec3.fromValues(x-1, y+1, z-1);
    var p7 = vec3.fromValues(x+1, y+1, z-1);

    // vertexIds
    var v0, v1, v3, v4, v5, v6, v7;

    v0 = addVertex(Array.from(p0));
    v1 = addVertex(Array.from(p1));
    v2 = addVertex(Array.from(p2));
    v3 = addVertex(Array.from(p3));

    addTriangle([v0, v1, v2]);
    addTriangle([v0, v2, v3]);

    v4 = addVertex(Array.from(p4));
    v5 = addVertex(Array.from(p5));
    v6 = addVertex(Array.from(p6));
    v7 = addVertex(Array.from(p7));

    addTriangle([ v4, v5, v6]);
    addTriangle([ v4, v6, v7]);

    // Right

    v1 = addVertex(Array.from(p1));
    v4 = addVertex(Array.from(p4));
    v7 = addVertex(Array.from(p7));
    v2 = addVertex(Array.from(p2));

    addTriangle([ v1, v4, v7]);
    addTriangle([ v1, v7, v2]);

    // left

    v5 = addVertex(Array.from(p5));
    v0 = addVertex(Array.from(p0));
    v3 = addVertex(Array.from(p3));
    v6 = addVertex(Array.from(p6));

    addTriangle([ v5, v0, v3]);
    addTriangle([ v5, v3, v6]);

    // Top

    v3 = addVertex(Array.from(p3));
    v2 = addVertex(Array.from(p2));
    v7 = addVertex(Array.from(p7));
    v6 = addVertex(Array.from(p6));

    addTriangle([ v3, v2, v7]);
    addTriangle([ v3, v7, v6]);

    // Bottom

    v5 = addVertex(Array.from(p5));
    v4 = addVertex(Array.from(p4));
    v1 = addVertex(Array.from(p1));
    v0 = addVertex(Array.from(p0));

    addTriangle([v5, v4, v1]);
    addTriangle([v5, v1, v0]);
}

for(var x = -8; x < 4; x++) {
    for(var y = -8; y < 4; y++) {
        for(var z = -8; z < 4; z++) {
            var block = blocks[x][y][z];
            if(block.isActive === false)
                continue;

            // 2 is the blockSize
            CreateCube(x*2, y*2, z*2, block);
        }
    }
}

```

---
Tags: 3d, javascript, webgl
---


# Question
Title: How to only allow one space in an InputField?
I've been messing with this for a while now and I can't get this to work 100%. I'm using an InputField for players to enter a character name, and I want to allow a first and last name. Here's how I've been trying this:

```
private void CharNameRestrictions() {
    Debug.Log(spaceCount);

    if (Input.GetKeyUp(KeyCode.Space)) {
        spaceCount++;
        if (spaceCount > 1) {
            spaceCount = 1;
            playerNameInput.text = playerNameInput.text.Remove(playerNameInput.text.Length - 1);
        }
    }

    if (!(playerNameInput.text.Contains(" "))) spaceCount = 0;
    if (playerNameInput.text.Length > 15) playerNameInput.text = playerNameInput.text.Remove(playerNameInput.text.Length - 1);

}

```

This sort of works, but if you press and hold space while typing another character, it still lets you add additional spaces. Is there a way to simply ignore the space keycode when there is already a space in the field?

# Answer
> 2 votes
Your script suffers of many drawbacks. Nothing prevent the user from moving the caret at the beginning of the inputfield and add a space.

Here is a script I made for you which seems to work. However, it's quite frustrating to not see any result of a user input action.

Instead of deleting the character, I would suggest to outline the inputfield with a red color.

```
using System.Text.RegularExpressions;
using UnityEngine;
using UnityEngine.UI;

public class CheckInput : MonoBehaviour
{
    // Drag & Drop your inputfield in the following Inspector field
    [SerializeField]
    private InputField inputField ;

    private Regex regex ;

    private string validValue ;

    private void Awake()
    {
        regex = new Regex( @"^[a-z\-]+ [a-z\-]+$", RegexOptions.IgnoreCase );
    }

    private void OnEnable()
    {
        inputField.onValueChanged.AddListener( OnInputFieldValueChanged );
    }

    private void OnDisable()
    {
        inputField.onValueChanged.RemoveListener( OnInputFieldValueChanged );
    }

    private void OnInputFieldValueChanged( string newValue )
    {
        int index = newValue.IndexOf(' ');
        int length = newValue.Length;

        if ( index < 0 || index == length - 1 )
        {
            validValue = newValue;
            return;
        }
        else if ( regex.IsMatch( newValue ) && length <= 15 )
        {
            validValue = newValue;
        }
        else
        {
            inputField.text = validValue;
        }
    }
}

```

---
Tags: unity, c#, gui, input
---


# Question
Title: How can I launch the Unity Editor and open a specific project from C# code?
I created a very simple console application:

```
namespace ConsoleApplication4
{
    class Program
    {
        static void Main(string[] args)
        {
            // The project I want to open
            var arg = @"""-projectPath C:\Users\Administrator\Downloads\New Unity Project""";

            // Start Unity and open the project
            Process.Start(@"C:\Program Files\Unity\Editor\Unity.exe", arg);
        }
    }
}

```

But only the Unity Editor is launched; the specified project is not opened.

What do I need to modify to launch the project?

# Answer
> 2 votes
This might be a better question for the SuperUser StackExchange, as your problem isn't specific to game development, it's just about formatting your command line arguments correctly.

When you write arg like this:

```
var arg = @"""-projectPath C:\Users\Administrator\Downloads\New Unity Project""";

```

That's equivalent to typing this into your command line:

```
Unity.exe "-projectPath C:\Users\..." (etc)

```

As Hellium points out in the comments above, you want the quotation marks around the *path*, not the whole command line argument string. Like this:

```
var arg = @"-projectPath ""C:\Users\Administrator\Downloads\New Unity Project""";

```

Then in the command line it looks like this:

```
Unity.exe -projectPath "C:\Users\..." (etc)

```

---
Tags: unity, c#
---


title: Gradient Banding in Unity Android

text:
# Question
Title: Gradient Banding in Unity Android
In an Android game, I have a gradient background that changes color over time. This was achieved by creating a 1x2 pixel texture in code, and stretching it over a large quad with bilinear filtering.

This all works fine in the editor, but as soon as it is viewed on an Android device, the banding is ridiculously noticeable and annoying.

**Since this texture is generated in code, I cannot set the compression to "truecolor" like most other post suggest, nor can I tick the "Generate Mipmap" option.**

Here is how the gradient look on the phone :

Code to generate gradient (stripped of unimportant stuff):

```
Texture2D gradient;
MeshRenderer render;
Color HSV1, HSV2;
Color primaryColor, secondaryColor;

render = GetComponent<MeshRenderer>();

Update() {
    HSV1.x += 0.01F * Time.deltaTime;
    HSV2.x = HSV1.x;

    if (HSV1.x > 1)
        HSV1.x = HSV1.x - 1;

    if (HSV2.x > 1)
        HSV2.x = HSV2.x - 1;

    primaryColor = Color.HSVToRGB(HSV1.r, HSV1.g, HSV1.b + HSVdifferece);
    secondaryColor = Color.HSVToRGB(HSV2.r, HSV1.g - HSVdifferece, HSV1.b - HSVdifferece);

    gradient.SetPixel(0, 0, primaryColor);
    gradient.SetPixel(0, 1, secondaryColor);
    gradient.filterMode = FilterMode.Bilinear;
    gradient.Apply();

    render.material.SetTexture("_MainTex", rainbow);

}

```

The color banding is really obvious and annoying. How can I fix this?

# Answer
While this question is old, I'll leave a note here for anyone following on later:

Colour interpolation between adjacent texels is performed using fixed point math. The exact precision of this math isn't specified in the standard - desktop GPUs pretty much all use 24.8, but it wouldn't surprise me if mobile GPUs use even lower precision, which would account for the artifacts showing up only on the Android device.

This texture filtering is designed to help fill in gaps of a few pixels between texture samples when you get a bit too close to a wall in 3D games, for example - but it doesn't hold up as well when you try to stretch two texels to fill the entire screen.

The simple fix is to add a few more pixels to your gradient texture, so you're not leaning quite so hard on the interpolation texture filtering to generate all the intermediate colours you want. A 1x16 texture is still lightweight, and gives you about 15 times the number of intermediate colour values.

You could even skip the texture lookup outright and calculate your gradient in the shader, with full floating point precision if you so desire.

For extremely close colours like in the example image, you may also hit the precision limits of the back buffer, or the screen's rendering capabilities. Adding a slight dither to the gradient, by offsetting your lookups by a bias that varies per screen pixel, can help mask this by breaking up the sharp banding lines (graphics programs like Photoshop do this for their gradient fill tools).
> 1 votes

# Answer
Texture2D constructor has textureFormat and mipMap arguments. So create texture with options needed and set your pixels you want.
> -1 votes

---
Tags: unity, android, textures, color
---


# Question
Title: How does this hash function work in this perlin noise implementation?
In Perlin's implementation of his noise function, he uses an array to hash the input coordinates and later find the gradient vectors. But in Stefan Gustavson's implementation, a strange "permute" function is used:

```
vec4 permute(vec4 x)
{
  return mod289(((x*34.0)+1.0)*x);
}

vec4 mod289(vec4 x)
{
  return x - floor(x * (1.0 / 289.0)) * 289.0;
}

```

Then, it is used like this:

```
vec4 i = permute(permute(ix) + iy);

vec4 gx = fract(i * (1.0 / 41.0)) * 2.0 - 1.0 ;
vec4 gy = abs(gx) - 0.5 ;
vec4 tx = floor(gx + 0.5);
gx = gx - tx;

```

I understand that the "\*2.0 - 1.0" is for getting gx to the range -1 to +1, but I do not understand the rest of the hashing. How does this "permute" function work and why does it divided by 41.0?

Thanks.

# Answer
That 41 is an arbitrary prime number value that happens to look good.

You want to values to be perceived as repeating as little as possible coming out of the hash function. One good way to do that is to use some prime numbers (or numbers with very few common denominators) as a scaling factor so they don't often reach a common multiple or denominator.

It's one of those things you tweak by trial-and-error.

41 is a prime number, 289 is 17\*17.

The Least Common Multiple of both 41 and 17 is 697, 41 and 289 is 11849, which in theory one or the other (697 or 11849) would be how far coordinates have to go before the texture repeats.

In practice human perception might see a pattern emerge earlier and rounding errors may also play into this.
> 3 votes

---
Tags: perlin-noise, noise
---


title: OpenGl problem with indicies

text:
# Question
Title: OpenGl problem with indicies
hi guys i'm new of these topics(opengl and others) To begin i want only to create a simple circle that can be route on touchevent. So i decided to learn opengl and to try.

These is my class called circle

```
public class Circle
{

private ByteBuffer byteBuffer;
private FloatBuffer floatBuffer;
private FloatBuffer colorBuffer;
private ShortBuffer indicesbuffer;

float[] buffer=new float[360*3];

float[] color={
        1f,0f,0f,0f,
        1f,0f,0f,0f,
        1f,0f,0f,0f,
        1f,0f,0f,0f,

        1f,0f,0f,0f,
        1f,0f,0f,0f,
        1f,0f,0f,0f,
        1f,0f,0f,0f,
};

short indices[]=new short[180*2];

public Circle()
{

    for(int i=0;i<360;i++)
    {
        buffer[i]=(float)Math.cos(Math.toRadians((double)i))*0.5f;
        buffer[++i]=(float)Math.sin(Math.toRadians((double)i))*0.5f;
        buffer[++i]=0f;
       // Log.i("",""+buffer[i-2]+" "+buffer[i-1]+" "+buffer[i]);
    }
    short count=0;

    for(int i=0;i<360;i++)
    {
        indices[i++]=count;
        indices[i]=(short)(360-count);
        count++;
        Log.i("Prova",""+indices[i-1]+" "+indices[i]);
    }
    byteBuffer=ByteBuffer.allocateDirect(4*buffer.length);
    byteBuffer.order(ByteOrder.nativeOrder());
    floatBuffer= byteBuffer.asFloatBuffer();
    floatBuffer.put(buffer);
    floatBuffer.position(0);

    byteBuffer=ByteBuffer.allocateDirect(4*color.length);
    byteBuffer.order(ByteOrder.nativeOrder());
    colorBuffer= byteBuffer.asFloatBuffer();
    colorBuffer.put(color);
    colorBuffer.position(0);

    byteBuffer=ByteBuffer.allocateDirect(indices.length*4);
    byteBuffer.order(ByteOrder.nativeOrder());

    indicesbuffer=byteBuffer.asShortBuffer();
    indicesbuffer.put(indices);
    indicesbuffer.position(0);

}

public void draw(GL10 gl10)
{
    gl10.glMatrixMode(GL10.GL_PROJECTION);
    gl10.glLoadIdentity();

    gl10.glVertexPointer(3, GL10.GL_FLOAT,0,floatBuffer);
    gl10.glColorPointer(4,GL10.GL_FLOAT,0,colorBuffer);

    gl10.glEnableClientState(GL10.GL_VERTEX_ARRAY);
    gl10.glEnableClientState(GL10.GL_COLOR_ARRAY);

    gl10.glDrawElements(GL10.GL_LINES,360
            ,GL10.GL_UNSIGNED_SHORT,indicesbuffer);

    gl10.glDisableClientState(GL10.GL_VERTEX_ARRAY);
    gl10.glDisableClientState(GL10.GL_COLOR_ARRAY);
}

public void route(float x,float y,GL10 gl)
{
    gl.glClearColor(255,255,255,0);
    gl.glClear(GL10.GL_COLOR_BUFFER_BIT);

    gl.glMatrixMode(GL10.GL_MODELVIEW);
    gl.glLoadIdentity();

    gl.glRotatef(x,0,1,0);
    gl.glRotatef(y,-1,0,0);

    this.draw(gl);
}
}

```

it was really simply..i use goniometric function to get polar coordinates of circle and then i draw it. I want to draw it red colored. So i use indicies to unite the points that are opposite respect x axis. But the output is this

These is the main and render code

```
public class MainActivity extends AppCompatActivity implements GLSurfaceView.Renderer,View.OnTouchListener{

int wi,he;
    Circle cube= new Circle();

    float la_x,la_y,diff_x,diff_y=0;
    GLSurfaceView gl;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        gl= new GLSurfaceView(this);
        final Prova prova= new Prova(100,100);
        gl.setRenderer(this);
        this.addContentView(gl,new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

        gl.setOnTouchListener(this);
        gl.setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);

    }

    @Override
    public void onSurfaceCreated(GL10 gl, EGLConfig config) {

        gl.glClearColor(255,255,255,0);
        gl.glClear(GL10.GL_COLOR_BUFFER_BIT);

        cube.draw(gl);

    }

    @Override
    public void onSurfaceChanged(GL10 gl, int width, int height) {

    }

    @Override
    public void onDrawFrame(GL10 gl) {

            cube.route(diff_x, diff_y,gl);
            Log.i("Differencese",""+diff_x+" "+diff_y);

    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        float x=event.getX();
        float y= event.getY();

        switch (event.getAction())
        {
            case MotionEvent.ACTION_DOWN:
                la_x=x;
                la_y=y;
                break;

            case MotionEvent.ACTION_MOVE:
                diff_x=x-la_x;
                diff_y= y-la_y;

                la_x=x;
                la_y=y;
                gl.requestRender();
                break;

            case  MotionEvent.ACTION_UP:
                la_x=0;
                la_y=0;
                break;

        }

        return false;
    }

}

```

Can anyone plese tell where is my errors.. Sorry for the english and thanks to all

# Answer
> 0 votes
You only need to draw 179 vertical lines. You want to skip point 0, since you didn't define a point 360, and if you had, it would have had the same location as point 0.

```
short indices[]=new short[179*2];

count = 1;
for(int i=0;i<358;i++)
{
    indices[i++]=count;
    indices[i]=(short)(360-count);
    count++;
    Log.i("Prova",""+indices[i-1]+" "+indices[i]);
}

```

As for color, you've only assigned the color for the first 8 points.

For those 8 lines, the color will start out red, then vary towards black.

---
Tags: opengl, android
---


title: UI clicks hitting game objects below

text:
# Question
Title: UI clicks hitting game objects below
I have a canvas with a panel with set width / height inside. The canvas rendermode is set to ScreenSpace Overlay.

My clicks on the panel are falling through and hitting the game objects below triggering their mouse events.

The little green circle is a Sprite with the following event

```
  public void OnMouseDown() {
        Debug.Log("click");
        Vector3 newPos = Camera.main.WorldToScreenPoint (this.transform.position);
        newPos.x -= panel.GetComponent<RectTransform>().rect.width / 2.0f;
        newPos.y -= panel.GetComponent<RectTransform>().rect.height / 2.0f;

        panel.transform.position = newPos;
  }

```

I've been reading through the docs but I'm missing something... How do I stop my clicks hitting the game objects below the panel?

# Answer
> 1 votes
You can try to use IsPointerOverGameObject to check if the mouse is over a UI element. Something like this:

```
public void OnMouseDown() {
        if (EventSystem.current.IsPointerOverGameObject()) return;

        Vector3 newPos = Camera.main.WorldToScreenPoint (this.transform.position);
        newPos.x -= panel.GetComponent<RectTransform>().rect.width / 2.0f;
        newPos.y -= panel.GetComponent<RectTransform>().rect.height / 2.0f;

        panel.transform.position = newPos;
  }

```

If you use `IsPointerOverGameObject()` without a parameter, it points to the "left mouse button" (`pointerId = -1`); therefore when you use `IsPointerOverGameObject` for touch, you should consider passing a pointerId to it. For example:

```
private static bool IsPointerOverGameObject()
{
    #if !UNITY_EDITOR && (UNITY_ANDROID || UNITY_IPHONE)
        const int fingerId = 0;
    #else
        const int fingerId = -1;
    #endif

    return EventSystem.current.IsPointerOverGameObject(fingerId);
}

```

---
Tags: unity, gui
---