title: Cannot find bug in frustum culling code

text:
# Question
Title: Cannot find bug in frustum culling code
I've written some code for frustum culling, but for some reason, it is not working, and i can't find the bug in it... Maybe a bug in the math, somewhere? So, i'm asking you if anyone could check these values, or give me an idea... Sorry for the lengthy post, but i'm fresh out of ideas, so i'm giving you all available data.

Basically, i have a bounding box centered at (0, 10, 0), with a side of ( 2, 2, 2 ). Corners are correctly calculated to be at ( -1, 9, 1 ), ( 1, 9, 1 ), (-1, 11, 1), ( 1, 11, 1), (-1, 9, -1), (1, 9, -1), (-1, 11, -1), (1, 11, -1).

The camera is at ( 0, 3, 10 ), set up with FOV=60, AspectRatio=800/600, near clip = 1, far clip = 50.

The planes are set up with this function:

```
void CPlane::SetFrom3Points ( const Vector3f &In_P0, const Vector3f &In_P1, const Vector3f &In_P2 )
    {
    CPlane Plane;
    Vector3f V0, V1;

    // Creates vectors between all three points
    Point = In_P0;
    V0 = In_P1 - In_P0;
    V1 = In_P2 - In_P0;

    // Taking the cross-product of these two vectors, i get the normal to the plane
    Normal = CrossProduct ( V0, V1 );
    Normal.Normalize();
    A = Normal.X;
    B = Normal.Y;
    C = Normal.Z;
    D = - DotProduct ( Normal, Point );
    }

```

The extracted top plane is: A = 0 B ~= -0.86 C = -0.5 D ~= 7.59

I'm using these 3 first values as the plane's normal. It fails right at the first ( top ) plane, so i'm only presenting that.

Then, there's the check function:

```
int CFrustum::BoundingBoxInFrustum ( SBoundingBox In_Box )
    {
    int result = FRUSTUM_INSIDE, out,in;

    // for each plane do ...
    for ( int i=0; i < 6; i++ )
        {
        // reset counters for corners in and out
        out=0;
        in=0;
        // for each corner of the box do ...
        // get out of the cycle as soon as a box as corners
        // both inside and out of the frustum
        for ( int k = 0; k < 8 && ( in==0 || out==0 ); k++ )
            {

            // is the corner outside or inside
            float D = Planes[i].GetDistance ( In_Box.Corners[k] );
            if ( Planes[i].GetDistance ( In_Box.Corners[k] ) < 0 )
                out++;
            else
                in++;
            }
        //if all corners are out
        if ( !in )
            return ( FRUSTUM_OUTSIDE );
        // if some corners are out and others are in
        else if ( out )
            return FRUSTUM_INTERSECT;
        }
    return ( result );
    }

```

and Plane::GetDistance

```
float CPlane::GetDistance ( Vector3f In_Point )
    {
    return ( D + DotProduct ( Normal, In_Point ) );
    }

```

In the first iteration in the checking function the point is incorrectly categorized as being outside the plane ( so, above the top plane ), and as such, the bounding box will be categorized as intersecting.

what could be wrong here?

EDIT:Here's an animation showing what's wrong...

That yellow sphere should be considered completely inside the frustum. It's not.

This is what happens with a "field" of spheres so i can check the frustum code...

Don't know if you can see, but most of the spheres inside the frustum are colored yellow ( meaning intersection ), and the whole first row too...

EDIT2: ok, so i re-wrote the code a bit, and came up with this:

```
int CFrustum::BoundingBoxInFrustum ( SBoundingBox In_Box )
    {
    unsigned Counters[3] = {0, 0, 0};

    for ( int plane = 0; plane < 6; ++plane )
        {
        unsigned PlaneNegative = 0;
        for ( int corner = 0; corner < 8; ++corner )
            {
            Math::CPlane::EHalfspace PointResult = ClassifyPoint ( Planes[plane],     In_Box.Corners[corner] );
            ++Counters[PointResult];
            }
        if ( Counters[Math::CPlane::NEGATIVE] == 8 ) // If all points are on the         negative side of this plane, then the bounding box is not visible
            return FRUSTUM_OUTSIDE;
        Counters[Math::CPlane::NEGATIVE] = 0;
        }
    if ( Counters[Math::CPlane::POSITIVE] == 8 * 6 )
        return FRUSTUM_INSIDE;
    return FRUSTUM_INTERSECT;
    }

CPlane::EHalfspace ClassifyPoint ( const CPlane &In_Plane, const Vector3f &In_Point )
    {
    float Result = In_Plane.D + DotProduct ( In_Plane.Normal, In_Point );
    if ( Result < 0 ) return CPlane::NEGATIVE;
    if ( Result > 0 ) return CPlane::POSITIVE;

//     float d;
//     d = Plane.A * Point.X + Plane.B * Point.Y + Plane.C * Point.Z + Plane.D;
//     if ( d < 0 ) return CPlane::NEGATIVE;
//     if ( d > 0 ) return CPlane::POSITIVE;
    return CPlane::ON_PLANE;
    }

```

I'm wondering if i may have messed up my plane calculation, since the frustum drawing is so off.. Also, the bounding boxes seem to sometimes disappear on certain positions, and re-appear, so i'm definitely miscalculating something... Can you please double-check my results? For a 60 degree FOV, 1.(3) aspect ratio, 1 and 100 for near and far planes, positioned at (0, 3, 10), this is what got calculated: Planes:

Top 0, -0.866025388, -0.5, 7.59807587

Bottom 0, 0.866025388, -0.5, 2.40192366

Left 0.792405784, 0, -0.609994292, 6.09994316

Right -0.792405784, 0, -0.609994292, 6.09994316

Near 0, 0, -1, 9

Far 0, 0, 1, 90

The frustum corners are then at: ( -0.769800365, 2.42264986, 9 ) ( 0.769800365, 2.42264986, 9 ) ( -0.769800365, 3.57735014, 9 ) ( 0.769800365, 3.57735014, 9 ) ( -76.9800415, -54.7350273, -90 ) ( 76.9800415, -54.7350273, -90 ) (-76.9800415, 60.7350273, -90 ) ( 76.9800415, 60.7350273, -90 )

The code to calculate the planes and corners is this:

```
float Tangent = ( float ) tan ( DegToRad ( 0.5 * FOV ) ) ;
float NearHeight = Near * Tangent;
float NearWidth = NearHeight * AspectRatio;
float FarHeight = Far * Tangent;
float FarWidth = FarHeight * AspectRatio;

Math::Vector3f NearClip = -ZVector * Near;
Math::Vector3f FarClip = -ZVector * Far;

Corners[SBoundingBox::TOP_NEAR_LEFT] = Position + NearClip +  YVector * NearHeight  - XVector * NearWidth;
Corners[SBoundingBox::TOP_NEAR_RIGHT] = Position + NearClip + YVector * NearHeight +  XVector * NearWidth ;
Corners[SBoundingBox::BOTTOM_NEAR_LEFT] = Position + NearClip - YVector * NearHeight  - XVector * NearWidth;
Corners[SBoundingBox::BOTTOM_NEAR_RIGHT] = Position + NearClip - YVector * NearHeight + XVector * NearWidth;

Corners[SBoundingBox::TOP_FAR_LEFT] = Position + FarClip + YVector * FarHeight - XVector * FarWidth;
Corners[SBoundingBox::TOP_FAR_RIGHT] = Position + FarClip + YVector * FarHeight + XVector * FarWidth;
Corners[SBoundingBox::BOTTOM_FAR_LEFT] = Position + FarClip - YVector * FarHeight - XVector * FarWidth;
Corners[SBoundingBox::BOTTOM_FAR_RIGHT] = Position + FarClip - YVector * FarHeight + XVector * FarWidth;

Planes[FRUSTUM_TOP].SetFrom3Points ( Corners[SBoundingBox::TOP_NEAR_RIGHT], Corners[SBoundingBox::TOP_NEAR_LEFT], Corners[SBoundingBox::TOP_FAR_LEFT] );
Planes[FRUSTUM_BOTTOM].SetFrom3Points ( Corners[SBoundingBox::BOTTOM_NEAR_LEFT], Corners[SBoundingBox::BOTTOM_NEAR_RIGHT], Corners[SBoundingBox::BOTTOM_FAR_RIGHT] );
Planes[FRUSTUM_LEFT].SetFrom3Points ( Corners[SBoundingBox::TOP_NEAR_LEFT], Corners[SBoundingBox::BOTTOM_NEAR_LEFT], Corners[SBoundingBox::BOTTOM_FAR_LEFT] );
Planes[FRUSTUM_RIGHT].SetFrom3Points ( Corners[SBoundingBox::BOTTOM_NEAR_RIGHT], Corners[SBoundingBox::TOP_NEAR_RIGHT], Corners[SBoundingBox::BOTTOM_FAR_RIGHT] );
Planes[FRUSTUM_NEAR].SetFrom3Points ( Corners[SBoundingBox::TOP_NEAR_LEFT], Corners[SBoundingBox::TOP_NEAR_RIGHT], Corners[SBoundingBox::BOTTOM_NEAR_RIGHT] );
Planes[FRUSTUM_FAR].SetFrom3Points ( Corners[SBoundingBox::TOP_FAR_RIGHT], Corners[SBoundingBox::TOP_FAR_LEFT], Corners[SBoundingBox::BOTTOM_FAR_LEFT] );

```

# Answer
The bounding box you described *is* intersecting the frustum, even if your visualisation isn't making it apparent.

At a position of 0, 10, 0, and the camera's position at 0, 3, 10, the difference in position is 0, 7, 10.

Further, the difference of position from the camera to the top-most near corner of the 2x2x2 box is actually 0, 8, 9.

With a FOV of 60 degrees, the camera has 30 degrees between the horizon and the top plane. Over a horizontal distance of 9 units, the frustum will certainly fall short of the 8 units it needs to rise (atan(8/9) = ~42 degrees).

I hope that makes sense. I can't imagine what would bring about the problems in your second picture -- especially the whole first row "intersecting" the frustum, but perhaps it's another issue altogether.
> 1 votes

---
Tags: opengl, mathematics
---


title: How can i fix my Ground detection code?

text:
# Question
Title: How can i fix my Ground detection code?
My ground detection works by checking if the player's x position is between the range of a sprite xpos+16 and xpos-16 if it is,then it uses a separate axis theorem on the y axis to see if the player is colliding or touching with the sprite if it is then the player is grounded. Else then the player isn't grounded.

