# Question
Title: How do I simplify a 2D game grid for level management while keeping its by-pixel features?
(I cross-posted this from StackOverflow as this seems to be a more appropriate f̶o̶r̶u̶m̶ community. I've looked around a little here and I did not find an answer, so I hope this is not a recurring question.)

This is a question dealing with 2D world design.

I am playing around by creating a 2D bird's eye view shooter game, and I am looking to make the game sleek and advanced. I hope to be able to write physics so projectiles have momentum and knock-down properties.

I am immediately running into the problem of world design.

I need a way to have level files that store everything there is about a game. This is easiest by just having a grid of objects. But there are thin-walls and other objects that don't seem to fit into a traditional cell of a grid. I want to be able to fit all these together so I can streamline level design; so I don't have to put in the exact pixel-specific start and end of a wall.

There doesn't seem to be an obvious translation from level file to game without forcing myself into a pacman-life scenario, meaning a scenario where the game feels boxy and discrete. There is a contrast between the smoothly (relatively) moving characters and finite jumps in a grid.

I would appreciate an answer that would describe implementation options or point me to resources that do. I would also appreciate references to sites that teach game design.

The language I am using is Java (although I would love to use C or C++, but I can never find convenient resources in those languages).

Thank you for any answers. Please leave any questions in the space below; I will be able to answer them later tonight (28th Nov).

**Answering Questions:**

I will definitely consider using a game engine; I wanted to write a lot of it myself, but I am rethinking gradually.

Perhaps there is no answer to this question that I will "like", and the process is just inherently a bit tedious.

I meant to find a way to easily specify things like "wall goes here" without saying "add wall at 293, 195 with width 123 and height 5". This of course, is easy by dividing the game world into a grid. But dividing a gameworld into a grid is not ideal, because it has to deal with things like objects taking up more than one grid, objects being irregularly shaped and taking up only part of the grid, etc..

I've had more time to think about this, and I think that there is no way to "gridify" my world without losing some major functionality, and so I think I will have to create a world editor, where I can more easily create levels.

I still foresee problems though, specifically with AI. I need to have pathfinding capabilities, and so the algorithms naturally have some sort of search-space reduction, which is essentially making a grid. I will have to read more about this.

Until then I would still appreciate answers and suggestions on this design choice. I hope this clarifies my question - if it does not, please direct a question and I can try to answer it.

(Storing object locations is the only practical way to do any of this, I now realize).

# Answer
> (Storing object locations is the only practical way to do any of this, I now realize).

That says everything. Store your objects location by-pixel or using floats in your level file.

Now if you need a grid layout for something else (for instance pathfinding), you'll have to use some kind of approximation. E.g. consider a square occupied if there's at least one object inside. Or if *some kind* of object is inside.

You could also forget completely the idea of using a discrete grid, and go for another technique, e.g. waypoints or a navmesh for pathfinding.
> 1 votes

---
Tags: game-design, level-design, data-structure
---


title: Questions for QueryAABB

text:
# Question
Title: Questions for QueryAABB
I'm currently having trouble getting my head around QueryAABB, and hope to find some answers here.

* The LowerBound of an AABB the upper-left corner (and vice versa). Why is that and what idea is behind that?
* When exactly does an object count as inside the AABB and is therefor found by a query?

# Answer
The idea is that you only need 2 points to define the Rectangle you will use in your AABB query. Draw point A and point B on a piece of paper. You can easily create a rectangle based on only these two points.

When an object is contained inside this rectangle, partially or fully, it will be returned as part of your AABB query. The trick is to store your objects in such a way that your query will run extremely fast, using techniques such as space partitioning.
> 0 votes

---
Tags: javascript, box2d
---


title: C# in vedio game industry?

text:
# Question
Title: C# in vedio game industry?
Other than Indie game development, C# is also used for in house tool development at large studios.

I have two questions -:

1) Is microsoft planning to release a native C# compiler sharing the backend code generator with the C++ compiler? http://www.compilerjobs.com/db/jobs\_view.php?editid1=648

2) If microsoft IS planning a native C# compiler, then can C# replace C++ as the industry standard in AAA vedio games?

# Answer
> 0 votes
1) Who knows?

2) Even if they do release such a thing (unlikely), it still would generate far less efficient code than pure C++, because it includes many safeguards, generalizations, etc. you can't just optimize out, because code might depend on them. Also you most likely wouldn't gain any significant performance boost, because what you describe is essentially what is done at runtime anyway (to some extend).

# Answer
> 5 votes
1) Regardless of whether or not Microsoft is planning to, Mono already has an "Ahead of Time" (AOT) compilation option, converting C# to native code at compile time. Both Mono and Microsoft's implementation will JIT-compile C# to native code at runtime as well.

2) C# is already being used in AAA titles such as The Sims 3, including on consoles. C# is unlikely to outright "replace" C++: There's no practical reason to throw out existing codebases if they work well to rewrite them in C#. There's still plenty of C floating around which hasn't been replaced with C++ to this day, and a lot of C with a minor splattering of C++ as existing code has been updated and modernized as needed, rather than replaced wholesale.

tl;dr: C# is viable to use today in AAA titles, but languages replace each other at a glacial pace which is quite difficult to predict or speculate on in a worthwhile manner.

If you're interested in mono or ahead-of-time compilation, I recommended reading: http://tirania.org/slides/AltDevConf-2012-Mono.pdf

---
Tags: c++, c#
---


# Question
Title: XNA Sprite Clipping Incorrectly During Rotation
I'm having a bit of trouble getting my sprites in XNA to draw when near the edge of the screen.

Seemingly if you use SpriteBatch to draw then XNA will not draw it if for example (mPosition.X + mSpriteTexture.Width \< 0) as it assumes it is offscreen.

However, it seems to make this decision before it applies a rotation. This rotation can mean that, even though (mPosition.X + mSpriteTexture.Width \< 0), some of the sprite is still visible on screen.

EDIT: The rotation being a part of the problem is only a hypothesis but to clarify, as the sprite moves towards the edge of the screen at a steady rate (applying a small constant velocity) it will suddenly disappear when it is still partially (usually about half of the sprite) on screen.

My question is, is there a way to get it to draw further outside the viewport or temporarily disable sprite clipping during a certain spriteBatch.draw(...)?

```
sb.Draw(mSpriteTexture, mPosition,
                new Rectangle(0, 0, mSpriteTexture.Width, mSpriteTexture.Height),
                Color.White, Globals.VectorToAngle(mOrientation), new      Vector2(halfWidth, halfHeight), scale, SpriteEffects.None, 0);

```

# Answer
Turns out I was well off the mark, the mPosition variable I used was a part of a translation to do a wrap-around on-screen. When doing a wraparound with the sprites drawn at their centres it is necessary to include the halfWidth and halfHeight of the sprite when calculating wraparound. Final wraparound code looks as follows

```
            if (mTranslation.X > (Globals.Universe.X - halfWidth)) mTranslation.X -= Globals.Universe.X;
            else if (mTranslation.X < -halfWidth) mTranslation.X += Globals.Universe.X;
            if (mTranslation.Y > (Globals.Universe.Y - halfHeight)) mTranslation.Y -= Globals.Universe.Y;
            else if (mTranslation.Y < -halfHeight) mTranslation.Y += Globals.Universe.Y;
            mPosition = mTranslation;

```
> 0 votes

# Answer
I don't think you assertion that the sprite is clipped is true. I've just tested the following code, which draws part of the sprite after rotation of 7/8's of a circle

```
   protected override void Draw(GameTime gameTime)
    {
        float rotation = (float)MathHelper.TwoPi * 7.0f / 8.0f;
        Vector2 mPosition = new Vector2(-(mSpriteTexture.Width + 1), 100);

        GraphicsDevice.Clear(Color.CornflowerBlue);
        spriteBatch.Begin();
        spriteBatch.Draw(mSpriteTexture, mPosition, null, Color.White, rotation, Vector2.Zero, 1, SpriteEffects.None, 0);
        spriteBatch.End();
        // TODO: Add your drawing code here

        base.Draw(gameTime);
    }

```

As you can see, `mPosition.X + mSpriteTexture.Width < 0` is true in this case.

In your code, it looks like you are setting sprite origin to be;

```
new Vector2(mSpriteTexture.Width / 2, mSpriteTexture.Width/2)

```

