text:
Slick2D Networking Crash
This is my first post, so I apologize if it's been put in the wrong place or something. Anyways, here's my problem:
I've run into an issue with running my client-side code in one of my game-states. The game crashes because the update method isn't able to keep running. I know it's because the program waits for a connection, stalling the rest of the program. This line is responsible:
connection = new Socket(InetAddress.getByName(serverIP), port);

My game-state is a standard BasicGameState with an init(), a render(), and an update(). I don't know where to put the connection code into the game-state class. Here's the game-state code if you need it:
public class ConnectState extends BasicGameState {

private UnicodeFont ufont;
private Client client = new Client();
private final int ID;

public ConnectState(int state) {
    ID = state;
}

@SuppressWarnings("unchecked")
@Override
public void init(GameContainer container, StateBasedGame game) throws SlickException {
    try {
        Font font = new Font("Sitka Small", Font.BOLD, 70);
        ufont = new UnicodeFont(font, font.getSize(), font.isBold(), font.isItalic());
        ufont.addAsciiGlyphs();
        ufont.addGlyphs(400, 600);
        ufont.getEffects().add(new ColorEffect(Color.WHITE));
        ufont.getEffects().add(new OutlineEffect(5, Color.RED));
        ufont.loadGlyphs();
    } catch (SlickException e) {
        e.printStackTrace();
    }
}

@Override
public void render(GameContainer container, StateBasedGame game, Graphics g) throws SlickException {
    g.setFont(ufont);
    g.drawString(client.displayMsg, container.getWidth() / 2 - ufont.getWidth(client.displayMsg) / 2,
            container.getHeight() / 2 - ufont.getHeight(client.displayMsg) / 2);
}

@Override
public void update(GameContainer container, StateBasedGame game, int delta) throws SlickException {
    Input input = container.getInput();
    boolean isRunning = false;

    if (!isRunning) {
        client.run();
        isRunning = true;
    }

    if (input.isKeyPressed(Input.KEY_F1))
        if (container.isShowingFPS())
            container.setShowFPS(false);
        else
            container.setShowFPS(true);
    if (input.isKeyPressed(Input.KEY_ESCAPE))
        container.exit();
}

@Override
public int getID() {
    return ID;
}}