```
void groundCheck(Player& player,sf::Sprite sprite)
{

        sf::Vector2f bounds = sf::Vector2f((sprite.getPosition().x - 16),(sprite.getPosition().x + 16));

  //if(player.grounded == false)
  if(player.sprite.getPosition().x < bounds.y && player.sprite.getPosition().x > bounds.x )
    {
        float lengthy = abs(player.sprite.getPosition().y-sprite.getPosition().y);
        float half1y = player.sprite.getGlobalBounds().height/2;
        float half2y = sprite.getGlobalBounds().height/2;
        float gapy = lengthy - half1y - half2y;
        if(gapy <= 0)
        {
            player.grounded = true;
        }
        else
        {
            player.grounded = false;
            std::cout << gapy <<","<<half2y<<","<<half1y<<","<<lengthy<<","<<player.sprite.getPosition().y<<"\n"; //<<","
        }
    }

}

```

The problem is that when there are 2 or more sprites with the same x position ,the check then performs sat on all sprites below the player and I'm not sure what a solution to this would be.

# Answer
If you have multiple sprites at the same position, are they all supposed to prevent the player from falling? if so, you can either merge them, or disable collision for one.

Else, if not all the sprites should collide, maybe you can add a flag to indicate if they are ground colliders.

On a side note, you could use a complete AABB instead of using arbitrary values to detect if the player is y-aligned.
> 1 votes

---
Tags: c++, collision-detection, algorithm, sfml
---


title: Proper Text-RPG Monster Generator

text:
# Question
Title: Proper Text-RPG Monster Generator
I'm making a text-based RPG in C++ just for fun, and in a way that I can keep adding to it and hopefully give it graphics one day, and I've got a lot of code for everything. My only problem is that I can't come up with a decent way to create enemies that will be fair across the levels and classes. Tweaking the formulas doesn't seem to help. I will give some examples, there are only 10 enemies now, and I'm just wondering if anyone has a better way of going about this that keeps the variety between classes and fairness across levels. Here are a few of the monsters:

```
    Monster.Name = "Minotaur";
    Monster.monsterOption = random1;
    Monster.level = Player.level;
    Monster.health = 30+(5*Monster.level)+(rand()%7);
    Monster.workinghealth = Monster.health;
    Monster.attack = 15+(7*Monster.level+(rand()%4));
    Monster.defense = 26+(11*Monster.level)+(rand()%4);
    Monster.speed = 10+(2*Monster.level)+(rand()%3);
    Monster.luck = 2+(1*Monster.level)+(rand()%1);
    Monster.accuracy = 90+(rand()%5)-(rand()%10);
    Monster.gold = (rand()%120)+(30*Monster.level);

    Monster.Name = "Bandit Leader";
    Monster.monsterOption = random1;
    Monster.level = Player.level;
    Monster.health = 20+(2*Monster.level)+(rand()%15);
    Monster.workinghealth = Monster.health;
    Monster.attack = 20+(7*Monster.level+(rand()%3));
    Monster.defense = 20+(10.5*Monster.level)+(rand()%3);
    Monster.speed = 20+(4*Monster.level)+(rand()%8);
    Monster.luck = 2+(1*Monster.level)+(rand()%1);
    Monster.accuracy = 90+(rand()%5)-(rand()%10);
    Monster.gold = (rand()%150)+(32*Monster.level);

    Monster.Name = "Dragon";
    Monster.monsterOption = random1;
    Monster.level = Player.level;
    Monster.health = 35+(4*Monster.level)+(rand()%10);
    Monster.workinghealth = Monster.health;
    Monster.attack = 20+(7*Monster.level+(rand()%10));
    Monster.defense = 25+(11*Monster.level)+(rand()%10);
    Monster.speed = 20+(1*Monster.level)+(rand()%10);
    Monster.luck = 2+(1*Monster.level)+(rand()%6);
    Monster.accuracy = 90+(rand()%5)-(rand()%10);
    Monster.gold = (rand()%100)+(30*Monster.level);

```

So you can see the formulas aim to keep some degree of randomness between each of the same type of monster, and they should be changed based on your level but not your class, weapons, armor, etc. That is all the information about each kind of monster while there is more information about the player (Armor and weapons added to base defense and attack). Here is an example player from a file I have saved right now:

```
           SAVED CHARACTER INFORMATION
================================================
| Name:     WarriorRawrry                      |
| Class:    Warrior                            |
| Level:    32                                 |
| Health:   207/241                            |
| Attack:   231                                |
| Defense:  159                                |
| Speed:    159                                |
| Luck:     45                                 |
| Accuracy: 90%                                |
| Exp Pnts: 1228/16000                         |
| Gold:     7183                               |
| Weapon:   Sword of 1000 Truths  +125 attack  |
| Chest:    Blinding Breastplate  +90  defense |
| Legs:     Oblivion Greaves      +88  defense |
| Helmet:   Crown of Death        +64  defense |
| Hands:    Gauntlets of Fate     +54  defense |
| Feet:     Hell's Sabatons       +60  defense |
================================================

```

Note: That is output from the command line, I just put it in code format to make it easy to read.

So you guys can see what I'm trying to accomplish here, I'm not asking you guys to create math formulas for me, but any ideas on what would be a better way to go about this would be much appreciated.

# Answer
I think your problem is not program but staff. You need a Beta tester to give you comment on what to pike down or buff up.

If your character has certain unique skill it can also contribute or harm the player.

Also note on some games, it's not actually possible to kill high level monster without a bit of team play.

You can also apply randomness on range of hits and damages but it must have a max or min hit computable.

Take into account the weapons. Most gameplays who can not change monster stats (cause it was already deployed)... depends on ever changing list of arsenal available to characters.

The game experience and know-how should be your main factor in Testing.

**How we do it before on our server.** (Manually on gameplay)

> 1.) tweak monsters so it does not attack and not aggressive
>
> 2.) Pour Admin buffs (no time expiration) and hit monster to see max damage
>
> 3.) do 2.) in combination with other different factors (team play, weapons, armor, etc) mentioned above
>
> 4.) Pour Admin curse and hit monster too see min damage apply 3.)

In my experience, what's more difficult is balancing character types. Example Sword versus magic versus range during Player Vs Player. If you do not solve this balance you will end up with just a few type character on your server.

Consider also player able to shift armor and weapons at there will. It's their right to protect themselves or counter-attack according.

The beauty of RPG is you go by your audience experience and feedback. You can only hope your computation might be accurate on certain scenarios but if other players can not adopt, by changing tactics they will leave your server.

**An Alternative to balance Players vs Monsters.**

> 1. Assign a total number of stats you can contribute to different stats to a player per certain level.
> 2. Since monsters won't have and weapons or armor you need to add certain percentage to the total stats of monsters. Say 5% to 50%. Assuming monsters do not level up.
> 3. Let your players do the assigning of stats.
> 2 votes

# Answer
Make some playtests around what equipment/stats will have a certain player on average on certain level.

Create a monster roster with monsters valid on certain levels, I mean, Minotaur is never always a player level, but instead create a Minotaur that has level 2, Orc with level 3, Dragon with level 19 etc.

When you are generating encounters for player, check his level and randomly choose an enemy ranging from his level-5 upto level+5 or something like that.

This way you can balance foes easier, fine tuning for example Dragon values so it will be challenging for character level 16, usual enemy for level 19, and pushover for level 24.

Also always keep same scaling on monsters and players, for example in Final Fantasy series (older ones like 5,6,7,8 etc) characters are scalling exponentially, so does enemies. In Dunegons & Dragons v5 for example characters and enemies are scalling lineary with very slow curve. You must choose one and be consistent.
> 0 votes

---
Tags: c++, rpg, text-based, xcode
---


# Question
Title: Efficient billboarding sprites in Unity 5
What's the most efficient way to do billboarding sprites in Unity 5?

I want to make a forest of sprite trees in 3d space. Those sprites need to face the camera at all times. I am working on VERY performance restricted hardware - I need the game to run on mobile at 60+ FPS - the scripts have their overhead and moving/turnign trees cannot be static, so I cant use static batching for them.

The naive method of adding a script to each tree that makes it LookAt the camera each update is not good enough in terms of FPS.

I know the grass/details for terrain uses billboards, but it uses the sprite only as a silhouette for the grass and paints it with a flat colour.

# Answer
> 6 votes
Instead of using LookAt, you can have the shader force the object to be rendered facing the camera. Thus, no script needs to be added to the tree, and the extra work the shader does is very little. Here's an example: Billboard Shader

Also, since they don't actually move or rotate (as far as the CPU is concerned) and share the same material, you can turn on static batching.

I hope this helps!

---
Tags: unity, sprites, efficiency, billboarding
---


# Question
Title: SharpDX / DirectX: How to render text to a transparent BitmapRenderTarget?
I'm trying to render text to a `BitmapRenderTarget`, cleared with transparent color.

My `TextBox` is drawn on its own `SharpDX.Direct2D1.BitmapRenderTarget`, which I create in this way:

```
var bitmapRenderTarget = new SharpDX.Direct2D1.BitmapRenderTarget(renderTarget,
    SharpDX.Direct2D1.CompatibleRenderTargetOptions.None, null, null, null);

```

As you can see, I don't change the pixel format of `BitmapRenderTarget`. The pixel format of underlying `SharpDX.Direct2D1.RenderTarget`, on which I draw my `TextBox` through `DrawBitmap` method, is defined in the following code:

```
renderTargetProperties = new SharpDX.Direct2D1.RenderTargetProperties()
{
    PixelFormat = new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.Unknown,
    SharpDX.Direct2D1.AlphaMode.Premultiplied)
};

```

Here is the code, that produces visual results:

```
// In the case 1: opaque white background
bitmapRenderTarget.Clear(SharpDX.Color.White);
...

// In the case 2: white background with 50% transparency
bitmapRenderTarget.Clear(new SharpDX.Color4(1f, 1f, 1f, 0.5f));
...

// In the case 3: fully transparent background
bitmapRenderTarget.Clear(SharpDX.Color.Transparent);
...

// The color of textBrush in all these cases is the same solid Black.
bitmapRenderTarget.DrawTextLayout(vector, textLayout, textBrush, ...);

```

The results:

As you can see, alpha value of the text color is somehow bound to the one in the clear color. The black line around the text is cursor, and it is drawn as it should.

How to fix this issue?

# Answer
I'm not familiar with either SharpDX nor Direct2D.

However, my guess is that what you're seeing is caused by AlphaMode.PremultipliedAlpha.

This is the blend equation for pre-multiplied alpha:

> blend(source, dest) = source.rgb + (dest.rgb * (1 - source.a))

As you can see, the alpha channel of the source is not taken into account, since the mode assumes that the color channels of the source have already been multiplied by its opacity.

In your example, source is the opaque black (r = 0, g = 0, b = 0, a = 1) text you're rendering and dest is the white background and it's (varying) opacity.

For opaque white background (r = 1, g = 1, b = 1, a = 1), you get:

> source.rgb + (dest.r * (1 - source.a)) = (0,0,0) + (1,1,1) * (1-1) = (0,0,0) =\> black

For 50% opaque white (r = 1, g = 1, b = 1, a = 0.5) you get:

> source.rgb + (dest.r * (1 - source.a)) = (0,0,0) + (1,1,1) * (1-0.5) = (0.5,0.5,0.5) =\> grey

And for fully translucent white (r = 1, g = 1, b = 1, a = 0) you get:

> source.rgb + (dest.r * (1 - source.a)) = (0,0,0) + (1,1,1) * (1-0) = (1,1,1) =\> white

As you can see, it's not really 'fading' but rather 'whitening' that's happening here.

In short, I think the fix you're looking for is is to change the blend mode from PremultipliedAlpha to AlphaBlend.

Further reading: http://blogs.msdn.com/b/shawnhar/archive/2009/11/06/premultiplied-alpha.aspx
> 1 votes

---
Tags: directx, sharpdx
---


# Question
Title: Why is Unity3D on OSX ignoring my XBox 360 controller?
I'm using a fork of the Tattie Bogle driver that has a signed kext. The System Settings panel shows all inputs correctly.

One axis is configured in Unity3D 5 like this:

Still, I don't see any input when the game is running. I also cannot configure Positive/Negative Buttons for any input in the Input Manager panel - clicking the input line edit and entering a keyboard key works fine, but pressing a controller button does nothing.

What am I missing here?

# Answer
In addition to the Tattie Bogle Drivers, you also need to use Unity-XboxCtrlrInput for Unity if you want to use your Xbox Controller on Unity.
It is working for both Unity 4 and Unity 5.
They have a working example project that you can download from the project page if you want to test your Xbox Controller with a working project.
> 0 votes

# Answer
After a bit of research it appears your biggest issue, assuming you have just plugged in and hoped for the best, is that (naturally) mac does not have the drivers to understand an Xbox controller.

A good rule of thumb: If you plug anything Microsoft into anything Apple and just hope for the best, your going to have a bad time. They just don't like talking to each other. These two sites gave me a bit of insight into connecting various original and third-party controllers. I assume if you follow the driver installation you have a good chance of that fixing everything, just remember that the driver is what the computer uses to understand the device. It is possible that a different driver will interpret the controller a little differently - this may go as far as swapping buttons on the player.

That said, the driver refereed to at jacobtomlinson.com (provided by tattiebogle.net) has come up in a few times in the past, so I would assume that is the general driver players would be using.

http://www.jacobtomlinson.co.uk/2014/10/17/use-xbox-360-pad-with-yosemite/

http://www.instructables.com/id/Use-an-Xbox-360-Controller-on-OS-X-wired-wirele/step2/Wired-third-party-360-controller/

---

Also keep in mind that the drivers impact the identification of the buttons themselves, so you can not use native windows reference to the controller and expect the buttons to remain the same. This last link shows the button references on a Windows system, and the reference system used by the tattieboggle driver.

http://wiki.unity3d.com/index.php?title=Xbox360Controller
> 0 votes

---
Tags: unity, macos, xbox-controller
---


# Question
Title: How do I create a multiplayer server also suitable for local single-player?
I've created a voxel game in C++, OpenGL and SFML, and I want to make it multiplayer.

I'd like to make it similar to Minecraft's client-server model: The single-player is just a client to the hidden server underneath; but can be configured to connect to multiplayer as well so that the single player and multiplayer code are one and the same.

Spitball-ideas:

* Use a separate thread for the server logic and then share the data between a synchronized point in the code for the client.
* Just send packets to local host from the server thread and collect them from the client thread.

How should I do this?

# Answer
> 5 votes
## General concept

Create a server class (to handle connections and messaging) and a client class (to handle connecting to server by IP and port).

Then ask the player whether they want to create or join a server.

* If *create*, start a server and join it with the client.
* If *join*, join the existing server.

Minecraft singleplayer can be opened to the LAN, by just clicking that option. So it is already running singleplayer with server client setup. It works, because latency is basically 0. It adds a bit overhead, but nothing noticeable if done decently.

## Coding it

You should definitely run the server in its own thread.

Handle all actions as network messages. Instead of directly calling `WalkForward()` (for example), you would do:

```
client.SendInput(inputSnapshot);

```

and in the server

```
while(server.ReadMessages())
   Handle(server.messages.next())

////
void Handle(MessageBase message)
{
   if(message.readByte() == InputMessageType
      HandleInputSnapshot(message);
}
void HandInputSnapshot(..)
{
   world.Update(message.getConnection(), message)
   server.CreateAndSendWorldStateUpdateMessageForPlayer(message.getConnection());
}

```

The server would store the world state with all objects in the world, their locations, rotations etc. It would calculate each client's local area for objects that they should know, and send each a personal `worldStateMessage` (or similar).

Each client would also have world state, but from its own view. It would not know about all the objects around it, only those that server has sent it. Clients constantly receive `worldStateMessages`, maybe something like 20 times per second?

## Why this works