Which has the effect of moving the sprite to the left of mPosition by `mSpriteTexture.Width / 2`, so maybe the sprite is a bit further 'offscreen' than you initially thought.
> 2 votes

---
Tags: xna, c#, spritebatch, culling, clipping
---


# Question
Title: Computer Games Technolgy or Software Engineering?
I'm in the last year of my college and going to university next year. Could you tell me what the difference between Software Engineering and Computer Games Technology is?

I know a bit of both but don't know the actual difference. I'm kind off in a dilemma between these two. I want to be a programmer, I'd love to go into gaming but I heard getting a job within a computer games company is really hard.

# Answer
At my school we have both a Software Engineering (SE) programme and Games Development(GD) programme(which focuses on game programming & technology). Both are 4 year bachelor degrees(B.Sc).

Both programmes have a lot in common, stuff that every programmer should know

* programming
* s/w engineering
* computer architecture-
* data structures
* some DB
* some networking
* some general math

The SE programme then has modules which are applicable for general purpose software development

* Operating systems
* systems analysis
* more networking
* computer science
* software quality
* databases
* more software engineering

The GD programme focus more on topics of particular interest to game programmers;

* graphics programming
* some AI for games
* physics & simulations
* maths for graphics
* animation
* on-line gaming
* HCI
* internships with game companies

These aren't exhaustive lists, they just show the intent of both programmes.

The technologies used over the 4 years also reflect the direction of the two programmes

SE= java, c++, c#, .NET, prolog, linux

GD= XNA, c++, opengl, havok, ogre3d, a little python & javascript.

The GD graduates have enough programming and s/w engineering skills to get work as general software engineers and developers, and they regularly do. A GD degree is no guarantee that you will get a coding job in a games company, a good portfolio is also required and the development of a portfolio is supported and encouraged in the structure of the GD programme.

A lot of people sign up for the GD program thinking (without reading the prospectus carefully) that the course is about gameplay, art work, game mechanics, level design, story telling, you know, all the 'fun' stuff. The get a reality check in the first week, when they have lectures in c#, linear algebra & line drawing algorithms (this is fun stuff for me!).
> 6 votes

# Answer
Having done both courses, Bachelors in Information Technology (more like SE) and Masters in Computer Games Technology, I find the difference in curriculum is profound. Just like what Ken had mentioned, SE covered topics that were close to designing software and how the systems worked, while CGT was geared more towards SE for Games. If you're looking for a career in games, CGT would be the way to go as you get to learn (in a concentrated manner) the stuff required for games. It would also give you a better chance at getting a job in the games industry. I say better because it's not necessarily the degree that decides if you get the job or not. But when it comes to game development basics, you'd already be well-versed at how things fit together in game, while a SE student will have to go through the extra learning curve and learn graphics/AI/physics for games on his/her own to prove their worth to game companies.

I should warn you about the downside though. As good as the game industry sounds, it doesn't always provide a lucrative career. For those who've settled themselves in a well-paid job in games industry, two words, WELL DONE! You're living the dream! But it's not an easy task. You've to work your mind off to prove your worth before they even consider to keep you in the company. And typically, you'd first end up working in a start-up (or self-found) game company, which doesn't provide you *any* form of job security and with basic salary. Trying for a big-shot company usually ends up with them telling you that you don't have enough experience. Not only that, if you do manage to get through to a big-shot company, they usually don't pay you as much as what you'd earn as a Software Engineer.

With that warning, if it's your dream to be working for a game company, GO FOR IT! But beware of what is to come and be prepared for it. In the end, when all your hardwork pays off, it's the sweetest achievement of your life.

If however, you're not sure if you'd like a lifelong career in games industry but still like to dabble on the idea of working with one, I would suggest first taking up an SE Bachelors degree, try to get internship in a games company based on your degree and progress your career from there. Failing to find any, you could go for Masters in CGT and try for a game company after that. If all fails, you'd still be able to get into software companies based on your Bachelors degree and the fact that you've got a Masters degree related to CS (they don't usually care if it's CGT or not) as long as you can prove your worth.
> 1 votes

# Answer
I dont know the real diffrence between them as i never did any of thos. But i do know that you will be employeed as an Software Engineer at game companys. Or some similar title.

And it´s not hard to get a job, not if you are good at what you do. But you are going to spend alot of time trying to learn stuff, and i mean alot of time. Game development is like an game itself, you try to compete with the other companys at making better tech, beter games and to outsell them, and to do that you need to stay ahead of everything. And That is going to force you to work huge amounts of time. Since every one else dose that.

So my best advice, go with what you want to do. And see how it works out.
> 0 votes

---
Tags: software-engineering
---


# Question
Title: Ray Tracing Shadows in deferred rendering
Recently I have programmed a raytracer for fun and found it beutifully simple how shadows are created compared to a rasterizer. Now, I couldn't help but I think if it would be possible to implement somthing similar for ray tracing of shadows in a deferred renderer. The way I though this could work is after drawing to the gbuffer, in a separate pass and for each pixel to calculate rays to the lights and draw them as lines of unique color together with the geometry (with color 0). The lines will be cut-off if there is occlusion and this fact could be used in a fragment shader to calculate which rays are occluded.

I guess there must be something I'm missing, for example I'm not sure how the fragment shader could save the occlusion results for each ray so that they are available for pixel at the ray's origin. Has this method been tried before, is it possible to implement it as I described and if yes what would be the drawbacks in performance of calculating shadows this way?

# Answer
The point of deferred shading is ambient occlusion samples *a small* number of pixels surrounding each pixel in the depth buffer. That's what makes it fast and real-time.

If you're talking about ray-casting in the deferred shader, you're significantly increasing the cost of deferred shading.

If you're ray-casting in the GPU to figure out your deferred shading shadowing, you may as well raytrace the entire scene.
> 0 votes

---
Tags: shadows, deferred-rendering, raytracing
---


# Question
Title: Web application interacts bi-directional with server program?
I want to write a web application to play chess against the engine Crafty. I'm not new to PHP and javascript, but must learn how to interact with a server process : how can a web application and/or (jQuery) ajax interact bi-directionally with a (linux) program running on the server?

At this moment i am developing on (Apache) local host. Crafty is installed on my Ubuntu PC. This well-known chess engine has no GUI, it runs in terminal by the command

```
$ /usr/games/crafty

```

and so you can play chess against it and even see it's calculations. I can make Crafty run by PHP, using the functions proc\_open() or exec(), and most documentation i found states that the output stream should be a file .. But i think i don't want such setup, because then the webpage should be constanty polling that file (eg. by ajax) to see if some new data was appended, right?

How can Crafty talk to the web page directly, saying "i have calculated another variation" or "i have decided a move" etc, then display this info on the web page and let the user give some counter move, just like in terminal. Isn't it possible to use some session / stream / listener?

I have no clue at all, can anybody point me in a right direction?

# Answer
> 6 votes
1) giving JS end-users direct access to your terminal is the scariest idea ever, in terms of security, and is 100% impossible without some interfacing server language/framework (php/perl/ruby/c#/python/java/c++/NodeJS), because it is so scary.

2) running `exec()` on user-input, directly, rather than building an interface in your server language is 100% as scary as giving them access to Apache itself.

3) what you want to do is build out a simple facade/proxy/whatever in your language, for playing the game. That proxy should take user-input and decide what the user wanted to do (what piece is moving where), and based on those parameters, feed Crafty hard-coded or php-generated parameters (and not the direct-input).

This allows safety, first, but also allows you to build your communication strings any way you want, as long as the php and client agree on format.

4) on compatible browsers, you can run websockets -- the standard is volatile right now, but there are some libraries out there which can swap between websocket, flash and old-school XMLHttpRequests ("AJAX").

For a 100% native, backwards-compatible experience, just use AJAX, and poll the server either on a user-move or asking for Crafty's update.

In fact, if the user goes first, every time, then you can just respond to their request with Crafty's next move.

Next -- cheating:

Don't update the game based on what the user sends you, take what the user sends you and validate that the unit at that position (according to the server) is allowed to move in that fashion, and if not, return an error or exception which the client machine then has to deal with (reverting the move, showing an error, and making the player move again)