Here's the Client code if you need it as well:
public class Client {

public String displayMsg = "";

private ObjectOutputStream output;
private ObjectInputStream input;
private String serverIP = "localhost";
private Socket connection;
private boolean shouldExit = false;
private Object recievedData;

public void run() {
    try {
        connect();
        setupStreams();
        whileConnected();
    } catch (EOFException e) {
        showMessage("The client closed the connection!");
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        close();
    }
}

public void setShouldExit(boolean should) {
    shouldExit = should;
}

private void connect() throws IOException {
    System.out.println("So far...");
    showMessage("Attempting to connect...");
    System.out.println("...so good?");
    connection = new Socket(InetAddress.getByName(serverIP), 1337);
    showMessage("Connection successful! ^_^");
}

private void setupStreams() throws IOException {
    output = new ObjectOutputStream(connection.getOutputStream());
    output.flush();
    input = new ObjectInputStream(connection.getInputStream());
    showMessage("The streams have been setup! Don't cross 'em!");
}

private void whileConnected() throws IOException {
    do {
        try {
            recievedData = input.readObject();
            //send or do stuff
        } catch (ClassNotFoundException e) {
            showMessage("Something square was shoved through the circular tube...");
        }
    } while (!shouldExit);
}

private void close() {
    showMessage("Closing...");
    try {
        output.close();
        input.close();
        connection.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

private void sendData() {
    //TODO
}

private void showMessage(String message) {
    displayMsg = message;
}}

In short, how do I run the aforementioned line of code in a constantly updating game-state? Also, if you know a better/easier way for tcp (I'm making a turn-based game, so tcp is fine) in slick, let me know!

Welcome to the site.  Your quest seems fine, but it also seems like almost none of your posted code is relevant to your problem.  Posting your exception or error message might be useful, in case you've misdiagnosed the problem.
Anyway, it seems like the core of your question is about how to initiate an asynchronous process in Slick.  Is that correct?

Thanks for reading, turns out I just needed to spend a bit more time on my problem. For those who find this in the future, I used Kryonet to run my network code in a separate process.

Mark your answer as correcr


text:
Creating a Slide-Up Menu
How can I create a menu that slides up while "un-fading" as illustrated in this video?
As you can see in the video, the menu also falls down a bit in the end which gives it a realistic feel. I really have no idea on how to approach this, and searching the web did not help either.
Any help is appreciated.

You can animate just about anything in Unity. Fade effects are generally just the animation of the UI item's alpha color.
https://unity3d.com/learn/tutorials/modules/beginner/live-training-archive/animate-anything
http://forum.unity3d.com/threads/changing-a-new-ui-images-alpha-value.289755/

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
What is the more appropriate way to implement a health bar in iOS?
I'm building a game a pokemon like rpg game in iOS using Swift. I'm currently in the process of making graphics and is in the dilemma of either just using a health bar blank and dynamically changing the length of a health bar or should I instead use intervals (100percent.png, 90percent.png) to represent damage? Which way is more appropriate to conserve memory and is more efficient?

Generally, I wouldn't think the efficiency of drawing your health bar would be a bottleneck in your game. If it is, you should figure out why by profiling your code and seeing where the slowdown is.
Having said that, you could just make it a rectangle that you fill in and then it takes no texture memory. It may not look as cool, but if you're concerned about the amount of memory you're using, it's very efficient. It also allows you to make the health any value between the minimum and maximum, so you aren't constrained to just 10% intervals.
If you still want to use textures, you could also look into compressed textures. I'm not sure whether or not iOS supports them and if so which types of compression, but if you're concerned about size, that may be a reasonable option.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Apply Pixel Perfect by script in Unity?
How can I apply Pixel Perfect by script in Unity? All I could find on the web is this which does help at all..

http://blogs.unity3d.com/2015/06/19/pixel-perfect-2d/

Are you asking how to toggle the Pixel Perfect box on a given Canvas? Your link to the script reference seems to answer that... Maybe you can clarify why that doesn't help?

You need to set the orthographic camera's size so that each asset pixel renders ton an integer number of screen pixels. I have made a simple script that calculates that for you and adjusts the camera's size. You can get it for free from the asset store: https://www.assetstore.unity3d.com/en/#!/content/64563

You need to override pixel perfect inheritance first if the GameObject's Canvas component is not considered the root canvas.
myNewUIGameObject.GetComponent <Canvas> ().overridePixelPerfect = true;
myNewUIGameObject.GetComponent <Canvas> ().pixelPerfect = true;

or
myCanvas.overridePixelPerfect = true;
myCanvas.pixelPerfect = true;


text:
XNA makes the console flicker
I create a Window XNA game project from the template in Visual studio 2015. Then I right click and set the property to console application because I think it is convinient to use Console.WriteLine() for debugging.

In the game constructor I add
graphics.PreferredBackBufferWidth = 1920;
graphics.PreferredBackBufferHeight = 1080;
graphics.IsFullScreen = true;

Now the console text flicker. I use Console.Clear() the first thing I do in Update(). When I run the game in a window then the console text do not flicker. I even add counter to not update the text every time Update() is called and the console text still flicker in full screen mode. The same problem is there when I start form Windows Powershell. (The exact same thing do not flicker with MonoGame though.)

When there is no console, by default Console.WriteLine() writes to the output window/tab in Visual Studio. If you can't find a fix for the flickering, that can still work for you.

The flicker you see is the result of clearing the console which is being displayed by the graphic card, then text get drawn and "reappear".
It's only by sheer luck that it didn't flicker before.
Using the Console.Clear() command will "always" make the console text flicker.
It's not designed to redraw text like this.
Invest time in making your own virtual terminal console that you can display in a separate window or as an overlay over your game with the option of writing the text to a log file and possibly a command line.
It'll make it easier later to test your game by typing cheat commands.
You can probably get this done in a day or two.

I don't have that experience. I worked with loads of console application that use "clear" in one form of another to keep numbers updated in real time and it never flickered before. Both in terminal only and in windowed mode.

Utilize double buffering when you draw to eliminate flickering. Instead of displaying debug information through the console draw your own output onto your game screen in whatever way you see fit.


text:
Text independent of screen resolution in Unity?
I have the following code that depends on the resolution of the user's display:
void OnGUI()
{
    GUI.Label(new Rect(432, 525, 9000, 9000), ("Hello!"));
}

And of course, the location of the text changes in devices with different resolutions. How can I make the text independent of screen resolution in Unity?

I'm voting to close this question as off-topic because it is an intra-network cross post.

You can use a canvas scaler and put UI text on it.
http://docs.unity3d.com/Manual/script-CanvasScaler.html
http://docs.unity3d.com/ScriptReference/UI.Text.html
GUI.Label on the game screen is only for quick debug hacks as far as I know.

I have a work around for this problem. Idea is to assign position in percentage instead of hard coded coordinates.
1- First find out your base resolution, on which further work will base on. Print Screen.width and Screen.height. In my case it is 428 x 321.
2- Find out the percentage of current position with resolution. If I consider GUI.Label(new Rect(50, 50, 300, 300), ("Hello!"));, then it'd be 50.0f/428.0f width percentage and 50.0f/321.0f height percentage.
3- Now assign position w.r.t. these percentages. Like, GUI.Label(new Rect((50.0f/428.0f) * Screen.width, (50.0f/321.0f) * Screen.height, 300, 300), ("Hello!"));

Instead of using a gui label, you could simply add a text object to your project hierarchy (Create->UI->Text).  This will automatically add a canvas object as well.  Changing the UI scale mode on your canvas scaler to "Scale with Screen Size" will make the UI scale based on the screen resolution.  You would then set the anchors/pivot of your text object depending on exactly how you want it to behave.
I recommend watching this series of videos by 3DBuzz on youtube.  It goes in depth about how to set up UIs in Unity.
https://www.youtube.com/playlist?list=PLt_Y3Hw1v3QTEbh8fQV1DUOUIh9nF0k6c


text:
Cannot detect input in void OnCollisionEnter()
Code:
void OnCollisionEnter()
{
    if (Input.GetMouseButton(0))
       {
            // do something
       }
}

Of course, this code does not work. What I intend to do: "After collision, if the user is pressing down, do something". How can we write this another way? I can't figure it out.

I think you want to open the door from any side panel or standing on any special block? something like that?

Do something like this:
var timeSinceCollision = 999;

void Update() {
    timeSinceCollision += Time.deltaTime;
    if(timeSinceCollision < 0.5 && Input.GetMouseButtonDown(0)) {
        // do something
    }
}

void OnCollisionEnter() {
    timeSinceCollision = 0;
}

The 0.5 makes it so that there's a bit of allowable tolerance for when the player collides with whatever and them being able to perform the action (no one is going to be able to press the button the same frame the collision occurs on: ideally that would be 1/60th of a second!).
Edit:
Also use GetMouseButtonDown, which will only be true on the frame that the button is first pressed and false thereafter.  It prevents the player from holding down the button, then bumping into something, and getting the effect despite doing things out of order.

Instead of adding frame time every frame, it would be better to store Time.time on action and do Time.time - storedTime < maxTime.

Can you please upload an example project? Your code doesn't seem to be working for me...

@SamedTarıkÇETİN why is that?

@Draco18s There may be small delays between frames. It's always better to use exact time, which is independent from deltaTime or delay between frames.

The small delay between frames is in fact, the Time.deltaTime. http://docs.unity3d.com/ScriptReference/Time-deltaTime.html Time.time is also "time at the beginning of this frame and returns the same value every time it is polled in a given frame. http://docs.unity3d.com/ScriptReference/Time-time.html Your method and mine would have exactly identical results in Unity.

@Draco18s No, certainly. Time.deltaTime returns the duration of the last frame before current. It has nothing to do with delay or something else. And Time.time is the time passed in seconds since startup.

@SamedTarıkÇETİN No, Time.time is the number of seconds from the game start at the beginning of the current frame. "The time at the beginning of this frame (Read Only)."Also, both Time.time and Time.deltaTime also scale on Time.timeScale, so it's not even guaranteed to match the system clock. "Except for realtimeSinceStartup, timeScale affects all the time and delta time measuring variables of the Time class."

I think you scenario is to stand over a special block then do something or open up the door from side panel. In block type case OnCollision is OK but in door type case I'd recommend OnTrigger, well according to your code, use OnCollisionStay instead of OnCollisionEnter
void OnCollisionStay(Collision col)
{
    if (Input.GetMouseButton(0))
       {
            // do something
       }
}

I considered a trigger volume as well, but immediately thought of wall-jumping, which could not be a trigger.  Depending on exact needs, OnCollisionStay may be a better solution.


text:
Designing loots for chests
Let's say we have a game, with enemies you fight, items to get and also chests to find and loot. Imagine a RPG game if you will.
We also have a table with x items that the player can loot from these mentioned chests. Some of these items are "one drop only", while others can drop more than one time. We might set that as a variable in the table.
Now to the question: When would you scatter the items in the table to the chests?

Would you do this as soon as the level loads?
Would you do a lookup when the player opened a chest?

As far as I see it, if you scatter the items when the level starts, the player could miss a unique item, if the player skipped that specific chest containing that unique one-time-only item.
But, if you do a lookup when the player opens a chest, the player does not need to worry (if the player knew exactly how it was coded) about actually missing unique items.
How would you handle this design wise? Is it ok for players to miss unique items for being lazy/bad/unlucky? Or, do we always want the player to be able to get just about all the items in this table at one point?
Which way would you prefer as a dev? Which way would you prefer as a player? Have I missed an important factor, a third way to handle it, or something else?

My view: if you generate on chest open this will induce save scrimming (spelling?) and people re-loading saves for better loot unless it's MMO. If you do it on a per-level basis, on the other hand, you risk people missing cool loot due to (P)RNG screw ups and missed drop chances. Neither is terribly optimal IMO.
As a single player, story based and not random-generated loot developer, I personally prefer pre-set loot in most cases with minor variance cast on 'chapter' initialization (removed from level loads but still playthrough specific) states which are flipped, i.e. Item1 always appears somewhere, the question becomes is it in Part I, Part II, or Part III. I can also include minor variance in scenes based on the same RNG cast, making the game world seem less fixed, even if you reload prior to starting a new 'part' - whatever that mean in context, and parts for different 'types' of items may be cast at various points which are not advertised to the player but are internally consistent.
Seen from a practical perspective, my motivation is to ensure the player will (probably) run across all the items of type X if they do the appropriate quests/missions and access the thematically relevant content. At the same time, every playthrough is a bit different, because where items drop - both in a thematic 'set' progression and in general timeline progression - will influence how the character plays, but only within a certain spectrum.
This isn't a perfect system, to be honest, but when playing my own games (assuming someone like me, who knows where all the loot can be), it's incredibly annoying to NOT get an item just because a stupid RNG roll screwed me over. I prefer to walk over a trigger point for a specific encounter 10 times hoping for the respective outcome than to bungle around, looting randomly, and not getting what I want despite hours spent trying to perfect my character.
My philosophy is to allow a player who wants X and knows how to get X to get X reliably within the scope of a sub-progression, but not on a per level (or per-encounter) basis. This generally only works in SP games however. If you're going for something MP or group-centric, this will turn out badly.


text:
Advice on how to approach building background glow for 3d galaxy?
I've got a proceduraly generated 3d galaxy galaxy, very large. Milky Way scale. It is broken up into sectors, where I can relatively quickly get the star density and average star color of any given sector with a simple call:
Color GetColorAt(x,y,z); //where hue represents star color and intensity is density

I am already pulling in the sectors around the player's location, so that the player can fly through the stars. Works great, performance is fine. Now what I want to do is add in the collective glow from stars in the galaxy that are very far away. Just like when you look at the night sky (in a rural area) you can see the glow of the milky way.
So one approach is to build a skybox. For each pixel of the skybox, cast a ray through the volume of the galaxy, and check at some # of points along the ray for the star density/color there, and add it all up, then use that to set the pixel of the skybox.
However this is computationally extremely expensive. ~6x1024x1024x10 operations or thereabouts at a minimum.
Another idea was do to a much sparser sampling of the galaxy density around the player, and use that data to create a particle system. Where each particle will take up way more than just 1 pixel. The effect might even look pretty good.
Any other ideas? Is there a data structure that would let me do this quickly?

Well... very large is an pretty elastic term.
I would suggest these 2 ways.
Generation&Preparation stage

Arrange your sectors into a tree like spatial data structure (e.g. an
octree-like structure) with lod support, so that you can get the
spatially neighbourhood of sectors fast. You will need the lod
technique to filter to filter 'invisible stars' in the distance.

Rendering stage

Get the minimum amount of this tree's nodes within the player's view
frustum. This results in O( log( |Nodes within tree| ) ).
For each star in your node selection, cast a ray from the star to the
camera (!) resulting in O( |Stars in Selection| ).

If this is not enough, performance-wise, you could try this:
Generation&Preparation stage

Arrange your sectors into spatial data structure (e.g. an octree), so
that you can get the spatially neighbourhood of sectors fast.
For each sector generate a skysphere.

Rendering stage

Take the current sector's skysphere and the skyspheres from the
adjacent sectors.
Combine these displaced and weighted to use the resulting skysphere
for the actual rendering of the 'sky' in the next step.


text:
What is a good way to procedurally generate large tilemaps?
I'm sorry if this question was already asked before.
The game I'm aiming to make is a 2D-top down game in similar fashion to Zelda. I'm generating tilemaps, simple grids with 16x16 pixels per tile, and I'm using cellular automata combined with some other methods to generate these tilemaps. I can generate fairly large tilemaps, but It's problematic to go too big and it seems very ineffiecent. To be able to have a big world I decided it was probably smart to divide everything up in smaller seamlessly connected tilemaps, but I'm really unsure how to actually deal with such a large map. Since I'm planning on having maybe 40x40 tiles per area, and 100x100 areas for the whole world that will add up to a ridiculous amount of tiles in total.
What is the best way to generate such a huge area and still letting it all flow together nicely and naturally? I'm currently generating a mini map of a world to get the general layout of the world. (100x100 pixels) And I could generate all of the areas seperately based on this layout, but i'm not sure it would allow me to create larger open and natural environments.
I see 3 different options:
1) Generating the whole map at once as the game is started, everything in one go, this including all the different regions like forests, lakes, mountains etc.
2) Breaking the areas down by the type of region, for example, getting the bounds of a forest area (which spans over several tilemaps) and then generating it with more detail, and moving on to other regions after that
3) Generating the areas one by one as you enter them, meaning the world will only be fully generated once you explored it all.
I appreciate all replies a lot! It's more of a general question and I imagine there are a lot of ways to do these, so any suggestions are welcome! Maybe I have the wrong approach altogether? I'm very new to procedural map generation so I apologise if I come off as very inexperienced
Thank you!

(40x40) x (100x100) isn't a completely ridiculous number of tiles. At the minimum, using one byte per tile it's only 16MB. In addition to the question you're asking, you might also try to figure out how much space you're using per tile, and whether you can use a more efficient memory layout (e.g., can you fit everything into 1 byte per tile?).

I develop games as a hobby by myself and never actually talked or advised anyone about the details of game development before so my comment might be a bit off.
You say you use cellular automata to generate your map; I'm not sure but it sounds like every tile is reliant on one of the tiles before it to be generated, right? If that is the case you should definitely switch to a noise function such as simplex or Perlin, with these you can compute any coordinate irrespective of any other tiles on your map. The way I do it is I only calculate the tiles around visible and a bit outside the players view and I save the results in a cache so that the program doesn't have to keep recalculating the same tiles. Of course you should also limit the size of your cache also, so that the game doesn't keep data from areas the user visited way back for too long.
I think this guide could be helpful for you: http://www.redblobgames.com/maps/terrain-from-noise/