With this kind of system, you would not send "DestroyBlockXY", but "Client X targeted xyz and clicked mouse 1". When the server receives such a message, it would execute that action in its own world model and notify other clients, that "Client X just targeted xyz and clicked mouse 1". Other clients would pick up this message (if it's in their local area) and update their view of the world, to mirror the server's.

As you see, you can't just plug a client-server model in. You have to code your game around it. But when done like this, you can play on a local server or internet server, using exactly the same code.

---
Tags: c++, networking, multiplayer, client-server, sfml
---


title: Mesh deformation maya to unity

text:
# Question
Title: Mesh deformation maya to unity
I have a model that has been modeled & rigged in Maya, whenever i export it as an FBX and take it into unity it seems to collapse at certain areas (see the attachments for a before and after). The model is fine when brought into unity in the T position but once I give a pose in maya & get it to unity it seems to collapse in certain areas. I’ve even tried importing FBX file into 3ds max , model seems to have no problem in it. Its only when I import into unity I seem to get this problem.

# Answer
> 2 votes
I would go back and and check all of your topology, if you have any faces that are open or any floating vertices, it may do strange stuff to your model. An easy way to check it is to throw it into 3DS Max and run STL Check. It will show you where all of the potential mistakes are.

---
Tags: unity, assets, maya
---


# Question
Title: Simple Tanks game - Client-Server communication approach doubts
I want to create simple a multiplayer 2D game with tanks ( cooperative ) in C# with .NET. I also want to keep it simple, because it is only a semester project, and unfortunately i don't have time to learn additional game engines like Unity.

So, can i do it without Unity, XNA or other game engine ? If yes, here is an architecture/design problem that i am facing: How should i notify the two players regarding the position of the other player on the map, the position of the bullets and the position of the enemies ?

1. Should i query the server at 50-100 ms intervals and get a list of JSON messages containing positions and states ( a tank exploded ) ?
2. Should i send a message from server regarding a bullet let's say, bullet no.1 started from x,y heading on axis y, then in the client, i will draw it until i will receive like an interrupt in case it hits an obstacle ( a tank that was passing by) ?

The first option seems more simpler, but it will kill the server in a real life ( 100000 players ) situation. The second seems like on overkill and over-engineering from client side.

Any other suggestions ? Thanks

# Answer
> 1 votes
First, lets get this out of the way, aiming for 100k user is *ridiculous* for semester project. Aiming for 100k users playing in one physical server is insane for *any game*.

---

XNA is not an engine and no where near as high level as Unity. XNA just provides nice set of code, gathered in library with all the necessary "boilerplate code" done. It is DirectX for C#. So when doing games, with C# you should definitely check XNA ( or MonoGame)

For example, loading texture to your game:

```
 Texture2D tank = content.Load<Texture2D>("myTankImage");

```

and drawing

```
 spriteBatch.Draw(tank,new Vector2D(100,100),Color.White);

```

Inserting these, to right places, would draw your tank to locations 100,100.

---

Typical action based game sends anywhere from 10 to 30 ( 100ms/33ms) worldUpdate packets to all clients per second. Each client will send same or more to server each second.

WorldUpdate message would have all the necessary object info in it, that the client needs. It could be new position and/or movement speed and direction. Client could use that to rebuild the servers view on the client side. Messages are flying so fast around, that in local server, just updating the positions and setting them without any analysis ( predictions etc ), it would still show correctly.

Networking will definitely be the **hardest** part of your project, do not underestimate that.

There's great Networking library for C# game networking called Lidgren Network. There's tutorials at internet about basic game networking with Lidgren.

Some links for networking:

1. http://en.wikibooks.org/wiki/Game\_Creation\_with\_XNA/Networking/Network\_Engines
2. Shameless plug: My blog post ( it's bit old and have not updated it )
3. http://forum.unity3d.com/threads/lidgren-tutorial.55017/
4. Lidgren wiki tutorials

---
Tags: c#, networking, game-loop, .net
---


# Question
Title: Will I lose the mesh if I delete the original prefab?
I'm working in Unity 5, and I currently have the following setup:

My project contains two prefabs which we'll call "Cube" and "CubeT". Cube was imported from an FBX file generated by Autodesk 3DS Max, and CubeT was created within Unity. I want to be able to modify Cube's mesh collider, but Unity will not allow me to do so. Therefore, I've thought about adding the mesh within Cube to CubeT and removing Cube. The thing is, I'm worried that I'll lose the mesh when I delete Cube, and subsequently lose the reference to it in CubeT.

If I reference Cube's mesh in CubeT and then remove Cube from the project by deleting the asset within Unity, what will happen? Will the needed mesh remain in the project or am I going to have to find another way?

# Answer
If I understand you correctly, you have created a model and then imported it to Unity. This model is what you call Cube and contains a mesh.

So, just check the file extension of your Cube - Unity5 shows it in the status bar at the bottom of the Project window, when you select a file. If the extension is .fbx - this is NOT a prefab at all. You will lose your mesh if you delete it. In this case keep both Cube and CubeT in the project. But, if the file extension is .prefab, then you could delete it without losing the mesh - mesh is stored in separate file.

If you want only a single file in the project, it is better to apply changes to the original model in 3DS Max and reimport it to Unity.

Editing a mesh collider isn't an option in Unity, but there are some common hints:

* You can create a compound collider for your mesh using multiple Unity's built-in colliders (cube, sphere, capsule), and, obviously, it will be completely editable inside Unity.
* Another hint is what 10001110101 suggested: create another mesh (most likely simplified), generate a collider for it. In the Hierarchy disable the mesh renderer component and use it's collider for your mesh.
> 2 votes

# Answer
The FBX file will not get deleted unless you delete it yourself. That being said, it's generally good practice to build your collision mesh (if you need something more complicated that a simple primitive), in the modeling program itself and export both meshes together. You can then link the underlying collision mesh in the FBX to the mesh collider.
> 0 votes

---
Tags: unity, models, assets
---


# Question
Title: Google Play Game Services real-time multiplayer secure game data architecture
Is it secure to allow all game clients in a multiplayer game session to store sensitive opponent player data which should be revealed in the UI only upon a certain action (e.g. enemy building type only revealed after the player has hit the building) to save network traffic? Clients could then calculate public ("visible to them") information to render on the UI on their own after the action has taken place (without the need for a response from the server providing the type of building which was destroyed in this example). Or is this approach too insecure, provided Android app data can be compromised revealing sensitive opponent information, which otherwise would only be revealed on demand while progressing through the game session?

# Answer
My personal opinion on this is that if it's a competitive game, the information should not be available on the client until it's ready to be shown to the player.

The League of Legends launcher at one time knew the names of your opponents, but displayed "Summoner 1", "Summoner 2" etc. So a few times someone said in the pre-game chat "Hey Summoner 1 is an Ahri main. Ban Ahri."

Give your players as little opportunity to cheat as possible.
> 1 votes

---
Tags: android, multiplayer, google-play, realtime
---


# Question
Title: How do i load, render and trasnform 2D images using Direct3D 11 API?
In my small game project using DirectX 11 API, I created a Direct3D device, and can draw 3D meshes, using web tutorials and a book. But I cannot figure out how to load, transform (rotate, scale, resize) and draw 2D sprites (loaded from PNG files, for example).

How can I do this?

I'd prefer to use no third-party libraries.

# Answer
> 1 votes
Please consider this first-party library; it is from MS, so if it is not-third-party enough for you, it will make your life considerably easier. It provides an interface to DX11 that is very similar to XNA. Specifically, SpriteBatch, SpriteFont, etc..

Rastertek and Reimer's are generally helpful.

For Rastertek, I linked directly to their DX11 2D tutorial, but the site is pretty comprehensive.

Reimer's is DX9 and/or XNA, but covers many concepts that you can probably adapt to DX11 yourself. The processes are usually similar.

---
Tags: c++, 2d, directx, sprites, directx11
---


# Question
Title: How to draw portion of a sprite in libGDX
Let's say i have a sprite like this:

and i want to draw the lower portion of it, only the yellow color.. Initially the sprite has dimensions 10x10, i want it to be drawn 10x3

Do i have to redimension both the sprite and the texture region to mantain proportion between the two?

# Answer
> 0 votes
The answer I gave in the other question doesn't quite do exactly what you want, but the following example might help. You still need to re-proportion both the heights to do what you want, but you also need to move the input data region down to compensate for the smaller window:

```
spriteBatch.draw(
    sprite.getTexture(),
    x,
    y,
    width / 2,
    height / 2,
    width,
    height * 0.3f,                                        /* Scale output height */
    sprite.getScaleX(),
    sprite.getScaleY(),
    0,
    sprite.getRegionX(),
    sprite.getRegionY() + sprite.getRegionWidth() * 0.7f, /* Move input data position */
    sprite.getRegionWidth(),
    (int)((float)sprite.getRegionWidth() * 0.3f),         /* Scale input height */
    false,
    false);

```

---
Tags: libgdx, sprites
---


# Question
Title: In Unity, why do my animator states wait until the end of each animation to change?
I'm trying to make a simple idle-walk transition in Animator using Unity. I've set a script that changes the Speed value from the Animator, and it works perfectly when I move the character forward when the game is on.

The transitions work well between both animations, except that they don't start automatically after the speed has changed to greater than zero.

I've found out that it waits until the animation loop gets to it's end, which makes the game feel dull and not fluid at all.

---

I don't think there's an issue with the code, but I'm attaching it anyway:

```
#pragma strict
var anim : Animator;

function Start () {
    anim = GetComponent("Animator");
}

function Update () {
    var move : float = Input.GetAxis ("Vertical");
    anim.SetFloat("Speed",move);
    transform.Rotate(0,Input.GetAxis("Horizontal"),0);
    transform.Translate(0,0,(Input.GetAxis("Vertical")*Time.deltaTime*move));
}

```

# Answer
> 4 votes
Ok just fix it:

I needed to check off the "Has Exit Time" option of every transition link in order to work fluid.

I hope it help anyone having the same issue

---
Tags: unity, animation, character, timing
---


# Question
Title: Are there any topics on Procedural Generation based on a predefined mesh?
I see a lot of post about procedural terrain generation, but this is not what I'm looking for. **I want procedural generation**, but I want to be able to **define** the **shape** of the generation based on a **predefined mesh** so that I can modify the mesh at run-time. Say I hit armor with a sword, the armor takes damage and the mesh is modified based on the sharpness of the sword, at the exact location (ex: vertices, chunks) on the armor where the sword hit.

Edit: To make the question a little less general. How would one go about modifying a predefined mesh using procedural generation. If that's too broad to introduce here, where has this been done before in games?

I've spent quite a few hours searching Google for this type of technique but its hard to find what I'm looking for as I am inexperienced in the subject.

I've looked at marching cubes and marching tetrahedrons but I'm not really sure if that's what I'm looking for. those techniques seem to send back a quality not really acceptable for a video game. Meta-balls look nice but they seem to be only suitable for liquids. And as I said earlier, random terrain generation or pseudo-random based on seeds is definitely not what I'm looking for. I need to be able to control the mesh enough to reliably create and modify objects. IE, carve a Z in your armor if at runtime

# Answer
> 0 votes
Many of such methods exist. Though typically their in mesh editing programs, such as Blender 3D. For example, the "Boolean" modifier, allows you to intersect, subtract, or add, on one mesh volume, based on another mesh volume.

Going through a modeling program, and learning how to manually do it in that program would be a good first step to doing what you want. Then figuring out how that program does it, (eg. going through the blender source code and looking through the code of the Boolean modifier.) Then actually creating your own implementation.

An example program outline might be:

1. Grab the meshfilters for the armor mesh, and the sword mesh, including object transformations, and velocity vectors.
2. Enter processing loop
    * Early out based vertex-position and vertex-normals to decide which vertices could not possibly be hit. (Eg, you don't need to process the left shoulder if the right shoulder is the one that gets hit. Just copy it over into your new "generated" mesh.)
    * Triangle intersection tests, to determine the volume being removed from the armor.
    * Continue until the entire mesh has been appropriately processed.
3. Do one of the fallowing:
    * Delete the triangles within the volume calculated by step 2, and generate new triangles to replace them based on the given information.
    * Modify the vertices within the volume calculated by step 2, based on the given information.
4. finalize the changes
5. cleanup any temporary resources

However, creating such detailed meshes can become **very** costly. Especially if you are doing that every few frames, it ties up your CPU with generating the mesh, and your GPU with having to load the data off of your RAM and process the extra vertices.

Typically what is done is a simple decal applied to the mesh. Then you only pass a few vectors to the GPU telling it where to put the "scratch" decal, and it get's done quickly.

Edit: This still isn't really a complete answer. But it's the best I could do. There would be to much information to cover for a complete explanation.

---
Tags: procedural-generation
---


# Question
Title: Optimization for Normal maps with lots of wasted space?
I'm working on level/character assets where I'm finding that I use only very little amounts of normal mapping on them, resulting in 2048x2048 textures that are mostly blue/purple. Is there any method to better optimize this, perhaps use one normal map for several assets?

# Answer
With any asset with UV coordinates, it's good practice to have parts that need more detail take up more area than parts that don't (usually, anyway). So you can have the UV coordinates for the detailed parts of your normal map scaled quite large, and the UVs for the less detailed parts scaled quite small.

You can also have two different sets of UV coordinates -- the first used to sample the diffuse texture and the second used to sample the normal map. The second UV set could be laid out to make more efficient use of the texture space based on what needs more detail.
> 5 votes

---
Tags: optimization, normal-mapping, unreal-4
---


# Question
Title: PhysicsConstraints Module not found in Blender 2.71
I am trying to export bullet from blender using python console however it raises an error while reaching to import PhysicsConstraints; The error says Module not found, Since bullet exporter and PhysicsConstraints expected to be present in Blender 2.71, Can anybody tell me what is this error about? I tried to run the script while I was in Game Engine (Someone suggested to do so in previous answers of a closed thread) But it didn't work too.

Thanks

Iman

# Answer
> 1 votes
It seems that bge module is not available while running a script in text editor or in python console with the direct command : import bge

actually there is nothing wrong with the module and there is nothing missed! only that the scripts with import bge can't be executed from console or text editor, to do so you have to add a controller to your script and press P to start game mode,Take a look at this : http://pymove3d.sudile.com/stations/blender-game-engine/a\_introduction.html

Hope this helps someone...

---
Tags: blender
---


title: MMO game made with Unity

text:
# Question
Title: MMO game made with Unity
this is my first post in stack exchange i am currently making a 2D MMO game with Unity 5 and Bolt engine for the networking

but i realized that a friend of mine has already made a Fan based game with is own server codded by himself what is the good part of making a custom server and will a bolt engine can provide me with that much performance ?

i need you help could you contact me on skype if your free ?

: sreenandhu4

# Answer
Don't get discouraged on your first, but this is a very low-quality question for this site. The "best" answers for this will be to pick one, implement it, then profile it if/when you encounter performance problems. You may be trying to solve a problem, today, that you'll never even have.

**In general:**
Using a library from someone else has the generic advantage of you not having to know how all of the guts work and/or write and debug all of the code yourself. Bolt has many users and when the author screws up a revision, there are many people to let them know exactly how. If you design your own and it doesn't work, you are out of luck.

The primary disadvantage of using third-party libraries is that after you integrate them, you must do everything "their way". You may find, later, that Bolt doesn't do everything you need and/or does some things in ways that you don't like.
> 2 votes

---
Tags: c#
---


# Question
Title: How to determine if character has fallen into the gap in an infinite runner/jumper?
I'm building a 2D infinite runner. In the game, character jumps from pillar to pillar and pillars are randomly generated. I have this working. But how to determine if the character failed to jump on to a pillar and has fallen into the gap between pillars? A pillar is ordinary rectangular in shape.

# Answer
> 20 votes
Add a rectangular region at the bottom of the level, lower than the minimum allowable height of a platform. If the player has intersected this region, they have fallen off a platform.

# Answer
> 24 votes
If your game only scrolls horizontally, you could check whether the vertical position of the character is below the lower edge of the stage.

If your game scrolls vertically as well (probably upward), you could check whether the player has fallen below the bottom edge of the view (i.e. the area of the stage that is onscreen, or in focus of the camera).

In general, the death condition is if the character fails to remain "in camera". By controlling the movement of your camera, you'll be able to tune your gameplay. For example, if in a vertical scrolling stage you only allow your camera to "rubberband" a little bit downward, while allowing full upward motion, you will penalize deep, offscreen falls.

# Answer
> 2 votes
Alternatively to checking the vertical *coordinate*, you could just check the vertical velocity. If the character is falling down faster than some threshold, conclude they're dead (even if there *is* some platform low enough to still reach, the impact would be fatal).

Of course, this only works if your game properly implements basic free-fall physics, i.e. the downwards velocity actually *increases* during the fall, as it does in reality (up until terminal velocity).

# Answer
> 1 votes
If you have height of pillars, you can find lowest existing, and compare it to vertical position of player. If he is below lowest pillar, there is no chance he can get back. You can limit this check only to pillars behind and in front of player.

Example: We have 3 pillars, with heights \[10, 20, 40\]. Player jumped is on pillar with height 40, he jumps forward to 20. He felt in gap between 40 and 20, he's now at height 15. That means he felt. For less strict check, wait till he is below 10.

# Answer
> 0 votes
Keep a count of how long a character has fallen. (i.e. how long they've been moving "down"). Once they've fallen more than a screenful of time, they by definition have fallen off the stage, yes?

---
Tags: unity
---


# Question
Title: How do I make a sprite blink on an HTML5 canvas?
I'm thinking of the flashing effect many games have when a character gets hit and takes damage. Something like overlaying a lighter color on visible sprite pixels for a second.

# Answer
The simplest way to get such an effect is to literally blink the sprite: Just don't draw it half the time.

```
var frequency = 200;
if (! blinking || Math.floor(Date.now() / frequency) % 2) {
    ctx.drawImage(...);
}

```

The idea is that when `blinking` is set to `true`, the sprite will flash at the given `frequency`.
> 5 votes

# Answer
As Maksim said about canvas pixels. You can draw your sprites in unusual way. I can share what I have been working on last week.

```
function drawImageBlended(src, sx, sy, dest, dx, dy, w, h, blendMode) {
    var srcCont = src.getContext("2d");
    var srcData = srcCont.getImageData(sx,sy,w,h);
    var sPixels = srcData.data;
    var destCont = dest.getContext("2d");
    var destData = destCont.getData(dx,dy,w,h);
    var dPixels = destData;
    var a = 0;
    for (var i = 0, il = sPixels.length; i < il; i += 4) {
        a = sPixels[i+3];
        if (a!==0) {//Skipif alpha is 0
            dPixels[i] = blend(dPixels[i], sPixels[i], blendMode, a);
            dPixels[i+1] = blend(dPixels[i+1], sPixels[i+1], blendMode, a);
            dPixels[i+2] = blend(dPixels[i+2], sPixels[i+2], blendMode, a);
        }
    }
    destCont.putImageData(destData,dx,dy);
}

function drawImageBlendedWithColor(src, sx, sy, dest, dx, dy, w, h, rgb, blendColorMode, blendMode) {//rgb = {r,g,b} each [0..255]
    var srcCont = src.getContext("2d");
    var srcData = srcCont.getImageData(sx,sy,w,h);
    var sPixels = srcData.data;
    var destCont = dest.getContext("2d");
    var destData = destCont.getData(dx,dy,w,h);
    var dPixels = destData;
    var a = 0;
    for (var i = 0, il = sPixels.length; i < il; i += 4) {
        a = sPixels[i+3];
        if (a!==0) {//Skipif alpha is 0
            dPixels[i] = blend(blend(rgb[0], dPixels[i], blendColorMode,a), sPixels[i], blendMode, a);
            dPixels[i+1] = blend(blend(rgb[1], dPixels[i+1], blendColorMode,a), sPixels[i+1], blendMode, a);
            dPixels[i+2] = blend(blend(rgb[2], dPixels[i+2], blendColorMode,a), sPixels[i+2], blendMode, a);
        }
    }
    destCont.putImageData(destData,dx,dy);
}

function overlay(a, b) { // a, b = [0..256]
    return (a < 128) ? (a*b) >> 7 : 255 - ((255-a) * (255-b) >> 7);
}

function multiply(a, b) { // a, b = [0..256]
    return a * b >> 8;
}

function screen(a, b) { // a, b = [0..256]
    return 255 - ((255 - a) * (255 - b) >> 8);
}

function blend( a, b, mode, o) { // a, b, o = [0..256]
    return a + ((mode(a, b) - a) * o >> 8);
}

```

drawImageBlended takes your sprite canvas (hope its on canvas) and destination canvas, reads every pixel in drawing boundaries and blends in your sprite canvas. If your hero is not a canvas but many sprites, think of doing its own small canvas to pre draw it on, and feed to this function. For other Blend modes visit pegtop site There you will find effective delphi code and mathematical formulas. Pretty and comfy.

I hope my untested code will work, because I just piled it up from my scratches. Yeagh, I could do something like

```
CanvasRenderingContext2DPrototype.prototype.drawImageBlended= function (src, sx, sy, dx, dy, w, h, blendMode) { var dest = this; ...}

```

But I'm not going to test it. Good luck with that.
> 0 votes

---
Tags: sprites, html5, html-canvas, graphic-effects
---


title: Image edges are distorted inside game

text:
# Question
Title: Image edges are distorted inside game
I dont know how to explain this, so I will use images to describe my problem.

The image I made using InkScape:

What it looks like in-game (ignore the runner):

As you can see the edges are not "sharp" ingame, even the static background (front-mountains and grass is scrolling) is distorted. I think you can see what I mean. What causes this? How can I fix it?

I use LibGdx to build my game, inside Android studio.

some relevant code:

```
background = new Sprite(new Texture(Gdx.files.internal("runner_background.png")));
camera = new OrthographicCamera();
viewport = new FitViewport(480, 800,camera);
viewport.apply();
camera.position.set(camera.viewportWidth / 2f, camera.viewportHeight / 2f, 0);
camera.update();

```

I draw my background like this, my RunnerScreen render method:

```
runnerWorld.update(delta);
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
camera.update();
batch.setProjectionMatrix(camera.combined);
batch.begin();
runnerWorld.render(batch);
batch.end();

```

my runnerWorld render-method:

```
public void render(SpriteBatch batch){
batch.draw(background, 0 ,0);
scroller.render(batch);
runner.render(batch);
}

```

# Answer
> 4 votes
The artifacts are caused by scaling the images using point sampling / nearest neighbourhood filtering, which effetively doubles some of the pixels from the original image.

To get better results, switch to bilinear filtering which uses weighed average of multiple pixels. The result will be a little blurry, but should look a lot better than the current one.

With libGDX I guess you can do this with setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear) for your texture object.

---
Tags: opengl, libgdx, graphics, image, png
---


# Question
Title: How do I draw a circular portion of a texture within LibGDX using an OpenGL ES shader?
What is the simplest way to implement a shader to draw a circular portion of a full screen texture where the circle is dynamically resized as part of an animation using LibGDX?

Is a shader even the best place to do this kind of thing?

I'm sure you could do this in software using a Pixmap but that would be slow. In the end I managed to get something working using the OpenGL depth buffer, a ShapeRenderer to draw a circular mask and a SpriteBatch to draw the texture but it feels messy and awkward.

# Answer
# Alpha mask texture approach

In case your circle would always be the same size, using a second **alpha mask texture** would be the way to go. You would make it a grayscale mask texture and use its value as the alpha value while drawing. Using a texture had the benefit of having anti-aliasing built into the mask (ie. at the borders of your circle, the pixels can be partially opaque, rather than either fully opaque or transparant).

---

# Fragment discarding approach

But as you mention it should be animated, this is not a possibility. A **shader approach using fragment discarding** would be to pass the circle's parameters (center position \[x,y\] and radius \[r\]) as uniforms to the shader. As you want to render a specific circular region of your texture, you would express these in terms of UVs. Then, in the frament shader, you check whether the fragment's UVs fall within the circle's boundaries (aka. if their distance to the center of the circle is larger than the radius of the circle). If so, you can discard the fragment (this means nothing will be rendered). Note that this is a binary approach; pixels get drawn or they don't get drawn, they cannot be partially opaque. This can cause jaggy edges, aka aliasing.

---

# Alpha calculation approach

To get rid of aliasing, you could adapt the previous approach. Rather than using the circle's parameters to check whether to discard the fragment, you could also use it to **calculate an alpha value**. To get rid of aliasing, you could specify to radii rather than one \[r\_inner, r\_outer\]. Everything inside the inner radius will be fully opaque and everything outside the outer radius will be fully transparant. For fragments inbetween the radii, you could apply linear interpolation. This will give you a smoother border. For example, using a 2 pixel difference between the inner and outer radius will give you a 2 pixel border around your circle where pixels smoothly transition from fully opaque to fully transparant. In short, you would calculate the alpha as (pseudocode, not actual GLSL):

```
distance = sqrt(pwr(u - circle_x, 2) +  pwr(u - circle_y, 2))
alpha = ((distance - r_inner) / (r_outer - r_inner));
clamp(0, 1, alpha)

```

---

# Generate a circle using polygons

You can also **use polygons to define the circle**. Rather than drawing your texture on a quad, draw an actual circle. Calculating the vertices of your polygons to form a circle is very simple, as you just need to use points at regular angular intervals around the center point, at the desired radius. In the same way calculate the UVs by calculating the respective points on the texture.

---

# Dynamically calculated mask

Another approach, resembling the alpha mask texture approach would be to create your **masking texture on-the-fly**. Reserve a texture for the mask, render it fully black. Draw a white circle on it. Then use this texture as an alpha mask.

---

In short, a clean approach that works for all shapes is to use an alpha mask. This is not suitable for dynamic animation however. The cleanest approach that allows for animation is to generate a circle of polygons to draw on. An good alternative is to calculate the alpha in the fragment shader.
> 5 votes

---
Tags: libgdx, shaders, opengl-es
---


# Question
Title: OpenGL Shader Storage Buffer Objects array length problem
Ok guys, I think I have a very strange problem.

I have an old laptop, but its HD 6370M currently supports opengl 4.4, so i decided to learn how to use some new features of this platform, so after glVertexAttribFormat, glVertexAttribBinding and so on, I moved to shader storage buffer objects.

I thought they were useful for things like passing light data to shaders, so I tried to make a trivial example working.

the relevant pieces of code in my program are: C++ creation of buffer

```
    struct Values
    {
        float val;
    };

    void CreateBuffers()
    {
        glGenBuffers(1, &ssbo);
        glBindBuffer(GL_SHADER_STORAGE_BUFFER, ssbo);

        Values v;
        v.val = 0.3;

        glBufferData(GL_SHADER_STORAGE_BUFFER, sizeof(Values), &v, GL_STATIC_DRAW);
        glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0);
    }

    void Render()
    {
        ...
        glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, ssbo);
        ...
    }

```

Then in the fragment shader: GLSL

```
    struct Values
    {
        float val;
    };

    layout(std430, binding = 0) buffer ssbo
    {
        Values vals[];
    };

```

And then in the main I could assign a random color to the output variable and I just see my geometry of that color, as expected:

```
    out vec4 out_color;
    void main()
    {
         out_color = vec4(0.4, 0.3, 0.6, 1); // Yeah, random
    }

```

Or if I output the value of the variable in the ssbo directly everything works just fine (I see a grayish color on my geometry)

```
    out vec4 out_color;
    void main()
    {
         out_color = vec4(vals[0].val);
    }

```

BUT, if I try to get the length of the array with

```
    vals.length();

```

in any kind of operation, like in a for loop or simply scale the output color by the length of the array, I get a completely white screen, even if the clear color is set to black, and no geometry is visible at all. It is important to say that this only happen if in the ssbo i put an array of structures.

I don't think that's relevant, but I'm using Windows 8.1 and MSVC compiler with VS13.

Thanks in advance.

**EDIT**: I want to say that no error is generated during runtime, the shaders compile successfully and the program is validated and linked

**EDIT** 2: Ok, now it seems that there is a linking error on the program where the ssbo is, but the infolog says nothing:

```
    Vertex shader(s) failed to link, fragment shader(s) failed to link.
    Vertex link error: INVALID_OPERATION.
    unexpected error.
    fragment link error: INVALID_OPERATION.
    unexpected error.

```

Driver bug?

# Answer
> 1 votes
I have the same issue, windows 8.1x64 R9290. The shader cannot read the length of a buffer. I got round this by creating another SSBO with containing the lengths of the Light array.

I don't need to do this on Nvidia or Intel chips. Another issue is that vec3 types didn't seem to work due to memory padding, so I manually pad all data as a vec4.

This somewhat *'works'*, I can access any struct in the light array, but I'm having issues with only being able to access the first element of that struct. So I can access DLights\[0\].ambient, and DLights\[3\].ambient; but not DLights\[0\].light\_dir. Again, this isn't an issue on nvidia or intel.

Here is the rough gist of my shader, hope this helps.

```
struct directional_light {
  vec4 ambient;
  vec4 light_colour;
  vec4 light_dir; // Light_dir is a vec3, padded in a vec4
};

layout(std430, binding = 1) buffer DirectionalLights { directional_light DLights[]; };

//lightNumbers.x = Number of Dlights, lightNumbers.y = Number of Plights...
layout(std430, binding = 4) buffer LightStats { vec4 lightNumbers; };

...
void main(){
  ...
  // for (int i = 0; i < DLights.length() ; i++) {
  for (int i = 0; i < lightNumbers.x; i++) {
   colour += calculate_dir(DLights[i], position, normal, view_dir, tex_colour);
  }
}

```

---
Tags: opengl, shaders, glsl
---


# Question
Title: Unity 2D - scale sprite according to screen width
So I have a square sprite (width == height) and I want to scale it so that both width and height are exactly one fifth of the width screen. To find the desired pixel width I do:
`float desiredWidthPixels = Screen.width * 0.2f;
float desiredHeightPixels = Screen.width * 0.2f;`

How do I apply these values to the sprite?

# Answer
You don't want to actually resize the sprite. What you want to do is resize the *texture* this sprite is being rendered on.

Once you get the texture you can call `Texture2D.Resize(Screen.width * 0.2f, Screen.width * 0.2f)`

If you're not sure which texture you are using, you can call `Sprite.texture` to get the texture used. If you wanted to, you could even do `Sprite.texture.Resize(width, height)`.

http://docs.unity3d.com/ScriptReference/Sprite-texture.html http://docs.unity3d.com/ScriptReference/Texture2D.Resize.html
> 1 votes

---
Tags: unity, 2d, sprites
---


title: Unity 2D Current object force

text:
# Question
Title: Unity 2D Current object force
I'm working on a game with an entity firing a shot. This shot could destroy other entities as well as the entity who generated the shot. My first step was to apply a force to the rigidbody2D of the shot, but when my entity is too fast the shot destroy it (the speed does not match).

I tried adding the speed to the force but the values mismatch by far (the force is a vector of like 150 magnitude, whereas the speed as a magnitude of 1).

I wonder how one can achieve this, to add the current speed of the entity to the shot fired, and i wonder if there's any litterature concerning the way physics is actually handled in Unity, i find very little documentation on the Physics.

Thanks.

# Answer
> 3 votes
For a one-off change of velocity, I'd recommend changing velocity yourself. So rather than applying a force to the object, try something like `rigidbody2D.velocity += shooter.velocity` after you create the shot and figure out the regular shooting velocity.

Secondly, it'd probably be best not to count on the speed difference to avoid the shooter being destroyed by its own bullet. When you create the shot, you could use Physics2D.IgnoreCollision to make it impossible for the shot to hit the entity that created it. If you *do* need the shot to hit its creator (such as with a ricochet), you could use the same function to let them hit each other again after the shot has already travelled a certain distance.

Let me know if any of that is unclear :)

---
Tags: unity, physics
---


# Question
Title: How to achieve high Level of Detail on 3D models
I'm developing a 3D space-based game which allows free movement in all directions and features planets. Currently I am using the Visual Studio content manager to import models (spheres) with 2D textures applied to them. These planets are supposed to be very large, which allows the player to come very close to their surfaces.

From afar, the textures look great. Up close, however, they become very blurred or pixelated (depending on whether I draw them with linear or point clamp).

I understand that I can enable mipmaps for the textures to change the level of detail shown at different draw distances, but obviously this can only be as high resolution as the texture files I provide it. The Visual studio content pipeline only allows Texture2D of size 2048x1024 or less and obviously I don't want to be holding enormous image files in memory for use in game.

**Should I produce a set of higher resolution tiles of small sections of the planet's texture, load them on demand and stitch them together? How would this be achieved in XNA?**

The effect I'm looking for would be similar to google maps.

It may be that in the future, I will decide that the textures being blurred or pixelated is acceptable, but since this is much a learning process for me, I'd still like to know how it would be solved.

Below is a demonstration of what I mean using a Mercator map of the Earth as an example:

# Answer
> 2 votes
# The way Google does it

The way **Google Maps** does it, is indeed by having multiple levels of detail. Moving through these levels, tiles will get smaller and smaller. Fitting a 2k texture on a tile that contains a full continent, will give you less detail than fitting a 2k texture on a tile that contains a small neighbourhood with only a few roads.

It is important to note than tiles get loaded, depending on what area you are looking at (your **region of interest**). You can't simply switch from a 2k texture to a 4k texture as the player zooms in on the planet, as you will run into memory problems very soon, due to the exponential increase in image data. Instead, you will want to draw only the segment of the sphere the player is looking at, and only load the associated textures. What is off camera should not be rendered, nor should the textures be loaded.

The problem with this approach is, that you will need an **extreme amount of textures** to get the fidelity Google Maps will offer you. If you want to be able to zoom in, all the way to street level, you need textures at that level (and all levels before), for all tiles across the entire planet. Google has this data via years of gathering satellite images, but it's infeasable to have this data available in a game.

---

# A feasible way you could do it

For that reason, I think only a **procedural approach** is viable in this case. A procedural approach means that the planet's geometry and textures get generated on-the-fly, via some mathematical formula. Techniques for this are readily available if you do a search on "terrain generation" or "procedural planet generation". This approach let's games like Spore and Destiny generate planets with detail up to surface level.

A downside is that you have **less control** over what your planet will exactly look like. For example, if you want a planet that looks exactly like earth (with bodies of water, mountians, roads, etc in the same position, you will not be able to do this in a procedural way). It is however the only feasible way to "store" an entire planet in great detail. (The key is that, rather than "storing it", you are encoding it as a set of parameters, generating actual geometry and textures on-the-fly).

Something to be aware of (as Rioki pointed out), is that textures slapped onto a sphere will not cut is. At higher levels of detail, you will need to **deform the geometry** (for example around mountains). Techniques such as displacement mapping or tessellation will help here. Procedural methods will give you this data for free however.

In short, your question is a problem of scale. A procedural approach is a very feasible approach for planet rendering in general, but I'm not sure if it fits your use case. If your use case is to render planet earth specifically, at a level of detail Google Maps offers, I'd say that's impossible as you cannot store the amount of satellite imagery that would be needed for the textures.

# Answer
> 1 votes
If you want to space game where you can get close to the planets you actually need to model the planets in a significant more realistic fashion, just using one humongous texture is not going to cut it.

Now it really depends on the level of fidelity on what you want to do. But the problem with the scale of planets, when they fill your almost your entire view, a large part of it is not visible. To maintain a decent performance you need to be able to render only the relevant bits. Also you need to account for the different materials aspects, like terrain and oceans' reflectivity. Also things like atmosphere and weather play a role in the plausibility of the planet.

There are a myriad algorithms you can try, but but you may want to look at this algorithm that extends ROAM to spheres: A Real-Time Procedural Universe, Part Two: Rendering Planetary Bodies Also here is a list of research papers on this subject.

If you want an extreme illustration of the approach, you can watch this Infinity Engine Demo

# Answer
> 0 votes
This method will save you some resources

1. create a sphere for your planet with a small height map, make your texture 2.5k for compact pixels
2. add sphere with transparency + weather around the planet.

that is the best way to fudge planets for games just ask **bungie**

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


title: Pan camera within bounds of large image

text:
# Question
Title: Pan camera within bounds of large image
I have a camera that I pan around a large image which works fine, however when I reach the end of the image I can keep panning on and on, forver. I have looked everywhere for an answer on how to prevent this but the only one I found did not use panning and I could not get it to work.

My code atm is very simple:

```
map.setPosition(-map.getWidth()/2, -map.getHeight()/2);

public boolean pan(float x, float y, float deltaX, float deltaY) {
        cam.translate(-deltaX * PAN_SPEED, deltaY * PAN_SPEED);
        cam.update();
        return true;
    }

```

My Image is very large, `4096x4096`, and my camera is `480x800`. My problem is I have no idea how to get the distance I have panned, and even if I did I dont know how to stop a pan from moving past a certain point, just setting camera position won't work because then there will be a "bounce" back.

Basically I have a rectangle inside another rectangle, and the inner rectangle should not be allowed to move outside the larger. But as I said I don't really know where to start since I can't get the panning distance.

Ex of something I've tried:

```
@Override
public boolean touchDown(float x, float y, int pointer, int button) {
    startX = x * PAN_SPEED;
    return false;
}

@Override
public boolean pan(float x, float y, float deltaX, float deltaY) {
    if(-totalX > map.getX() + cam.viewportWidth/2){
        cam.translate(-deltaX * PAN_SPEED, deltaY * PAN_SPEED);
        cam.update();
    }
    return true;
}

@Override
public boolean panStop(float x, float y, int pointer, int button) {
    endX = x* PAN_SPEED;
    totalX += endX - startX;
    System.out.println("pan: " + totalX + ", map: " + map.getX());
    return true;
}

```

This is just a test, basically I can't move anymore after I hit the left border of the image, but totalX still keeps adding up so this will not work.

EDIT: Got it to work, code below:

@Override

```
public boolean pan(float x, float y, float deltaX, float deltaY) {
        cam.translate(-deltaX, deltaY);
        keepCameraInBounds();
        cam.update();
    return true;
}

private void keepCameraInBounds () {
    OrthographicCamera c = this.cam;
    Vector3 camPos = c.position;
    float HW = c.viewportWidth / 2, HH = c.viewportHeight / 2;
    camPos.x = MathUtils.clamp(camPos.x, map.getWidth()/2 - map.getWidth() + HW, map.getWidth() - map.getWidth()/2 - HW);
    camPos.y = MathUtils.clamp(camPos.y, map.getHeight()/2 - map.getWidth() + HH, map.getHeight() - map.getHeight()/2 - HH);
}

```

# Answer
> 1 votes
I will assume you are using a DragListener or something similar to achieve the "panning" effect. This is the method I have that keeps the camera within its bounds:

```
private void keepCameraInBounds () {
        Camera c = this.getCamera();
        Vector3 camPos = c.position;
        float HW = c.viewportWidth / 2, HH = c.viewportHeight / 2;
        camPos.x = MathUtils.clamp(camPos.x, HW, mapWidth - HW);
        camPos.y = MathUtils.clamp(camPos.y, HH, mapHeight - HH);
    }

```

Essentially what this does is clamp (keep between) the camera's position to legitimate points within the map. This means from half of its viewport off the left and bottom to the right and top edges of the map (or picture; the variables `mapWidth` and `mapHeight` control the size) minues half of its viewport. You need to use halves because a camera's viewport is **centered** about its position.

As long as you call this method directly after you change its position (due to the pan) it should not move outside of its boundaries. Also, make sure the `camera.update()` call is made after you check its bounds since you might be changing its position.

---
Tags: java, libgdx, camera
---


title: Recurring stalls in SwapBuffer

text:
# Question
Title: Recurring stalls in SwapBuffer
I am currently doing measurements on a test scene implemented in OpenGL 4.5 with different "setups".

I noticed that in case I have a very high amount of FPS (1550 in this specific case), SwapBuffer does stall about every 20th frame and the frame time increases from ~0.5ms to ~1.2ms. This does ONLY happen when the FPS is above a certain threshold. I already figured out that it is not related to pre-rendered frames (i disabled pre-rendered frames in the NV control panel) and it is also not related to vsync (`wglSwapIntervalEXT(0)` is used).

Can someone tell me what might be causing this stalls/lags or wathever.

I attached two screenshots made with Nsight.

The first shows a "healthy" setup with no stalls:

While the seconds shows the setup with the stalls:

# Answer
Unfortunately these kinds of unexplained stalls can be common, and very hard to answer perfectly.

To answer the question precisely, we would have to know what is happening inside the driver during that short stall. NVidia and AMD only provide us with so much information about their driver's behaviour. Sometimes we have to make guesses.

And sometimes the behaviour of the driver isn't perfectly logical. The drivers get optimised for the kinds of use cases required by current games. That can mean that other use cases end up less efficient. Running at 1550fps isn't a normal kind of situation, so we can't expect the driver to be optimised for this case.

One thing to consider is that GPU events are desynchronised from the CPU using a FIFO queue. The queue contains rendering commands (like bind-render-target, copy-memory-to-constant-buffer, draw-indexed, etc). The CPU writes commands to the queue. And at some desynchronised time, the GPU will read those commands from the queue. We can think of it as like a producer/consumer pattern.

In some cases, the CPU might run faster than the GPU. This means the queue will get longer and longer. For very simple frames, the queue could become several frames long.

There are few API commands to control how the driver manages this queue. So the driver has freedom to limit the size of the queue (even if that means synchronising the CPU and the GPU).

I think this might be the most likely explanation... The driver has probably decided that the CPU has become too far ahead of the GPU. And so it is injecting small pauses to slow down the CPU and allow the GPU to catch up.

There are other possibilities as well... Maybe the driver is doing some defragmentation work on GPU memory? It could even be that nsight is causing the stalls (maybe doing some work managing it's profiling buffers).

If you want to explore some more, there are some tools you can try:

**GPUView** -- http://graphics.stanford.edu/~mdfisher/GPUView.html This profiles events inside the windows driver model. You can even see some of the queuing behaviour, where packets of commands get stalled waiting for GPU time.

**Profile enabled drivers** -- If you have access to developer support at nvidia or AMD, they have tools that can profile their driver code. That can give an indication of what the driver is doing.

However, my real suggestion is to try profiling a real, practical case. The behaviour of the driver code and your engine code at 1550 frames is not really that important. If you can recreate the same stalling behaviour in a practical case (eg, rendering a game scene), then that might be something that is more productive to explore.
> 7 votes

---
Tags: opengl, performance
---


# Question
Title: Why can't I access List<T> through System.Collections.Generic?
I have the following small and incomplete script, and I was wondering if anyone knew about this issue. I'm trying to access `System.Collections.Generic.List<T>`, but I keep getting the error `The name 'List' does not exist in the current context.`. I have the proper headers, but it still won't work. Here's my code for reference.

```
using UnityEngine;
using System.Collections.Generic;

/// <summary>
/// C# File for generating worlds with
/// LIMITED terrain.
/// </summary>
public class GenerateLimitedTerrain : MonoBehaviour
{
    public int positiveWorldLength;
    public int negativeWorldLength;
    public int positiveWorldHeight;
    public int negativeWorldHeight;

    public GameObject grassBlock;
    public GameObject dirtBlock;
    public GameObject stoneBlock;

    private List blockData = new List<List<GameObject>>(); // The error occurs on this at line at 'List'
}

```

# Answer
> 2 votes
It should be: `private List<List<GameObject>> blockData = new List<List<GameObject>>();`

It needs to know what kind of List the variable is.

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


# Question
Title: Calculate 3D "up" vector to align ship to an arbitrary axis
I'm writing a script to control the movement of a 3D ship in a game. Given the ship's position and the coordinates of the destination, I've successfully calculated the Yaw and Pitch necessary to aim the ship at the target.

The part I haven't figured out is Roll. In addition to the target coordinates, I'd like to specify that the ship's "up" vector be aligned on a particular axis (X, Y, Z, positive or negative). Since the target coordinates could be anywhere, the ship will never be perfectly aligned on an axis, but I'd like to calculate the "up" vector for the ship that is the closest it can get to being aligned to that axis.

Essentially, I want to rotate the ship to point at the target, and also ensure that the ship is "upright" relative to the target.

The closest I've gotten is something like this:

```
Vector3D upVector;  // The ship's normalized "up" vector
Vector3D rollVector = new Vector3D( upVector[0], upVector[1], 0 );
rollVector.Normalize();
float shipRoll = (float)Math.Acos( rollVector.Dot( new Vector3D(0, 1, 0) ) );
if ( upVector[0] < 0 ) {
    shipRoll *= -1;
}

```

This almost works, for certain axis, but not well enough. The ship rolls to approximately the right angle, but then rocks back and forth, trying to reach perfect alignment to the axis. Which is impossible given the ship's arbitrary rotation. I think I'm just not understanding it well enough.

I think what I need to do is calculate the correct vector, given the ship's rotation, and roll into that, rather than just trying to roll towards the axis itself. But how would I calculate that for an arbitrary axis?

# Answer
```
//Everything normalized
shipRight = shipForward.Cross(target.Up);
shipUp = shipForward.Cross(shipRight);

```

The cross-product is perpendicular to both vectors. For this diagram, I gave both spheres random orientations. The left view shows the steps from an arbitrary, third, perspective; I couldn't find a better alignment, so you'll have to take my word that the cross product vectors are at right angles. The right view shows the apparent alignment of the "ups" looking along shipForward.
> 1 votes

---
Tags: c#, 3d, rotation
---


title: Pixel Shaders To Create Predator Effect

text:
# Question
Title: Pixel Shaders To Create Predator Effect
I am learning shaders, and I figured I would try to use them to create sort of a predator effect. I got to the point where I rendered my level to a rendertarget and passed that to the shader file, and attempted to get the color from it. This, by my understanding, should render the player completely invisible from the code I have. I have included relevant portions of my code.

Shader Code:

```
float4x4 World;
float4x4 View;
float4x4 Projection;

sampler s0;
texture land;
sampler land_sample = sampler_state{ Texture = land; };

float4 PixelShaderFunction(float2 coords: TEXCOORD0) : COLOR0
{
    float4 color = tex2D(s0, coords);
    float4 land_color = tex2D(land_sample, coords);

    if (color.a)
        return land_color;

    return color;
}

```

Main Draw Method:

```
protected override void Draw(GameTime gameTime)
{
    //First draw the level to the land rendertarget
    GraphicsDevice.SetRenderTarget(land);
    GraphicsDevice.Clear(Color.Black);

    spriteBatch.Begin(SpriteSortMode.Immediate, null, SamplerState.PointClamp, null, null, null, camera.Transform);
    levelOne.Draw(spriteBatch, gameTime);
    spriteBatch.End();

    GraphicsDevice.SetRenderTarget(null);

    spriteBatch.Begin();

    //Draw land
    spriteBatch.Draw(land, new Vector2(0, 0), Color.White);

    spriteBatch.End();

    //Draw the player and npcs normally
    spriteBatch.Begin(SpriteSortMode.Immediate, null, SamplerState.PointClamp, null, null, null, camera.Transform);
    npcs.ForEach(n => n.Draw(spriteBatch, gameTime));

    effect.Parameters["land"].SetValue(land);
    effect.CurrentTechnique.Passes[0].Apply();
    player.Draw(spriteBatch, gameTime);

    spriteBatch.End();

    base.Draw(gameTime);
}

```

Level Draw Code:

```
public void Draw(SpriteBatch spriteBatch, GameTime gameTime)
{
    //Will cull tiles from level based on camera position later
    for (int i = 0; i < tiles.Length; i++)
    {
        for (int j = 0; j < tiles[i].Length; j++)
        {
            tiles[i][j].Draw(spriteBatch, gameTime);
        }
    }
}

```

Based on the tutorial I was following, this should replace the color in the player's sprite with that of the render target, but it does not. Furthermore, the 'level' drawn in the player's sprite is scaled down a bit.

My question is why this isn't working? Is there something I'm missing in the shader code? Also, as a beginner shader learner please try to keep your responses rather simple, or point me to a reference. Thanks! :)

# Answer
> 1 votes
```
float4 color = tex2D(s0, coords);
float4 land_color = tex2D(land_sample, coords);

```

You are sampling the "world" using the SpriteBatch quad's UV's. The blue UV's are used to sample the color-texture; the yellows are used to sample the world-texture. A Draw() parameter and/or the camera matrix is inverting the Y-axis, so it is using the bottom corner as (0,0) instead of the top, with Y increasing as you go "up".

```
UV.X = (pixelPosition.X / (TextureWidth - 1));
UV.Y = (pixelPosition.Y / (TextureHeight - 1));
UV.Y = 1.0f - UV.y; //invert Y

//I'm starting to forget XNA... (I think SpriteBatch does this for you)
//If it looks very close, but not quite...
//UV.X = ((pixelPosition.X + 0.5f) / (TextureWidth - 1)); //May also need to offset all
//UV.Y = ((pixelPosition.Y + 0.5f) / (TextureHeight - 1));//samples by one half-texel

```

**Texel-alignment:**
In case you need this, an example 2x2 texture. It also doesn't show the inverted Y, but the idea is the same; I'm willing to generate the inverted diagrams if you need additional assistance.

```
//screen-coordinates are -1:1 range
pixelPosition += 1; //move to 0:2 range
pixelPosition /= 2; //scale to 0:1 range
pixelPosition.Y = 1.0f - pixelPosition.Y; //invert Y
//for screenPosition (-1,1), pixelPosition calculates to (0,0)
UV.X = ((pixelPosition.X + 0.5f) / (TextureWidth - 1));
//UV.X = ((0 + 0.5f) / (2 - 1));
//UV.X = (0.5f / 1);
UV.Y = ((pixelPosition.Y + 0.5f) / (TextureHeight - 1));
//UV.Y = ((0 + 0.5f) / (2 - 1));
//UV.Y = (0.5f / 1);

```

---
Tags: xna, c#, shaders
---


# Question
Title: How to use TextureArray's Pre-OpenGL 4.2?
I've been using TextureArray's in my current Project; However, I have come to the problem of OpenGL 4.2 functions not being on the present Mac software when ported over. Due to only version 4.1 of OpenGL being supported.

All my problems stem from the single function. **glTexStorage3D** which is the only function not supported.

**This is how it currently works on my OpenGL 4.2 capable machine.** (and works wonderfully I might add.)

1.) I allocate the memory beforehand with glTexStorage3D.

```
glGenTextures(1, &_texture);
glBindTexture(GL_TEXTURE_2D_ARRAY, _texture);
glTexStorage3D(GL_TEXTURE_2D_ARRAY, 255, GL_RGBA8, 16, 16, _maxLayerCount);

```

2.) Then per image I would load it into the before allocated memory block with the following.

