title: Server architecture software side

text:
# Question
Title: Server architecture software side
I'm making a game some like Terraria. I have a couple of prototypes, but most of them use a "entity-component-system"(ESC) and some custom terrain implementation. Now I've reached the part where I feel like researching some multiplayer-technology. So here I am.

This is what I have so far; * I want to write the server in python, I don't HAVE to but I like python because I feel that I can easily change logic, and the workings of it.

Know, my first question is; the ESC, should run on the server, right? But how do I sync entities and components between the client and the server?

When the client connects to the server, how do I sync the world? The world is randomly generated as it expands. Can someone explain or link some data about how the server entity -\> client entity is done? And how to sync the terrain?

# Answer
> 3 votes
Whether to choose TCP or UDP often depends on the mechanics and needs of the game. For example, First Person Shooter games often rely on UDP because of the minimal network overhead for exchanging information between two end points.

Using UDP does mean that packets could get lost or received out of order and your protocol and systems need to be prepared to handle this situation. There are UDP software solutions on the market which address these needs. See things like Raknet or ENet for examples.

Using TCP generally implies a bit more network overhead but offers you the reliable stream between the two endpoints. It also makes sure that the order you send data is the same order that it gets received at the remote end point.

Some games exploit the use of both protocols to exchange different data depending on whether the packet is order dependent or needs reliable delivery. Information that is important and should be received in order is sent via TCP and the other information exchanged via UDP that perhaps isn't as important or if it is lost will be resynced when the next UDP packet arrives.

Regarding the Entity Component System, you'll likely have this system running on both the server and client. You'll have the more heavy weight version on the server side where all the rules and logical systems exist. On the client end, its mostly just the rendering aspects of the Entity Component System with some minor logical systems that make sense to delegate to the client such as physics.

There are several ways to keep these entities synchronized. The first thing to keep in mind is that you will often have two types of Entities, Local and Networked. There are also two categories of Components, Local and Networked.

Local Entities are things such as perhaps spawning an object to point the player in a specific direction that wouldn't be necessary on other player screens that could see your avatar. A good example of this is the Archaeology surveyor object in World of Warcraft. It is purely a client side local entity when you use the Survey ability.

Generally you'd have some ID framework in place which allows the server to assign the unique IDs to network managed entities and their networked components. For local entities and components, those are purely managed by the client side only. For example, we use a 32-bit number where one of the bits on the high order end of the number represents local or networked.

Synchronizing the dynamic content from the server to the client is generally based on an concept that the avatar has a Field of Interest (FOI) circumference about them based on their current position. Anything that is within, enters, or leaves this FOI is sent to the client and it responds accordingly. Things like terrain, buildings, and water are all static content, usually delivered when the game gets installed. So this information isn't sent to the client. It's thing slike NPCs, weather changes, other players that get transmitted. Here's an example exchange from our game.

```
C>S: Account 'crancran' login realm Deep Earth.
S>C: Client connected
S>C: Sending Player Data to client
S>C: Player current location is 1049.0031, 1.984, 75.0494, Map Id 2.
S>C: Game Object Update - Spawn NPC 1234 - Object entered client FOI.
S>C: Game Object Update - Spawn NPC 1235 - Object entered client FOI.
S>C: Map Id 2 Current Weather is Rain.
/* player begins to move */
C>S: Player has moved.  Present position is currently 1052.948, 1.984, 73.0478.
S>C: Game Object Update - Spawn NPC 99 - Object entered client FOI.
S>C: Game Object Update - Despawn NPC 1234 - Object left client FOI.

```

HTH.

---
Tags: architecture, networking, component-based, entity-system
---


# Question
Title: Receiving keyboard events on a canvas in Javascript
I need to receive keyboard events in a canvas element. Click events are received but key presses aren't.

Here is my code which doesn't handle key events:

```
var canvasElm = $('canvas');
Event.observe('canvas', 'keypress', function(e) {
    console.log('Key event is received!!');
    console.log(e);
});

```

How can I make it handle those key events?

# Answer
I suspect the canvas never has the keyboard focus. Keyboard events will be sent to the Window object.

Try adding the events to the Window object. (NB: It might be clearer what's happening if you don't use JQuery)
> 2 votes

# Answer
I'm really sorry. I found the solution after ask the question by trying. As MarkR said, we need give focus on our canvas. Here is the pure javascript (without JQuery);

```
canvasElm.setAttribute('tabindex','0');
canvasElm.focus();

```
> 4 votes

---
Tags: javascript, html5, html-canvas, keyboard, jquery
---


title: PHP Browser Game Private Messages?

text:
# Question
Title: PHP Browser Game Private Messages?
First off, I'm asking this question here because gaming and messaging are intimately connected. Why win if you can't gloat? Nevertheless, I won't be offended if this needs to be moved to overflow.

I need a PM system for my browser game, which already has a user and authentication system (To clarify: the game already has a user system). Specifically, I'm wondering if a PHP library already exists that I can use to save some time. Better yet, if anyone knows of a nice Codeigniter library for messaging, that would be perfect.

I already have a good idea on how I would approach this if I have to write my own, but it seems like something that would already exist in a robust form (despite my failed Google searches).

**Requirements:**

1. Messages can be sent to individuals, multiple users, and guild mates (which is essentially just multiple users with server-side selecting who to target).
2. Users can reply to individual or all recipients
3. Messages appear in sender's outbox and receiver's inbox.
4. Utilizes some 2-table design to handle marking read / deleting messages on a user-by-user basis
5. Messages are semi-threaded. I.e. I won't necessarily have them appear in the GUI as threaded, but previous messages should be included at the bottom of a reply. Maybe better to say, previous messages are identifiable and accessible. (This, I'm not yet 100% sure how I would design if I write my own. I.E. whether to include the text of the previous message into the new message or somehow remember the previous message's database ID to link later)

**Technology in Use:** PHP, Codeigniter, Javascript, JQuery, Ajax, Sqlite

**Note:** I *have* seen that there are some similar questions on overflow, but they were very little help in the answer department. Otherwise, people were looking for either chat boxes or more umm.. like social media site threads, which I find a bit different than something you would find in a game.

# Answer
This sounds like a pretty simple task. First of all, you need a database to store your messages; presumably you already have one for your user accounts, but if you want recommendations, MySQL, PostgreSQL and SQLite are all common choices and should do fine.

Next, you'll need a table to store the messages. A typical message table should probably contain at least the following columns:

* Message ID, the primary key to the table. This can be just an auto-incrementing number.
* A timestamp of when the message was sent; useful for chronological sorting. Create an index on this column. (In fact, if you frequently sort messages by this columns, you may also want to include it as the last column of any *other* indexes.)
* The sender of the message; a user ID. Also index this column (or mark it as a foreign key into your user table, if your DB supports those).
* A parent message ID, for threading. May be `NULL`. Should be indexed as a foreign key to this table itself.
* The title / subject of the message; a `VARCHAR` type should be good.
* The body of the message, whatever variable character type your DB has that lets you store at least several kilobytes of text.

Obviously, that's just a bare-bones sketch of a message table. You might want to add some other fields, like a last edit timestamp if messages can be edited after sending. Also, some of the fields above could be left out if the information is stored in some other way; for example, the sender could instead be stored in the same table as the recipients (see below), and it *could* be more efficient to store the message body in a separate table as a form of vertical partitioning.

Now we also need to store the recipients. Since a single message might have several of those, we need a separate link table, with columns like this:

* Message ID: a foreign key to the message table.
* Recipient ID: a foreign key to the user table.

Make sure both of these columns are indexed, so that finding both the recipients of a given message and the messages sent to a given recipient will be efficient.

That's basically enough, but you might also want to add a few more columns. For example, this table could conveniently store a flag indicating whether or not the recipient has seen the message. Also, if you added a "role" column, you could use it to indicate different types of recipients (maybe some only got "carbon copies"?), or even use it to store the sender of the message, and any other possibly associated users, in this same table.

Note that you don't really need a separate ID column for this table: the first two columns above (and possibly the role column, if any) already make up a natural primary key together.

Here's what the definitions of these tables might look like in SQL. I've written these for MySQL since it's what I'm most familiar with, but they shouldn't be hard to adapt for other DBs:

```
-- here's our basic message table
CREATE TABLE message (
  message_id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
  sent TIMESTAMP NOT NULL,
  sender INTEGER NOT NULL, -- foreign key to user table (not shown)
  parent_id INTEGER NULL, -- optional foreign key to this table
  title VARCHAR(255) NOT NULL
);

-- timestamp index for chronological sorting, also appended to other indices
CREATE INDEX i_sent ON message (sent);

-- foreign key indices (because MySQL doesn't really have true foreign keys)
CREATE INDEX i_sender_sent ON message (sender, sent);
CREATE INDEX i_parent_sent ON message (parent, sent);

-- optional, for sorting messages by title if that's a common use case
CREATE INDEX i_title ON message (title);

-- let's make a separate table for the body, just to show how it's done
CREATE TABLE message_body (
  message_id INTEGER NOT NULL PRIMARY KEY, -- also foreign key to msg table
  body TEXT NOT NULL
);

-- and finally, the recipient table
CREATE TABLE recipient (
  message_id INTEGER NOT NULL, -- foreign key to message table
  rcpt INTEGER NOT NULL, -- foreign key to user table (not shown)
  seen TINYINT NOT NULL DEFAULT 0, -- MySQL doesn't have a real boolean type
  PRIMARY KEY (message_id, user_id)
);

-- an optional index for quickly finding unread messages
CREATE INDEX i_rcpt_seen_msg ON recipient (rcpt, seen, message_id);

```

Using these tables, here are some examples of common queries:

* A user's outbox, newest first:

```
SELECT * FROM message
WHERE sender = :sender
ORDER BY sent DESC

```
* A user's inbox, newest first:

```
SELECT * FROM message
  JOIN recipient USING (message_id)
WHERE rcpt = :recipient
ORDER BY sent DESC

```
* The number of unread messages to a user:

```
SELECT COUNT(*) FROM recipient
WHERE rcpt = :recipient
  AND seen = 0

```
* One or more full messages with body and comma-separated recipient list:

```
SELECT
  message.*,
  message_body.body AS body,
  GROUP_CONCAT(recipient.rcpt) AS recipients
FROM message
  LEFT JOIN message_body USING (message_id)
  LEFT JOIN recipient USING (message_id)
WHERE message_id IN (:message1, :message2, :message3)
GROUP BY message_id

```
* Replies to a message (iterate to find replies to replies, etc.):

```
SELECT * FROM message
WHERE parent = :message_id
ORDER BY sent ASC

```