I should probably add that if Crafty has a decent error-handling output (eg: it outputs what was moved where and why it's wrong, in a consistent format), then your PHP interface can lean on that to handle validation.
PHP would then figure out what the user *meant* to do, based on the input parameters, feed a prepared statement into Crafty, and read the result -- if the result succeeded, then get Crafty's turn and feed it back to the player's response, in the format you built for communicating between client and server. If it failed, then figure out why, and send that back to the client in an agreed-upon fashion (agreed via PHP and JS), so that your client-side app can handle the error and reset the player's turn.

Oh. Also, if you're looking to allow multiple users to play against the same instance of Crafty, or multiple instances of Crafty, or whatever, then I'd suggest a data-storage format, where you can store instances of the game-state by session-id, or by REST-based client-id, or whatever.
JSON could be seriously lightweight for that, in this case.

I won't tell you HOW to structure these things, but from a "don't hack my server and delete my c:/ drive" and a "don't move three times in a row, or teleport your queen to an insta-checkmate, or move any of MY pieces, instead of yours" standpoint, these are the key points you need to address.

# Answer
> 2 votes
with newer browsers you can use WebSockets, but since you probably don't want to build it all by yourself, checkout http://www.jmesnil.net/stomp-websocket/doc/

stomp is supported by php aswell, so its quite easy to push messages to the queue: http://php.net/manual/de/book.stomp.php

---
Tags: php, linux, ajax
---


# Question
Title: Spritebatch drawing sprite with jagged borders
Alright, I've been on the making of a sprite class and a sprite sheet manager, but have come across this problem. Pretty much, the project is acting like so; for example:

Let's take this .png image, with a transparent background. Note how it has alpha-transparent pixels around it in the lineart.

Now, in the latter link's image, in the left (with CornflowerBlue background) it is shown the image drawn in another project (let's call it "Project1") with a simpler sprite class - there, it works. The right (with Purple background for differentiating) shows it drawn with a different class in "Project2" - where the problem manifests itself.

This is the Sprite class of Project1:

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;

namespace WindowsGame2
{
    class Sprite
    {
        Vector2 pos = new Vector2(0, 0);
        Texture2D image;

        Rectangle size;
        float scale = 1.0f;

        // ---

        public float X
        {
            get
            {
                return pos.X;
            }
            set
            {
                pos.X = value;
            }
        }

        public float Y
        {
            get
            {
                return pos.Y;
            }
            set
            {
                pos.Y = value;
            }
        }

        public float Width
        {
            get
            {
                return size.Width;
            }
        }

        public float Height
        {
            get
            {
                return size.Height;
            }
        }

        public float Scale
        {
            get
            {
                return scale;
            }
            set
            {
                if (value < 0) value = 0;
                scale = value;

                if (image != null)
                {
                    size.Width = (int)(image.Width * scale);
                    size.Height = (int)(image.Height * scale);
                }
            }
        }

        // ---

        public void Load(ContentManager Man, string filename)
        {
            image = Man.Load<Texture2D>(filename);

            size = new Rectangle(
                0, 0,
                (int)(image.Width * scale), (int)(image.Height * scale)
            );
        }

        public void Become(Texture2D frame)
        {
            image = frame;

            size = new Rectangle(
                0, 0,
                (int)(image.Width * scale), (int)(image.Height * scale)
            );
        }

        public void Draw(SpriteBatch Desenhista)
        {
            // Desenhista.Draw(image, pos, Color.White);
            Desenhista.Draw(
                image, pos,
                new Rectangle(
                    0, 0,
                    image.Width, image.Height
                ),
                Color.White,
                0.0f,
                Vector2.Zero,
                scale,
                SpriteEffects.None, 0
            );
        }
    }
}

```

And this is the code in Project2, a rewritten, pretty much, version of the previous class. In this one I added sprite sheet managing and, in particular, removed Load and Become, to allow for static resources and only actual Sprites to be instantiated.

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;

namespace Mobby_s_Adventure
{
    // Actually, I might desconsider this, and instead use static AnimationLocation[] and instanciated ID and Frame;

    // For determining the starting frame of an animation in a sheet and being able to iterate through
    // the Rectangles vector of the Sheet;
    class AnimationLocation
    {
        public int Location;
        public int FrameCount;

        // ---

        public AnimationLocation(int StartingRow, int StartingColumn, int SheetWidth, int NumberOfFrames)
        {
            Location = (StartingRow * SheetWidth) + StartingColumn;
            FrameCount = NumberOfFrames;
        }

        public AnimationLocation(int PositionInSheet, int NumberOfFrames)
        {
            Location = PositionInSheet;
            FrameCount = NumberOfFrames;
        }

        public static int CalculatePosition(int StartingRow, int StartingColumn, SheetManager Sheet)
        {
            return ((StartingRow * Sheet.Width) + StartingColumn);
        }
    }

    class Sprite
    {
        // The general stuff;
        protected SheetManager Sheet;

        protected Vector2 Position;
        public Vector2 Axis;

        protected Color _Tint;

        public float Angle;
        public float Scale;

        protected SpriteEffects _Effect;

        // ---

        // protected AnimationManager Animation;

        // For managing the animations;
        protected AnimationLocation[] Animation;

        public int AnimationID;
        protected int Frame;

        // ---

        // Properties for easy accessing of the position of the sprite;
        public float X
        {
            get { return Position.X; }
            set { Position.X = Axis.X + value; }
        }

        public float Y
        {
            get { return Position.Y; }
            set { Position.Y = Axis.Y + value; }
        }

        // ---

        // Properties for knowing the size of the sprite's frames
        public float Width
        {
            get { return Sheet.FrameWidth * Scale; }
        }

        public float Height
        {
            get { return Sheet.FrameHeight * Scale; }
        }

        // ---

        // Properties for more stuff;
        public Color Tint
        {
            set { _Tint = value; }
        }

        public SpriteEffects Effect
        {
            set { _Effect = value; }
        }

        public int FrameID
        {
            get { return Frame; }
            set
            {
                if (value >= (Animation[AnimationID].FrameCount)) value = 0;
                Frame = value;
            }
        }

        // ---

        // The only things that will be constantly modified will be AnimationID and FrameID, anything else only
        // occasionally;

        public Sprite(SheetManager SpriteSheet, AnimationLocation[] Animations, Vector2 Location, Nullable<Vector2> Origin = null)
        {
            // Assign the sprite's sprite sheet;
            // (Passed by reference! To allow STATIC sheets!)
            Sheet = SpriteSheet;

            // Define the animations that the sprite has available;
            // (Passed by reference! To allow STATIC animation boundaries!)
            Animation = Animations;

            // Defaulting some numerical values;
            Angle = 0.0f;
            Scale = 1.0f;

            _Tint = Color.White;
            _Effect = SpriteEffects.None;

            // If the user wants a default Axis, it is set in the middle of the frame;
            if (Origin != null) Axis = Origin.Value;
            else Axis = new Vector2(
                Sheet.FrameWidth / 2,
                Sheet.FrameHeight / 2
            );

            // Now that we have the axis, we can set the position with no worries;
            X = Location.X;
            Y = Location.Y;
        }

        // Simply put, draw the sprite with all its characteristics;
        public void Draw(SpriteBatch Drafter)
        {
            Drafter.Draw(
                 Sheet.Texture,
                 Position,
                 Sheet.Rectangles[Animation[AnimationID].Location + FrameID], // Find the rectangle which frames the wanted image;
                 _Tint,
                 Angle,
                 Axis,
                 Scale,
                 _Effect,
                 0.0f
             );
        }
    }
}

```

And, in any case, this is the SheetManager class found in the previous code:

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;

namespace Mobby_s_Adventure
{
    class SheetManager {
        protected Texture2D SpriteSheet; // For storing the sprite sheet;

        // Number of rows and frames in each row in the SpriteSheet;
        protected int NumberOfRows;
        protected int NumberOfColumns;

        // Size of a single frame;
        protected int _FrameWidth;
        protected int _FrameHeight;

        public Rectangle[] Rectangles; // For storing each frame;

        // ---

        public int Width {
            get { return NumberOfColumns; }
        }

        public int Height {
            get { return NumberOfRows; }
        }

        // ---

        public int FrameWidth {
            get { return _FrameWidth; }
        }

        public int FrameHeight {
            get { return _FrameHeight; }
        }

        // ---