text:
Accurately simulating the lots of dice rolls without loops?
OK so if your game rolls lots of dice you can just call a random number generator in a loop.
But for any set of dice being rolled often enough you will get a distribution curve/histogram.
So my question is there a nice simple calculation I can run that will give me a number that fits that distribution?
E.g. 2D6 - Score - % Probability
2 - 2.77%
3 - 5.55%
4 - 8.33%
5 - 11.11%
6 - 13.88%
7 - 16.66%
8 - 13.88%
9 - 11.11%
10 - 8.33%
11 - 5.55%
12 - 2.77%
So knowing the above you could roll a single d100 and work out an accurate 2D6 value.
But once we start with 10D6, 50D6, 100D6, 1000D6 this could save a lot of processing time.
So there must be a tutorial / method / algorithm that can do this fast?
It is probably handy for stock markets, casinos, strategy games, dwarf fortress etc.
What if you could simulate the outcomes of complete strategic battle that would take hours to play with a few calls to this function and some basic maths?

Even at 1000 d6, the loop will be fast enough on a modern PC that you're unlikely to notice it, so this may be premature optimisation. Always try profiling before replacing a clear loop with an opaque formula. That said, there are algorithmic options. Are you interested in discrete probability like dice in your examples, or is it acceptable to model them as a continuous probability distribution (so a fractional outcome like 2.5 might be possible)?

DMGregory correct, calculating 1000d6 isn't going to be that much of a processor hog.  However, there is a thing called a Binomial Distribution which (with some clever work) will get the result you're interested in. Also, if you ever want to find the probabilities for an arbitrary roll ruleset, try TRoll which has a modest language set for specifying how to roll a set of dice and it will calculate all of the probabilities for every possible result.

Use a Poisson distribution :p.

For any set of dice being rolled often enough you will probably get a distribution curve/histogram. That's an important distinction. A dice can roll a million 6s in a row, it's unlikely, but it can

@RichardTingle Can you elaborate? A distribution curve / histogram will also include the “million 6s in a row” case.

I agree with @DMGregory that 1000 d6 should be plenty fast. In C++, you can probably get a billion random numbers per second *. Even in a slow language like Python, you can get a million random numbers per second (python -m timeit -s 'from random import randint' 'randint(1,6)'). Is your goal optimization or understanding the math of probability distributions?

Surprisingly enough (to me...), a test rolling 100 million 3D6 (300 million D6) as either 1) the naive 3 loops java random operations any tutorial will show you or 2) with cached standard deviation and cached inverse normal distribution (NORM.INV if you're using Excel) took 1) 6.894 s (returning a double instead of an int took 9.669 s), 2) 8.727 s. A diff of ~1-2 sec and it will go away almost completely if you roll in the millions or 100 thousands. If only my program wasn't relying on percentages and double results all over the place I could have avoided that complication altogether... :|

As I mentioned in my comment above, I recommend you profile this before overcomplicating your code. A quick for loop summing dice is a lot easier to understand and modify than complicated math formulae and table-building/searching. Always profile first to make sure you're solving the important problems. ;)
That said, there are two main ways to sample sophisticated probability distributions in one fell swoop:

1. Cumulative Probability Distributions
There's a neat trick to sample from continuous probability distributions by using only a single uniform random input. It has to do with the cumulative distribution, the function that answers "What is the probability of getting a value no greater than x?"
This function is non-decreasing, starting at 0 and rising to 1 over its domain. An example for the sum of two six-sided dice is shown below:

If your cumulative distribution function has a convenient-to-calculate inverse (or you can approximate it with piecewise functions like Bézier curves), you can use this to sample from the original probability function.
The inverse function handles parcelling up the domain between 0 and 1 into intervals mapped to each output of the original random process, with the catchment area of each matching its original probability. (This is true infinitescimally for continuous distributions. For discrete distributions like dice rolls we need to apply careful rounding)
Here's an example of using this to emulate 2d6:
int SimRoll2d6()
{
    // Get a random input in the half-open interval [0, 1).
    float t = Random.Range(0f, 1f);
    float v;

    // Piecewise inverse calculated by hand. ;)
    if(t <= 0.5f)
    {
         v = (1f + sqrt(1f + 288f * t)) * 0.5f;
    }
    else
    {
         v = (25f - sqrt(289f - 288f * t)) * 0.5f;
    }

    return floor(v + 1);
}

Compare this to:
int NaiveRollNd6(int n)
{
    int sum = 0;
    for(int i = 0; i < n; i++)
       sum += Random.Range(1, 7); // I'm used to Range never returning its max
    return sum;
}

See what I mean about the difference in code clarity and flexibility? The naive way might be naive with its loops, but it's short and simple, immediately obvious about what it does, and easy to scale to different die sizes and numbers. Making changes to the cumulative distribution code requires some non-trivial math, and it would be easy to break and cause unexpected results without any obvious mistakes. (Which I hope I haven't made above)
So, before you do away with a clear loop, make absolutely certain that it's really a performance problem worth this kind of sacrifice.

2. The Alias Method
The cumulative distribution method works well when you can express the inverse of the cumulative distribution function as a simple math expression, but that's not always easy or even possible. A reliable alternative for discrete distributions is something called the Alias Method.
This lets you sample from any arbitrary discrete probability distribution by using just two independent, uniformly distributed random inputs.
It works by taking a distribution like the one below on the left (don't worry that the areas/weights don't sum to 1, for the Alias Method we care about relative weight) and converting it to a table like the one on the right where:

There is one column for each outcome.
Each column is split into at most two parts, each associated with one of the original outcomes.
The relative area/weight of each outcome is preserved.

(Diagram based on images from this excellent article on sampling methods)
In code, we represent this with two tables (or a table of objects with two properties) representing the probability of choosing the alternate outcome from each column, and the identity (or "alias") of that alternate outcome. Then we can sample from the distribution like so:
int SampleFromTables(float[] probabiltyTable, int[] aliasTable)
{
    int column = Random.Range(0, probabilityTable.Length);
    float p = Random.Range(0f, 1f);
    if(p < probabilityTable[column])
    {
        return column;
    }
    else
    {
        return aliasTable[column];
    }
}

This involves a bit of set-up:

Compute the relative probabilities of every possible outcome (so if you're rolling 1000d6, we need to compute the number of ways to get every sum from 1000 to 6000)
Build a pair of tables with an entry for each outcome. The full method goes beyond the scope of this answer, so I highly recommend referring to this explanation of the Alias Method algorithm.
Store those tables and refer back to them each time you need a new random die roll from this distribution.

This is a space-time tradeoff. The precomputation step is somewhat exhaustive, and we need to set aside memory proportionate to the number of outcomes we have (though even for 1000d6, we're talking single-digit kilobytes, so nothing to lose sleep over), but in exchange our sampling is constant-time no matter how complex our distribution might be.

I hope one or the other of those methods may be of some use (or that I've convinced you that the naive method's simplicity is worth the time it takes to loop) ;)

Awesome answer. I like the naive approach though. Much less room for errors and easy to understand.

FYI this question is a copy-paste from a random question on reddit.

For ccompleteness, I think this is the reddit thread that @AlexandreVaillancourt is talking about. The answers there mainly suggest keeping the looping version (with some evidence that its time cost is likely to be reasonable) or approximating large numbers of dice using a normal/Gaussian distribution.

+1 for the alias method, it seems like so few people know about it, and it really is the ideal solution to a lot of these types of probability choice situations and +1 for mentioning the Gaussian solution, which is probably the "better" answer if we only care about performance and space savings.

The answer unfortunately is that this method would not result in an increase in performance.
I believe that there may be some misunderstanding in the question of how a random number is generated. Take the example below [Java]:
Random r = new Random();
int n = 20;
int min = 1; //arbitrary
int max = 6; //arbitrary
for(int i = 0; i < n; i++){
    int randomNumber = (r.nextInt(max - min + 1) + min)); //silly maths
    System.out.println("Here's a random number: " + randomNumber);
}