(In all the examples above, identifiers beginning with `:` denote placeholders to be substituted with (or bound to) values from the client.)

Also note that there are several other ways of storing hierarchical data like threaded messages in a database which avoid the need for iterated queries at the cost of some complexity. (Also, some database engines provide built-in support for recursive queries.) However, if you don't mind occasionally doing multiple queries in a loop to fetch a set of results, a simple parent message ID column like I used above will do the job just fine.
> 2 votes

# Answer
Ok to break this down.

1,2 and 3 would simply be a UI to send message and view the message from different "links/pages". When message sent it is just insert into the table which sends the message and reply to one... standard PHP/MYSQL insert.

4 is just a method of providing message state and changing it.

5 Threading in regards to web browsers is non-existant. However taking it to mean run Async and providing the user news they have a message without refreshing page, you could do it either by:

1. Poll the table of user messages and count how many new there are for that user if `> 0` show how many new ones there are.
2. Use a pushing mechanism in regards to ui one way that works down to ie 6 is opening a 'long' connection to the server which as soon as the server has anything to give the user it puts it on that connection at which point the UI processes the response and request a new long connection. One such library for that is ape-project

In short.. I don't know of a library that will implement this for you and provide you the UI too which is majority of the work involved to add this to your game.

Hope this helps
> 0 votes

---
Tags: multiplayer, browser-based-games, php, messaging
---


# Question
Title: What matrix operations do I perform to translate then rotate then translate then rotate?
In an android game I want to draw a running leg. To output the thigh I do something like:

```
// legCX,legCY is the location on screen about which the leg rotates.
Matrix m = new Matrix();
m.postTranslate(-legCX,-legCY);
m.postRotate(legRot);
m.postTranslate(legCX,legCY);

```

So, the above translates the 0,0 point over to the point of rotation about which I want to rotate the leg, then it rotates by the amount I want the leg rotated, then it translates 0,0 back to the original origin.

I then use that matrix to draw the thigh. It ends up rotated as expected. So far so good.

How do I draw the second part of the leg below the knee? It rotates differently than the part of the leg above it and has a center point which moves with the leg above it. I tried the following, but it turns out that the end result is rotation around some single point which doesn't follow the thigh.

```
Matrix m = new Matrix();
m.postTranslate(-legCX,-legCY);
m.postRotate(legRot);
m.postTranslate(0,-thighLength);
m.postRotate(shinRot);
m.postTranslate(0,thighLength);
m.postTranslate(legCX,legCY);

```

I suspect that it's probably necessary to do the two rotations in two different Matrix objects and then combine them somehow, but I can't figure out how exactly to do that.

I've tried reading the various wikipedia articles on matrix operations, but I'm having trouble finding the sort of operation that I'm trying to perform.

EDIT: This type of matrix seems to be called a "transformation matrix". Combining multiple operations is called composition of transformations. However, none of the pages on this topic mention how to do a series of translations and rotations.

Surely, if you can use a matrix to do rotation about one point, it must be possible to do multiple matrix operations somehow to allow rotation about one point and then an additional rotation around a different point.

I've tried looking at pages on skeletal animation, but I can't make head nor tail of what they're talking about. My game won't involve many characters, so I don't need to use a physics engine to do super complex stuff. I just want to do the calculations to draw a character that runs.

EDIT: Hooray! Thanks dkantowitz! Your answer wasn't quite right, but you got me really close. I've edited your answer to be correct now. The second matrix needed to translate from the origin, not relative to the leg's center of rotation. And, the combined matrix needs to preConcat the shin matrix first and then the thigh's matrix. Thanks!

# Answer
> 4 votes
I don't have an Android dev environment setup, but this looks like basic linear algebra.

Try this:

```
Matrix moveLeg = new Matrix();
moveLeg.postTranslate(-legCX,-legCY);
moveLeg.postRotate(legRot);
moveLeg.postTranslate(legCX,legCY);

```

.. and another:

```
int shinCX = legCX;
int shinCY = legCY + thighLength;
Matrix moveShin = new Matrix()
m.postTranslate(-shinCX,-shinCY);
m.postRotate(shinRot);
m.postTranslate(shinCX,shinCY);

```

Now a combination of the two:

```
Matrix moveBoth = new Matrix();
moveBoth.postConcat(moveShin);
moveBoth.postConcat(moveLeg);

```

Obviously you need to apply the series of transforms that make sense to depending on how your figure is drawn.

You can think of a matrix as 'storing' all the transformations performed on it and becoming a new matrix operation. That matrix can the be applied to another matrix to 'repeat' those transformations.

For example:

```
Matrix spin245 = new Matrix();
spin245.postRotate(245);

```

You now have a new matrix 'operation': spin245. You can apply this any time you want:

```
Matrix foo = new Matrix();
foo.postConcat(spin245);

Matrix bar = new Matrix();
foo.postConcat(spin245);

```

# Answer
> 0 votes
This code should get you started on the necessary linear algebra. I built this class in all-int for an A-star algorithm.:

```
    /// <summary>Initializes a new fully-specificed non-normed <code>IntMatrix2D</code>.</summary>
/// <param name="m11">X-scale component.</param>
/// <param name="m12">Y-shear component</param>
/// <param name="m21">X-shear component</param>
/// <param name="m22">Y-scale component</param>
/// <param name="dx">X-translate component</param>
/// <param name="dy">Y-translate component</param>
/// <param name="norm">Normalization component</param>
public IntMatrix2D(int m11, int m12, int m21, int m22, int dx, int dy, int norm) : this() {
  Matrix = new int[3,3];
  Matrix[0,0] = m11;  Matrix[0,1] = m12;  Matrix[2,0] = 0;
  Matrix[1,0] = m21;  Matrix[1,1] = m22;  Matrix[2,1] = 0;
  Matrix[2,0] = dx;   Matrix[2,1] = dy;   Matrix[2,2] = norm;
}
#endregion

#region operators
/// <summary>(Contravariant) Vector application.</summary>
/// <param name="v">IntVector2D to be transformed.</param>
/// <param name="m">IntMatrix2D to be applied.</param>
/// <returns>New IntVector2D resulting from application of this matrix to vector v.</returns>
public static IntVector2D operator * (IntVector2D v, IntMatrix2D m) {
  return new IntVector2D (
    v.X * m.M11 + v.Y * m.M21 + m.M31,   v.X * m.M12 + v.Y * m.M22 + m.M32,  v.Z * m.M33
  ).Normalize();
}
/// <summary>Matrix multiplication.</summary>
/// <param name="m1">Prepended transformation.</param>
/// <param name="m2">Appended transformation.</param>
/// <returns></returns>
public static IntMatrix2D operator * (IntMatrix2D m1, IntMatrix2D m2) {
  return new IntMatrix2D (
    m1.M11*m2.M11 + m1.M12*m2.M21,           m1.M11*m2.M12 + m1.M12*m2.M22,
    m1.M21*m2.M11 + m1.M22*m2.M21,           m1.M21*m2.M12 + m1.M22*m2.M22,
    m1.M31*m2.M11 + m1.M32*m2.M21 + m2.M31,  m1.M31*m2.M12 + m1.M32*m2.M22 + m2.M32,  m1.M33 * m2.M33
  );
}
#endregion

```

As you build the three matrices, yo can cimply multiply them together to obtain a matrix for the resultant transformation, and apply it where needed.

---
Tags: android, matrix, skeletal-animation
---


# Question
Title: Space partitioning when everything is moving
**Background**

Together with a friend I'm working on a 2D game that is set in space. To make it as immersive and interactive as possible we want there to be thousands of objects freely floating around, some clustered together, others adrift in empty space.

**Challenge**

To unburden the rendering and physics engine we need to implement some sort of spatial partitioning. There are two challenges we have to overcome. The first challenge is that everything is moving so reconstructing/updating the data structure has to be extremely cheap since it will have to be done every frame. The second challenge is the distribution of objects, as said before there might be clusters of objects together and vast bits of empty space and to make it even worse there is no boundary to space.

**Existing technologies**

I've looked at existing techniques like BSP-Trees, QuadTrees, kd-Trees and even R-Trees but as far as I can tell these data structures aren't a perfect fit since updating a lot of objects that have moved to other cells is relatively expensive.

**What I've tried**

I made the decision that I need a data structure that is more geared toward rapid insertion/update than on giving back the least amount of possible hits given a query. For that purpose I made the cells implicit so each object, given it's position, can calculate in which cell(s) it should be. Then I use a `HashMap` that maps cell-coordinates to an `ArrayList` (the contents of the cell). This works fairly well since there is no memory lost on 'empty' cells and its easy to calculate which cells to inspect. However creating all those `ArrayList`s (worst case N) is expensive and so is growing the `HashMap` a lot of times (although that is slightly mitigated by giving it a large initial capacity).

**Problem**

OK so this works but still isn't very fast. Now I can try to micro-optimize the JAVA code. However I'm not expecting too much of that since the profiler tells me that most time is spent in creating all those objects that I use to store the cells. I'm hoping that there are some other tricks/algorithms out there that make this a lot faster so here is what my ideal data structure looks like:

* The number one priority is fast updating/reconstructing of the entire data structure
* Its less important to finely divide the objects into equally sized bins, we can draw a few extra objects and do a few extra collision checks if that means that updating is a little bit faster
* Memory is not really important (PC game)

# Answer
> 6 votes
The technique you are using is very similar to a computational physics technique called molecular dynamics, where the trajectories of atoms (usually now in the 100k to 10M particle range) are followed with very small time steps. The main problem is that to figure the force on one particle, you have to compare its position to the position of every other particle, which scales very poorly (n squared).

There are a trick I can suggest, which requires you to pick a maximum distance that things can interact. As a starting point, I'd start with something like 1/10 of the long dimension of your space, and adjust to taste (longer cutoff means more accurate, but more calculations).

The method is to loop through every particle (i). (I) gets an array where all the particles in range of i are added to the array. What you get in the end is a 2d array, where the ith entry is an array of the particle in range of i. To calculate the forces for i, you only have to check the entries in i's array.

The art of this method is picking the cutoff distance, and the extra padding (eg 20%). The speed gain is that you only have to check a few interactions for each particle, and you recalculate neighbors only every several steps. I'd suggest picking a somewhat fast speed, and figure out how many time steps it would take to cross the "padding" region. Making the padding larger (50% or even 100% of the cutoff) gives you more steps between neighbor recalculating, but makes each step a bit slower. The balancing of this is a tradeoff.

One other trick in calculating the distances is to work with d^2 instead of d, removing a bunch of calls to pow() and sqrt().