```
glTexSubImage3D(GL_TEXTURE_2D_ARRAY, 0, 0, 0, _layerCount, 16, 16, 1, GL_RGBA, GL_UNSIGNED_BYTE, image.getPixelsPtr());

```

3.) Success.

How would I go about mimicking this functionality pre OpenGL 4.2 without using Immutable Storage? Aka (glTexStorage3D).

I've tried stuffing all my images into a horizontal single image and then loading that into just glTexImage3D with no success. Am I missing something?

Additional Note: I prefer to use TextureArray's for my project in order to avoid rendering artifacts I had using a TextureAtlas. It's simplicity during shaders is also a big plus.

# Answer
Without immutable storage you can just specify a texture array using glTexImage3D.

I note that you say you've tried this but it didn't work; it would have been helpful if you had given us the code that didn't work, as you clearly have an error in it which we may have been able to help you with.

That aside, there is another way which is minimally invasive and will work for you with just a single line of code changed; from:

```
glTexStorage3D(GL_TEXTURE_2D_ARRAY, 255, GL_RGBA8, 16, 16, _maxLayerCount);

```

To:

```
glTexImage3D (GL_TEXTURE_2D_ARRAY, 0, GL_RGBA8, 16, 16,
    _maxLayerCount, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);

```

Like glTexStorage3D, glTexImage3D with a NULL *data* pointer will reserve storage for the texture, but in this case without the constraint that the texture be immutable (you'll also need to make an additional glTexImage3D call for each submip if you want to mipmap the texture).

From the documentation:

> *data* may be a null pointer. In this case texture memory is allocated to accommodate a texture of width *width*, height *height*, and depth *depth*. You can then download subtextures to initialize this texture memory.

Once you have that done you can just load the individual array slices using glTexSubImage3D in exactly the same way as you are doing so now.
> 2 votes

# Answer
Texture arrays have been part of the OpenGL core context for as long as there's been a core context; ever since OpenGL 3.0. Pretty much every desktop computer sold within the last six years will support OpenGL 3.0 or later. Ultra-mobility laptops more than three years old might be problematic, but anything more recent or more beefy than that should be completely fine. So there's how you support it under OpenGL pre-4.2; do exactly what you're already doing, as long as you have 3.0 or later.

You only need to think about alternate implementations if you're trying to support OpenGL 2.1. But even in 2.1, texture arrays were available in many drivers as an extension, so few changes might be required to your texture handling: EXT\_texture\_array.

But honestly, the differences in the rendering pipeline between OpenGL 4.x and OpenGL 2.1 are huge -- texture arrays will be the least of your problems if you're really trying to support both in a single program. Probably better off picking one or the other, and running with it.
> 1 votes

---
Tags: opengl, textures
---


# Question
Title: Are GPU physics implementations branchless?
I've implemented MPR on the CPU and in pixel shaders (long story!) and there seems to be unavoidable conditional loops both to find the starting portal as well as to find the final solution. I know that there is middleware that runs physics on the GPU though. Have they found ways to make MPR or GJK more GPU friendly, such as going branchless? Is it proprietary or published knowledge? Thanks!

# Answer
> 1 votes
GPUs can branch conditionally. It's just more expensive when not all threads in the SIMD execution follow the same path.

What will actually happen is that the pixels that break out of the loop will "disable" themselves so that when all pixels in the group are out of the loop some will have the variables from earlier loops iterations.

---
Tags: physics, gpu, gpgpu
---


title: (Fat) ray cast with MPR OR GJK?

text:
# Question
Title: (Fat) ray cast with MPR OR GJK?
I know that it's possible to see if a line segment or a swept shape (to make a "fat" line segment) intersects objects using MPR and GJK. Is it possible in those situations to find out the distance down the ray cast that the collision occurred? Thanks!!

# Answer
> 4 votes
I don't believe there's an elegant solution to that problem. It's something I put a lot of time into investigating a few years ago writing my own collision detection.

The solution I ended up using was iterative:

1. Simple (no sweeping) GJK to find the minimum distance between object A (the fat ray cast) and object B (the potential collider -- this is after culling candidates through simpler means, of course). Let's call that distance vector **D**;
2. Calculate the maximum safe distance we can move A along sweep vector **V** without intersection given D -- that was something like `D.SquareMagnitude/Dot(D, V.Normalised)`, I think. That is, if we're moving directly towards the target the result is just **|D|**, but if we're moving tangentially to the D, we get... well... divide by zero. But that's just because we'll never hit it, so you can catch that or a negative denominator before it happens and say, "No collision!"
3. If we haven't covered the whole distance we want to sweep, then a collision is still possible. Move A the distance we just calculated in step 2 along **V**. Repeat from step 1 over remaining length along **V** until we know there's no collision, or we have come within a very small range of the target (let's call that the *skin thickness*). In the latter case, it's the distance covered to get there that your fat ray cast will return.

The lack of an elegant, exact way to calculate what you're looking for is at least part of the reason most physics engines have a *skin width* or *skin thickness* parameter, defining how close you want to get to something and call it a collision.

---
Tags: physics, gpu, gpgpu
---


title: SDL pixel access very slow

text:
# Question
Title: SDL pixel access very slow
I'm using SDL and need to plot pixels one by one on the screen. When I do this, it's extremely slow. I followed the tutorial here:

http://www.programmersranch.com/2014/02/sdl2-pixel-drawing.html

Which basically said to call:

SDL\_RenderClear();

SDL\_RenderCopy();

SDL\_RenderPresent();

SDL\_UpdateTexture();

Right after I update my pixel array.

I ran a loop (which calls the above functions) to demonstrate the issue:

```
for (unsigned int i = 0; i < 128; i++)
    for (unsigned int j = 0; j < 128; j++)
        plot_pixel(j, i, 0xff); // x, y, ARGB val

```

But it runs painfully slow. Is there a better way to plot pixels with extreme speed? The whole idea of my program is to plot pixels as fast as possible, and it takes several seconds to run through that loop and plot 128\*128 pixels.

Here is the code for plot\_pixel:

```
void plot_pixel(int x, int y, int argb)
{
    pixels[y*width+x] = argb;
    SDL_UpdateTexture(texture, NULL, pixels, width * 4);
    SDL_RenderClear(renderer);
    SDL_RenderCopy(renderer, texture, NULL, NULL);
    SDL_RenderPresent(renderer);
}

```

The code works exactly like I want it to (it plots a pixel) but its painfully slow.

# Answer
You need to move all the SDL functions out of the compound for loop.

```
for
{
 for
 {
   pixels[y*width+x] = argb;
   //Updating them all at once should be fine
   //Nothing else can happen while this is running
 }
}
//Update entire array at once, then...
SDL_UpdateTexture(texture, NULL, pixels, width * 4); //Copy entire array only once
SDL_RenderClear(renderer);
SDL_RenderCopy(renderer, texture, NULL, NULL);
SDL_RenderPresent(renderer);

```
> 1 votes

---
Tags: c++, sdl, pixel, sdl2
---


# Question
Title: Can I generate collision boxes from a model file with BepuPhysics and XNA?
I am currently developing a game using BepuPhysics in XNA 4.0, and I am trying to reasonably match the in game collision Entities with the Model they are associated with.

My current workflow involves guessing what size the various segments of the model are, guessing a size and position of a box to match each segment, and throwing stuff at it to see if I'm right.

This is not an efficient process.

Is there a way to automatically generate the Entity from the Model? If not, is there some other way to speed up my workflow?

# Answer
This is very late, but just use the TriangleMesh class. In the future, I highly recommend the BEPU Forums for questions like this.
> 0 votes

---
Tags: xna, models
---


# Question
Title: JBullet - How can I make my object float on the water?
I'm trying to use JBullet for a ship PVP game.

I've got two ships which are meant to rest on the water. Obviously these ships will be colliding, but the problem I have currently is "water" collision.

Water cannot be a "solid" object, and I cannot work anything out that will allow it to have the ship resting in it without falling over or having some sort of speed dampening effect.

Also, the ships keep being launched upwards or downwards depending on the collision. The problem here is that I cannot set a weight for the ships, because if I did, they would currently be sinking into what JBullet believes to be nothingness.

How would I simulate water in this collision world?

# Answer
Do some manual tracing to determine where in the water the ship is... it could be as simple as checking the Y or Z coordinate being below 0 if your world is all water with the water table at level 0.

Anyway, if the ship is in water, every timestep, push it upward with a force/impulse. The deeper in the water it is, the stronger the push. This should work pretty well, once you get the force levels worked out, it should quickly find a balance point - perhaps with a bit of bobbing as your push-up code and gravity fight each other a microbit, but it should be small enough to not be a problem.
> 3 votes

---
Tags: java, lwjgl
---