This code will loop 20 times printing out random numbers between 1 and 6 (inclusive). When we talk about the performance of this code, there is some time taken to create the Random object (which involves creating an array of pseudo-random integers based on the computer's internal clock at the time it was created), and then 20 constant time look-ups on each nextInt() call. Since each 'roll' is a constant time operation, this makes rolling very cheap time-wise. Also notice that the range of min to max doesn't matter (in other words, it's just as easy for a computer to roll a d6 as it is for it to roll a d10000). Speaking in terms of time complexity, the performance of the solution is simply O(n) where n is the number of dice.
Alternatively, we could approximate any number of d6 rolls with a single d100 (or d10000 for that matter) roll. Using this method, we first need to compute s [number of faces to the dice] * n [number of dice] percentages before we roll (technically it's s * n - n + 1 percentages, and we should be able to divide that roughly in half since it's symmetrical; notice that in your example for simulating a 2d6 roll, you calculated 11 percentages and 6 were unique). After rolling we can use a binary search to figure out which range our roll fell into. In terms of time complexity, this solution evaluates to an O(s*n) solution, where s is the number of sides and n is the number of dice. As we can see, this is slower than the O(n) solution proposed in the previous paragraph.
Extrapolating from there, say you created both of these programs to simulate a 1000d20 roll. The first would simply roll 1,000 times. The second program would first need to determine 19,001 percentages (for the potential range of 1,000 to 20,000) before doing anything else. So unless you're on a weird system where memory look-ups are severally more expensive than floating-point operations, using a nextInt() call for each roll seems like the way to go.

The analysis above is not quite correct. If we set aside some time up-front to generate probability & alias tables according to the Alias Method, then we can sample from an arbitrary discrete probability distribution in constant time (2 random numbers and a table lookup). So simulating a roll of 5 dice or a roll of 500 dice takes the same amount of work, once the tables are prepared. This is asymptotically faster than looping over a large number of dice for every sample, though that doesn't necessarily make it a better solution to the problem. ;)

If you want to store the dice combinations, the good news is that there is a solution, the bad is that our computers are somehow limited in regards to this kind of problems.
The good news:
There is a determistic approach of this problem:
1/ Compute all the combinations of your group of dice
2/ Determine the probability for each combination
3/ Search in this list for a result instead of throwing the dices
The bad news:
The number of combination with repetition is given by the following formulae
\$\Gamma_n^k={n+k-1 \choose k}=\frac{(n+k-1)!}{k!~(n-1)!}\$
(from french wikipedia):

That means that, for example, with 150 dices, you have 698'526'906 combinations. Let's assume you store the probability as a 32 bit float, you will need 2,6 GB of memory, and you still have to add memory requirement for the indexes...
In computing terms, the combination number can be computed by convolutions, which is handy but doesn't solve the memory constraints.
In conclusion, for a high number of dices, I would advise throwing the dices and observe the result rather than precomputing the probabilities associated with each combination.
Edit
However, as you are only interested in the sum of dices, you can store the probabilities with much less resources.
You can calculate precise probabilities for each sum of dice using convolution.
The general formula is \$F_i(m) = \sum_n F_1(n) F_{i-1}(m - n)\$
Then starting from 1/6 form each result with 1 dice, you can construct all the correct probabilities for any number of dice.
Here is a rough java code I wrote for illustration (not really optimized) :
public class DiceProba {

private float[][] probas;
private int currentCalc;

public int getCurrentCalc() {
    return currentCalc;
}

public float[][] getProbas() {
    return probas;
}

public void calcProb(int faces, int diceNr) {

    if (diceNr < 0) {
        currentCalc = 0;
        return;
    }

    // Initialize
    float baseProba = 1.0f / ((float) faces);
    probas = new float[diceNr][];
    probas[0] = new float[faces + 1];
    probas[0][0] = 0.0f;
    for (int i = 1; i <= faces; ++i)
        probas[0][i] = baseProba;

    for (int i = 1; i < diceNr; ++i) {

        int maxValue = (i + 1) * faces + 1;
        probas[i] = new float[maxValue];

        for (int j = 0; j < maxValue; ++j) {

            probas[i][j] = 0;
            for (int k = 0; k <= j; ++k) {
                probas[i][j] += probability(faces, k, 0) * probability(faces, j - k, i - 1);
            }

        }

    }

    currentCalc = diceNr;

}

private float probability(int faces, int number, int diceNr) {

    if (number < 0 || number > ((diceNr + 1) * faces))
        return 0.0f;

    return probas[diceNr][number];

}

}

Call calcProb() with the parameters you want and then access the proba table for results (first index: 0 for 1 dice, 1 for two dices...).
I checked it with 1'000D6 on my laptop, it took 10 seconds to compute all probabilities from 1 to 1'000 dices and all possible sums of dices.
With precomputing and efficient storage, you could have quick answers for a high number of dices.
Hope it helps.

Since OP is only looking for the value of the sum of the dice, this combinatorial math does not apply, and the number of probability table entries grows linearly with the size of the dice and with the number of dice.

You are right ! I've edited my answer. We are always clever when many ;)

I think you can improve efficiency a bit by using a divide & conquer approach. We can calculate the probability table for 20d6 by convolving the table for 10d6 with itself. 10d6 we can find by convolving the 5d6 table with itself. 5d6 we can find by convolving the 2d6 & 3d6 tables. Proceeding by halves this way lets us skip generating most of the table sizes from 1-20, and focus our effort on the interesting ones.

And use symmetry!


text:
Is it possible to fake momentum by tracking an objects last known positions?
Basically I am making a melee combat system. I want to be able to apply force based on where/how things are hit.
I am NOT using physics simulations for this, which is why I cannot just rely on that.
Instead, can I track the part of the sword that hits the target somehow, to work it's average momentum/direction of attack?
I tried by just using the last frame position and the current frame position, but this doesn't give a great angle (as the sword rotates a lot, it always taps it towards the player, when really all the momentum is going directly left).
Is there a formula for working this out? Or is it as something as simple as just totally up the directional changes each frame, with some kind of decay time.

Verlet Integration uses current & previous position instead of velocity, so if you can generate an acceleration term from your impacts then that might be usable - have you looked into that? It sounds like rotational effects are significant in your case though. Would you be able to provide an image sequence/video/diagram of a typical or problem case so we can better visualize what we're dealing with?

Why did you use 'post-processing' tag? Anyway:
I would start with why you want to do this with that kind of precision.
Just to compare, you could consider a simpler system such as "when hit, the enemy is knocked back/up at a 30-degree angle." This system is easy to implement and predictable for the player. So for example maybe the player knows how to try to set up an enemy to knock them into that pit or exploding barrel or man-eating plant's mouth or whatever.
Making a more realistic system that depends on the exact frame of impact might sound cool, but are you expecting the player to understand what's happening? Are you expecting them to utilize the differences as a mechanism of control? That second one is critical because now you're opening like 1-frame timing windows for the player to achieve some exact knockback direction.
In this most recent Ludum Dare I made a tennis/arkanoid mashup and it's fairly tricky to get the player feeling in control of the angle of a shot. If that's a key element of your game it will require a lot of focus and feedback... for example in my tennis game I have a fairly intense slo-mo moment for 8 frames when the player impacts the ball, so their eye can really observe and they feel the weight. Then I have a directional impact flash that lingers so they can observe an arrow that shows them the vector they achieved. The ball also takes on a temporary trails effect so they can see the movement off the racket for a moment. Still, only some players felt their aim was strong and a number never even realized how or to what extent they could control the angle of impact.
My point is that you will need to treat it carefully if you expect control of knockback direction based on momentum of an arcing sword to be important. If it's not important, perhaps you will be better off with something extremely simple and thus easily understandable, predictable, and reliable. If the simple system feels wrong in a few cases, you can always have a couple of simple checks, like do this if the enemy is standing, that if he is caught midair while jumping, or something.
Good luck!


text:
How do I ensure proper date formatting?
I'm trying to load a date in the form of a string. As there is always 4 possible date formats (x.x.xxxx, x.xx.xxxx, xx.x.xxxx, xx.xx.xxxx (day month year)) I had to take this into account and it is especially hard with the strings length of 8 as it is either xx.x or x.xx.
So I came up with this:
public void setDate(String CompleteDate, boolean loadOrNew){
  Date = CompleteDate;
  if(loadOrNew){
    int totalLength = Date.length();
    String sday = null;
    String smonth = null;
    String syear = null;
    if(totalLength == 9){
      sday = String.valueOf(Date.toCharArray(), 0, 2);
      smonth = String.valueOf(Date.toCharArray(), 3, 2);
      syear = String.valueOf(Date.toCharArray(), 6, 4);
    }else if(totalLength == 8){
      sday = String.valueOf(Date.toCharArray(), 0, 2);
      if(sday.contains(".")){
        smonth = String.valueOf(Date.toCharArray(), 2, 2);
      }else{
        smonth = String.valueOf(Date.toCharArray(),3, 1);
      }
      syear = String.valueOf(Date.toCharArray(), 5, 3);
    }else if(totalLength == 7){
      sday = String.valueOf(Date.toCharArray(), 0, 1);
      smonth = String.valueOf(Date.toCharArray(), 2, 1);
      syear = String.valueOf(Date.toCharArray(), 4, 4);
    }else{
      Toast.makeText(c, "Critical date format error occurred. Error G205", Toast.LENGTH_LONG).show();
    }
    sday.replace(".", "");
    smonth.replace(".", "");
    syear.replace(".", "");
    this.day = Integer.parseInt(sday);
    this.year = Integer.parseInt(syear);
    this.month = Integer.parseInt(smonth);
  }
  date.setText("Date: " + CompleteDate);
}

However it isn't correct as I get NumberFormatException with "1."
This means I somewhere messed up and the removing of the "." doesn't work. So I need help improving this so it works.
NOTE:
Some of this is android-specific, e.g. the Toast class and TextView class, but everything else is in standard Java.
date and Date isn't the same. Date is the String, date is the TextView(android).

The easiest way to do this is to use String.split to find out the different parts of the date. The following is pseudo-java but it should give you the idea.
String date = <YourDateStringHere>
String dateParts[] = date.split("\\.");
int day = dateParts[0].toInt();
int month = dateParts[1].toInt();
int year = dateParts[2].toInt();

Basically the idea is to split the string at each "." character and parse the data between each dot. You can also take different order formats (MM.DD.YYYY instead of DD.MM.YYYY) into account by just swapping some indices around. We use the sequence "\\." to match the single character "." because the split method wants a regexp pattern.


text:
Detecting first or second Mouse Button Release?
I want to know how to detect if the user has released the mouse button the first time, or the times after that:
Pseudo-Code:
 if *first* (Input.GetMouseButtonUp(0))
   {
       do something
   }

 if *second, third, fourth..etc.* (Input.GetMouseButtonUp(0))
   {
       do something else
   }

I really have no idea on how to accomplish this. I'm sure it's pretty simple though!

You need to store the count in a separate variable yourself, then check the value of that variable.

@Draco18s I'm new to programming, I don't know how to do that sir! :)

Programming with Variables

I see you have edited your question.  The question appears to be a new question, rather than a rephrasing/clarification of the old question.  If this is the case, you should ask a new question instead.  If not, in what way are the current answers insufficient?

You should have private member in your class that will indicate if button was pressed for first time. You need to initialize it in starting function ( could be Awake, Start etc., read more about execution order in Unity ) as false. And then, in Update function - check it. If it is first time, the do X and set this var to true, else do Y.

using UnityEngine;
using System.Collections;

public class ClickerClass : MonoBehaviour {
    private bool m_clicked;

    void Awake() {
        m_clicked = false;
    }

    void Update() {
        if( Input.GetMouseButtonUp(0) )
        {
            if( m_clicked == false ) {
                m_clicked = true;
                // code for first time
            } else {
                // code for not first time
            }
        }
    }
}

Good answer although m_clicked would not need to be initialized and Awake() can be left out.  The default of a boolean in C# will always be false.

int ClickCount;

void Update()
{
    if (Input.GetMouseButtonUp(0))
    {
       if (ClickCount == 0)
       {
              //First Click
              //do stuff
       }
       else
       {
             //Not first click
             //do stuff
       }

       ClickCount++;
    }
}

Keep in mind that the ClickCount variable will overflow once it reaches 2,147,483,648.

Comments are not for extended discussion; this conversation has been moved to chat.


text:
Skeletal Animation - Caching global bone transforms
Very often I see skeletal animation implemented like this:

On Init - store bone's local transforms and inverse bind pose
On Update - traverse the skeleton tree, multiplying local transforms on the way (and inverse bind pose)

However, it is more efficient to pre-calculate global poses from local transforms and just reassign them at specified time point to constant buffer.
What is the benefit of keeping all those local matrices? Does it have any meaningful application in other systems like physics, collision detection?
People still choose the first scenario and that actually keeps me puzzled.

In a lot of cases animations are blended between to create a pose. In some cases many animations are layered at once, sometimes on only part of the body. Finally inverse kinematics can be applied on top or under animations. The only way for all this to work is if the bones transforms are first calculated in local space.

I've just tested animation cross-fading, and you are right :) Blending between local transforms of bones separately provides better results than blending between ready global transforms.


text:
Animation Scaling?
I have an animation that changes the scale of the GameObject but also happens to change the position as well. I do not want the position to be changed by the animation, only the scale. How can I do that?

Is that gameObject a child of other?

@Hamza Hasan No.

Can you share some relevant code snippet and screenshot?

Depending on the object you can try to adjust your position-pivot accordingly. Probably at the bottom middle of the object.

I can say that there is not nearly enough information present to accurately answer the question.

You need to use the new scale to factor the new position!  (I just solved this for my game camera)
should be something like:
target.position.x = (target.width - target.width * target.scale.x) + target.position.x;

My code for re-positioning my stage (camera), centering on a target entity
stage.position.x = (- target.position.x * stage.scale.x) + renderer.width/2;


text:
How can non-CG shader code in Unity be included?
In Unity shaders, #include, #define, and other preprocessor commands seem to not be able to be used outside the CGPROGRAM section of the shader. Since these are required for compiling multiple shader variants, and a large portion of the shader is non CG, this would be incredibly useful to reduce shader duplication. Do these commands exist outside CG?

check this link


text:
Optimize algorithm: finding all possible moves for a turn based game
I am working on the ai for a turn based game. To illustrate my problem this are the simplified rules of the game:
The game takes place on a tiled map with obstacles (black quads) like this:

The player has several tokens (like the two colored dots in the example picture)
The player can move all his tokens in his turn
the tokens move in a straight line until they hit an obstacle, the border of the map or another token
each token could move two times in each turn.
the player can move his tokens in any order he likes

The AI needs a list of all possible turns it could make of one game state. My first attempt was to recursively go through all tokens and move them in any possible direction and order. that works of course but the problem is that with just four tokens there are several millions of possible turns (if each token could move two times). Most of the outcomes of these turns are the same (the tokens end in the same place). In the example above the tokens could move like this:

No matter in which order the four move actions (A,B,C,D) are made, the end positions of the tokens are the same. I am only interested in the possible end turn situations. So I implemented a transposition table in the turn generation algorithm to negate all of the equal turns. That works and in the end I have only several hundred of possible turns with four tokens rather than several millions.
The problem is that the algorithm takes too much time because it has to calculate every possible turn. Does anybody has a hint how to prune the turn generation  tree? Or any other idea how to calculate only the different possible turn outcomes?
Note: In the real game the map is slightly bigger (30-40 free cells) and there are up to 6 tokens.

Are you interested in "the best" solutions or simply "all the possible solutions"?

all possible solutions

The token collision makes this difficult. In the worst case, the order of the moves can create arbitrarily varied destinations, each of which must be checked. This is what makes it interesting as a puzzle, though. Even in your example the order changes the outcome. Consider CDBA: the 'B' motion stops in the tile you have written 'D' into, so the final 'A' motion should place the red tile one step to the left of where it is. You may need to settle for standard optimization techniques (data structures, memoization, etc.) rather than a smarter search algorithm.

Are the token identities significant? eg. If I move the green token right, then up (so it finishes in the top-right corner), and then move the red token right and right (second move colliding immediately and resulting in no movement - is that allowed? Or can a player move a token fewer than two times?) so it finishes in the middle-right, then the occupied cells are the same as the example above but the colours are interchanged. Is that a distinct game state from the example above, or are the two states equivalent?

@Chris Yes the token collisions and the order of the moves are making the possible turns calculation complex. I want to use MiniMax for the AI. I only need a MiniMax search depth of 2-3. I optimized the algorithm quite a bit with several techniques but it still takes too much time. In the final game there are billions of possible turns (more tokens, each can perform several actions) but most of them have the same outcome. So I thought about a smarter algorithm for calculating the different turn outcomes without going through all possible turns.

@DMGregory Yes the token identities are significant. The game state you described is a different than the one in the picture. In the real game the tokens are different characters with a different amount of "move points". Every token must at least moved once. But it could move as many times as it has "move points".

I don't have a complete answer for you, just a few lines of thought...
1) Construct a dependency graph
As you consider each move each token can make, store a reference to that move with each cell it passes through.
When a later move ends in one of the marked cells, we've identified a potential new dependency: performing move B before move A can change the outcome of move A. Then you can recursively check the outcome of the modified move A...
This requires some care to ensure you don't follow cycles of mutually-exclusive moves (ie. performing move A first modifies the outcome of move B which modifies the outcome of move A... but no it doesn't, because A already happened!)
Hypothetically this could get you some savings in the event that your tokens are separated from each other, so that many of the outcomes are independent of one another (your dependency graph ends up sparsely-connected). You can separate a turn into clusters, where each cluster contains multiple mutually-affecting moves (where you need to consider order, but of a smaller subset of moves) and clusters minimally affect one another (so you can ignore order between clusters, or consider fewer ordering cases).
However, my suspicion is that mutual interactions are much more common, and that you'd be introducing a lot of complexity to the algorithm for comparatively little pruning.
2) Consider a goal-based approach
A human player won't visualize every possible move. They'll usually have a strategy in mind, like "I want to get my red token in position to do X" then they'll look for a sequence of moves that accomplish this goal, often by working backwards from the goal state and considering only interactions that move them towards it.
So if your aim is to get a reasonable-performing adversary rather than one which always finds the best possible move, structuring it around goal-seeking behaviours rather than minimax tree search may reduce your problem space to a more manageable size.
Since I don't know much about the rules of your game, I can't speculate on what your goal logic might be, and generally they require more sophisticated AI design than search-based approaches.
You can even try a hybrid approach, where you do a minimax search over a set of goals rather than individual moves, pruning goals which turn out to be unfeasible once their move sequence is examined.
3) Consider sampling
If none of the above work, a fallback is to just try to search as much of the tree as you can within your available time & performance budget. This means trying to optimize your exhaustive search inner loop as much as possible, making sure you're using your transposition table to save redundant work on intermediate states and not just final configurations.
You'll want to randomize the order in which you consider moves, to avoid biasing the AI to search moves for the first token more exhaustively than the last, for example.
Whenever you hit your limit, stop, and use the best result you've found so far. You'll likely want to frame this limit in terms of steps rather than realtime, so that players on faster machines don't have to contend with stronger AI than those closer to the minimum spec. ;)