Edit: Hard to find a ref link that isn't super technical. This is the only one I could find.

# Answer
> 2 votes
Your own solution sounds pretty good if you can achieve building the data structure in o(n) then I would say the optimisation must be done on the choice of data structure rather than on the algorithm.

I have a similar implementation with some differences : The main data structure is an fixed-size array (like ArrayList) which is the best for direct access to an element. Each cell of the array contains a linked list, which is the best for insertions and as good as array list to loop into. We'll need later to delete elements from the linked list, so to make this operation very fast an idea is to store in each element of the list an iterator that points to itself (you said memory is not a problem, right?)

For initialisation, each "particle" is inserted at the end of the linked list that corresponds to the cell in the array that matches its position in space, assuming that the space is partitioned in fixed-size tiles. So we're still with o(n) complexity, but we optimize the whole thing by using containers more fitted to the use.

Each "particle" has a reference to its containing linked list to provide fast access to its neighbours.

At each frame we can make the interaction between each particle with its list of neighbours, and I would say also with the 8 surrounding tiles to avoid treshold effects near tile borders.

There's no need to recalculate the whole partitioning at each frame ; we only need to remove and put again an item when it moves more than a given distance or, by security, every X frames. An idea could be to store the position of each item at the moment when it was inserted in a linked list, and at each frame compare the current position with the old one.

---
Tags: java, space-partitioning
---


# Question
Title: How to make a Unity3d program/plugin and publish it on Asset Store?
I want to make a plugin for Unity3d, like TornadoTwins's FPS Control. How can I do that? I already have Visual Studio 2010 installed.

# Answer
You can find documentation for building Unity plug-ins here:

Do note that plug-ins only work on the Pro versions only, which I assume means you'll be unable to test the plug-in if you have the free version.

More information about creating content on the Unity asset store can be found here.
> 3 votes

# Answer
Depending on what you are making, it may not have to be a native code plugin. Here is the documentation for extending the editor.
> 3 votes

---
Tags: 3d, unity, javascript
---


# Question
Title: Is there a game oriented graphics or image editor?
I remember looking a few times over the years for an alternative to Photoshop for editing images. I've tried using Gimp too, and that's also not quite sufficient. There are some problems that have only been solvable by breaking out into an asset compiling stage. For example, none of the graphics packages come with premultiplied alpha options, and none come boxed with previews of what the image will look like once it's been compressed for hardware. I've never come across a package that lets you modify the diffuse, specular, ambient and normal maps all at the same time with the same tools.

Is there an image manipulation package out there that can satisfy things like this, allow for textures that have more than just 4 channels, export with preview to final format, maybe even rendering them in some coherent way?

items on the wishlist include:

* batch conversion
* scriptable pixel shader/transform
* view diffuse+alpha over a background / allow alpha2coverage preview
* render depth mapping via height or normal map
* show mip-maps and allow editing them

# Answer
I doubt such a power tool exists, game companies create in house tools, max-scripts and Photoshop scripts to make up for the lack thereof.

They generally adapt because Photoshop is *the* tool that all artists need to know how to use. Even if you created a tool with all the functionality of Photoshop, artists would still prefer the original and even if you force them to use it, there will probably be a productivity drop during the time they get used to the new way of working. This may be made up for afterwards, but and new recruits will have to go through the same thing.

Photoshop can still be hooked up with 3DSMax and textures can be updated in real-time on your meshes, so no problem with viewing your four channels.

Your in-house level editor will have the game renderer's code in, so when the asset is imported, the final result will be seen. A tool could even be made to update the mesh at real time, but again, this would have to be an in-house tool with the renderer's code.

Basically, in-house tools (are they even called that?) are the only way to go.

I recently used The Gimp (with PowerShell) to create a batch converter to convert textures to the nearest power of two, it wasn't all that hard and is reusable even though The Gimp's batcher is slow. I also made a script to rescale textures depending on the resolution, and pad the full-screen textures so they're not distorted. It's a bit of work, and you'd think a tool should already exist, but hey.
> 9 votes

# Answer
Mesh material settings are dependent on the game and engine(s) used, which is why there are no specific tools that let you load up any kind of mesh file and take the referenced data from it.

Such a tool will have to cover a broad area of material formats, or expect custom ones. If you are working with OBJ files, for example, the editor will have to be able to read a .mtl file to load all diffuse maps, specs, normals for the object materials. If it's an .fbx mesh, that's even more involved. Will you use a generic naming scheme in your 3D modeler for basic material attributes or do you need custom attributes?

In short, you're basically asking for an editor that has a content pipeline *that can handle any arbitrary material format*, and that's more of a programmer's problem, which is why custom tools are needed/created.

The best you can do in Photoshop is using NVIDIA's plug-ins, which include things like converting grayscale bump maps to normal maps or DXT compression with built-in 3D previews.
> 3 votes

# Answer
I'd look into ToonBoom, perfect for 2D game sprites and other game stuff from what I've heard.
> 2 votes

# Answer
You could try the new game oriented graphics tools in the Visual Studio 11 preview.
> 1 votes

# Answer
www.inkscape.org

I'm no programmer, but the 'export', 'GPL', and 'layers', functions of Inkscape should work for about 3 of your wishlist.