        public Texture2D Texture {
            get { return SpriteSheet; }
        }

        // ---

        public SheetManager (Texture2D Texture, int Rows, int FramesInEachRow) {
            // Normal assigning
            SpriteSheet = Texture;

            NumberOfRows = Rows;
            NumberOfColumns = FramesInEachRow;

            _FrameHeight = Texture.Height / NumberOfRows;
            _FrameWidth = Texture.Width / NumberOfColumns;

            // Framing everything
            Rectangles = new Rectangle[NumberOfRows * NumberOfColumns];

            int ID = 0;
            for (int i = 0; i < NumberOfRows; i++) {
                for (int j = 0; j < NumberOfColumns; j++) {

                    Rectangles[ID] = new Rectangle (
                        _FrameWidth * j, _FrameHeight * i,
                        _FrameWidth, _FrameHeight
                    );

                    ID++;
                }
            }
        }

        public SheetManager (Texture2D Texture, int NumberOfFrames): this(Texture, 1, NumberOfFrames)
        {   }
    }
}

```

For even more comprehending, if needed, here is how the main code looks like (it's just messing with the class' capacities, nothing actually; the result is a disembodied feet walking in place animation on the top-left of the screen and a static axe nearby):

```
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

using System.Threading;

namespace Mobby_s_Adventure
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {

        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        static List<Sprite> ToDraw;

        static Texture2D AxeSheet;
        static Texture2D FeetSheet;

        static SheetManager Axe;
        static Sprite Jojora;
        static AnimationLocation[] Hack = new AnimationLocation[1];

        static SheetManager Feet;
        static Sprite Mutoh;
        static AnimationLocation[] FeetAnimations = new AnimationLocation[2];

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";

            this.TargetElapsedTime = TimeSpan.FromMilliseconds(100);
            this.IsFixedTimeStep = true;
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            // Loading logic
            ToDraw = new List<Sprite>();

            AxeSheet = Content.Load<Texture2D>("Sheet");
            FeetSheet = Content.Load<Texture2D>("Feet Sheet");

            Axe = new SheetManager(AxeSheet, 1);
            Hack[0] = new AnimationLocation(0, 1);
            Jojora = new Sprite(Axe, Hack, new Vector2(100, 100), new Vector2(5, 55));

            Jojora.AnimationID = 0;
            Jojora.FrameID = 0;

            Feet = new SheetManager(FeetSheet, 8);
            FeetAnimations[0] = new AnimationLocation(1, 7);
            FeetAnimations[1] = new AnimationLocation(0, 1);
            Mutoh = new Sprite(Feet, FeetAnimations, new Vector2(0, 0));

            Mutoh.AnimationID = 0;
            Mutoh.FrameID = 0;
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            // Update logic
            Mutoh.FrameID++;
            ToDraw.Add(Mutoh);

            ToDraw.Add(Jojora);

            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.Purple);

            // Drawing logic
            spriteBatch.Begin();
            foreach (Sprite Element in ToDraw)
            {
                Element.Draw(spriteBatch);
            }
            spriteBatch.Draw(Content.Load<Texture2D>("Sheet"), new Rectangle(50, 50, 55, 60), Color.White);
            spriteBatch.End();

            base.Draw(gameTime);
        }
    }
}

```

Please help me find out what I'm overlooking!

---

One thing that I have noticed and could aid is that, if inserted the equivalent of this code

```
spriteBatch.Draw(
    Content.Load<Texture2D>("Image Location"),
    new Rectangle(X, Y, images width, height),
    Color.White
);

```

in Project2's Draw(GameTime) of the main loop, it works.

---

**EDIT**

Ok, even if the matter remains unsolved, I have made some more progress!

As you see, I managed to get the two kinds of rendering in the same project (the aforementioned Project2, with the more complex Sprite class).

This was achieved by adding the following code to Draw(GameTime):

```
    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.Purple);

        // Drawing logic
        spriteBatch.Begin();
        foreach (Sprite Element in ToDraw)
        {
            Element.Draw(spriteBatch);
        }

        // Starting here
        spriteBatch.Draw(
            Axe.Texture,
            new Vector2(65, 100),
            new Rectangle (
                0, 0,
                Axe.FrameWidth, Axe.FrameHeight
            ),
            Color.White,
            0.0f,
            new Vector2(0, 0),
            1.0f,
            SpriteEffects.None,
            0.0f
        );
        // Ending here

        spriteBatch.End();

        base.Draw(gameTime);
    }

```

(Supposing that Axe is the SheetManager containing the texture, sorry if the "jargons" of my code confuse you :s)

Thus, I have noticed that the problem is within the Sprite class. But I only get more clueless, because even after modifying its Draw function to this:

```
    public void Draw(SpriteBatch Drafter)
    {
        /*Drafter.Draw(
             Sheet.Texture,
             Position,
             Sheet.Rectangles[Animation[AnimationID].Location + FrameID], // Find the rectangle which frames the wanted image;
             _Tint,
             Angle,
             Axis,
             Scale,
             _Effect,
             0.0f
         );*/

        Drafter.Draw(
            Sheet.Texture, Position,
            new Rectangle(
                0, 0,
                Sheet.FrameWidth, Sheet.FrameHeight
            ),
            Color.White,
            0.0f,
            Vector2.Zero,
            Scale,
            SpriteEffects.None, 0
        );
    }

```

to make it as simple as the patch of code that works, it still draws the sprite jaggedly!

# Answer
> 1 votes
How silly of me!

This was only happening because at Draw(GameTime)

```
protected override void Draw(GameTime gameTime)
{
    GraphicsDevice.Clear(Color.Purple);

    // Drawing logic
    spriteBatch.Begin();

    foreach (Sprite Element in ToDraw)
    {
        Element.Draw(spriteBatch);
    }

    spriteBatch.End();

    base.Draw(gameTime);
}

```

I forgot to the clear the sprite list after everything had been drawn!

```
protected override void Draw(GameTime gameTime)
{
    GraphicsDevice.Clear(Color.Purple);

    // Drawing logic
    spriteBatch.Begin();

    foreach (Sprite Element in ToDraw)
        {
        Element.Draw(spriteBatch);
    }

    // Alright!
    ToDraw.Clear();

    spriteBatch.End();

    base.Draw(gameTime);
}

```

Oh, these small things that happen while programming.

---
Tags: xna, c#, textures, sprites
---


title: Alpha From PNGs Butchered

text:
# Question
Title: Alpha From PNGs Butchered
I have a pretty vanilla Monogame game. I'm using PNG for all my sprites (made in Photoshop). I noticed that XNA is butchering the aliasing; no matter what I do, my graphics appear jaggedy.

Below is a screenshot. The bottom half is what XNA shows me when I zoom in 2X using a `Matrix` on my `GraphicsDevice` (to make the effect more obvious). The top is when I pasted the same sprites from Photoshop and scaled them to 200%.

Note that partially transparent pixels are turning whiteish.

Is there a way to fix this? What am I doing wrong?

Here's the relevant call to draw to the `SpriteBatch`:

```
spriteBatch.Draw(this.texture, this.positionVector, null, Color.White, this.Angle, this.originVector, 1f, SpriteEffects.None, 0f);