Overall, my algorithmic spidey sense is giving me that tingly feeling that there might not be any easy shortcuts here, and that a good approximation that's achievable with clear and maintainable code and scalable performance might be a better target to aim for than a complex algorithm that's provably optimal.

As a point of evidence that this problem may be excessively complex to expect a fast exact solution: Sokoban is a similar set of sliding token mechanics which is provably NP-Hard. I haven't found any similar analysis of games without a "pusher" avatar and blocks that slide until obstructed, so it's possible those elements make the problem easier, but my suspicion still leans toward NP-Hard. ;)

In fact, problems of this nature are often PSPACE-complete (move sequences can be longer than polynomial) and some variants of this particular problem are as well: http://tizian.cs.uni-bonn.de/publications/ek-crrg-05.pdf has a proof.

@DMGregory Thanks for your great answer! I also think that no.1 results in a too complex algorithm. But it is a fine idea! I am implementing your no.3 because I can use my existing algorithm for it. I have the feeling that the AI would be good enough with this approach. In the end the AI has to be fun to play against and not to be a perfect playing unbeatable bastard. If that doesn't work I think your no. 2 could be the way to go. But in the real game each token has more possible actions than just moving and so it could be nontrivial to implement that approach. Thanks again!

I would start from the end positions, because this is what matters.
There are 2 tokens and 21 blank squares in your example, which means that in the worst case (all ordered pairs of squares represent reachable outcomes) there are 420 valid outcomes.
Check each of these possible outcomes to look for one valid way of reaching it, once you find one way of moving your tokens there mark the outcome as valid and move to the next possible outcome to check. If you don't find any, mark it as invalid and move on.
At the end of the process you have your list of reachable outcomes and you have avoided computing duplicate ways of reaching the same outcome.
No free lunch though, of course. Now the problem becomes how to search for one way of taking all tokens in each ordered set of end positions. But you have a lot of information to use for making the algorithm smarter than "Check all possible moves and turns and verify whether they end up there". For instance, no need to turn left if the required end position is on the right; or, in your example, the green end position cannot be reached in any other way than coming from the left.
It's going to be tough but it's feasible IMHO. And a fun algorithm to code.

Thanks for your answer! I am not sure if this would save time. The example is a simplified one. In the real game the map is slightly bigger (30-40 cells) and there are up to 6 tokens. if the map has 35 blank cells there are 29^6 possible outcomes with 6 tokens. 29^6 are also way too many possibilities to check if they are valid.

Its not quite 29^6, its actually (29!) / (23!).  But the result is still a few hundred million.

I see. Question: how many of these outcomes do you expect to be invalid? Because my guess is that at least a million of those hundreds millions are, which means that the problem is that the tree is actually huge notwithstanding duplicate paths to the same node. If this is the case, anything you do with a MiniMax will be unmanageable.
From a game design perspective, a game with such a broad choice at each turn is easily unmanageable for the human mind as well. Go has less than a few hundreds alternate moves per turn, chess less than a few dozens, bridge, backgammon or Carcassonne even less.