\[Inkscape is an opensource image editor. It's powerful and quite intuitive; and since it uses the GPL liscense (making it FREEware), you can code your own modules and send them in for everyone to use.\]

Sharing counts. (-and up yours Adobe!)
> 1 votes

---
Tags: graphics, assets, image, editors, asset-creation
---


# Question
Title: What happens to data between vertex shader and pixel shader?
Short version: What can happen to the output of a vertex shader that leads to no(or very few) pixels being drawn, especially in relation to a perspective matrix.

Long version:

My problem refers to the fact that when using a projection matrix very few pixels are actually drawn, more often than not, no pixels are drawn. I have used the built-in debugger in VS2012 and inspecting the output of the vertex shader reveals that the transformations are most likely correct, it is only when it is passed to the pixel shader that things start to go astray.

What I tried:

* use different built in matrices for calculating perspective
* check the code for indirect modifications
* set "CULLING\_NONE" as a rasterizer state, that only increased the chance of something actually being drawn
* set the "w" component of the SV\_POSITION vector to 1, that also seemed to help to a certain degree
* checked winding of triangles

My implementation performs the View-Projection multiplication first (of their transposes) and then multiplies the position with the result of the former. I believe that's not where the problem lies due to the associative property of matrix multiplication.

I'd prefer it if I wouldn't have to resort to all sorts of hacks that can only increase the chance of something being drawn at all (never in the right way) as it seems clear that the problem lies in my implementation.

# Answer
> 12 votes
Well, a lot of stuff happens between the Vertex and Pixel shaders, but before we get into that, I'm worried that you may be a bit confused about what the Vertex and Pixel shaders do. So let's quickly go through the entire Direct3D 9 programmable pipeline again. This nice chart shows the entire pipeline, and you should print it out for reference.

(feel free to imagine I'm saying this with the voice of the "how it's made" videos)

It all begins at your program. There are several ways you can start drawing stuff on the screen. But regardless of whether you're using **Indexed Primitives**, **Regular Primitives**, **Rect/Tri Patches** (which are automatically tesselated for you) or directly with **DrawPrimitiveUp**, you will be feeding the pipeline with a lot of vertices.

Each vertex simply defines a point in space, maybe with some custom information for texture coordinates, or normals, or whatever you want to send with your vertices. But remember that they're just vertices. Triangles and Pixels don't even exist at this stage.

Then, a program called the **Vertex Shader** is applied to each one of these vertices indiscriminately. The main job of the Vertex Shader is to transform each vertex and convert it to viewport coordinates. Nothing is yet drawn at this stage (the white lines you see are put in there by the debugger for your debugging pleasure, but don't exist in the GPU at all).

Afterwards, all vertices go through **Primitive Assembly**, which takes vertices in groups of three, and makes triangles out of them.

If you're using DirectX 10 or above, triangles (or whatever your primitive topology is) can get sent to another program called the *Geometry Shader*, where you can create more triangles from the current ones if you wish. This is mostly used for tesselation and for particle systems.

Each triangle then goes through **Face Culling** if it's enabled. In Face Culling, triangles not facing the camera are discarded. Generally, half of all triangles are expected to be discarded in this stage.

Even more triangles are discarded in the **Plane Clipping** stage. Triangles too close or too far from the camera are discarded.

If this were too little, one additional round of triangle discarding goes on at the **Frustum Clipping** stage, which discards triangles that are outside of the viewport, and therefore not visible.

The next step consists of performing a **Homogenous Divide** (or "Division by *w*") to normalize the position of all triangles in the viewport.

Finally, all the triangle coordinates are transformed to those of the viewport (actual pixels) in the **Viewport Mapping** stage.

Next comes the **Rasterization and Component Interpolation** stage. Each triangle is disassembled into the fragments that make it up (one fragment for each pixel in the screen). For each fragment, all the components you passed into the original vertices, such as texture coordinates, normals, or your custom data, are interpolated throughout the entire triangle, and assigned to each fragment.

Each fragment is then passed to a program called the **Pixel Shader**, whose function is to make a pixel out of each fragment. You're supposed to use the interpolated texture coordinates, normals or whatever custom data you originally passed, to figure out what the color of each pixel is. In simpler terms, this is where "drawing happens".

Afterwards, pixels outside of a region you define called the *Scissor Rect* are discarded by the **Scissor Test**, if you enabled it.

Then each pixel goes through the **Alpha Test**, if you have enabled it. Pixels that fail the Alpha Test are discarded.

If there are triangles that overlap in the viewport, there will be more than one pixels meant to be drawn for each actual pixel in the screen. If you enable the **Depth Test**, you can make sure pixels belonging to triangles behind those that have already been rendered are discarded (no point in drawing what won't be seen)

The **Stencil Test**, if enabled, is similar to the Depth Test, and is used for effects such as volume textures.

Finally, **Alpha Blending**, if enabled, blends pixels in the same location with a function and parameters you can define.

The pixels can then be sent to the **Dithering** stage, if enabled (I've never enabled it myself). Afterwards, a *Channel Mask* can be applied, and everything gets sent to the **Render Target**.

At this point, the scene is considered to be rendered. No further per-pixel operations are performed. If the render target is the actual screen, the image can then be sent to the display.

Now, onto your specific problem, I'm not sure exactly where in the pipeline is each of the debugger views probing, but my guess is that you're using the `w` coordinate incorrectly, because after the Vertex Shader, the only thing that can change the location of your vertices is the homogeneous divide.

In general, your vertices should be sent without a w coordinate. Make sure you use the right world and view matrices, and if after multiplying each vertex by your world and view matrices (you can do this by hand for debugging), your X and Y coordinates fall between -1 and 1, and your Z coordinate falls between your near and far clipping planes, your vertices will appear on the screen.

---
Tags: mathematics, directx, hlsl
---


# Question
Title: How to Change default Mouse pointer on emulator in Android?
I want to change default mouse pointer in Android emulator. I want to change it for my game to use different type of cursor.I am using AndEngine for my game development. Is there nay way to change default mouse cursor for my Application. Thanks in Advance

# Answer
I don't think the emulator has such a feature. It's built to emulate Android environment and Android environment has no such thing as a mouse cursor.
> 2 votes

# Answer
## "Faking" a Mouse-Like Interface Using AndEngine GLES2

As JanithaR mentioned, there's no "default mouse cursor" in Android. Newer versions of the Android operating system support a developer mode that shows touch events with a screen image and various apps exist that create a mouse effect for touch events.

For your own application, if you want to have something like a mouse, you should think of it as a sprite that gets re-positioned based on touch events. You'll have to decide if you want the "pointer" visible on the screen when the screen isn't being touched (i.e., whether to leave it in the last touched location or whether to remove it). You'll also have to decide whether you want multiple pointers appearing for multitouch.

Do render a sprite, you should take a look at the SpriteExample from the examples library. Basically you'll be doing something along these lines:

```
this.mTexture = new BitmapTexture(this.getTextureManager(), new IInputStreamOpener() {
    @Override
    public InputStream open() throws IOException {
        return getAssets().open("gfx/pointer.png");
    }
});

this.mTexture.load();
this.mPointerTextureRegion = TextureRegionFactory.extractFromTexture(this.mTexture);

final Sprite pointer= new Sprite(centerX, centerY, this.mPointerTextureRegion, this.getVertexBufferObjectManager());

```

You're going to want some kind of pointer image in your gfx directory. Something like these:

And you're going to want to override the onTouch() method of the sprite, so it gets relocated as you touch:

```
final Sprite pointer = new Sprite(centerX, centerY, this.mPointerTextureRegion, this.getVertexBufferObjectManager()) {
            @Override
            public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
                this.setPosition(pSceneTouchEvent.getX() - this.getWidth() / 2, pSceneTouchEvent.getY() - this.getHeight() / 2);
                return true;
            }
        };

```

## Alternative Approach to Controlling the Pointer

As an alternative, you might consider using an analog or digital on screen control (from the libraries in AndEngine) to "steer" the pointer around the screen. One of these:

Take a look at the examples library to see how to build them in and use them. If you do this you'll have to do some work to "bind" the sprite to the screen area. (Here's a discussion on that.)

## What to Do for AndEngine GLES1

As you noted in the comments, the above sample code was for GLES2. I think you'll find yourself in increasingly a land of no support if you're determined to use the older version GLES1, so the real advice I'd give is to upgrade to GLES2. (It's free, after all.)

BUT, if you really don't want to upgrade, you can still accomplish everything I've described. The key is to break it down into steps. You'll just need to:

## A Sidenote About User Experience

I know your question isn't directly getting at this, but I suspect the User Experience community would have aneurysms at the idea of implementing a mouse in this manner in Android. From a usability standpoint, it really is contrary to the "touch" experience people expect with Android and iOS. (Reminds me a bit of some early console ports of PC games.) That doesn't mean there isn't an appropriate time and place to do it, but I think it's worth giving thought to whether you really want to fake a "mouse" or if there might be an alternative, more android-friendly, approach to your problem.
> 1 votes

---
Tags: android, andengine, user-experience
---


# Question
Title: Making a Box2D ball bounce to constant height
I want to create a game like Doodle Jump. I'm using libgdx and Box2d. I needadvice on how to make my ball bounce constantly and with the same height.

I've tried setting the ball's body restitution to 1 so it can jump constantly, but when I jump on a block the "impulse" is smaller. I also tried to detect the collision, then apply an impulse but it didn't work either.

How can I make the ball bounce to the same height every time?

# Answer
When the **ball** (red trajectory curve) hits a **block higher up** (blue rectangle), it will be moving slower than when it hit a **block lower down** (green rectangle). Hence why it doesn't bounce any higher than where it came from.

Physically, this makes sense.

Doodle Jump obviously isn't physically accurate. If you want an effect like in Doodle Jump where the impulse from a collision is always the same, you should set the vertical velocity to some value yourself whenever collisions happen, with `ball.speed.y = 7;` or similar.
> 15 votes

# Answer
Box2D worlds use damping and friction, consider that the world may be applying a damping to your objects as they are simulated.
> 2 votes

# Answer
I'd also like to throw in to the mix that it may not be necessary to use a physics engine for this. Depending on how your game collisions are handled (specifically, the collision response) you may find you can create a very simply bounding box system over which you have complete control. In fact, in "doodle jump" style games it's even easier. Rather than worrying about detecting collisions in box2d and working out whether the collision should be disabled or not (e.g. you hit a platform from underneath), the doodle jump scenario actually a lot simpler. If your ball is travelling "down" (y is decreasing) and it passes the y value of a platform, and it's within the left/right bounds of a platform, then it collides. The only really "complex" thing is the parabolic flight path you'd take after, but that's just a tiny bit of math (http://en.wikipedia.org/wiki/Parabola#Equation\_in\_Cartesian\_coordinates).

Collisions with other items in the world that don't require a response (e.g. hitting a bonus) can be easily solved with just bounding boxes.

Box2D is phenomenal, but often overkill if you have simple requirements.. IMO.
> 1 votes

# Answer
Remember (float value = velocity.y) velocity of the ball before it collides with platform, and set after bounce: ball.velocity.y = value * (-1)

Maybe you will be interesting to look in this posts:
first post
second post

P.S. I can't submit code here, please look in "first post" in last comment. There is code how I resolved similar issue.
> 0 votes

---
Tags: physics, box2d, libgdx
---


# Question
Title: Farseer Physics: How to create shape from Vertices?
As you can understand from the title, I'm pretty new to game development. I'm doing this for fun. Anyway here's my question.

I have this Farseer Physics samples and i've been studying them for a few days. One thing i can't understand is, how the vertices creates the shape? I mean, in the game sample, where you create a shape for your car from vertices, there is a code like this:

```
Vertices vertices = new Vertices(8);
vertices.Add(new Vector2(-2.6f, 0.10f));
vertices.Add(new Vector2(-2.375f, -0.46f));
vertices.Add(new Vector2(-0.58f, -0.92f));
vertices.Add(new Vector2(0.46f, -0.72f));
vertices.Add(new Vector2(2.7f, -0.07f));
vertices.Add(new Vector2(2.5f, 0.205f));
vertices.Add(new Vector2(2.3f, 0.23f));
vertices.Add(new Vector2(-2.55f, 0.35f));

PolygonShape chassis = new PolygonShape(vertices, 2f);

```

I understand you create a vertices list and add 8 points(?) to it and then you make a polygonshape from those vertices, a random shape created from your points(?). The thing i can't understand is what are those numbers which inside the Vectors? I mean where in the shape are those? Corners? Edges? or a line between those two floats? Or the line between the corners?

Now lets say I want to make a shape like this

https://i.stack.imgur.com/Ac7Dv.png

What are those vertices for this picture? You can give random numbers thats not a problem, only thing I want to understand is, what are those Vectors on this picture? Thank you very much for your help and time.

# Answer
> 0 votes
`Vector2`, in this case, represents a position in 2D space. The first number you pass to the constructor is a position along the X-axis, and the second is a position along the Y-axis.

(You can also use `Vector2` to represent the relative displacement between two positions, or a direction and a magnitude - as in a velocity.)

The `Vertices` class from Farseer Physics represents a closed shape. That shape is made of of a list vectors (it derives from `List<Vector2>`). `Vertices` interprets its list of vectors as a list of *vertices* (to use the technical term). That is to say: **`Vertices` is a list of *positions* that form the *corners* of a polygon**.

`Vertices` represents a closed shape. So there are implied straight edges between each vertex and the one following it, and between the first and the last vertex.

Furthermore, many parts of Farseer expect shapes to be defined in counter-clockwise order (in standard Cartesian space, with the Y-axis pointing *upwards* \- this differs from Client space, which is used for drawing by `SpriteBatch`, where the Y axis points down). Fortunately `Vertices` provides `IsCounterClockWise` and `ForceCounterClockWise` to help ensure your shapes are defined in the correct order.

The `PolygonShape` class is essentially a wrapper `Vertices`, which allows Farseer to differentiate it from other possible shapes, like `CircleShape`.

(For context: A `Body` provides position, rotation, velocity, etc, and has one or more `Fixture`s. A `Fixture` provides friction, collision detection, etc, and has a `Shape`. If that `Shape` is a `PolygonShape`, then it will have `Vertices`.)

# Answer
> 1 votes
Those points describe the perimeter of the polygon. For your random shape those would be

(-10, -10), (10, -10), (-15,10) (15, 10)

---
Tags: c#, xna, farseer-physics-engine
---


# Question
Title: How can I switch between scenarios in a text game?
I am making a text-based adventure game. How should I go about changing to another scene if the player wants to e.g. *go to the house* or *walk down the road*?

I am using Objective C, but C will work also. Here is my code so far:

```
printf("Welcome to Kingdom Quest! This is a text game.\nYou will be shown what is going on ");
printf("and it is up to you to decide what to do. Use words like get, go and pick up.\nDo not use any upper case letters.");

printf("\n\nYou are in a feild and it is almost nighttime. You are facing north. The only thing you have is an empty ruksak.");
printf("\nWhere do you want to go");
printf("\n>");

while (true) {

char string[256];
fgets(string, 255, stdin);

if (strcmp(string, "go north\n") == 0 || (strcmp(string, "go n\n") == 0))
{
    printf("There is a rusty old sword on the ground.");
    printf("\n>");
}
else if (strcmp(string, "get sword\n") == 0 || (strcmp(string, "pick up sword\n") == 0))
{
    printf("Sword taken.");
    printf("\n>");
}
else if (strcmp(string, "go south\n") == 0 || (strcmp(string, "go s\n") == 0))
{
    printf("Nothing is this way.");
    printf("\n>");
}
else if (strcmp(string, "go east\n") == 0 || (strcmp(string, "go e\n") == 0))
{
    printf("There is a dirt road here.");
    printf("\n>");
}
else if (strcmp(string, "go west\n") == 0 ||  (strcmp(string, "go w\n") == 0))
{
    printf("There is a small mountain up ahead, with a house on top of it.");
    printf("\n>");

}
else
{
    printf("What?");
    printf("\n>");
}

```

# Answer
> 4 votes
Ok, let's go at this in a multi-stage fashion:

# Room representation

Before we can do anything else, we need to consider how to represent the rooms internally. This is just a rough thumbnail sketch, refine as necessary:

```
@interface TARoom : NSObject {
  NSDictionary *_links;    // Contains neighbouring rooms.
  NSString *_identifier;   // This will become important later.
  NSString *_description;  // The text that displays when you enter a room.
  TAInventory *_inventory; // This can get as simple or as fancy as you want, but for now we'll just pretend it's a full class.
}

@end

```

`room.links` is essentially a `{ north: TARoom(identifier) }` type dictionary.

# Input handling

With `TARoom` in place, we can focus on handling input, as a method on a notational `TAGame` class:

```
// Object here refers to a gramatical object, rather than Objective-C object.
// verb is essentially the first word of a string from the input system, and object is the rest
- (NSString *)handleVerb:(NSString *)verb withObject:(NSString *)object {
  // the player wants to move
  // a refinement would be providing synonyms
  if ([verb isEqualToString:@"go"]) {
    TARoom *destination;

    if ((destination = [self.currentRoom.links valueForKey:object])) {
      // the room exists
      return [self moveToRoom:destination]; // -[TAGame moveToRoom:] returns the room description, for instance
    } else {
      // no such room
      return [NSString stringWithFormat:@"You cannot go \"%@\"", verb];
    }
  } else if ([verb isEqualToString:@"get"]) {
    // left blank as an exercise to the reader
  } else {
    return [NSString stringWithFormat:@"I don't know \"%@\"", verb];
  }
}

```

# Answer
> 8 votes
You could think of individual places as "rooms" with "doors" connecting them:

To implement this, you could create a `struct Room` to hold a room, with fields for a *set of items currently in it* and *what directions its exits lie in*. Then simply keep an array of all rooms and have a pointer to the one the player is currently in.

There are ways of getting extra fancy with this, but simplicity is a virtue in programming.

---
Tags: objective-c, c, text-based
---


# Question
Title: How does 8-bit computers emulator work on modern days computer if the 8-bit computers software is proprietary? Do they need a permission?
How does 8-bit computers emulator work on modern days computer if the 8-bit computers software is proprietary?

I mean, that e.g. ZX Spectrum has a copyright on the stuff how it works etc. so how it is possible that there are legal emulators on the internet?

# Answer
Reverse engineering a particular system's hardware architecture and emulating it is apparently legal in most (if not all) jurisdictions. Otherwise you wouldn't find emulators for game consoles so easily. See the link provided by Derfder in comment for details on how this is considered by the US courts. This is for the hardware side of things.

But as you said yourself, the software running on those systems is most of the time proprietary. It's thus perfectly illegal to distribute ROMs for emulators without the owner's consent. If the owner doesn't care, then it's abandonware and you're in a grey area. Probably most of the ZX Spectrum games can be considered abandonware today, but I wouldn't be too confident either. That's why most emulators creators never ever distribute ROMs.
> 5 votes

---
Tags: emulation
---


title: Managing graphic state and components?

text:
# Question
Title: Managing graphic state and components?
I often tend to do a lot of premature optimazation when dealing with graphics. There are a few principles I always try to follow:

* **Keep the number of D3D components to a minimum.** (Render states, buffers, shaders, etc.)
* **Only bind components if absolutely necessary.** (Not bound already, etc.)
* **Specialize the components as much as possible.** (Only set necessary BindFlags, etc.)

This lead me to building very elaborate wrappers for managing the created components and the current pipeling state. Not only does this consume a lot of my valuable development time, it also adds another big layer of complexity.

And worst of all: **I don't even know if it is all worth the trouble.**

Some of my optimization considerations may already be implemented on a lower level and I am just replicating them, additionally wasting time on the CPU. Other considerations may be completely unnecessary, since the effect on performance is negligible.

So my questions are:

1. Which of the above guidelines are valid and to which extent should I follow them?
2. How does the GPU handle state changes?
3. What happens if I change a state that is never used? (No draw call being made while it is active.)
4. What are the actual performance penalties for binding the various different components?
5. What other performance considerations should be made?

Please don't just tell me, that I just should not care about performance until I hit actual limits. While that is obviously true from a practical point of view, I am mainly interested in the theory. I somehow need to combat the urge of building *the optimal graphics framework* and I don't think I can do that with the usualy "premature optimization lecture".

### Managing components

I am currently writing DirectX 11 applications in C# using SlimDX as a managed wrapper. It is a very low level wrapper and my current abstraction is built on top of it.

There are some obvious advantages when using a Direct3D abstraction. Setting up the environment, loading shaders, setting constants and drawing a mesh is much simpler and uses *a lot* less code. Also, since it manages creation and disposing of most components they can be automatically reused *everywhere* and I almost completely avoid memory leaks.

1. How do you usually manage all the graphics components and resources?
2. Can you recommend any managed wrappers doing something similar to my example below?

Here is an example of my current implementation. I am quite happy with the interface. It has enough flexibility for my needs and is very simple to use and understand:

```
// Init D3D environment
var window = new RenderForm();
var d3d = new Direct3D(window, GraphicsSettings.Default);
var graphics = new GraphicsManager(d3d.Device);

// Load assets
var mesh = GeometryPackage.FromFile(d3d, "teapot.gp");
var texture = Texture.FromFile(d3d, "bricks.dds");

// Render states
graphics.SetViewports(new Viewport(0, 0, 800, 600);
graphics.SetRasterizer(wireFrame: false, culling: CullMode.Back);
graphics.SetDepthState(depthEnabled: true, depthWriteEnabled: true);
graphics.SetBlendState(BlendMethod.Transparency);

// Input layout
graphics.SetLayout("effect.fx", "VS", "vs_4_0",
    new InputElement("POSITION", 0, Format.R32G32B32_Float, 0),
    new InputElement("TEXCOORD", 0, Format.R32G32_Float, 0)
);

// Vertex shader
graphics.SetShader(Shader.Vertex, "effect.fx", "VS", "vs_4_0");
graphics.SetConstants(Shader.Vertex, 0, 4, stream => stream.Write(wvpMatrix));

// Pixel shader
graphics.SetShader(Shader.Pixel, "effect.fx", "PS", "ps_4_0");
graphics.SetTexture(Shader.Pixel, 0, texture);
graphics.SetSampler(Shader.Pixel, 0, Sampler.AnisotropicWrap);
graphics.SetConstants(Shader.Pixel, 0, 1, stream => stream.Write(new Color4(1, 0, 1, 0);

d3d.Run(() =>
{
    // Draw and present
    d3d.BackBuffer.Clear(new Color4(1, 0, 0.5f, 1));
    graphics.SetOutput(d3d.BackBuffer);
    graphics.Draw(mesh);
    d3d.Present();
}

```

# Answer
> 3 votes
I like the abstraction approach outlined by Hodgman in these threads on gamedev.net:

He describes a three-tier rendering system:

1. Low-level rendering API that accepts "commands", abstracting no more than the differences across different graphics API's, such as Direct3D 9, Direct3D 11, and OpenGL. Each "command" maps to a different state or draw-call, such as binding a vertex stream or texture, or drawing the primitives.
2. API that accepts "render items", which group together all the states and a single draw-call needed to render a certain object, and sorts and translates them into commands which are sent to the first level. A render state contains a draw-call and a stack of "state groups", which logically group state-changes. For example, you'd have a state group for the render pass, a state group for the material, a state group for the geometry, a state group for the instance, and so on. This level is responsible for sorting these render items to reduce redundant state changes and culling any state changes which are, in fact, redundant.
3. High-level systems like a scene graph or GUI renderer which send off render items to the second level. The important thing to notice is that these systems don't know about either the state sorting algorithms or the specific rendering API, making them completely platform-agnostic. They're also easy to use once the lower-level API's have been implemented.

In conclusion, this model solves both of your problems at once.

---
Tags: directx, performance
---


# Question
Title: How can I ease the work of getting pixel coordinates from a spritesheet?
When it comes to spritesheets they're usually easier to use, and they're very efficient memory-wise, but the problem that I'm always having is getting the actual position of a sprite from a sheet. Usually, I have to throw in some aproximated values and modify them several times until I get it right.

My question: is there a tool which can basically show you the coordinates of the mouse relative to the image you have opened? Or is there a simpler method of getting the exact rectangle that the sprite is contained in?

# Answer
> 4 votes
There are tools for creating spritesheets from individual images that will also output a meta-data file describing where each image is placed in the spritesheet.

For example you could use Texture Atlas Generator to create the spritesheets. In this blog post I show how you'd work with the output to get animations playing in Flash quite effortlessly.

Even if Flash is not your language of choice you might still be able to use a similar approach.

# Answer
> 3 votes
If you use Photoshop, you can use this method.

1. Set units to pixels. *Edit → Preferences → Units and Rulers*.
2. Open the *Info* tab to see the current mouse position.

You can also draw a *Rectangle Marque* selection around your sprite and see it's width and height in the *Info* tab.

# Answer
> 2 votes
There is a tool you can use to do it manually that is relatively painless:

http://tech-tutors.net/downloads/

And there is a tutorial here:

http://www.youtube.com/watch?v=smOtRuxoIs8

I can share something automated on github if people are interested, the main catch is that if the frames are not even in size which is common, you may need to adjust them manually anyway.

What normally happens when I work with sprites is that the frames are put into an even grid for ease of use. Then every sprite depending on the frame size is in `(j * FRAME_WIDTH, i * FRAME_HEIGHT);`. If that is not the case cause the artist is not aware of programming needs, I cook up a tool that displays the sprite sheet on screen and saves my click's `(mouseX, mouseY)` positions into a file. I then use that file to split the spritesheet.

I can elaborate on how to create a tool like this or you could use Ivan's advice.

If you do go with making a tool, you may want to both save the first click (for frame's top-left corner, and another click in the bottom-right to get the width and height).

I personally prefer the grid method, have your artist or friend cut and paste the frames into an even grid made of sufficiently large blocks. It would save you time if you have several sprites. Otherwise if there are many spritesheets and they are not in an even grid, you may want to cook up a tool or look for one online(I am not aware of any). They are not difficult to make.

I can upload the source for the tool I use myself to a github for you to download. It saves the results into a text file organize by a list of four values for each frame.

example:

x, y, width, height, x2, y2, width2, height2, ... ,xn, yn, widthn, heightn

You will have to sort (in the code which frame is which) to use the animation correctly.

# Answer
> 1 votes
Hope I am not late here

You can use a tool like this and get background positions of the icons in the sprite.

You need to first upload your image, then select an icon from the sprite. CSS will be generated, just copy the generated CSS and use it in your class.

Other options are

1. You need to open the image in an image editor like Photoshop. From there you can find the X and Y position anywhere in the image. Please note that left, top is 0,0. Get the x and y position and use like this

background-position: -310px -123px;

Please note the "-" sign before X and Y co-ordinates.

2. Start with

background-position: 1px 1px;

Use Firebug (a firefox extension)to modify the values on the fly. By trial and error method you can find exact position.

---
Tags: sprites, tools, spritesheet
---


# Question
Title: Should I target a mobile phone or simulation tools are good enough?
1. I'm starting mobile development, and I would want to know if it's necessary to target a specific smartphone, or nowadays one can run a simulation that will provide accurate data of how the game will perform on a given device.
2. If simulation tools are not good enough, what version of **iPhone** and what **Android** mobile should I target as of 2013, for making games like Angry Birds, Jetpack Joyride, etc? (2D games only) I would buy that smartphone and make my tests there.

# Answer
> 6 votes
No simulators that I know of give reasonable expectations of on-device performance. The iOS simulator, in particular, is very bad. And I think the Android one is an emulator.

# Answer
> 1 votes
Yes, before starting Android game development, you must have a real phone, not emulator. Emulator in almost all cases doesn't work as expected and it can really make trouble.

---
Tags: 2d, android, iphone, mobile, testing
---


title: Sketchup model renders wrong in XNA

text:
# Question
Title: Sketchup model renders wrong in XNA
My XNA model renders wrong.

It should render like that:

But it renders like that:

The background doesn't matter. It's just the model that renders wrong.

Here is the drawing code:

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

    DrawModel(model);

    base.Draw(gameTime);
}

private void DrawModel(Model m)
{
    GraphicsDevice.RasterizerState = RasterizerState.CullNone;

    Matrix worldMatrix = Matrix.CreateRotationY(MathHelper.ToRadians(rot))
        * Matrix.CreateTranslation(new Vector3(0,0,0));

    foreach (ModelMesh mesh in m.Meshes)
    {
        foreach (BasicEffect effect in mesh.Effects)
        {
            effect.EnableDefaultLighting();
            effect.World = worldMatrix;
            effect.View = viewMatrix;
            effect.Projection = projectionMatrix;
        }

        mesh.Draw();
    }
}

```

# Answer
The problem you are describing could be caused by polygons with more than 4 vertices. Please make sure that you have edges in the model as seen in the image below:
> 5 votes

---
Tags: xna, c#, xna-4.0, rendering, models
---


# Question
Title: Last level of puzzle games - hard or easy?
Currently I am creating a puzzle game, and I am finishing all the levels... and then I run into this problem:

From puzzle games that I played, I find that the design of the very last level goes into two distinct categories:

1. Very hard level, possibly the hardest of all.
2. A very simple level, like a farewell (e.g. the level is composed of a word "BYE", something like that)

Though in most games I lately played go for the first approach, I would like to ask **which is better**?

---

For more information, my levels are divided into 10 sets. Each set consists of 10 levels. Every set introduces a new element. Within each set, the first level is easiest (as well as used to introduce the new element) and last hardest.

However, for the last set, no new element is introduced but consists of hard levels.

Actually, with above design, I would *feel* that I should go for the first approach, but I would like what others say.

# Answer
I think it should reflect the way the other levels are handled. If the others become sequentially harder, I'd make the last one the hardest. Making it simple feels like it might be a letdown to the player. They are prepared for the level, and then there's nothing much to do.

I guess it's just my opinion that this kind of change ought to be fairly predictable to the player at some point in the game. I suppose you could intersperse easier and harder ones.

At some point, it depends on what hard means for your game.
> 2 votes

# Answer
If your last level is ridiculously easy, the players will not perceive it as a challenge, or even a "level" per se, but as you already said, like a goodbye message.

Technically speaking, the "last level" isn't the goodbye message, which is just a novel, slightly more engaging way of saying "bye" or "well done".

You could also see it as a reward for finishing a set of levels.
> 1 votes

# Answer
Well I would say it depends on some factors, if it is just a plain puzzle game it's one thing, but if it's, for example, a game with a story, characters and whatnot you could also make something like: Present something that looks like a near impossible puzzle, but then something happens or everything breaks and then it's just a minimal task to get to the end.

That "something" could be some sort of turn of events, a catastrophe, anything that could fit the story.

If the game is not story based and just pure puzzle solving, I would say that it is a good idea to make a hard puzzle, but easier than before, so that they still get some challenge while getting a breather at the same time and just relaxing while they finish it.
> 1 votes

---
Tags: level-design, puzzle
---


title: Viewport like Angry Bird in Corona

text:
# Question
Title: Viewport like Angry Bird in Corona
Not sure if that's the right name for it, but I'm looking for a way to implement zooming in my game.

Essentially the game should zoom in on my character during the moving and shooting phase (its like Worms), but zoom out when the character has shot (preferably by following the shot, like Angry Birds does).

Can Corona/Lua do something like this?

# Answer
I think you can attach everything to the same group and then scale that group: http://docs.coronalabs.com/api/library/display/newGroup.html
> 1 votes

# Answer
Actually, you can do it with scaling all images on the stage. It's like scaling all display objects include physics and/or non-physics objects.

You can check out xScale, yScale features from CoronaLabs website. Also, you should be careful about the reference points of the objects. Cause of, scaling depends on the reference point of the object that you scale.

If there are more specific questions in your mind about these usages, then please comment.
> 0 votes

---
Tags: lua
---


# Question
Title: SpriteBatch.end() Issue because of a thread
While playing, I use a thread to `Load()` and `Unload()` `Texture2D`. I have multiple `ContentManager` to only `Unload()` `Texture2D` I want to unload.

But sometimes, I have this issue on the `SpriteBatch.End()` :

```
    ObjectDisposedException: Cannot access a disposed object
    Object name : texture2D

```

I don't understand very well the `Threads`, and I think it's the main problem. Roughly :

```
    Game.Update(GameTime gameTime)
    {
        character.Update(gameTime);
        //...Things.Update(gameTime)...
        CheckThingsToLoadandUnload();
    //etc
    }

    CheckThingsToLoadAndUnload()
    {
        For each texture to check
        {
            if(HasPrerequists)
            {
                if(!thisTexture.isLoaded)
                {
                    ThreadStart ths_LoadInGame = delegate {
                        LoadInGame(param1, param2, param3); };
                    new Thread(ths_LoadInGame).Start();
                }
            }
            else
            {
                if(thisTexture.isLoaded)
                {
                    ThreadStart ths_UnloadInGame = delegate {
                        UnloadInGame (param1, param2); };
                    new Thread(ths_UnloadInGame ).Start();
                }
            }
        }
    }

```

I overrided the `T Load<T<(string assetname)` `ContentManager` to add a `Lock`.

I think this issue happens when the `Unload() Thread` unload a Texture used by the SpriteBatch(). But I really don't know how to prevent this. Hope you can help.

# Answer
> 0 votes
With the participation of "dadoo Games", here is my answer.

Thread :

```
Unload()
{
   if(canUnload) { UnloadTextures() }
}

```

DrawMethod :

```
Draw(GameTime gameTime)
{
    canUnload = false;
    DrawScenes();
    base.Draw(GameTime);
    canUload = true;

```

---
Tags: xna, c#, multithreading, spritebatch
---


# Question
Title: Movement constrained to the faces of a cube
The basic setup I'm working with is a cube rendered in-Engine (Panda3d, although I only am looking for a generalized solution) as well as a 2d square on one face of the cube. The eventual outcome I'm looking for is for the player to control the 2d square with WASD as it moves on the faces of the cube (never anywhere else)

My current solution is to have the player object contain two unit vectors: `forward` and `right`. The `forward` vector controls with direction the player moves when W/S are pressed, and `right` controls the direction for A/D. So for example, the player starts out on the near Y face (y = -1), so the vectors are:

```
forward = {0, 0, 1}
right = {1, 0, 0}

```

When the player's position exceeds the a boundary of the cube (e.g. on a unit-cube, the Z coordinate is greater than 1), `forward` and `right` are recalculated for the new face the square should be on, and the square is appropriately rotated.

I've started to get this working, however, in this early implementation, there is a fixed camera. Eventually, the camera is planned to move to be orthogonal to the face the cursor is currently on, so I realized that what signifies "forward" is going to vary based on the path a player takes to get to a face. My struggle is to now find an appropriate movement method to the cube-face constrained motion, with a moving camera.

# Answer
Your forward vector should always equal the up vector of your camera in this case(where you are rotating the camera around the world) after you have applied the rotation to it. For the right vector, you can take the cross product of the camera up vector and the camera look at vector, keeping in mind that the order that you do the crossproduct matters and depending on what coordinate system you are using (right or left handed).
> 1 votes

---
Tags: 3d, mathematics, graphics, movement, vector
---


# Question
Title: Xna custom mouse not allowing me to move its sprite past certain bounds
I have written a Custom mouse, with a Custom sprite, using `MouseState`, and getting the X and Y variables. However i also have a camera that i wrote, and this allows me to leave the initial box. One sprite that can freely move this area, but my mouse gets stuck in a box that seems proportional to my screen resolution some times.

```
  //This is where i create the Texture, Vector and MouseState of the Custom Cursor
Texture2D Mouse_texture;
MouseState mouse_state;
Vector2 Mouse_pos;

  // This is my Resolution and i have IsFullScreen = true
graphics.PreferredBackBufferWidth = 1600;
graphics.PreferredBackBufferHeight = 900;

  // Loading the Texture
Mouse_texture = Content.Load<Texture2D>("mouse");

  // Getting the current mouse State this is in the update function
mouse_state = Mouse.GetState();

  // How i set the mouse position Simple Vector2 stuff and i never do anything else
  //   to handle the the position of the mouse
Mouse_pos = new Vector2(mouse_state.X, mouse_state.Y);

  // and this is me Drawing it
spriteBatch.Draw(Mouse_texture, Mouse_pos, Color.White);

```

If you need any more code let me know

# Answer
> 4 votes
This sounds like an issue of not translating mouse coordinates / screen coordinates into world coordinates.

The easiest way you could solve this that also comes with its own limitations is to calculate your mouse draw position based on the camera position and the mouse state. Something like:

```
Mouse_pos = new Vector2(mouse_state.X + Camera.Position.X, mouse_state.Y + Camera.Position.Y);

```

The exact code for your implementation will likely be slightly different but you should be able to get the gist of it from this snippet.

There are much more versatile solutions than this which include projecting screen coordinates into world coordinates and get away from using pixels as the units for your world altogether. This is going to be a much more elegant solution that you may want to look into, and perhaps someone else could post an answer on, but to keep things simple you can definitely start with what I've shown above.

This solution should also solve the problem if you are shifting the camera negatively along the axis instead of positively.

Here's an image to help better illustrate the problem and the solution:

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


# Question
Title: Poor image quality on Android through Unity Remote
I have started to work on the company's latest project using Unity3D and the workflow is just awesome.

The problem is when running the game on a real Android device (using Unity Remote) the image quality is very poor in comparison to how it looks in the editor:

(Click for a full view. Look at those sprite edges.)

Is this...

# Answer
> 5 votes
You've answered your own question. Yes, Unity remote compresses the hell out of your game and sends screenshots to the phone. It looks entirely different with an actual build. (an installed .apk)

---
Tags: android, unity, graphics
---


# Question
Title: Using compressed(ETC1) textures in LibGDX
I use standard android tool for compressing PNG texture and archiving it with gzip:

```
/android-sdks/tools/etc1tool texture.png --encodeNoHeader
gzip texture.pkm

```

Then I try to load it:

```
FileHandle file = ...;
ETC1.ETC1Data data = new ETC1.ETC1Data(file);
ETC1TextureData td = new ETC1TextureData(data, false);
Texture texture = new Texture(td);

```

But I get an `java.nio.BufferOverflowException` inside `ETC1Data (FileHandle pkmFile)` constructor:

```
  in = new DataInputStream(new BufferedInputStream(new GZIPInputStream(pkmFile.read())));
  int fileSize = in.readInt();
  compressedData = BufferUtils.newUnsafeByteBuffer(fileSize);
  int readBytes = 0;
  while ((readBytes = in.read(buffer)) != -1) {
      compressedData.put(buffer, 0, readBytes);//Exception occurs here
  }
  compressedData.position(0);
  compressedData.limit(compressedData.capacity());

```

How to fix it? Thanks.

ps if it's important: unarchived pkm file size is 33KB

# Answer
> 2 votes
Standard tool from Google is not suitable for compression. But ETC1Compressor works fine.

---
Tags: opengl, android, textures, libgdx, compression
---


# Question
Title: Returning The Position Of A Sprite Drawn & Updated By A List
My problem is this, when iceBoy hits any of the newGrounds in the ground.groundAmmount list, it will return the specific position of this newGround so that i can set iceBoy's position based on the newGround that he touched. Here is the code that i have for this:

```
foreach (Ground newGround in ground.groundAmmount)
{
      if (HitGround())
      {
           iceBoy.position.Y = newGround.position.Y;
      }
}

```

but like Byte56 this will only loop through all of the newGrounds in the list and then iceBoy.position.Y will only equal the last newGround added to the list. how could i create another method that will have a return value of the position of the exact newGround that iceBoy is touching?

# Answer
The main problem with this code is that you don't know where it hit ground.

```
foreach (Ground newGround in ground.groundAmmount)
{
      if (HitGround())
      {
           iceBoy.position.Y = newGround.position.Y;
      }
}

```

So if `iceBoy` has hit *any* ground, you'll loop through and change his `y` position to each `newGround` block. That's why you're only seeing this: "only worked for the last sprite drawn in the list".

I don't know how your `HitGround()` function works, but you'll want to modify it in one of the following ways:

1. Make it take an argument to test against a specific tile.
2. Make it return the tile that iceBoy hit.

In the first case:

```
foreach (Ground newGround in ground.groundAmmount)
{
      if (HitGround(newGround))
      {
           iceBoy.position.Y = newGround.position.Y;
      }
}

```

For the second case:

```
 Tile newGround = HitGround();
 if (newGround != null)
 {
     iceBoy.position.Y = newGround.position.Y;
 }

```

Additionally, depending on your drawing origins, you'll want to modify your offsets as Roy T. suggests.
> 3 votes

# Answer
Are you having problems detecting when two sprites touch? Detecting if two rectangle colide is relatively easy, especially if the rectangles don't rotate (eg they are axis-aligned). A good start would be to read this article and to look up the separating axis theorem (which is a fast way to determine if two non-rotated rectangles intersect).

Another problem you might have is that your code, as it is now, makes two sprites overlap. To place one sprite on top of another sprite you should not write this:

`iceBoy.position.Y = newGround.position.Y;`

But this:

`iceBoy.position.Y = newGround.position.Y + iceBoy.dimensions.Y;`
> 2 votes

---
Tags: xna, xna-4.0, sprites
---


title: Outline sprites

text:
# Question
Title: Outline sprites
I'm currently working on a 2D game, and my current task is to outline selected object.

I basically use a blur shader to do it fully runtime. I first draw my sprite using a vertical gaussian blur shader, then I draw it with an horizontal gaussian blur shader, and then I draw my sprite normally.

Here is my blur shader: sampler TextureSampler : register(s0);

```
#define SAMPLE_COUNT 15

float2 SampleOffsets[SAMPLE_COUNT];
float SampleWeights[SAMPLE_COUNT];

float4 PixelShaderFunction(float2 texCoord : TEXCOORD0) : COLOR0
{
    float4 c = 0;

    // Combine a number of weighted image filter taps.
    for (int i = 0; i < SAMPLE_COUNT; i++)
    {
        c += tex2D(TextureSampler, texCoord + SampleOffsets[i]) * SampleWeights[i];
    }

    return c;
}

```

SampleOffets are the offsets allowing me to test rounding pixels SampleWeights are weights calculate with gaussian function (http://en.wikipedia.org/wiki/Gaussian\_blur)

Here is the result:

It's not that bad, quite smooth, but not enough visible in game... But I'd like to be able to control the thickness (to make it larger), and add a first opaque outline before fading it in alpha (to make it more visible). And i feel like gaussian blur is maybe not as good as I thought for my task :)

Another idea is to generate it automatically from the .png (using a photoshop script to make it automatic). I just need to fill the outline pixels with a custom color, storing the alpha value in the Red component for example, and set all other components to 0. Then I just have to apply a shader which replaces transparent pixels to the color I want

```
float4 PixelShaderFunction2(float2 texCoord : TEXCOORD0) : COLOR0
{
    float4 color = tex2D(TextureSampler, texCoord);
    float4 newColor = 0;
    if (color.a == 0 && color.r != 0)
    {
        color.a = color.r;
        // Blue outline
        color.b = 1;
    }
}

```

Problem is, I'm using DXT5 compression for my sprite, so I can't be sure the color I'll get in my shader will be the exact same I wrote. That's why I didn't even try it... Any thoughts?

Any advice would be welcome :)

# Answer
What you are probably looking for is a form of edge detection before, after, or even before and after your Gaussian blur. Maybe a version of Sobel Edge Detection could work. I know your game is 2D but if the wiki page is too rough here's a tutorial on how to get it working in the UDK that might translate over better.

Your edge detection only really has to find the edges of the alpha channel if you need a speed boost.
> 6 votes

# Answer
What worked for me with text outlining was:

* Pick the outline colour
* Draw the text at (x-1, y-1) with outline colour
* Draw the text at (x+1, y-1) with the outline colour
* Draw the text at (x-1, y+1) with the outline colour
* Draw the text at (x+1, y+1) with the outline colour
* Draw the text at (x, y)

You can do the same thing -- all you need to do is draw the sprite with the opaque pixels coloured with your outline colour. (Maintain transparency values so that round edges still look round).

This works, looks better than drawing a scaled version, and has some other cool properties (like being able to control the outline alpha for boldness, and retaining any "holes" in your sprite image) -- the only drawback is that you can't really control the width of the outline too well.
> 2 votes

# Answer
I'm kind of new to all of this, but here is my idea:

You could use your texture's alpha channel to make another texture. Any alpha value below a threshold value will be set to fully transparent. Any above will be fully opaque. Using this new texture, you could set the values of RGB to be any color you'd like. Scale this new "texture" to be slightly bigger than your character texture. This would give you a nice solid color around the character. Then use that color with your Gaussian shader to give the nice outlined glow around your created texture. I'm guessing this could be done without creating another texture, and be all shader based off the character texture.

Does this make sense at all?
> 1 votes

---
Tags: xna-4.0, fragment-shader
---


# Question
Title: What kinds of 3D objects should a game engine have?
I know this is a pretty general question. But I've been looking for different kinds of 3D objects and their names to implement in my engine to boost its speed.

Static meshes, dynamic(?) meshes and what else?

Thanks in advance!

# Answer
This is really a very unspecific question and an answer would completely depend on the game you are trying to build. I also wonder what performance improvements (?) you expect.

The system I am building consists of two layers. The bottom layer is the renderer. It can draw *instances* of meshes. Each instance type has its own specialized vertex shader. These are the instance types I am currently using:

* **SimpleShape**: Has a 2D position and size in screen space and a source rectangle for the texture. Vertices consist only of a 2D vector for the position. Can be used for simple sprites or font letters. Uses hardware instancing.
* **Shape**: Same as SimpleShape, but has an individual origin and can be rotated and flipped. I use it for more complicated sprite effects.
* **Billboard**: Billboards are very similar to shapes, but they are positioned in 3D space and always face the camera. They can be used for particle effects or vegetation.
* **Static**: 3D models that are not animated. They have a translation, rotation and scaling amount in 3D space. The vertices consist of a position, texture coordinates, normal and tangent vector. I use them for all kinds of props. The tangent is used for bump mapping.
* **Animated**: Same as the Static instance, but additionally has an array of matrices (bone transforms). The vertices also have an array of weights. This type is used for animated meshes.
* **Terrain**: Basically I could use the static type for terrains as well. But since my terrains are always regular grids, there is room for optimizatiom. A terrain instance cannot be rotated or scaled, only translated. Also, instead of a normal and tangent the vertices have a 2D *slope* component. I use it for calculating tangent space in the vertex shader.

The second layer is built on top of the rendering layer. It has more complex objects that are then translated to the above instances. There is a lot of room here for creativity. Here are some ideas:

* **Text**: I use sprite fonts for drawing text. Using the font data each character can be translated to a SimpleShape instance.
* **Sprite**: Textured squares that can be drawn to the screen. Sprites are translated to shapes.
* **Particles**: Spawns particles that behave in a certain way. For example, the movement can be controlled by a script. Individual particles are translated to billboards.
* **LenseFlare**: Lense flares are attached to a light source and consist of various components, which behave in a certain way. Each component is translated to a collection of Shape instances.
* **Model**: Consists of various meshes that are bound to a node structure. Each node can be transformed relatively to a parent node. The individual meshes are translated to Static instances. Additionally, nodes can also contain particle effects or other types of complex objects.
* **Character**: Has various animations that can be played. When rendered, a single frame (a set of transformation matrices) is used for drawing the mesh as an Animated instance.
> 0 votes

---
Tags: architecture
---


# Question
Title: XNA Skinned Model - Keyframe.Bone out of range exception
I'm getting an IndexOutOfRangeException on this line of AnimationPlayer.cs: `boneTransforms[keyframe.Bone] = keyframe.Transform;`

I don't get what it's really referring to. The error happens when keyframe.Bone is 14, but I have no idea what that's supposed to mean. The 14th bone of my model? What would that even be? I read this thread, but nothing there seemed to work. I don't have many bones, stray edges/verts, unassigned verts, unparented/non-root bones, or bones with dots in the name. What else can I be missing?

Thank you for any help!

# Answer
> 1 votes
Found the problem. It was because I was trying to call two animations with different lengths for the same AnimationClip. I had a `Move` class that would run animations for the correlating model based on a name parameter, 'Walk' in this case--there should've been two different instances of `Move`, even if they both use the same animation name.

---
Tags: xna-4.0, skeletal-animation
---


title: 3D Character Development

text:
# Question
Title: 3D Character Development
First and for most. I do have a fair amount of experience programming. I have experience with many programming languages and I have taken a few courses in computer science. I have development some basic 2D games from scratch (Tron, Pong and Tic-Tac-Toe). However, I am a noob when it comes to 3D games design. What I wanted to do was to create a basic character and to implement some movements on the character in a blank space. Now there are numerous software out there and I can't wrap my head around all the information. Could someone please set me in the right direction with what software I should learn (e.g. Autodesk, 3DS Max, I dont even know if these are the right ones).

As a side note I also wanted to develop some advanced character movements, kinda like the ones you see in the Assassins Creed series. I was very curious as to how this is done and the software involved. So again could someone please point me in the right direction here as well.

Thanks for the help, I really appreciate it.

# Answer
> 1 votes
Ok you listed 'Autodesk' as example but Autodesk is not one software it is the company that make Autodesk Revit, Autodesk AutoCad, Autodesk Maya, Autodesk 3ds MAX studio and Autodesk Inventor. But since you can do animation with said softwares, you will be limited in what you can do in a free trial unless you are ready to buy them...

I will suggest Blender because it is free and opensource. If you make something and later wish to publish it as a game, you can. No strings attached. It has also been used in many animation movies through out and is quiet famous in the industry as such.

The best part is, it also comes with it's built-in game engine which you can use to create your very own 3D game.

There are also a lot of good tutorials to get your feet wet.

---
Tags: 3d, movement, character
---


title: Automatch / queueing players

text:
# Question
Title: Automatch / queueing players
I'm using Node.js and Redis. I'm trying to come up with a reliable way to automatch players. There is a matching server and then multiple game servers set up.

The following is what I need to have happen:

1. Player sends join request with game type (small/medium etc)
2. Matching server adds player to the current game type that is waiting for players
3. Game server sends player the game ID

Currently I have implemented this as follows:

1. Matching server listens to game:queue:small using BRPOP
2. Checks if game:queue:small:id = id exists
3. Checks if game:id:users length is \<= 6 (max players)
4. Adds player to game:id:users list if it is
5. If game length is now 6, it removes game:queue:small:id

If the matching server finds game:queue:small:id is missing, it does as follows:

1. INCR game:nextGameId
2. Sets game:queue:small:id to the previously generated ID
3. Adds the game ID to game:queue:waiting

The game servers wait using BRPOP for new games. When they get one, they wait until the game has a minimum of 2 users then start a timer. If they don't fill up in that time, they begin with the users they have and subsequently remove game:queue:small:id (thus forcing the matchmaker to request a new game).

Whilst my method is working, I'm not convinced it will work well in production and it seems very convoluted. I can see the potential for the following issues:

* Game server crashes after accepting the game ID from the waiting list resulting in users getting added to the game:id:users but nothing happening with them (the crash itself isn't a problem, but users continuing to get added to that games queue is)
* If a user disconnects and the game hasn't started, the game server will remove the user from the game:id:users list. Whilst it is in the process of doing that, the matchmaking server could be adding a user to the list and think the game is full, thus removing it from the queue.

My initial thoughts were to change to a single queue of users waiting for one game type. However, this presents further issues:

* If the server that the users connects to crashes, it won't remove the user from the queue thus leaving that user to be entered into a game when they don't exist. I could use sorted sets to store the time of the request and have the client poll until it gets a game ID returned but this would mean that I have no idea of how long that client has waited and therefore do not know whether to start the game with fewer users.
* Without putting the users into a game, they have no ability to see what users have joined, nor the ability to chat with the users that are waiting (as that requires a game ID).

None of the way I have set this up feels right so I was hoping someone might be able to offer some better suggestions. I really need to keep the game servers and the matchmaking servers separate though in order to grow them out as required.

# Answer
Your first and foremost error is to use a database for a live queue, that data is much better off stored in process memory in the matchmaking process. Let the processes communicate with one another directly. Then it is also pretty much forced on you that it is the sole responsibility of the matchmaking server to remove players from the queue when they are put in a game, as it should be.

More generally about matchmaking, delay the decisions of what exact matches to make until the point where the game starts, if you have 3 players that fit a 4 player game, don't decide that they have to play that type of game before there is also a 4th player, it could take long for that player to arrive, and some of them might quit waiting in the meantime. A decent implementation for this is to have a queue for each game type and put each player in all queues matching their request, then when a queue is full start the game and remove the involved players from all of their queues.
> 2 votes

---
Tags: server, node.js, matchmaking
---


# Question
Title: Matrix in constant buffer on the GPU contains NaNs but not on the CPU
I've got a shader with the following constant buffer:

```
cbuffer ShaderParameters
{
    matrix inverseViewProjectionMatrix;
    float4 cameraPosition;
};

```

When using Visual Studio 2012's graphic debugger I see that the last column of this matrix contains only NaNs, the other values are correct. So somehow my program is passing wrong values to the GPU.

However when I debugged my C++ code I see no NaNs in the matrix that I upload to the GPU. So what is going on? Below are the relevant parts of code

Struct for the constant buffer on the CPU:

```
struct ShaderParameters
{
    XMMATRIX inverseViewProjectionMatrix;
    XMFLOAT4 cameraPosition;
};

```

Buffer creation:

```
D3D11_BUFFER_DESC shaderParametersDesc;
shaderParametersDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
shaderParametersDesc.ByteWidth = sizeof(ShaderParameters);
shaderParametersDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
shaderParametersDesc.MiscFlags = 0;
shaderParametersDesc.StructureByteStride = 0;
device->CreateBuffer(&shaderParametersDesc, NULL, &m_shaderParameters);

```

Buffer setting (every frame)

```
D3D11_MAPPED_SUBRESOURCE mappedResource;
ShaderParameters* shaderParameters;
deviceContext->Map(m_shaderParameters, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
shaderParameters = (ShaderParameters*)mappedResource.pData;

XMMATRIX view = camera->GetViewMatrix();
XMMATRIX proj = camera->GetProjectionMatrix();
XMMATRIX mult = XMMatrixMultiply(view, proj);
XMMATRIX invp = XMMatrixInverse(nullptr, mult);

if(XMMatrixIsNaN(invp))
    throw std::exception("invp is NAN");

shaderParameters->inverseViewProjectionMatrix = XMMatrixTranspose(invp);
shaderParameters->cameraPosition = camera->GetPosition();

deviceContext->Unmap(m_shaderParameters, 0);
deviceContext->VSSetConstantBuffers(0, 1, &m_shaderParameters);

```

Note that the exception is never thrown and if I inspect the matrix manually there are sane values in there (see image)

EDIT: some asked (via twitter) to include some more shader source code as unused values might be seen by the debugger as NaN. So here is the complete vertex shader:

```
cbuffer ShaderParameters
{
    matrix inverseViewProjectionMatrix;
    float4 cameraPosition;
};

struct VertexInputType
{
    float4 position : POSITION;
    float4 uv       : TEXCOORD0;
};

struct PixelInputType
{
    float4 position         : SV_POSITION;
    float4 direction        : TEXCOORD0;
    float4 cameraPosition   : TEXCOORD1;
};

PixelInputType main(VertexInputType input)
{
        PixelInputType output;

        input.position.w = 1.0f;
        output.position = input.position;

        output.direction = mul(input.position, inverseViewProjectionMatrix) - cameraPosition;
        output.direction.xyz = normalize(output.direction.xyz);

        output.direction.w = 1.0f;

        output.cameraPosition = cameraPosition;

        return output;
}

```

# Answer
> 5 votes
The person on Twitter was right.

Because you overwrite output.direction.w with 1.0f the shader optimizer will see that it doesn't need to use that row of the matrix to calculate it.

Try commenting out that line to see the effect - the disassembly will include an extra dp4 instruction when it's gone.

---
Tags: directx, shaders
---


# Question
Title: Pygame fails on KEYDOWN with Russian keyboard layout
When I press a keyboard button on a keyboard with a Russian layout, my application pygame game crashes with this message:

> UnicodeEncodeError: 'ascii' codec can't encode character '\u0444' in position 40: ordinal not in range(128)

This is my code:

```
 event = pygame.event.poll()
 if event.type == KEYDOWN:
    print(event)

```

(I pressed the latin 'a' key.)

Pressing keys in the English layout works fine.

I tried changing the `event.type == KEYDOWN` to `event.type == KEYUP`: Everything works, but then I cannot access the `event.unicode` field to get the pressed key.

How do I get `KEYDOWN` events to work with any keyboard layout?

Python version **3.2**

# Answer
> 2 votes
Solved. Way to get correct non ASCII code :

```
event = pygame.event.poll()
if event.type == KEYDOWN:
   print(event.unicode)

```

# Answer
> 4 votes
The program is trying to convert a unicode wide character format into a standard ascii format. The code you are trying to convert is out of the available ASCII format range.

http://www.fileformat.info/info/unicode/char/444/index.htm

This is the code you are trying to convert, and ASCII only supports 128 different values, with extended ASCII supporting 256.

*edit* you need to use functions that support unicode characters, instead of standard or wide ASCII characters.

---
Tags: pygame, keyboard, localization
---