```

(`this.positionVector` can easily be `Vector.Zero`; `Color.White` as 100% alpha, I think; `this.Angle` can be a real angle (small `>` in the image) or zero (the orb itself).

# Answer
Ensure you're enabling blending in your `SpriteBatch.Begin()` call. I think for PNGs, `BlendState.NonPremultiplied` is probably the one you want.
> 1 votes

---
Tags: xna, antialiasing, monogame
---


# Question
Title: Which open source licenses can address these concerns for an open source game engine?
I am on a team that is looking to open source an engine we are building. It's intended as an engine for Online RPG style games. We're writing it to work on both desktops and android platforms.

I've been over to the OSI http://opensource.org/licenses/category to check out the most common licenses. However, this will be my first time going into an open source project and I wanted to know if the community had some insight into which licenses might be best suited.

**Key licensing concerns**:

* Removing or limiting our liability (most already seem to cover this, but stating for completeness).
* We want other developers to be able to take part or all of our project and use it in their own projects with proper accreditation to our project.
* Licensing should not hinder someone's ability to quickly use the engine. They should be able to download a release and start using it without needing to wait on licensing issues.
* Game content (gfx, sound, etc.) that is not part of the engine should be allowed to be licensed separately. If someone is using our engine, they can retain full copy right of their content, including engine generated data.
* Our primary goal is exposure, which is why we're going open source to start with. Both for the project and for the individuals developing it. Are there any licenses that can require accreditation visible to players? **Update**: As per comments, I mean this to be a requirement for either a splash screen or placement in the credits. Not a constantly visible logo.

While I'd put our primary goal as exposure, for licensing the accreditation is less of a concern.

From what I've read through (and have been able to understand) it doesn't seem like any of the licenses cover anything that is produced by the licensed software. Are there any that state this specifically, or does simply not mentioning it leave it open for other licensing?

Are there any other concerns that we should consider?

Has anyone had any issues using any of these licenses?

# Answer
> 6 votes
Based on your stated requirements, it sounds like you want a BSD-style permissive open source license. The only slightly unusual part is in your wish to "require accreditation visible to players".

I'm not aware of any existing permissive licenses that would include such a requirement (although that doesn't necessarily mean there aren't any). The GNU GPL does include a somewhat similar requirement (see section 2(c) in GPL 2.0 or 5(d) in GPL 3.0), but the GPL is in other ways more restrictive than you seem to want.

What you could do, however, would be to take an existing permissive license (like, say, the 2-clause BSD license) and just graft an extra clause requiring player-visible attribution onto it. Since it's your own code you're licensing, you're free to include any such restrictions you want.

However, a word of warning: *if* you want your license to be officially accepted as an open source license, you may want to be careful in how you phrase the requirement, lest you inadvertently end up recreating the BSD advertisement clause problem. Specifically, the old 4-clause BSD license used to carry the following requirement:

```
3. All advertising materials mentioning features or use of this software
   must display the following acknowledgement:
   This product includes software developed by the <organization>.

```

Sounds harmless, right? And it is, as long as the software uses only one component with such a license, or maybe two or three. But what if there were, say, 75 of them — as Richard Stallman famously claims to have counted in a old version of NetBSD — each one requiring a different acknowledgement to be displayed?

To avoid this issue, I'd recommend making your attribution requirements fairly flexible. For instance, you could follow the example of the Creative Commons Attribution 3.0 license (which would actually seem a fairly good fit for your requirements, except for the fact that it's not really designed for licensing software), which qualifies its attribution clause with the words:

> "The credit required by this Section 4 (b) may be implemented in any reasonable manner; provided, however, that in the case of a Adaptation or Collection, at a minimum such credit will appear, if a credit for all contributing authors of the Adaptation or Collection appears, then as part of these credits and in a manner at least as prominent as the credits for the other contributing authors."

Whatever wording you settle on, you might also want to show it to the OSI/DFSG folks and ask for comments (and maybe even request formal approval). Of course, if you don't really care that much about whether your license officially qualifies as open source, then you're always free to ignore such issues and just make up whatever requirements you think your target audience will accept.

---

Ps. One possible option for a suitable existing license, which I only thought of while writing the above, would be the GNU LGPL. It's a more permissive variant of the GPL, specifically intended for libraries and other components that are meant to be usable as parts of other programs without those other programs having to be GPL-licensed, and it does include a user-visible attribution clause of sorts (*emphasis* mine):

> "4. Combined Works.
>
> You may convey a Combined Work under terms of your choice \[...\] if you also do each of the following:
>
> a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License.
> b) Accompany the Combined Work with a copy of the GNU GPL and this license document.
> c) *For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices*, as well as a reference directing the user to the copies of the GNU GPL and this license document.
> \[...\]"

# Answer
> 4 votes
I'm not sure why you've discounted the GPL for this engine; it certainly seems to cover all bases.

Let's look at your individual requirements with reference to the GPL and it's FAQ.

* Removing or limiting our liability (most already seem to cover this, but stating for completeness).

This is explicitly part of the "no warranty" clause in the GPL.

* We want other developers to be able to take part or all of our project and use it in their own projects with proper accreditation to our project.

The GPL clearly satisfies the first part of this requirement, and the second part is answered by this FAQ entry: http://www.gnu.org/licenses/gpl-faq.html#IWantCredit.

> **I want to get credit for my work. I want people to know what I wrote. Can I still get credit if I use the GPL?**
>
> You can certainly get credit for the work. Part of releasing a program under the GPL is writing a copyright notice in your own name (assuming you are the copyright holder). The GPL requires all copies to carry an appropriate copyright notice.

* Licensing should not hinder someone's ability to quickly use the engine. They should be able to download a release and start using it without needing to wait on licensing issues.

No issue under the GPL.

* Game content (gfx, sound, etc.) that is not part of the engine should be allowed to be licensed separately. If someone is using our engine, they can retain full copy right of their content, including engine generated data.

The GPL doesn't require game content to also be under the GPL. The copyright holder of the game content is perfectly free to license it separately. In fact there are currently existing works that use exactly this kind of setup; Quake being one well-known example: https://github.com/id-Software/Quake/blob/master/readme.txt.

> All of the Quake data files remain copyrighted and licensed under the original terms, so you cannot redistribute data from the original game, but if you do a true total conversion, you can create a standalone game based on this code.

* Our primary goal is exposure, which is why we're going open source to start with. Both for the project and for the individuals developing it. Are there any licenses that can require accreditation visible to players?

Also covered. From GPL V2:

> If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.)

And V3:

> If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.

# Answer
> 3 votes
Have a look at Apache License 2.0- it satisfies your needs except a visual accreditation to the players while they are playing.

In fact, visual accreditation to the players will become a deterrent to the use of your work. If OSS suppliers ask for it, the screen will become an advertising bill board, and there will be no room left on the screen for the game!

---
Tags: legal, licensing, open-source
---


# Question
Title: The right way to start out in game development/design
I'm a 19 year old student looking for some help in the field of game development.

This question may or may not seem a bit overused, but **the fact is that game development has been my life long dream**, and after several hours of search I've realized that I've been going in circles for the past three or four months whilst doing such research on how to really get down and dirty with game development, therefor I decided to ask you guys if you could help me out at all.

Let me start off with some information about me and things i've already learned about GameDev which might help you out on helping me out (wordplay!):

* I'm not an expert programmer, but **I do have knowledge on how to program in several languages including C and Java** (Currently learning Java in my degree in Computer Engineering), but **my methodology might not be most correct in terms of syntax** (hence my difficulty in starting out, i'm afraid that the starting point might not be the most correct, and it would deploy a wrongful development methodology that would be to corrected later on, in terms of game development or other projects).
* I have yet to work in a project as large as a game, never in my learning curve of programming I've done a project to the scale of a video game, only very small software (PHP Front-ends and Back-ends, with some basic JQuery and CSS knowledge).
* I'm not the biggest mathematician or physicist, but I already know that is not a problem, because there are several game engines already available for use and integration with home-made projects (**Box2D**, etc).
* I've also learned about some libraries that could be included in said projects, to ease out some process in game development, like **SDL** for example.
* I do not know how sprites, states, particles or any specific game-related techniques work.

With that being said, you can see that I have some ideas on game development, but I have absolutely no clue on how to design and produce a game, or even how game-like mechanics work. It does not have to be a complex game just to start out, I'd rather learn the basic of game design (Like 2D drawing, tiling, object collision) and test that out in a language that I feel comfortable in which could be later on migrated to other platforms, as long that what I've learned is the correct way to do things, and not just something that I've learned from some guy on Youtube by replicating that code on the video.

I'm sorry if my question is not in the best format possible, but I've got so many questions on my mind that are still un-answered that I don't know were to start!

Thank you for reading.

# Answer
> 3 votes
Here is some suggestions based on my personal experience and observations.

TEH main rule that sould be your absolute priority: **you should make complete games.**

That's quite funny, since the thing is pretty obvious. However there are some reasons why people are failing with it:

1. Falling into technology paralysis, then you can decide which engine, framework to use. It's actually important, but not much for a start. My general suggestion is to use langugage which are you most proficient with, and use some established game framework/library for which you can easily find answers for most of beginner questions. Don't spent much time on it, it's all doable in one day.
2. Different kinds of phobias of "not doing it right". While particularly it's good to have some background for a start, you can end up in constantly reading books, tutorials, etc. but not actually starting to code yourself.
3. A "make a game engine" syndrome. You start to make an engine for your game. Do not do that. Remember main rule: write a game, not engine.
4. Making a complex game as a first project. Failing, especially at the beggining hurts your motivation a lot. You should limit yourself to a most simple projects as possible. Making a Tetris or Breakout clone for example, is a good start, and you can also familiarize yourself with libraries you chosed.

In general you should not bother much about how to "do it right" and instead start some real coding. We learn faster on mistakes sometimes.

---
Tags: 2d, game-design, game-mechanics, assets
---


# Question
Title: Does AndEngine have a way to manage scenes?
Does AndEngine have a way to manage scenes (for example, main splash, menu, options, main game), and should I use a different scene per activity?

# Answer
Yes, you can separate your game per screen. In fact, usually only the game itself needs to use a specific 2D/3D rendering, but classic splash screen, menu, options can be done with the classic android layout and some tweaking on the appearance and animations.

Besides this let you change each screen independently, and just create different intents to play the game, with specific information (like which level to load, the saved states etc..) in the intent data
> 3 votes

# Answer
Personally I found it extremely easier to simplify the process with different "scenes". I created one for the menu-system, and one for the game itself. This allowed me to do some cool stuff (rendering/animation) in the menu. Just create one scene, throw some buttons/text on it. When you hit a button, remove those buttons from scene and add new ones. Just create a static management class to help your flow. Then just remove that scene, and give the gameScene to the engine, and you're good to play, and vice-versa when you're ready to exit game into menu.
> 2 votes

# Answer
AndEngine provieds specific classes to satisfy the game requirement.

You can have a single activity with different scenes for specific purpose:

Firstly, You can use Scene with `TimerHandler` to have asplash screen.

Secondly,You can use `MenuScene` from `andengine.entity.scene.menu.MenuScene` to manage MainMenu scene.

Third,on Click of a particular menu of the game u can either launch different activity say to show 'HighScore' or 'How To Play' or you can have scenes to do the same. Its your choice. But managing scenes this way is much better.

You can also refer this.
> 1 votes

---
Tags: android, andengine
---


title: Input Handling and Game loop

text:
# Question
Title: Input Handling and Game loop
So, I intercept the WM\_KEYDOWN and other messages.

Thing is, my game can't/shouldn't react to these messages just yet, since my game might be currently drawing to the screen or in the middle of updating my game entities. So the idea is to keep a keyboardstate and mousestate, which is updated by the part of my code that intercepts the windows messages. These states just keep track of which keys/buttons are currently pressed. Then, at the start of my game's update function, I access these keyboard and mouse states and my game reacts to the user input.

Now, which is the best way to access these states? I assume that windows messages can be sent whenever, so the keyboard/mouse states are constantly being edited. Accessing say a list of currently pressed keys in the keyboard state the same time another part of the code is editing the list would cause problems.

Should I make a deep copy of a state and act on that? How would I deal with the garbage generated though, this would take place every frame.

# Answer
If I understand you correctly, it's not the way you should read input in games. Instead of reading Windows messages, keyboard is instead polled in your `Update` function. In WinAPI you use `GetKeyState` function for that. So you have something like this:

```
KeyState prevKeys; //*
KeyState currKeys;