The actual result is 35 * 34 * 33 * 32 * 31 * 30 = (35!) / (29!), about 1.2 billion. It's a lot but it's much less than starting from the initial positions and checking all moves and turns, i.e. about ((6 + 6)!) * 4 * 4 * (average distance from wall or other token)^2 = 7.7 billion * (avg. dist. from wall or token)^2 = 30-50 billion in a 6x6 grid.
Nice but you're right, not enough to make it feasible, and the computation per iteration would be much heavier anyway.

"Check each of these possible outcomes to look for one valid way of reaching it" Unfortunately as per the paper linked by Steven Stadnicki in a comment on another answer, checking whether a given configuration is reachable under these mechanics is proven to be NP-Hard. So in this case exhaustively enumerating all end states and checking for feasibility might not actually reduce the workload compared to naively searching forward from the starting configuration. :(

You are right, the permutations in token order make the solving time grow factorially with the number of tokens. Forcing a fixed order of movement is the first change I would implement if reducing the broadness of the decision tree is a priority. I guess it is, not so much for the AI as for the humans.

For such problem I'd rather go for a Montecarlo algorithm. For each possible move make N random plays and count the number of computer wins. Let the computer do the move with the higher number of wins.
N should be sufficiently large. The larger that number, the strongest the computer will be
Doing this way the computer will force the game into the ''path'' in which it has the best chances of winning.
No need to implement a minmax algorithm nor to explore all the possible branches. Just pick a random move, do the simulation until either the human wins, the computer wins or it is a draw. Repeat.


text:
Cannot turn script back on
I've got an issue. When (Input.GetMouseButtonUp (0), Speedy script is disabled, thus we cannot enable it again from inside the script like shown below. How can we go around this?
public class  Speedy : MonoBehaviour {

GameObject car;

 if (speed == good)
    {
        GameObject car = GameObject.FindWithTag ("Car");

        if (Input.GetMouseButtonUp (0))
        {
            car.GetComponent<Speedy>().enabled = false;
        }

        else car.GetComponent<Speedy>().enabled = true;
    }
}

This is more an architecture issue than a problem with an if statement. Check for your mouse click outside Speedy, and activate or deactivate it from there.

@Almo Title edited.

once you disabled script so how do you expect to run same script to enable it? which is now disable?

@HamzaHasan That's my question. Is there another way?

Control all of these operations from another class.

Ok, let me write a short answer for you

First clear me first that do you want to enable/disable only script or gameObject on which this script is attached?

@HamzaHasan I want to disable the script.

If a script disables itself (or in any way becomes disabled) it cannot reenable itself because it cannot run!  It is disabled!

For this, you can use FindObjectOfType either.
FindObjectOfType gives you reference on relevant script once then you can play with it.
If I edit your code, then it should be something like this
public class  Controller : MonoBehaviour {

    Speedy car;

    Start()
    {
        car = FindObjectOfType<Speedy>();
    }

     if (speed == good)
        {

            if (Input.GetMouseButtonUp (0))
            {
                car.enabled = false;
            }

            else car.enabled = true;
        }

}

Drop this script to another GameObject in hierarchy.
NOTE: In your question you are disabling script from car but enabling if from cube. I don't know that you did it intentionally.


text:
How to reset a Script?
Is there a way where I can make the script restore its condition to that before I hit play? Should I create a new copy of the original script every time instead?

You mean, reset its parameters to the ones specified in the declaration, rather than the altered values shown in the inspector?

@Draco18s Exactly.


text:
Set default values by script?
Insted of Inspector, I want to set default values by script because there is MeshRenderer, a RigiBody etc. I don't know how to write this in script. These are not numerical values.

This can only be done in a standard way for prefabs. Are the game objects this script is attached to instances of prefabs? Otherwise, your best bet is a custom editor. Not regularly via a script like with numerical values, though.

If the component is on the same game object as your script, you can do:
void Awake()
{
    Rigi = GetComponent<Rigidbody>();
}

This will search the game object this script is attached to for a component of the given type(and return the first one found if there are multiple.)
If you want something that's in the same scene as this gameobject you can use:
http://docs.unity3d.com/ScriptReference/Object.FindObjectOfType.html
Correct me if I'm wrong, but I think that will only get scene objects since assets are not active.
If you want something that exists as only an asset then it's a little harder. You'll need to use a combination of:
http://docs.unity3d.com/Manual/editor-CustomEditors.html
And:
http://docs.unity3d.com/ScriptReference/AssetDatabase.LoadAssetAtPath.html
You could create a custom editor in order to use AssetData.LoadAssetAtPath(with a hard coded path). Assign this reference to a serialized field and it'll be available and valid in a build.
I don't recommend doing any of this. Just drag a drop the references. It has a lot of problems, but it's far better than the alternatives.

Inside your script where you have method void Start(), add there your default values for properties, for example:
void Start()
{
     Pop = 10;
     Bolly = true;
}

This does not set default properties, this just overwrites whatever the user configured.

@KevinvanderVelden That seems to be what he's asking despite the question title.

In order to do that you must have all the references in your script to assign it initially.


text:
Level of Detail algorithm(s) and texture coordinates
I'm playing with LOD these days and trying a couple of implementations, specifically quadric mesh simplification, there is a link.
I don't have problem simplifying my models but i do have problem finding the correct texture coordinates after simplification. None of the implementations i found (many) cover texturing, they only handle flat colored triangles, and i was wondering if it's possible anyhow to preserve coordinates.
Is there an approach to handle texture coordinates on quadric simplified meshes?
I tried storing the original texture coordinates into their faces before passing them to simplifier, then restore them but the results are clearly wrong.

The reason is usually these mesh simplifications are done before texturing.
Then the reduced mesh is UV unwrapped.
And finally using the original mesh as the source, the materials are baked into the target textures by raycasting from the reduced mesh into the original mesh to figure out the color maps and normal map.
A completely new texture and UV set is generated for the reduced mesh.

Thanx for clarifying this. Do you have any source link for the raycasting method to rebuild my coordinates, is there an approach or i have to use some software?

That's usually done in the 3D editor with the texture baking tool.


text:
C++ Opengl transforming a glm::vec4 with a glm::mat4
Its easy enough doing it on the gpu via GLSL, but how would I do this in c++? When I try it gives me an error telling me I cant cast a glm::mat4 to float, Which makes sense, but how should I do it?
EDIT
A little code example of my failed attempt:
glm::vec4 Off = glm::vec4(0, 0, 0, 1);
Off *= Util::createTransform(offset); // Util::createTransform(...) Creates a glm::mat4

for (int i = 0; i < Tvertex.size(); i++) {
    Tvertex[i] += glm::vec3(Off.x, Off.y, Off.z);
}

I think this is what you need.

You get the error because there is no operator*= for vec4 that takes a matrix as a parameter. It then tries to convert the matrix to a float, but just can't.
To work around this, you should try to not use the operator*= and write it all in the long form:
Off = Off * Util::createTransform(offset);

Also, as pointed out in the comments to the OP, what you need is probably this:
Off = Util::createTransform(offset) * Off;


text:
How should I rotate vertices around the origin on the CPU?
I have tried using glm::rotate and such. glm::translate works fine, but rotate doesn't work (if I rotate before/after a translation).
Here is my current setup:
glm::vec4 Off = glm::vec4(0, 0, 0, 1);
glm::vec4 result = Util::createTransform(offset) * Off;

for (int i = 0; i < Tvertex.size(); i++) {
    Tvertex[i] += glm::vec3(result.x, result.y, result.z);
    Tcolors[i] = currentColor;
}

And here is my Util::createTransform:
glm::mat4 Util::createTransform(glm::vec3 pos) {
    glm::mat4 trans = glm::mat4(1.0);
    trans = glm::translate(trans, pos);
    return trans;
}

glm::mat4 Util::createTransform(glm::vec3 pos, glm::vec3 rot) {
    glm::mat4 trans = glm::mat4(1.0);
    trans = glm::rotate(trans, glm::radians(rot.x), glm::vec3(1, 0, 0));
    trans = glm::rotate(trans, glm::radians(rot.y), glm::vec3(0, 1, 0));
    trans = glm::rotate(trans, glm::radians(rot.z), glm::vec3(0, 0, 1));
    trans = glm::translate(trans, pos);
    return trans;
}

What is your intention here? createTransform seems to take two parameters but you supply only one in your call. What is offset in the first code block?

Ah, I have another createTransform that only takes in a position.

Multiply all the vertices by the transformation matrix? (IIRC the transformation matrix needs to be on the left of the multiply, so note that you can't use *=)

It's unclear where your issue lies.
To rotate a vector about the origin, you create a rotation matrix, and then you multiply the vertex by the matrix. In order to create the rotation matrix, you need a rotation axis and an angle.
With glm, you can do it this way:
glm::vec3 v3RotAxis( 0.0f, 0.0f, 1.0f ); // Rotate about z+
float angleRad = glm::half_pi<float>(); // Rotate of a quarter of a turn
glm::mat4x4 matRot = glm::rotate( angleRad, v3RotAxis );

Alternatively, you can use a quaternion:
glm::quat quatRot = glm::angleAxis( angleRad, v3RotAxis );
glm::mat4x4 matRot = glm::mat4_cast( quatRot );

To apply this to a vertex (a point in space), you would then do:
glm::vec4 out = matRot * v4In;

If you need to rotate about a point that is not the origin, you have to

translate the pointToRotate to the origin
perform the rotation
translate back the point to the original location

To achieve that, you create a translation matrix, and an inverse of that translation. You then 'sandwich' the rotation matrix in-between these other two:
glm::vec4
rotateAround(
  glm::vec4 aPointToRotate,
  glm::vec4 aRotationCenter,
  glm::mat4x4 aRotationMatrix )
{
  glm::mat4x4 translate =
    glm::translate(
      glm::mat4(),
      glm::vec3( aRotationCenter.x, aRotationCenter.y, aRotationCenter.z ) );
  glm::mat4x4 invTranslate = glm::inverse( translate );

  // The idea:
  // 1) Translate the object to the center
  // 2) Make the rotation
  // 3) Translate the object back to its original location

  glm::mat4x4 transform = translate * aRotationMatrix * invTranslate;

  return transform * aPointToRotate;
}

Keep in mind that with all the operations done with matrices, the order is important.
I join the whole test program if you want to play with stuff.
#include <iostream>

#include <glm/glm.hpp>
#include <glm/gtc/quaternion.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/quaternion.hpp>
#include <glm/gtx/transform.hpp>

glm::vec4
rotateAround(
  const glm::vec4&   aPointToRotate,
  const glm::vec4&   aRotationCenter,
  const glm::mat4x4& aRotationMatrix )
{
  glm::mat4x4 translate =
    glm::translate(
      glm::mat4(),
      glm::vec3( aRotationCenter.x, aRotationCenter.y, aRotationCenter.z ) );
  glm::mat4x4 invTranslate = glm::inverse( translate );

  // The idea:
  // 1) Translate the object to the center
  // 2) Make the rotation
  // 3) Translate the object back to its original location

  glm::mat4x4 transform = translate * aRotationMatrix * invTranslate;

  return transform * aPointToRotate;
}

int main( void )
{
  {
    glm::vec4 v4In( 2.0f, 0.0f, 0.0f, 1.0f );
    glm::vec4 v4RotCenter( 1.0f, 0.0f, 0.0f, 1.0f );
    glm::vec3 v3RotAxis( 0.0f, 0.0f, 1.0f );
    float angleRad = glm::half_pi<float>();
    glm::mat4x4 matRot = glm::rotate( angleRad, v3RotAxis );
    glm::vec4 out = rotateAround( v4In, v4RotCenter, matRot );
    std::cout << out.x << " " << out.y << " " << out.z << " " << out.w << " " <<std::endl;
  }

  {
    glm::vec4 v4In( 2.0f, 0.0f, 0.0f, 1.0f );
    glm::vec3 v3RotAxis( 0.0f, 0.0f, 1.0f );
    float angleRad = glm::half_pi<float>();
    glm::mat4x4 matRot = glm::rotate( angleRad, v3RotAxis );
    glm::vec4 out = matRot * v4In;
    std::cout << out.x << " " << out.y << " " << out.z << " " << out.w << " " <<std::endl;
  }
  return 0;
}


text:
Heightmap terrain picking
I've implemented an OpenGL based terrain unsing a tesselation-shader for dividing each 'terrain-cell' into the desired tiles.
The heightmap is uploaded to the GPU and applied on the shader.
When it comes to picking, I don't really know what to do.
Testing triangles on intersection with the pick ray is not possible because only the GPU 'knows' the mesh.
Is render to texture with an unique color the way to go?
Or holding an additional mesh in RAM, only for picking/collision?

Ray-casting into the height map on the CPU will likely be much faster with proper optimizations and it wont unexpectedly fail (eg: due to some odd driver rounding issues on a rare-ish laptop chipset creating a few angry customers.)
Either of those solution would work but reading a texture or frame (or any data) from GPU RAM is extremely slow (relatively speaking).
You could also use a Transform Feedback to get the result from a geometry shader https://www.opengl.org/wiki/Transform_Feedback
The pipelining issue:
With either texture or transform feedback you'll need to implement pipelining to have the GPU do the picking without incurring a stall making sure you wait to get the result 1 to 4 frames later.
OpenCL might make it easier to get asynchronous results but that's potentially adding a lot of compatibility/timing/driver issues.
There can be multiple frames "in flight" being rendered/queued by the GPU which in most case needs to be finished before you get your data back so every time you ask the OpenGL driver for data it has to wait for everything to be done.
During that time no GPU render commands are queued so you're waiting (for example) for 2 frames for the GPU to finish its queue then waiting to get the data off the PCIe bus back into system RAM then the GPU sits idle for another frame while the CPU fills the render command queue back up, then it takes another frame for the GPU to finish drawing and display it so you've incurred a huge stall of 4-5 frames worth of rendering.
(This is an example, different GPUs and drivers will incur different penalties.)
All this just to get a coordinate on a height map.


text:
Extrapolation - synchronize destination point on a second device while moving
First of all, I read all of the Valve and Gaffer articles but I still have no clue, how to achieve my goal.
I am creating a UDP multiplayer game with a lot of physics (knockbacks, attacks). Packets delivery and sequence numbers are done - there is no loss, but the problem is with synchronizing ME (when I'm moving) on the second client (my opponent's).
As I read, there are two options:
1) delay the client by 100 ms and draw everything from the past - which is unacceptable, cause it really has to be a real time game. I know that for Valve this is enough, cause they have only shooting and they go back in time for just couple of variables, check some timesteps and they're done, but here, I have to check everything, if the player was in the air, if he was punched etc.
There is also a second option which is in a REAL TIME:
2) Real time, but with dead reckoning/extrapolation:

we get last two received positions
we make a normalized vector
no matter what - we just move the player by that vector in an update method

And here is the problem. I decided to pick option two - with extrapolation, cause it's the only solution, but I have no idea, how to stop the character in a place on the opponents client, where it was stopped on it's own client.
An example:
Speed is constant - 5 pixels per move.
Perfect world - we send a packet with position every frame.
So we move by 5 steps on X axis:
0,0 -> 5,0 -> 10,0 -> 15,0 -> 20,0 -> 25,0 (We stoppped on the client)
So we've sent 5 positions to the server and he sent it to the opponent.
We receive these packets on a second client (opponent) and we have to move the character with received packets.
And here comes the question, HOW?
Of course, vectors, I know these, but I have no idea how to synchronize this, that at the end the character on the opponent's phone is still on the same position (25,0).
An example of a problem:
We move 4 right, 2 left on the client:
0 > 5 > 10 > 15 > 20 > 15 > 10.
Opponents gets: 0, 5, 10, 15, 20 (he's moving by 1,0 normalized vector) but this is extrapolation, he moves also to 25, 30 (WHICH IS OKAY, it doesn't matter if he runned too far, it's only 10 pixels), then he get's the newest packet, he changes the vector to (-1,0) to move left, he moves two times and here comes the total misunderstanding, he will move only two times and he will land on (20,0), not on (10,0), cause this is the end of the packets.
A quicker explanation - he wasted his moves by moving 20 -> 25 -> 30, he should have use them to move these two points left - from x = 20 to x = 10;
I really need help with this, I went through hell by implementing reliable UDP and this desynchronization is killing me, really.
If someone had some experience with these things in Java, or anything, I would be grateful.

Send timestamps and old positions in your packets.

I do send old positions (last 32 positions) but why timestamps?

You receive a packet saying "At frame 305 I was at (10,20) and started moving at (0,5)". You might not get that until frame 307 - then you know to instantly teleport them to (10,30) and start moving them at (0,5).


text:
transform.Translate only for 10 units?
How can I transform.Translate (Vector3.up * Time.deltaTime * 2); a GameObject for 10 units? I mean only make it go up 10 units (10 y units).

you can move a object 10 units up using
transform.Translate(0.0f, 10.0f, 0.0f);

many ways to implement but I wrote this out to get you started
float yPos;
float yEnd;
void Start () {
    yPos = this.transform.position.y;
    yEnd = yPos + 10;
}
void Update () {
    if(yPos < yEnd)
    {
        yPos = this.transform.position.y;
        transform.Translate(0.0f, 10.0f * Time.deltaTime, 0.0f);
    }
}

Set a variable as your target destination before you start moving, then use Vector3.MoveTowards to gradually move towards your destination.
You'll also want to specify a movement speed.
Vector3 targetPosition = transform.position + new Vector3(0, 10, 0);
float movementSpeed = 1f;

void Move () {
    transform.position = Vector3.MoveTowards(transform.position, targetPosition, movementSpeed * Time.deltaTime);
}


text:
How do i set Lua variables?
You can pretty easily read variables, but what about writing them to the lua file?
Ive given it a little go, but it doesnt seem to work...
void Lua::setBool(string path, string var, bool val) { //"Lua" is a class with my Lua functions (such as get bool, get float...)
    lua_State *L = luaL_newstate();
    luaL_openlibs(L);
    if (luaL_dofile(L, path.c_str())) { // For some reason, "!luaL_dofile" triggers if i input the path Correctly
        string msg = "Unable to open file " + path;
        MessageBox(NULL, msg.c_str(), "Lua IO", MB_ICONERROR);
    }

    lua_pushboolean(L, val);
    lua_setglobal(L, var.c_str());

    lua_close(L);
}

And yes, ive inputted "var" and "path" correctly.

If you want to write them to the Lua file--as in the script text file itself--you'll have to do it as you would any other text file. As far as I know, Lua doesn't include any way to do this.

Lua doesn't provide any way to modify a chunk after it's been loaded, or to automagically convert it back into uncompiled source, but it certainly provides you the tools to modify or procedurally generate code.  The io library would be the place to start when you want to load/save files.  http://www.lua.org/manual/5.3/manual.html#6.8

If your intention is to modify your Lua State so that your Lua script can access parameters set from C++, you need to actually set those values before calling into Lua (luaL_dofile is a helper for loading a chunk from a file, compiling it if necessary, and immediately executing it).  So the following lines should be moved up just after luaL_openlibs.
lua_pushboolean(L, val);
lua_setglobal(L, var.c_str());

Note that a Lua chunk is actually a function from Lua's perspective, so you can actually just push parameters onto the Lua stack and avoid polluting the global environment.  Then you could access them in Lua using something like:
local paramA, paramB = ...

However you can't use luaL_dofile to do this.  It's just syntactic sugar for (luaL_loadfile(L, filename) || lua_pcall(L, 0, LUA_MULTRET, 0)).  In order to pass parameters on the stack you'd need to expand it out so you can replace the first 0 in lua_pcall with the number of arguments you want to pass.  You can return values from Lua chunks in a similar fashion.

Regarding your confusion in the comments of your code regarding the return value of  luaL_dofile, it returns an integer status code.  Most lua* functions that aren't retrieving a value return a status code indicating if everything went alright, or a vague idea of what went wrong.  If everything's peachy, it will return LUA_OK, which happens to be defined as 0.  So you should say:
if (luaL_dofile(L, path.c_str()) != LUA_OK)

But if i want to write to the lua file? does lua have anything to do that?


text:
How can I interpolate between two frames of a sprite-based 2D animation?
For example, I'm looking to animate at 60 frames per second, but clearly my artist isn't going to hand-author 60 frames of art for every second of an animation clip and even if he could, it would only work properly in locked-timestep.
So given two successive frames in a sprite-based animation, I want to smoothly "interpolate" or "morph" between them at runtime to produce a smoother, and higher frame rate animation based on where the update time for the current frame lies between the two frames.
Another way to look at it would be to say that my animation is authored such that the frames occur at regular intervals, much less frequent then 60 FPS. Say I'm 30% between when frame N should appear and when frame N+1 should appear. I want to render an image that looks like it's a 30% the way through a smooth transition from the frame N image and the frame N+1 image.
This paper seems promising, but am interested in other potential solutions I could look at for implementing this. Please do not recommend a tool as a solution.

Are you talking about "tweening"?

@ashes999 I will elaborate so that you can tell me.

We don't document "industry standards" here, but asking how to implement this kind of morphing is on-topic. I assume you're talking about purely sprite-based animation, not 2D skeletal animations? Are you willing to make any concessions for the input data (e.g., does the approach have to work with just sprites, or can you mark up the sprite data in some additional fashion)?

@JoshPetrie Currently I'm looking at pure sprite-based animation; the particular animation design isn't well suited to planar skeletal transforms. I'm willing to add whatever data is needed, as long as it can be done by the artist.

Quite frankly, I think that a pure sprite based implementation is going to be a lot harder to write (one that looks good and is usable), than it would be to just fill in some animation frames yourself -- or finding an artist who can do it for you.  Another option would be to split your sprite into separate entities (kinda like a bone system), and do the tweening like a sane person.

in case of sprite-sheet animation your artist has much better odds of exporting his animation at 60fps than you tweening/stretching/whatevering up to 60fps successfully

Generating 2d images at runtime by interpolating 3d physical movement is what 3d games do already. they simulate the 3d interaction, calculate the flattened image, then paint it to the screen. You might have better luck by having your artist build 3d animations, then rendering the animation frames to a file.

You can bake the "motion vectors" of the sprite-based animation and use this information to morph between frames of the sheet.
Take a look at this:
http://www.klemenlozar.com/frame-blending-with-motion-vectors/

Your best bet in this scenario would be to use some sort of interpolate/blend shader since your animation is purely sprite based. It would take the pixels from the current animation frame of the sprite and then blend/interpolate it with the ones from the new frame. This probably wont look as good as an animation that was created purely from sprite sheets with the intermittent frames. But it would probably give you a similar effect as those in the linked document.
But the major concern here would be performance. I'm not a shader expert, so can't really say how practical this is when it comes to games. You might just be able to do a limited number of animations this way.


text:
Inverting a Font?
How can I invert a font like so:
See here:

This is my own .ttf font, I can edit it. The image that I posted was inverted manually by me. I am searching for a way to invert automatically all characters of the font.
Invert means: convert 1 to 0 and 1 to 0. Which will convert the filled (black) parts to transparent and the transparent parts to filled.
I want a "Font Invertor" software or a simple way to achieve this. Does High-Logic FontCreator do this? I didn't find a way with the latter.

Can you clarify, are you working with a bitmap font or a vector font? With bitmap fonts, any old image editing software will let you invert your font texture, or do arbitrary processing (like omitting the coin's extrusion/shadow in your example at the right)

@DMGregory I'm working with a .ttf font.

Consider downloading the picture and inserting it within the question, because in the future if by any chance the link goes down, your question will become of little use for others who otherwise could find it by searching on a similar problem

The way outline fonts (such as ttf) work is by defining a set of curves by vector graphics (quadratic Bézier in the case of ttf).
What is inside or outside? At the moment of rendering the target area has a set of pixel where the character will be drawn. The following is a simplification of the algorithm to do so:

Go row by row:

Start by considering we are "outside"
If we are "outside" and we crossed an outline, are now "inside"
If we are "inside" and we crossed an outline, are now "outside"
If the current pixel is "inside" color it
Advance to the next pixel

Visually:
These are the outlines:

Now, we start outside. We advance to the first pixel. We have not crossed any outline, so the pixel is outside and we don't color it (highlighted in ligh gray):

We are outside, We advance to the next pixel. We crossed an outline, so now we are inside. Since the pixel is inside, color it:

Continue advancing, we don't cross any outline for the next few pixels - so we keep coloring them:

When we cross the other outline we are outside again:

If we do this for each row, we will have the character fully colored:

Note: this is disregarding antialias, subpixels, and any transformation applied to the character. Also, since this is a didactic explanation, I'm pretending the outlines alway fall between pixels, in reality you will have - for example - pixels that are 60% outside and 40% inside. For a more detailed explanation (and a bit of history) see the video The Font Magicians - Computerphile .

Getting the inverse outline
Now, see what happens if I remove the exterior outline:

If we follow the steps described above, the result is this:

Note: To do this in FontCreator select all the points - and only the points - of the exterior outline and hit delete.
Adjust the size and position of the character as needed.

Getting the inverse bitmap
Also if you are rendering without antialias, you may always take the character bitmap...

Fill the exterior (that may be tricky, as you need to start a flood fill on a pixel that you know is outisde, the key is to check the color first):

And then get the inverse of the image:

Note: this is proably ruined if you have antialias.

Your expected outcome contains a step that will become a problem.
To get to the result you must first determine what part of the graphic is considered a letter. Your original font is basically an outline.
So what you're looking for is to detect what part of the letter is the 'inside' and fill that.
The problem here is that it becomes hard to detect. How would you find the tittle (the dot on a i or j) to be part of what you want filled? And how to find if the inside of the p should not? And the complication added here is that you made a bitmaplike font where diagonals may be consist of separate blocks entirely.
So computationally this ttf font will be complex to invert.
Since the ttf font is monochromatic you can't actually this in post processing either. Draw a text to a bitmap and inverting the bitmap will not produce the desired result. Conside the top left empty block in your image. It is white in both the normal and the regular version.
So what to do?
Since you are using a bitmaplike font anyway... Use a bitmap font for this. You could use two colors to distinguish the outline and inside and use a shader/code to replace the colors with whatever you want. Use just the inside or just the outside or combine them with fancy color effects!
Note: the inverted process of creating an outline for a vector font is a lot easier, as it is basically enlarging the existing data (since that data is actually describing what is part of the glyph.


text:
Port forwarding client and server?
So, lets say i have a client and server sending information to each other. Do i have to port forward both the server and the client, or do i just port forward the server? If i have to do both, is there any way of not needing to port forward? Im using SFML to be specific.
This isnt on local networks and its using UDP.

No, you don't need to port forward the client. If the server runs on a home computer (behind a NAT) then yes, you need to port-forward the server or check out how udp-hole-punching works but if the server runs on a real server (a server you rent with a public ip-address) then it should work out of the box.
Note though, the client, which is probably behind a nat, needs to send the first (and possibly a few more) UDP-packets to the server before the server can reach the client.
Another thing to note: It doesn't matter on which port the client listens for UDP-packets (and on which port it sends), the server has to send it's packets back to the port which the receiving packets contain as sender-port, which is not necessarily the port the client listens on!
For example:
The client listens on port 5555 and therefore sends its packets from port 5555. The server also listens on port 5555 and sends its packets from port 5555.
The client now sends a packet to the server to port 5555 but the server sees the packet coming from client_ip:45671. The server now needs to answer to port client_ip:45671, not to client_ip:5555 even though the client listens on port 5555!

I didnt quite understand the last part

@JFrap added a simple example, hope this clarifies it.


text:
How could I access game data from a dev machine at runtime from a mobile platform?
When working on a game on a mobile platform, having read/write access to game data (assets, configuration files) stored on the dev machine at runtime would enable building of tools to quickly iterate, debug, and analyze the game at runtime.
For iOS & Android, is there any way to have access to these data files from the dev machine while the game is running on the mobile device?
Please do not recommend a tool, or a 3rd party engine that does this.

You generally need three things, basically, to accomplish this.

First, you need a system in your game that can hot-reload assets or other data in response to some notification that the asset has changed. When a texture changes, you'll want to upload the new pixels to the GPU. When a monster description changes, you'll want to swap out the monster's old stats with the new ones. Et cetera. This is usually tied in to whatever system the game is already using for resource loading/caching/management.
Second, you'll want to abstract the game's file IO operations so they talk through a virtual filesystem sort of API instead of directly reading files from the device storage. For the "shipping" version of the game you'd use an implementation that did just read files from the device storage, and which never sent any "file changed" notifications mentioned above (probably). For the development or iteration builds, you'd replace that with a version which talked over the network to a remote host and redirected all file IO to that host.
Finally, you'll need some kind of editor shell or other wrapper running on the remote (desktop) machine; this machine looks for actual file changes to its files and sends notifications remotely to your game running on the mobile device that files have changed. It also probably implements the networking protocol that the game's remote virtual file system uses to talk with it and read the content of those files.

This also works well for consoles, not just mobile platforms. Even on games developed purely for desktops, it can be a useful collaborative editing tool.
Because of network latency issues you may need to be clever in how you transfer files; you may want to do some negotiating to make sure you always send files in an access-coherent manner, you may need to pre-send some files that you are pretty sure the device might need, or you might need to send only deltas of the changes. You'd have to do some experimentation.
However, this approach is used fairly often on current shipping and in-development titles/engines to achieve the kind of iteration improvements you're alluding to in your post.

Hey Josh. Thanks for the reply. Once I have access, I know how to build all of these systems. The question is how to actually get r/w access to the files. Clearly a networked solution is possible, but adds a decent amount of overhead (both in developing the tools, and in actually uploading large amounts of assets). Is there no way to easily mount the mobile filesystem to the dev machine when plugged in via usb? (Or something equivalent - I'm told that iTunes doesn't actually mount the fs when syncing)

Not that I know of. You'd probably need to jailbreak the iOS device.

Thanks. Now that I think about it, this question ultimately boils down to a question that belongs on SO or other, even if I'm interested in game-dev applications. Thanks for taking the time to respond.