Update() {
    prevKeys = currKeys;
    ScanKeyboard(out currKeys);

    //...
}

```

\*) You need previous state to detect key state changes.

You can check this out for a attempt to use event instead of polling, and problems discovered during this process.
> 1 votes

---
Tags: c#, input
---


# Question
Title: Line Intersection from parametric equation
I'm sure this question has been asked before. However, I'm trying to connect the dots by translating an equation on paper into an actual function. I thought It would be interesting to ask here instead on the Math sites (since it's going to be used for games anyway ).

Let's say we have our vector equation :

```
 x = s + Lr;

```

where x is the resulting vector, s our starting point/vector. L our parameter and r our direction vector.

The ( not sure it's called like this, please correct me ) normal equation is :

```
x.n = c;

```

If we substitute our vector equation we get:

```
(s+Lr).n = c.

```

We now need to isolate L which results in

```
L = (c - s.n) / (r.n);

```

L needs to be 0 \< L \< 1. Meaning it needs to be between 0 and 1.

My question: I want to know what L is so if I were to substitute L for both vector equation (or two lines) they should give me the same intersection coordinates. That is if they intersect.

But I can't wrap my head around on how to use this for two lines and find the parameter that fits the intersection point. Could someone with a simple example show how I could translate this to a function/method?

# Answer
> 14 votes
Given two parametric equations of lines;

```
L=a+t.b // t is the paramerter, a & b are vectors
M=c+u.d //u is parameter, c & d are vectors

```

The the point of intersection is the one place in space where both these equations are equal(produce the same point). When the lines intersect at some value of t and some value of u, the equations are equal, because they resolve to the same point;

```
L=M
a+tb=c+u.d

```

Now we have an equation with two unknowns (u & t). In order to find the point of intersection we need at least one of the unknowns. First step is to isolate one of the unknowns, in this case `t`;

```
t=(c+u.d-a)/b

```

but this is a 2D Vector equation, so it is really two equations, one in x and the other in y. Two equations is (usually) enough to solve a system with two unknowns.

```
t=(cx+u.dx-ax)/bx
t=(cy+u.dy-ay)/by

```

So now we have two expressions, which equal the same value (`t`), so they must equal each other. That is why we isolated t, in order to have two equations which equal each other AND only one unknown on either side.

```
(cx+u.dx-ax)/bx = t = (cy+u.dy-ay)/by  //from above

// equate and isolate u

(cx+u.dx-ax)/bx=(cy+udy-ay)/by //note: `t` is gone

```

Now, we have an equation with only one unknown, which we will solve by isolating the remaining unknown, `u`

```
cx.by+u.dx.by-ax.by=cy.bx+u.dy.bx-ay.bx
u.dx.by-u.dy.bx=cy.bx-ay.bx-cx.by+ax.by

//result
u=(cy.bx-ay.bx-cx.by+ax.by)/(dx.by-dy.bx)
u=(bx(cy-ay) +by(ax-cx))/(dx.by-dy.bx) //tidied up slightly

```

Calculating u and putting it back into `M=c+u.d` will give you the point of intersection of the two lines.

of course you will need to check if `0<=u<=1` to see if the line ***segment*** intersects

Note that you cannot use this value of `u` in the equation `L=a+t.b`, you have to use a different but similar equation to calculate `t` and check if `0<=t<=1`.

```
//derived in a similar fashion to u
t=(dx(ay-cy) +dy(cx-ax))/(bx.dy-by.dx) //tidied up slightly

```

`u` & `t` will have different values for the same intersection point, but if both are between 0 & 1 the the two line segments intersect.

Note that if `(dx.by-dy.bx)` is zero, then the lines are parallel and never intersect.

By the way, if you only have the start and end points of the line segments, you can still use these equations, using the following conversions.

```
s1x,s1y // start point of line 1
e1x,e1y // end point of line 1
s2x,s2y // start point of line 2
e2x,e2y // end point of line 2

ax=s1x
ay=s1y

bx=e1x-s1x
by=e1y-s1y

cx=s2x
cy=s2y

dx=e2x-s2x
dy=e2y-s2y

```

# Answer
> 4 votes
Let's see if I can clarify the maths a bit.

You have two lines:

* Line `r1` such that some point `p1 = a + L*b` where `a` is a position vector and `b` is the direction and `L` is a parameter.
* Line `r2` such that some point `p2 = c + M*d` where `c` is a position vector and `d` is the direction and `M` is a parameter.

Each line has its own parameter.

You want to find where these intersect. At the intersection point, `p1 = p2`. Unless `r1` and `r2` are parallel, there must exist some values for `L` and `M` for which `p1 = p2` is true. You only need one of these values to find the intersection point.

This is easiest to solve by splitting `r1` and `r2` from *cartesian form* into *parametric form*, where the x and y coordinates of the vectors are described separately:

`r1` is such that `p1x = ax + L*bx` and `p1y = ay + L*by`.

`r2` is such that `p2x = cx + M*dx` and `p2y = cy + M*dy`.

You can then rearrange the equations to isolate and eliminate either `L` or `M` and solve for the other. The resultant equation (derivation here) is, `M = ((cy - ay) * bx - (cx - ax) * by) / (dx * by - dy * bx)`. You could write your code around that. This tutorial might also help to understand the concepts.

---
Tags: 2d, mathematics, vector, intersection
---


# Question
Title: GLES2.0 3D Android game performance and multi threading the update?
I have profiled my mixed Java\C++ Android game and I got the following result:

As you can see, the pink think is a C++ functions that updates the game. It does things like updating the logic but it mostly it generates a "request list" for rendering. The thing is, I generate DrawLists on C++ and then send them to Java to process and draw using GLES2.0.

Since then I was able to improve update from 9ms down to about 7ms, but I would like to ask if I would benefit from multi threading the update?

As I understand from that diagram is that the function that takes the most time is the one you see it's color on the timeline. So the pink area is taken mostly by update. The other area has MainOpenGL.Handle as it's main contributor(whch is my java function), but since it's not drawn to the top of the diagram I can conclude other things are happening at the same time that use the CPU? Or even GPU stuff that isn't shown in this diagram.

I am not sure how the GPU works on this. Does it calculate stuff in parallel to the CPU? Or is it part of the CPU usage as in SoC? I am not sure. Anyway, in case GPU things DO happen in parallel to CPU, then I would guess that if I do this C++ Update in parallel to the thread that makes the OpenGL calls, I might make use of "dead CPU time" due to GPU stalling or maybe have the GPU calls getting processed earlier because it won't have to wait for Update to finish?

How do you suggest to improve performance based on that?

# Answer
Your image is hard to see, could you please upload a bigger one?

GPU does happen in parallel to CPU but both sync when swapping buffers. I would move your updates to a different thread, even more than one thread and throw stuff to render to your GLThread. If done correctly you can even use different update frequencies for different stuff in your scene.
> 1 votes

---
Tags: android, 3d, opengl-es2, multithreading, profiler
---


# Question
Title: Key events outside of an SDL application
I'm developing an app under C++ and SDL running in Ubuntu. I'm using the SDL events to handle the keypad buttons. My problem is that my app launch other programs and it should close they with a key combination, but I can't detect the user presing buttons outside of my app.

¿How could I do this?

# Answer
XGrabKey if you're using an x environment (you probably are, unless you know otherwise)
> 3 votes

---
Tags: c++, sdl, linux, gamepad
---


# Question
Title: Space-efficient data structures for broad-phase collision detection
As far as I know, these are three types of data structures that can be used for collision detection broadphase:

1. **Unsorted arrays**: Check every object againist every object - O(n^2) time; O(log n) space. It's so slow, it's useless if n isn't really small.

```
for (i=1;i<objects;i++){
  for(j=0;j<i;j++) narrowPhase(i,j);
};

```
2. **Sorted arrays**: Sort the objects, so that you get `O(n^(2-1/k))` for `k` dimensions `O(n^1.5)` for 2d and `O(n^1.67)` for 3d and `O(n)` space.

Assuming the space is 2D and `sortedArray` is sorted so that if the object begins in `sortedArray[i]` and another object ends at `sortedArray[i-1]`; they don't collide
3. **Heaps of stacks**: Divide the objects between a heap of stacks, so that you only have to check the bucket, its children and its parents - `O(n log n)` time, but `O(n^2)` space.

This is probably the most frequently used approach.

Is there a way of having `O(n log n)` time with less space? When is it more efficient to use sorted arrays over heaps and vice versa?

# Answer
> 3 votes
If you want a memory efficient data structure then don't forget the almighty hash table for maintaining an implicit grid for spatial partitioning!

Simply put, you place a grid over your simulation space and implicitly maintain it in a hash table. The table will only contain active sectors (sectors with one or more colliders in it) with their keys corresponding to their grid index using whatever hash function that works for the grid dimensions. This can save a lot of memory depending on your grid size since you don't have a tree or array of empty sectors. So each update, you perform broad phase collision detection by simply clearing the hash table and iterating through each collider and placing it into it's corresponding sector. If it's a uniform grid you can derive the sector's index that it belongs to using the collider's coordinates and sector dimensions. Then for inner phase collision detection simply iterate through the hash table's sectors and check all the colliders in each sector and it's neighbors for collisions.

# Answer
> -1 votes
I just wanted to say your first example is slightly incorrect in that it will check `i` against `j` and `j` against `i` as well. You really want to check pairs only once:

```
for (i=0; i<objects-1; i++)
{
   for (j=i+1; j<objects; j++)
   {
      narrowPhase(i,j);
   }
}

```

This is then O( (n-1) n / 2 ).

As for your main question, there are a number of ways to handle broadphase, the most popular two are:

---
Tags: collision-detection, optimization, data-structure
---


title: Cheap ways to do scaling ops in shader?

text:
# Question
Title: Cheap ways to do scaling ops in shader?
I've got an extensive world terrain that uses `vec3` for the vertex position attribute. That's good, because the terrain has endless gradations due to the use of floating point. But I'm thinking about how to reduce the amount of data uploaded to the GPU. For my terrain, which uses discrete / grid-based vertex positions in `x` and `z`, it's pretty clear that I can replace my `vec3`s (`float`s, really) with `short`s, halving the per-vertex position attribute cost from 12 bytes each to 6 bytes. Considering I've got little enough other vertex data, and an enormous amount of terrain data to push into the world, it's a major gain.

Currently in my code, one unit in GLSL shaders is equal to 1m in the world. I like that scale. If I move over to using shorts, though, I won't be able to use the same scale, as I would then have a very blocky world where every step in height is an entire metre.

So I see these potential solutions to scale the positional data correctly once it arrives at the vertex shader stage:

* Use 10:1 scaling, i.e. 1 short unit = 1 decimetre in CPU-side code. Do a division by 10 in the vertex shader to scale incoming decimetre values back to metres. Arbirary (non-PoT) divisions tend to be slow, however.
* Use (some-power-of-two):1 scaling (eg. 8:1), which enables the use of a bitshift (eg. `val >> 3`) to do the division... not sure how performant this is in shaders, though. Not as intuitive to read values, but possibly quite a bit faster than div by a non-PoT value.
* Use a texture as lookup table to convert the value from decimetres to metres. I've heard that this is really fast.

Or whatever solutions others can offer to achieve the same results -- minimal vertex data with sensible scaling.

# Answer
It seems to me that you only need to push 4 bytes to the GPU and retain your full precision: only send the X and Z components once, since they will never change. It is also possible to not send any X or Z data by using `gl_VertexID` (I can provide you with some examples but this is slightly beyond the scope of the question).

Then you're only left with the Y data to send. That's 4 bytes per vertex to send. But your suggestion of using shorts is just as valid; and you will never have to do a division, because what you do is *multiply* by (1.0 / 8.0) instead. And if you really worry about the vertex shader performance, that multiplication can be hidden in your world matrix, but honestly I would not try to optimise that until I knew it really is a bottleneck (and I doubt it is).

Also, I suggest having a look at the GL\_NV\_half\_float extension, which lets you send 2-byte floating point numbers to the GPU.
> 6 votes

---
Tags: opengl, 3d, glsl, optimization
---


title: Isometric tile selection

text:
# Question
Title: Isometric tile selection
I'm not all that good with Maths. I'm trying to make a function to convert mouse coordinates into a particular tile in an isometric view.

All of the algorithms I have seen so far work with the X & Y axes going diagonal, my game is currently set up like this, and I would like to keep it so.

Is there an algorithm so that if the mouse was at the red dot, it would return the coordinates of the tile that it is sitting on? (6,2)

# Answer
Well, I'm assuming that for a given tile, you know the real-axes coordinates for each of its corners. i.e for the given tile (1,0) in your picture, you know its left-most corner is at, let's say, (5,10) on the actual xy axes. If so, you can use Java's Polygon class: create a Polygon instance containing a given tile's xy coordinates for each of its corners, then use the contains(x,y) method giving it as arguments the position of the mouse cursor, and it will tell you if mouse of tile or not:

```
int[] tileXcoords = new int[tileLeftMostCornerX, tileLowerCornerX, tileRightMostCornerX,tileUpperCornerX];
int[] tileYcoords = //... similar for the y coors (keep the order of the corners the same as for the x array)

Polygon tile = new Polygon(tileXcoords, tileYcoords, 4);
if(tile.contains(mouseX, mouseY)) {
    //mouse is over tile
}

```
> -1 votes

---
Tags: java, isometric
---


# Question
Title: OpenGL and Java user interface architecture/comunication
I'm working on the UIs for a turn based tactical rpg made with Java and LWJGL. I'd like to make a set of "dynamic" UIs similar to those of the game Torchlight 2. I would like to know if there are any good technique (or article) for build UI's architecture and regarding the comunication between UI and game (to handle, for example, events like button clicking).

# Answer
FengGUI is just such an implementation (Java GUI Framework on top of JOGL and LWJGL). You can get its sources here, maybe that will help you...
> 3 votes

---
Tags: opengl, java, rpg, gui
---


title: Spherical to Cartesian Coordinates

text:
# Question
Title: Spherical to Cartesian Coordinates
Well I'm reading the Frank's Luna DirectX10 book and, while I'm trying to understand the first demo, I found something that's not very clear at least for me. In the updateScene method, when I press A, S, W or D, the angles mTheta and mPhi change, but after that, there are three lines of code that I don't understand exactly what they do:

```
// Convert Spherical to Cartesian coordinates: mPhi measured from +y
// and mTheta measured counterclockwise from -z.
float x = 5.0f*sinf(mPhi)*sinf(mTheta);
float z = -5.0f*sinf(mPhi)*cosf(mTheta);
float y = 5.0f*cosf(mPhi);

```

I mean, this explains that they do, it says that it converts the spherical coordinates to cartesian coordinates, but, mathematically, why? why the x value is calculated by the product of the sins of both angles? And the z by the product of the sine and cosine? and why the y just uses the cosine? After that, those values (x, y and z) are used to build the view matrix.

The book doesn't explain (mathematically) why those values are calculated like that (and I didn't find anything to help me to understand it at the first Part of the book: "Mathematical prerequisites"), so it would be good if someone could explain me what exactly happen in those code lines or just give me a link that helps me to understand the math part.

Thanks in advance!

# Answer
In the image the red vector is the one we are trying to convert to cartesian, given angles phi & theta (in the description I will refer to the length of the vector as `r`, for radius of the sphere).

So, the y-coordinate is the easy one, we know what the angle is between the red vector and the y-axis (`phi`), we just project the vector onto the y-axis;

```
y=|red| * cos(phi) //|red| means 'length of red vector'
y= r *cos(phi)

```

\[if you don't understand projection, think of it this way, we are trying to find the length of the 'adjacent' side of the yellow triangle = cos(angle)\*hypotenuse\]

For the other two, we can't project directly, we don't know the angle between the red vector and the z or x-axis. `theta` is NOT the angle between the vector and the z-axis, it's a measure of **how far the vector has been rotated around the *y-axis***, as measured from the -ive z-axis.

In order to get the x & z coords we first need to project the red vector on the x-z plane, that gives us the length of the blue vector.

```
|blue|=r*sin(phi)

```

\[the length of blue is the length of the 'opposite' side of the yellow triangle, it will also be the hypotenuse of the pink triangle\]

As can be seen from the diagram we know what angle the blue vector makes with the z-axis (theta) so we can project the blue onto the z-axis;

```
z= -|blue|*cos(theta)
z=-r*sin(phi)*cos(theta) // minus sign comes from the fact we are projecting onto -ive z-axis

```

\[z is the length of the 'adjacent' side of the pink triangle\]

similarly, we can project onto the +ive x-axis

```
x=|blue|*sin(theta) =r*sin(phi)*sin(theta)

```

\[z is the length of the 'opposite' side of the pink triangle\]
> 11 votes

---
Tags: c++, mathematics, directx, coordinates, trigonometry
---


title: Wait till all CCActions have completed

text:
# Question
Title: Wait till all CCActions have completed
I am developing a simple cocos2d game in which I want to animate two `CCSprite`s simultaneously, and for this purpose I simply set `CCAction`s on respective \`CCSprite's as follows.

```
[first runAction:[CCMoveTo actionWithDuration:1 position:secondPosition]];
[second runAction:[CCMoveTo actionWithDuration:1 position:firstPosition]];

```

Now I want to wait till the animations are complete, so I can perform the next step. How should I **wait** for these animations to finish?

There are actually two method calls, the first one animates the objects via the code above and second call does the other animation.

I need to delay the second method call until the animations in first are complete. (I would not like to use `CCCallFunc` blocks as I want to call the second method from the same caller as the first one.

# Answer
Try with a CCSequence action, here is the doc

http://www.cocos2d-iphone.org/api-ref/2.0.0/interface\_c\_c\_sequence.html

Something like

```
[CCSequence actionsWithArray:first,second,finishCallFunc,nil]

```
> 2 votes

# Answer
You could use CCDelayTime to add a pause in the sequence

```
id delay = [CCDelayTime actionWithDuration:1];

```

Then just add this to your sequence.
> 0 votes

# Answer
Have a flag if animations are running( simultaneousSpriteActionsAreRunning ). Set to true when the animations start.

In the update method of your main game loop check if each sprite has running actions using numberOfRunningActions.

so

```
-(void)update
{
     [self checkIfSpriteActionsHaveFinished];
}

-(void)checkIfSpriteActionsHaveFinished
{
    if( simultaneousSpriteActionsAreRunning
        && sprite1.numberOfRunningActions == 0
        && sprite1.numberOfRunningActions == 0 )
    {
        //do stuff
        simultaneousSpriteActionsAreRunning = false;
    }
}

```
> 0 votes

---
Tags: animation, cocos2d-iphone, ios, objective-c
---


# Question
Title: Getting the height of Keyboard on Android
Hi I need to know the height of my keyboard so I can move up some textfield I have in my app. I'm using cocos2D-X but the app don't recognize the keyboardWillShow method.

Thanks

# Answer
> 2 votes
From my understanding of the virtual keyboard, you can't get the height. What you can do is set your window to re-size mode and handle the re-size.

For more information see this question on SO and this discussion on Google groups.

---
Tags: android, cocos2d-x, keyboard
---


# Question
Title: Do shader program compilers optimise divide-by-PoT-constants to bitshift operations?
So just to restate that, let's say we have this:

`float f = g / 2;`

Given the divisor is a constant, will the shader compiler auto-optimise this to a bitshift operation, as some language compilers are known to do? Where would I find more info on shader program compiler implementation details?

(I'm guessing there will be different answers for OpenGL & DirectX.)

# Answer
> 6 votes
If f and g are ints, then yes, compilers will in general do this type of optimization where it makes sense.

If f and g are floats, then multiplies/divides by powers of two cannot be done by bit-shifting. However, as it happens, some GPUs have hardware that can do a free multiplication by certain powers of two (such as 0.5, 2, or 4) at the same time as some other operation. So, for instance, (f + g) / 2 could be translated to (f + g) * 0.5 and done for free along with the addition.

Shader compiler implementation details are, unfortunately, not readily available. Both NVIDIA and AMD tend to be fairly secretive about this stuff. However, you can often look at the disassembly produced by the compiler for a given shader. Each vendor provides some tools to do that, such as NVIDIA ShaderPerf and AMD GPUShaderAnalyzer.

Note that the details will vary by GPU vendor and by chipset within a vendor, but will generally be the same for OpenGL and DirectX as those are just two different front-ends to the same back-end instruction set.

---
Tags: opengl, directx
---


# Question
Title: OpenGL : Keeping alpha in a render buffer
In my current task, i need to render a texture into a render buffer, in order to work on it (apply special filters) there. The result is then considered a "new texture", which is later displayed.

This works fine, except when the texture contains some transparent/semi-transparent parts.

My current guess it that, within the render buffer, the texture is "merged" with a kind of "grey background". In this case, it obviously impacts the R,G,B color components of transparent pixels. I've yet to find a way around this.

Even manually assigning alpha *after* the rendering process doesn't save the day for semi-transparent pixels, which RGB are "tainted" by the grey background.

# Answer
It sounds like something is wrong with your blend modes or shaders. When you initially copy the texture to the render target, you should disable blending, which will just copy all the RGBA components to the render target without modification. Then, any filters you apply will need to handle alpha appropriately, whatever that may mean for the specific filter.
> 1 votes

---
Tags: opengl, textures
---