text:
Is FreeGLUT still a good choice?
I recently decided to utilize the C++ library called FreeGLUT to have a window be managed from my program, where I can draw things via OpenGL. But at the same time I saw some people telling that it is an old library, not that much reliable and so on... Should I keep using that or move to another one?

I would only recommend using FreeGLUT if you are just learning OpenGL and don't want to worry yourself with things like window and context creation.
FreeGLUT is also use full when you would want to create a quick graphics demo, something that purely shows off some graphics related concept.
Its otherwise a bad choice for games as you don't have control over the game loop and raw input collection, which are quite important for high performance games.

Just to ask, do You know some good libraries I can use?

GLFW is a good alternative. It is still actively maintained, and easily allows creating an OpenGL context and window, supports multiple windows, and supports controller input.
http://www.glfw.org/
There are tutorials on their website for using it, but if you are already used to FreeGLUT, this tutorial here may be of use, as this tutorial series primarily used freeglut but transitions over at this point in the series.


text:
How do I keep 1v1 player positions consistent over UDP on Kryonet?
I have a server which is simple:
When two connections comes in, it opens a game room, pass their connections to it and runs a thread with a gameloop. (Everything is running on Kryonet)
So... I made the movement, it works on TCP and UDP, but it has to be done via UDP, cause it will be a real-time game, there is no place for a lag. After switching updating positions to UDP, as we all know, some of the packets are lost. Sometimes the server is loosing some packets and it doesn't send them to the second client - that's why the opponent seems to move by 2x, not by x (it happens only sometimes).
My question is: How this kind of things should be implemented? How everything should be handled, I mean - sending states (walking, running), positions etc that there is no visible lagg? Should I send the packets more often? I heard once, that the server should also save player's positions and send it back to him and his opponent (to avoid cheating and laggs). I know how to implement these things, but I don't know how should it look like in a real-time fighting game.
If there is any experienced programmer, that could give me an advice, I would be grateful.

This introduction to fast-paced multiplayer networking might be helpful.

You will always run the risk of losing packets and having latency - you need to hide this from the player while trying to give reliable gameplay. If the data being sent is small you can simply send the current frame and the last 32 frames of data in a single packet. Mark each frame with a sequence number before you send it. On the receiving end the peer only consumes those pieces of data it has not yet seen. In this way you get some data redundancy. On the receiving end, you will also want a buffer to delay processing this data to help smooth out the 'jitter' of the latency. Latency is never constant, and you don't want to be processing the data exactly as it arrives or you might have block waiting for the next piece. Instead you want to artificially delay the data once received to give your peer more time to receive late packets.
There are a lot of other options here - you could use a snapshot system with delta compression (Gaffer covers a lot of this here and it is an excellent read: http://gafferongames.com/networked-physics/introduction-to-networked-physics/) and extrapolation to help guess where people are going to be. There are a lot of details to explore.

source: Stack Exchange

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

sort: votes


text:
Does each game asset always require a prefix such as 'spr' or 'obj' in their name?
Having started only recently with using GameMaker for game development (keep in mind that this is the first time in a long while that I'm doing something like this, so I'm technically at beginner level), I've lately been thinking about something that seems to be common place throughout creating a game with the software.
Through all the tutorials I've been through so far in GameMaker:Studio, I've noticed that the tutorials seem to want the names of game assets to always have a prefix in their names depending on what the game asset is, usually something like spr_ for sprites or obj_ for objects.
I've never exactly liked this sort of naming method, but I don't know whether or not to keep doing this or to just avoid using the prefix entirely. Does the engine require these prefixes for a game to compile or something?
Are these prefixes necessary?

No, this is just a coding convention on the part of the people who wrote the code. You can name your objects however you want (within reason... I'm sure $@#$ would not be a legal name).
The idea behind this convention is that you know what type an object is just by looking at its name, which is supposed to aid understanding while reading code. I don't really like it, either. :)

It's especially helpful when getting to work with GML. Resource names must be unique, and having this prefix system means you can have spr_player and obj_player as two differently-named but easily-identifiable resources.

You bring up a good point, but I still wouldn't use this convention. I'd be more likely to do playerObject, playerSprite. This way, they alphabetize near each other, and you don't have all the xxx_ noise everywhere.

Maybe I'm just used to doing it that way XD Since Game Maker groups resources of a similar type together already, the problem of alphabetising is less of an issue. To each their own, however, and so long as it makes sense (which yours does) and is consistent (I'd gladly adjust my naming conventions to match yours if we were working on a project together), then all is well.

One of the reasons some people put the type as a prefix rather than as a suffix is to leverage autocompletion.  By starting with obj_ (or just o) you get a list of every object that you can then navigate or filter if you don't remember a particular name.

Admittedly the last time I used Game Maker was over 5 years ago, but at the time, all game resources were kept separate in the UI, so even naming them similarly would never have them end up next to one another.  Additionally, this convention was extra important since these identifiers simply resolved to numeric IDs which were only unique within their own category.  This meant you could give an object ID where a sprite ID was expected and everything would "work", although not in the way you intended usually.

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


text:
Stencil Buffer not working as expected in OpenGL ES 2.0 (Android)
I'm trying to get to grips with the stencil buffer.
Apart from setting up viewport, camera, etc, my OpenGL ES 2.0 initialisation code is:
GLES20.glDisable(GLES20.GL_CULL_FACE);
GLES20.glDisable(GLES20.GL_DEPTH_TEST);
GLES20.glEnable(GLES20.GL_BLEND);
GLES20.glEnable(GLES20.GL_STENCIL_TEST);

GLES20.glBlendFunc(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA);
GLES20.glClearColor(0.2f, 0.8f, 1.0f, 0);
GLES20.glClearStencil(0);

My main code is below.
        GLES20.glEnable(GLES20.GL_STENCIL_TEST);
        GLES20.glColorMask(false, false, false, false);
        GLES20.glStencilFunc(GLES20.GL_NEVER, 1, 0xFF);
        GLES20.glStencilOp(GLES20.GL_REPLACE, GLES20.GL_KEEP, GLES20.GL_KEEP);

        GLES20.glStencilMask(0xFF);
        GLES20.glClear(GLES20.GL_STENCIL_BUFFER_BIT);

        // draw sprites
        player.draw();

        GLES20.glColorMask(true, true, true, true);
        GLES20.glDepthMask(true);
        GLES20.glStencilMask(0x00); // don't effect the stencil buffer
        GLES20.glStencilFunc(GLES20.GL_EQUAL, 0, 0xFF);
        // draw where stencils value is 0 if we want...

        GLES20.glStencilFunc(GLES20.GL_EQUAL, 1, 0xFF);
        // draw where stencils value is 1 if we want...

        level.draw();

        GLES20.glDisable(GLES20.GL_STENCIL_TEST);

However, this doesn't work. As expected this code does not draw the payer. The player (or the filled square surrounding the player) should be drawn to the stencil buffer. The next part of the code should draw the level, which should be clipped to the boundary of the player (or the square boundary of the player). What this code actually does is draw the whole level.
Why is the code not clipping the level to the profile of the player, or at least the square bounding the player ?

The problem was I needed to set up the stencil buffer:
mGLSurfaceView.setEGLConfigChooser(8, 8, 8, 8, 16, 8);


text:
What's the best practice for a progress bar in OpenGL ES 2.0?
My attempt: I make a texture (could be a single colour or otherwise), and then stretch that texture from a minimum 0 up to a maximum max value. This works, but leaves me rather dissatisfied for a number of reasons, one of which being:

If I want rounded corners as the bar progresses, the edges are squashed or stretched.

My question: What is the best practice to achieve a progress bar result.
Thoughts: Is there a way to stop openGL from drawing anything from a certain x value onwards of a texture? That way I could draw the texture as it should appear, but specify the value of x.
I have found this potentially useful link.
Update
I get the impression that using the stencil buffer might be the way to go. The stencil buffer allows to define any region you like through which other rendered geometry can be clipped. Apparently there are many other uses for the stencil buffer, e.g. reflections.
Possible Solution
I ultimately achieved what I wanted using the stencil buffer combined with my own shader, since OpenGL ES 2.0 does not support glAplhaTest and related functions. Here's an image of the result:

The texture drawn to the stencil buffer was an elongated rectangle with rounded corners. The texture drawn to the image buffer was just a stretched red rectangle, which as you can see is clipped to the stencil contents. You need to write your own shader to deal with the alpha channel since OpenGL ES 2.0 does not support the glAplhaTest and related functions.
Note - perhaps this isn't the best image example. In fact the presented solution allows you to progressively reveal the left and right caps, which I unfortunately didn't demonstrate in the above image.

Did you mean u in texture or x in world coordinates?

I'm not sure to be honest - it was just an idea, but I'm not sure how to achieve that yet.

You probably want to pass separate mask texture and a uniform to you shader to allow un-stretch the mask. Or even easier would be to create quads for both ends and the body separately.

Why can't you just render only part of the progress bar you want to render? If it's at 50%, then render the left half, using the left half of the texture.

@immibis thanks... At the time I had no idea you could map any part of a texture to vertices, and I was just rendering each sprite individually using its very own texture. Having been using sprite atlases for some time now, I understand how I would implement your suggestion. It's much more efficient than my original idea ! Thank you.

In the end I just made use of the fact that OpenGL lets you map any part of a texture to your vertices. So, suppose you have a texture with three hearts in a row, of width 300 and height 80 say, and you only want to show two-thirds on screen. Then you would map texture (0, 0, 200, 80) to your vertices, but make sure your vertices are also reduced accordingly. Saves messing around with the stencil buffer and is much quicker and elegant. Seems obvious, but back when I thought each sprite had to use a separate texture I couldn't see it !

No need to bring in additional entities, KISS
Just render the progress bar out of three parts - left cap, right cap and the body. Schematic:
 {left cap] [body] [right cap}

Left and Right caps are usually always the same - half-circles with transparency. The body texture needs to be stretchable without noticeable effects.
Left and Right caps usually get rendered irregardless, and the required percentage is shown with body width. So e.g. 0% could be an empty bar, 1% is caps with body of 0 width.
Further reading for stretching without distortions in both axis: google for "nine-patch button".

I like the principle. However, I want a fluid look to these bars, and the described method does not allow for the (left cap] or [right cap) to gradually reveal itself. My current implementation does :-D In addition I am now able to achieve many other effects given my knowledge of stencil buffering. I will definitely keep KISS in mind though !

Stencil often could be replaced with a texture mask. Just in case it is not available or an overkill for a single progress bar )

I'll take a look. I don't know anything about texture masks !

There are a few ways to do this.
This is the solution described by poirot:

I ultimately achieved what I wanted using the stencil buffer combined
  with my own shader... The texture drawn to the stencil buffer was an
  elongated rectangle with rounded corners. The texture drawn to the
  image buffer was just a stretched red rectangle, which as you can see
  is clipped to the stencil contents.

You could instead use three instances of geometry; one half circle for each end and one rectangle stitched in between. Note how this does not require custom shader or stenciling. (This solution appears to be the same as suggested in comments by wondra.) This solution is my favorite for a number of reasons.
One note about stencil buffer it can be multisampled yielding anti-aliasing for a full frame without application intervention. Alpha testing (shader or not) however is a fragment operation which is not multisampled. If you combine the two stencil buffer never truly multisamples; all samples are treated equally, thus no anti-aliasing.

But using a half circle, a rectangle, and a final half circle how do you nicely show the progress of the half circles? E.g. supposing the half circles represented 10% each and the rectangle a remaining 80%. How would I nicely draw 5% ? The stencil approach permits to show progress before or after the start/end of the rectangle, i.e. anywhere between the width of either half circle.

@poirot Yes I know. It was not clear from your example how you wanted it to look like when the bar is empty or close to empty. A variant would be to render the bar shape to stencil (write ones) and then fill the masked area (where there are ones) with a rectangle with length based on %. When the bar is almost empty the rectangle does not fully cover the masked area. Does that make any sense to you? It is similar but does not require any addition shader programming and multisampling may still work.

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


text:
Filling a polygon with a texture (or a color) C# Visual Studio
I'm trying to figure how to put a texture or fill a "DrawPolygon" with a simple color in C# Visual Studio (using right now 2015).
 //Left Wall 1
 Point lw1a = new Point(18, 7);
 Point lw1b = new Point(99, 61);
 Point lw1c = new Point(99, 259);
 Point lw1d = new Point(18, 313);

 Point[] lw1 = { lw1a, lw1b, lw1c, lw1d };

 gr.DrawPolygon(pen, lw1);`

This is a example code for one of the things I'm drawing on screen. Any idea on how I can achieve that?
Thanks!

The programmers over at Stack Overflow would probably know more about this then us.

try using Graphics.FillPolygon
Example :
            // Create solid brush.
            SolidBrush blueBrush = new SolidBrush(Color.Blue);

            // Create points that define polygon.
            Point lw1a = new Point(18, 7);
            Point lw1b = new Point(99, 61);
            Point lw1c = new Point(99, 259);
            Point lw1d = new Point(18, 313);
            Point[] lw1 = { lw1a, lw1b, lw1c, lw1d };

            // Define fill mode.
            FillMode newFillMode = FillMode.Winding;

            // assuming gr a graphic object
            gr.FillPolygon(blueBrush, lw1 , newFillMode);

For using a texture you can try TextureBrush instead of SolidBrush
Follow example filling ellipse with texture :
 try
    {
        Bitmap image1 = (Bitmap) Image.FromFile(@"C:\Documents and Settings\" +
            @"All Users\Documents\My Music\music.bmp", true);

        TextureBrush texture = new TextureBrush(image1);
        texture.WrapMode = System.Drawing.Drawing2D.WrapMode.Tile;
        Graphics formGraphics = this.CreateGraphics();
        formGraphics.FillEllipse(texture,
            new RectangleF(90.0F, 110.0F, 100, 100));
        formGraphics.Dispose();

    }
    catch(System.IO.FileNotFoundException)
    {
        MessageBox.Show("There was an error opening the bitmap." +
            "Please check the path.");
    }

One thing (sorry for the question), but... how I use FillPolygonPointFFillMode? I mean, I don't understand what parameters or arguments I need to introduce when I call it (FillPolygonPointFFillMode(); for example). I'm a little new in C# and I don't know many things yet. Thanks for everything.

this is an example method.. consider only the body. I edited the example considering your piece of code


text:
Generate a 2d mesh terain out of triangles (low details)

I'd like to learn a good algorithm to generate a 2d mesh made out only of triangles to be used as a terrain.
Its not important to get a high detail terrain. It should just have a triangle looking style.
Also the mesh should be extendable endlessly in all directions because the map will be endless. I thought about to having chunks of meshes saved in a file so they can be loaded during the execution.
Something like this (from Chasing Aurora):

What is your data source? How should the terrain look like? Should it be just random or follow specific rules? Please specify what you want to know, currently we can't really help you as the possibilities are endless.

I should be able to create paths where the player can move. Or add some predefined structures like a vertical wall but with triangles and not staight. Or make a flatterd land.

Please add the image to which you refer directly to the question, it's hard to know what exactly you're referring to in the link you added.

link

If you want to use a voxel field as data source, you could search for the Marching Cubes algorithm. voxels have the benefit that you can have caves, what isn't possible with simple height fields. But pathfinding could be a little bit more difficult

Try this:

Generate random points
Compute delaunay triangulation of those points
Use those delaunay triangles as your mesh

By restricting the domain and distribution of the random points, you can control the height of your terrain more carefully.
If you want to go beyond this and generate consistent terrain, or geometries that aren't just random mess, you will want to try some kind of procedural terrain generation. A great write-up about this can be found on NVIDIA's GPU-Gems site. The NVIDIA write-ups are really good disregarding your implementation tool, you don't have to actually implement it on the GPU.

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


text:
Acceleration problems
Im trying to make a car game, but i cannot get the acceleration code right. With this code:
        if(gas){
        speed += 3;
    }else if(break_ && !(speed < 6)){
        speed -= 3;
    }else if(!break_ && !gas && !(speed < 6)){
        speed -= 0.3;
    }else{
        speed = 6;
    }

it is up on 1000 within 5 secounds. I tried multiplying it with smaller numbers, but it still doesnt work(in fact it got worse). So, how can this be improved so it has reasonable parameters? Asof the maximum speed, i can implement that on my own.

Quick tip: cars have "brakes" not "breaks". So your variable can be called "brake" and you don't need the underscore after it. :)

Do you have any concept of a frame time. Or change per second. I expect your loop is freewheeling as fast as it can. Hence the issue. Always measure frame time and multiply it by a rate of change to get actual change

What is this >6 stuff?

Jon it is to prevent the speed from going below 6

Try adding in a Velocity variable.  But more importantly, you need to keep track of your deltaTime, which is the time that elapsed since your last frame.
More than likely the framework you are using has this, if not you will need to implement one.
float Velocity;
float Speed = 3;     //Your speed could vary here

if(gas){
   Velocity += Speed * deltaTime;     //when gas is pressed, speed up
}
else if (brake && (Velocity > 6)) {
   Velocity -= Speed * deltaTime;      //When brakes are pressed, slow down
}
else if(!brake && !gas && (Velocity > 6)){
   Velocity -= Speed * deltaTime;     //friction should be a different value than Speed
}
else {
    Velocity = 6;
}

//Update the position
Position.Axis += Velocity;

The position.axis change should also be multiplied by delta. Other than that; exactly this

The speed determines how quick the stripes moves(everything else stands still). However, how do i get the delta time? Im using Android, but it should be the same as normal Java

@Polarbear0106 http://gamedev.stackexchange.com/a/56993/10728  typically you would use a framework/engine,  which takes care of this stuff for you ;)


text:
Replace black color by transparent color XNA
I'm actually trying to replace black color of my texture by a transparent one.
How can I do to remove the black pixels, should I use a AlphaTestEffect, or can I use the BasicEffect?

Thank you.

If your image background is already transparent, then you may need to enable alpha blending on the basic effect if its not already enabled.
If the textures background is not transparent, the easiest way would be to edit the texture outside of XNA, and replace the black background with a transparent one. If you have Gimp, Photoshop or Paint.NET installed, this is rather trivial.
If you are looking for a way to do this in code, one way will require you to use a custom shader in order to so so. My answer here describes how to do something similar with a different colour, and I've also copied across the code as well in case anything happens to that answer.
// WARNING! UNTESTED CODE FOLLOWS
void SpriteVertexShader(inout float4 color : COLOR0, inout float2 texCoord : TEXCOORD0,
                        inout float4 position : POSITION0)
{
    if (color == float4(0, 0, 0, 1)
        color = float4(0, 0, 0, 0)
}

Essentially what this psuedo shader code is meant to do is replace any black coloured pixel with a transparently one. If you are not familiar with custom shaders, or not comfortable using them, something similar can be done in C# code, but is best done when you load the texture, as it is not something you would want to run every draw call.


text:
Spriter model not touching ground in?
I was attempting to make a game in Construct 2 by using my Spriter Models plugin. However, when I imported the model, rescaled it & changed a few things, I got this:

As seen in the picture, the Spriter model is not touching the platform ground.
Do you know of any ways I could have the model touch the ground?
Thanks in advance,
Jamie
Ps. Here is the link to the files, just in case you guys might wanna have a look at it:
https://drive.google.com/folderview?id=0B11opD9YgSqWbVhaNEVTcGhIRTA&usp=sharing
Pps. You will need the Spriter plugin for Construct 2 to open the project file. The Spriter model files will need Spriter to open it.

It looks like your bounding box is too large for your sprite, try making sure that the sprite's feet touch the bottom of the bounding box in Spriter.
EDIT: It turns out can do it Contruct 2 itself, just double click on the part of the sprite that dosent touch the ground to open the sprite editor.
Then click on crop and you're good to go!

Thanks, @ZEKE, but can you please tell me how to do it, eg tutorials stuffs, etc? (Sorry, I'm quite a noob at these programs at the moment.)

I had a look at the collision polygons on COnstruct 2 although it showed this. Not sure what is going on here, @ZEKE.

@Jamie The legs bounding box looks fine in the picture, is this the same for all body parts?

Yes. Could it be because of the rectangular bound-things? That when it was turned diagonal that it then shifts the shape diagonally? @ZEKE

If that's the case,@Jamie, then it might be better to create a regular sprite for collision and game logic(make it invisible), then attach the Spriter object. That way you won't have to bother with Spriter's weird collisions.


text:
How to make your own 2D AABB collision system in unity?
I can't use the built in unity 2d physics engine for my game, so I tried to make my own using the unity bounds.Intersects, that is working perfectly but my problem is that I don't know how to make the player stop when It collides. Ive tried multiple things like storing the players last position and "teleporting" it back to that position when it collides (That looks choppy). Ive also tried to invert the controls when your colliding (So like W makes the player go down, A makes it go right ect) but that is extremely buggy. How should I do it?

Can you give us more details why Unity's physics is unsuitable or unavailable in this case? This is a very unusual constraint, and might have other spillover effects that would be important for answers to take into account.

@DMGregory To use the physics system I have to use the velocity and addforce functions but In my situation I really do need to use the Translate function in order to get a smooth motion (Because anti-aliasing is turned of because its a pixel art game)

Ah, I thought it sounded like an XY problem. Solving the aliasing is going to be far easier than writing your own physics system, so I'd recommend asking a question about the aliasing issue instead. One straightforward way is to use non-rendered objects for all your physics, then position rendered objects using translate (and any rounding you might want) to copy the movements of their physical counterparts.

@DMGregory no thats not whats causing the choppiness. Whats causing it it the speed for example if I do translate (new Vector3(1,0,0)); The sprite would move 1 pixel every second but if I change the velocity to 1 its not moving 1 pixel per second. What I mean by this is that I do not have full control over the speed. So for example if the player is moving 0.346 pixels every second (With anti-aliasing off it will look choppy)

Comments aren't a great place for back-and-forth discussion. Would you be interested in continuing our discussion by chat? There are solutions to the problems that you describe, like physics interpolation, which are less drastic than writing a new collision system.

There are multiple ways to approach this. If all your collision shapes are AABBs, you could calculate the velocity, then snap to the nearest edge of the other box e.g. for a box moving right, you would set its x to other.bounds.min.x - box.bounds.extents.x to snap it.

First of all, I don't know why you can't use the built-in physics, but you should consider using it. It's better for performances, and much easier.
if you need to make your own AABB collision system, you have to inform your script that handle moving the player.
you could do something like:
if(!YourCollisionObject.IsColliding()) {
    Move()
}

If there's no collision, your object is free to move, but if there is, your object won't move at all.

Well this dosen't work because if you collide you would have no way of getting away (You would be stuck basically)


text:
Streaming 3d model --> unity android
I want to include a feature in my game that allows me to host raw 3d models (.fbx/ .obj/ etc., not AssetBundles) on a server.
The game should download these files, save them to the device and load them into a scene.
I want to support multiple file formats, so writing my own parser is not an option!
First idea:Use the WWW class to load the model data, save it as a String in the player prefs, and load it if requested.(the last part is the problem)
Second idea:Use the WWW class to load the model data, extract the jar file containing StreamingAssets folder to the sdcard. Writing the model data into a new file in this directory. Creating a new ZIP..ah...JAR archive from the folder and replacing the old .jar file.Of course I would need an Android Plugin and a archive java library for that. Then the Models will be loaded from the Ressources.(this is a pretty weird idea and cannot be the right way)
Do you know, if that works?Has anybody ever done something like that?
UPDATE 1:
I tried to use the obj loader from samed-tarık-Çetİn's comment, but I got this error:
ArgumentNullException: Argument cannot be null.
Parameter name: key
System.Collections.Generic.Dictionary`2[System.String,UnityEngine.Material].get_Item (System.String key) (at /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System.Collections.Generic/Dictionary.cs:136)
GeometryBuffer.PopulateMeshes (UnityEngine.GameObject[] gs,     System.Collections.Generic.Dictionary`2 mats) (at Assets/OBJ/src/GeometryBuffer.cs:145)
OBJ.Build () (at Assets/OBJ/src/OBJ.cs:236)
OBJ+<Load>c__Iterator0.MoveNext () (at Assets/OBJ/src/OBJ.cs:63)

Replacing line 145 in GeometryBuffer.css with gs[i].GetComponent<Renderer>().material = new Material(Shader.Find("Standard")); did resolve the runtime error and a Material, OBJ (Mesh Filter) and Mesh Renderer Component have been added, but it still show a model.
UPDATE 2:
I am behind a proxy so loading the model from the web didn't work.
Loading .obj files from file:///<path to obj> works perfectly fine though.

Here is a solution for .obj only: http://www.everyday3d.com/blog/index.php/2010/05/24/loading-3d-models-runtime-unity3d/

@SamedTarıkÇETİN can you please post this as an anser (with my code changes from update 1), so I can accept it? Thank you for your help!


text:
How to calculate delta-time on Android?
How do I calculate the time between frames on Android? I'm using this for the thread:
public class GameThread extends Thread
{
  private int FPS = 30;
  private double averageFPS;
  private SurfaceHolder surfaceHolder;
  private Game gamePanel;
  public boolean running;
  public static Canvas canvas;
  public static double deltaTime;

  public GameThread(SurfaceHolder surfaceHolder, Game gamePanel) {
    super();
    this.surfaceHolder = surfaceHolder;
    this.gamePanel = gamePanel;
  }

  @Override
  public void run() {
    long startTime;
    long timeMillis;
    long waitTime;
    long totalTime = 0;
    int frameCount =0;
    long targetTime = 1000/FPS;

    while(running) {
      startTime = System.nanoTime();
      canvas = null;

      //try locking the canvas for pixel editing
      try {
        canvas = this.surfaceHolder.lockCanvas();
        synchronized (surfaceHolder) {
          this.gamePanel.tick();
          this.gamePanel.render(canvas);
        }
      } catch (Exception e) {
      } finally {
        if(canvas!=null)
        {
          try {
            surfaceHolder.unlockCanvasAndPost(canvas);
          } catch(Exception e){
            e.printStackTrace();
          }
        }
      }

      timeMillis = (System.nanoTime() - startTime) / 1000000;
      waitTime = targetTime-timeMillis;

      try{
        sleep(waitTime);
      } catch (Exception e) {
      }

      deltaTime = waitTime;
      totalTime += System.nanoTime() - startTime;
      frameCount++;
      if(frameCount == FPS)
      {
        averageFPS = 1000/((totalTime/frameCount)/1000000);
        frameCount =0;
        totalTime = 0;
        System.out.println(averageFPS);
      }
    }
  }

  public void setRunning(boolean b)
  {
    running=b;
  }
}

I tried doing it like in normal Java, but it didn't work (it only lead to a crash).

"but it didn't work (it only lead to a crash)" is not helpful at all for us to help you. Where does it crash? At what line? What's the error message?

It lead to a chrash in a array list. It was a nullpointer exception

It's still unclear what you're asking. You do not specify what line causes the crash. Most of your code is within try-catch blocks so the exception would not pop out from the core of your code...

I used a completly different system which i speed translated to android. What i want is a way to calculate delta time on anroid


text:
Java image in JFrame rendered weirdly
I'm not sure if this is intended or not, if it is, I'd like to know a way of preventing this: I've got this image (which is for testing purposes, the actual one has a texture, but I'm not using it right now):
Zoomed in, it looks like this in the JFrame:

These small 'arrangements' are what bothers me, because the image itself should be plain green, just as it is when viewing the tile image with a separate viewer
(like that:)
OOO
--O--
O--O
In the end, drawn as a tilemap, it looks like this (I'm changing the rgb values, that's why it's coloured differently on the left):

My Code:
(It draws 15 horizontal tiles and 10 vertical tiles, the orange ones are another piece of code which is irrelevant right now)
BufferedImage singleTile;
    try {
        singleTile = ImageIO.read(new File(filename));
    } catch (IOException e) {
        e.printStackTrace();
        return;
    }
    BufferedImage finalImg = new BufferedImage(tilesX*scaledTileSize, tilesY*scaledTileSize, singleTile.getType());
    for(int i = 0; i < tilesX; i++){
        for(int j = 0; j < tilesY; j++){
            finalImg.createGraphics().drawImage(singleTile, i*scaledTileSize, j*scaledTileSize, scaledTileSize, scaledTileSize, null);
        }
    }

I feel like this has something to do with filtering, can’t write a full answer right now, but play around with smooth vs fast filtering.

Firstly, It looks to me like whatever app you used to create your blank green texture put that pattern there. Try creating a texture using paint.net and see if the problem still persists. Also please show me the code to render the orange texture it could also be helpful. Also, you said that you are changing the RGB colors. Remove that code and it might solve your problem..

This feels more like a comment than a proper answer to the question.

@Tyyppi_77 I'm giving him a solution. That is an answer to the question

Just feels like you're asking for clarification and provide a lot of "might"s.

@Tyyppi_77 he doesn't provide a quality question so I cant give him a quality answer. I'm just doing the best I can with the info he provides me


text:
What's the difference between variables defined with and without the 'var' keyword?
I've been making my way through several tutorials on GameMaker: Studio at this point, and I've been trying to keep track of various aspects of the code used in them. One thing, however, confused me.
I have noticed that it's possible to define new variables in GM:S either with or without using the var keyword. I'm aware that you can use the var keyword to define multiple variables in one line, for example var xx, yy; (and, of course, defining null variables), but other than that, is there a particular reason why some variables don't need to use var? Is it all to do with functionality, or what? When, in that case, should I use var other than the example provided?

Variables declared with the var keyword are local variables, whereas variables declared without var are instance variables. More information on scope: https://yoyogames.com/tech_blog/41

If you say var test = 0, it is a local variable, and will be deleted at the end of the event.
If you say test = 0, it will be stored in that object until the game ends, or the object is deleted.
If you say globalvar test = 0, it will be stored until the game ends, and will not be deleted with the object. It can also be accessed in another object without typing otherObject.test.

Please do not use offensive language in your answer.


text:
Construct 2's Scroll-to too small?
I'm making a platformer that wants the screen to closely follow the player, and I know I need the Scroll TO behavior.
However, when I tried to make the screen move to the player, I get this:

As seen in the picture, the player's sprite is (I think) too small. Is there any way to increase the 'zoom-ness' of the Scroll-to behavior?
Below is the code's snippet:

Do you know what I have to do, or is there something wrong with my code?
Thanks in advance,
JamieK

The ScrollTo behaviour only moves the camera to the centre of your object.
The Zoom Level of a layout can be changed via the Set Layout Scale System parameter.
Example:

Image is a screenshot of Camera Zoom Tutorial | "Construct 2"


text:
How to deal with inconsistent network delay caused by packets arriving at different times in the frame?
I'm developing a multiplayer game that does not have prediction. It implements client-side interpolation. The problem with this is that input delay can be perceived. I've measured the various times involved in calculating the delay(packet arrival time, server respond time, time spent interpolating), and it seems about 50ms is spent on interpolating(correct), and 60ms is spent on ping and what I can only assume to be unfortunate message arrival time.
The ping is 18ms, which leaves 42ms. If the message arrives at the server immediately after the server has finished reading it's incoming messages this frame, we suffer at least a 16ms delay(at 60fps) that wouldn't be there if the message arrived right before the reading. If this happens with both the server and the client, the delay really adds up, especially at lower frame rates.
How can posts like this http://pastebin.com/ekk07PKn claim to have exactly 50ms  delay with 0 ping if this is an issue?
If it's relevant, this is being developed with Unity3d and the Lidgren networking library in C#. I've moved the server snapshot writing to a different thread with a lock around the game world update method. This helped a lot, but from what I understand moving the reading to a different thread won't help in the same way, because the client won't be able to use the new information until the next frame anyway.

To be honest, I can't even imagine a single scenario, where with well implemented client interpolation an input lag would be perceivable.
Just to counter check - Client Interpolation summarized
2 Concepts meet up
1) The Interpolation itself - let the client live in the past (ae 100ms)
2) The client sends every data with a timestamp, and the server has to keep the data of all entities for some time (ae 500ms). Now for actions, that depend on other entities, like shooting, the server now can verify the position of the other entities via the timeline and the send timestamp of the client.
With these 2 concepts merged together, you have a working, well implemented client interpolation.
So first of, if your current implementation doesn't meet the mentioned requirements then change it.
If you have both methods working fine, I will need more information to assist you in locating the problem.

Your second concept sounds more like prediction than interpolation.

This is not prediction this one important step of interpolation. When entity A sees the past and plays with this data as it would be present, A would never have the possibility to perform an action against entity B because it's state is not valid that A sees. So the server needs to validate that A h has seen B in A's present. And that can only work with time stamps. If you need more explaination just tell me

I don't see if the difference. If every one is delayed by the same amount, every one will be seeing the current state of the game.

And as soon as you do a collision detection like a shot or aoe skill u will get a hit on the client and a miss on the server with your method.

How? Everyone, including the player is delay by a certain amount. The player doesn't do anything until it has confirmation from the server. The entire game is just a delayed reflection of whats happening on the server. I think you're confused about something.

Wait what? The clients have to wait till the server responds and validates their actions/movement? Interpolation is used when u need very frequent movement. Frequent movement is not possible if the server has to validate everything. Normally the clients send a consistent stream to the server with their actions/movement and the server does not have to validate it, he just accepts the messages and counter checks, only if something invalid happen, he corrects the client.

Interpolation is used to smooth out low frequency updates from the server. To do this, the client must see the world a little bit back in time. What you're describing is prediction since the client is "predicting" where it will end up on the server before it has actually moved.

Let us continue this discussion in chat.


text:
Attach to a GameObject after collision?
How can I make a GameObject attach (or "stick") to another GameObject after collision? The problem: I want the GameObject to attach after collision even if it changes scale.
What I have tried:
protected Transform stuckTo = null;
protected Vector3 offset = Vector3.zero;

public void LateUpdate()
{
    if (stuckTo != null)
        transform.position = stuckTo.position - offset;
}

void OnCollisionEnter(Collision col)
{
    rb = GetComponent<Rigidbody>();
    rb.isKinematic = true;

    if(stuckTo == null
       || stuckTo != col.gameObject.transform)
        offset = col.gameObject.transform.position - transform.position;

    stuckTo = col.gameObject.transform;
}

This code makes a GameObject attach perfectly after collision. But when that GameObject changes scale (while it's attached), it visually no longer looks attached to whatever it collided with. Basically, this code makes the GameObject stick with only the original scale at the moment of the collision. How can I make the GameObject always stick to whatever it collided with? And with whatever scale it has during the process?

This question is not a duplicate.  The OP's code behaves the way the code in the answer of the supposed duplicate does.  This question asks how to achieve the same effect but continue to stick when the object is scaled.

It's much simpler than you think:
void OnCollisionEnter(Collision col)
{
    transform.parent = col.gameObject.transform;
}

You don't need the late update.


text:
How Apple Metal API distinguishes uniforms from vertices buffers?
I am not sure how metal distinguishes uniforms from vertices buffers?
As far as I know code for passing uniforms in buffers are the same like for vertices:
[self.commandEncoder setVertexBuffer:positionBuffer offset:0 atIndex:0];
[self.commandEncoder setVertexBuffer:uniformBuffer offset:0 atIndex:1];

In shader code there is no keyword defining some struct as uniforms, so how Metal know it? In Opengl GLSL was uniform keyword which was clear for me but I can't figure how it is solved in metal.

They are defined in vertex shader signature, eg.
vertex ColorInOut unlit_vertex(device vertex_t* vertex_array [[ buffer(0) ]],
                            constant uniforms_t& uniforms [[ buffer(1) ]],
                            unsigned int vid [[ vertex_id ]])

Earlier I define them like this:
typedef struct
{
    matrix_float4x4 _ModelViewProjectionMatrix;
    float4 tintColor;
    matrix_float4x4 _ShadowProjectionMatrix;
} uniforms_t;

typedef struct
{
    packed_float3 position;
    packed_float2 texcoord;
    packed_float3 normal;
    packed_float4 tangent;
    packed_float4 color;
} vertex_t;

Thank you for answer I missed that keyword uniform in shader signature.

But there is no keyword 'uniform' in the shader signature. uniforms_t is a user defined type - can be anything.


text:
Is there a way to get what pixel is being processed within the fragment shader?
In OpenGL, a fragment shader goes through each pixel, right? So is it possible (within the shader itself) to get what pixel it is processing and color each specific pixel?

There is, in the fragment shader, a variable called gl_FragCoord. This contains the coordinates of the currently executing fragment shader.
Note that (by default) a pixel at pixel coordinates (x,y) will have gl_FragCoordinates of (x+0.5,y+0.5)

Not too sure what you mean, but you can get the current pixel coordinate in the fragment shader by using gl_FragCoord! This is considerably easier than interpolation, as mentioned in the other answer.
Here are more details: https://www.opengl.org/sdk/docs/man/html/gl_FragCoord.xhtml

interpolation is done automatically for shader so it is basically just about reading the varying set by vertex attribute. But of course my idea of using uv coordinates was based on misunderstood question where I tough we were talking about multiple objects that don't fill whole screen.

I thought you meant something like drawing a full screen quad and interpolating that :) Can be useful, but not for many setups!

you can attach u and v coordinates for each vertex and then fragment shader interpolates those u and v coordinates for each pixel. UV coordinates are used to calculate where to sample from textures but they can be also used directly for math.


text:
Is there a way to determine Android physical screen size?
We're currently porting our games to Android, and would like to be able to release a universal build for tablets and phones. Is there a way to determine the actual screen size or DPI in order to adjust the size of interface elements accordingly? It took a fair bit of research.
Here's what we have tried:
using UnityEngine;

public class DisplayMetricsAndroid {

 // The logical density of the display
 public static float Density { get; protected set; }

 // The screen density expressed as dots-per-inch
 public static int DensityDPI { get; protected set; }

 // The absolute height of the display in pixels
 public static int HeightPixels { get; protected set; }

 // The absolute width of the display in pixels
 public static int WidthPixels { get; protected set; }

 // A scaling factor for fonts displayed on the display
 public static float ScaledDensity { get; protected set; }

 // The exact physical pixels per inch of the screen in the X dimension
 public static float XDPI { get; protected set; }

 // The exact physical pixels per inch of the screen in the Y dimension
 public static float YDPI { get; protected set; }

 static DisplayMetricsAndroid() {
     // Early out if we're not on an Android device
     if (Application.platform != RuntimePlatform.Android) {
         return;
     }

     // The following is equivalent to this Java code:
     //
     // metricsInstance = new DisplayMetrics();
     // UnityPlayer.currentActivity.getWindowManager().getDefaultDisplay().getMetrics(metricsInstance);
     //
     // ... which is pretty much equivalent to the code on this page:
     // http://developer.android.com/reference/android/util/DisplayMetrics.html

     using (
         AndroidJavaClass unityPlayerClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer"),
         metricsClass = new AndroidJavaClass("android.util.DisplayMetrics")
     ) {
         using (
             AndroidJavaObject metricsInstance = new AndroidJavaObject("android.util.DisplayMetrics"),
             activityInstance = unityPlayerClass.GetStatic<AndroidJavaObject>("currentActivity"),
             windowManagerInstance = activityInstance.Call<AndroidJavaObject>("getWindowManager"),
             displayInstance = windowManagerInstance.Call<AndroidJavaObject>("getDefaultDisplay")
         ) {
             displayInstance.Call("getMetrics", metricsInstance);
             Density = metricsInstance.Get<float>("density");
             DensityDPI = metricsInstance.Get<int>("densityDpi");
             HeightPixels = metricsInstance.Get<int>("heightPixels");
             WidthPixels = metricsInstance.Get<int>("widthPixels");
             ScaledDensity = metricsInstance.Get<float>("scaledDensity");
             XDPI = metricsInstance.Get<float>("xdpi");
             YDPI = metricsInstance.Get<float>("ydpi");
         }
      }
   }
}

Canvases do this automatically. Take a look at Canvas Scaler component.

Possible duplicate of Resolution problems when porting a Unity game to Android

What is it about DisplayMetrics that isn't working for you?

widthInInches = Screen.width / Screen.dpi

This question comes from here, and has more solution suggestions there.

I'm giving you how I did this in java before I switched to Unity. Perhaps you can use it in c# with small modifications:
So lately I did it this way:
screenWidth = getResources().getDisplayMetrics().widthPixels;
screenHeight = getResources().getDisplayMetrics().heightPixels;

But I used to do it this way too (probably deprecated):
Display display = getWindowManager().getDefaultDisplay();
        if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB_MR2){
            android.graphics.Point screenSize = new android.graphics.Point();
            display.getSize(screenSize);
            screenWidth = screenSize.x;
            screenHeight = screenSize.y;
        }else{
            screenWidth = display.getWidth();
            screenHeight = display.getHeight();
        }


text:
Scrolling Background - smoothest way
I am trying to find the best solution for drawing a scrolling background in my app in Java. For now, I have two images and I move them by 1x and put it's thread to sleep for hmm, 5ms.
The problem is here that the background is too fast. What should I do?
Probably put the thread to a longer sleep. But when I do this, the background 'freezes' - jumps for 15 pixels each step and it doesn't look smooth.
The main question is:
How to handle a thing like this? Should it be done by sleeping it's thread, or maybe I should make positions floats, increment them by 0.1 and move only when they are integers? << this is my idea, I don't have an idea if it would work.
We have floats: width = 1000.0 height = 1000.0;
When increment width by 0.1 in each 'update iteration' in a gameloop.
If it's a int (1001, 1002, 1003), we move the background. What do you thing? What would be the best way?

Have you tried using delta time yet?

Hmm, I heard about it, but unfortunatelly no :(

I'd recommend looking at this article then; it talks about different game loops and how you implement them.


text:
How can I run homebrew program discs on unmodified Wii consoles?
I know that one can play backup games on any Wii console via burned discs, but is there a way to actually run homebrew programs on a Wii?
I am asking this because I have run across GameCube Linux more than once, but most homebrew programs require using the Homebrew Channel, which must be installed on the internet through the Wii console, or via SD card. For Wii consoles that do not have this capability (specifically the Wii Mini), is it possible to run homebrew software discs that will work on Wii consoles without having to modify them? If so, can anyone show me which ones?


text:
Strange artifacting with textures (Pseudo 3D)
I'm using SFML to make a pseudo 3d engine (Technically not software rendered since SFML uses OpenGL) and things are going rather swimmingly, but then I tried to make another wall, the picture says everything:

The artifact gets worse the closer you get to the wall on the left.
And the Code...
#include "Quad3B.h"

Quad3B::Quad3B() {
    pos = sf::Vector3f(0, 0, 1);
    size = sf::Vector3f(1, 1, 0);
    shape = sf::VertexArray(sf::Quads, 4);
    c = sf::Color::Red;
    color = true;
}

Quad3B::Quad3B(sf::Vector3f p) {
    pos = p;
    size = sf::Vector3f(1, 1, 0);
    shape = sf::VertexArray(sf::Quads, 4);
    c = sf::Color::Red;
    color = true;
}

Quad3B::Quad3B(sf::Vector3f p, sf::Vector3f s) {
    pos = p;
    size = s;
    shape = sf::VertexArray(sf::Quads, 4);
    c = sf::Color::Red;
    color = true;
}

Quad3B::Quad3B(sf::Vector3f p, sf::Vector3f s, sf::Color c) {
    pos = p;
    size = s;
    shape = sf::VertexArray(sf::Quads, 4);
    Quad3B::c = c;
    color = true;
}

void Quad3B::loadTexture(string path, sf::Vector2f ts) {
    color = false;
    tex.setRepeated(true);
    tex.loadFromFile(path);
    texp = sf::Vector2f(ts.x * tex.getSize().x, ts.y * tex.getSize().y);
}

void Quad3B::dr(sf::Vector3f camPos, sf::RenderWindow &window, float hw, float hh, float rat) {
    bool draw = true;

    shape[0].position = sf::Vector2f((((pos.x + camPos.x) * rat) / (pos.z + camPos.z)) * hw + hw, (-(pos.y + camPos.y) / (pos.z + camPos.z)) * hh + hh);
    shape[1].position = sf::Vector2f((((pos.x + camPos.x) * rat) / (pos.z + camPos.z)) * hw + hw, (-(pos.y + size.y + camPos.y) / (pos.z + camPos.z)) * hh + hh);
    shape[2].position = sf::Vector2f((((pos.x + size.x + camPos.x) * rat) / (pos.z + size.z + camPos.z)) * hw + hw, (-(pos.y + size.y + camPos.y) / (pos.z + size.z + camPos.z)) * hh + hh);
    shape[3].position = sf::Vector2f((((pos.x + size.x + camPos.x) * rat) / (pos.z + size.z + camPos.z)) * hw + hw, (-(pos.y + camPos.y) / (pos.z + size.z + camPos.z)) * hh + hh);

    if (color) {
        shape[0].color = c;
        shape[1].color = c;
        shape[2].color = c;
        shape[3].color = c;
    }
    else {
        shape[0].texCoords = sf::Vector2f(0, texp.y);
        shape[1].texCoords = sf::Vector2f(0, 0);
        shape[2].texCoords = sf::Vector2f(texp.x, 0);
        shape[3].texCoords = sf::Vector2f(texp.x, texp.y);
    }

    if (pos.z + camPos.z < 0) { draw = false; }
    if (draw) { if (color) { window.draw(shape); } else { window.draw(shape, &tex); } }
}

Quad3B::~Quad3B() { }

There's nothing strange going on. You're drawing triangles. Those triangles have 3 texture coordinates it interpolates between nicely. Since I'm not familiar with SFML, I won't be able to solve this for you.

I accidently said "The wall on the right" if you were confused by that

The picture doesn't say anything. Is the perspective the way you want it to be and just the texture coordinates are wrong or is the perspective wrong?

The perspective is fine, when i add size to the z axis the texture goes odd

Truly classic artifact!

It seems you are projecting your 3D-coordinates into 2D-Space by yourself.
So the 3D information is lost for any HW-acceleration.
You need to supply 3D- information to your Positional Coordinates I think you can use sf::Vector3f and just use your z-coordinate as 3rd entry.
PS:
Funny detail: you just implemented affine texture mapping which was the best thing people could do 20 years ago :)

See this answer for more on affine versus perspective interpolation.


text:
How do I make players believe they're doing something wrong even when they're not?
You're doing it right. …right?
In the game Cart Life, you are led to consider this, even though you are doing fine. This effect is created by making you do mundane jobs, earn little money, and have and things happen that feel like your fault.
Is there a better way than life-like mundane and unfortunate encounters to make you feel like you're failing at the game? I want to use this to mess with how my players play the game. Overwhelm them. Make a little success feel huge. Make them feel depth. Any ideas?

When you give a player who are playing right the message that they are doing it wrong, what message would you give to those players who actually play wrong?

The ones that play right feel wrong and do right. The ones that play wrong  die.

When you don't get the answer you expect to receive then the reason could be that your question is too vague and unspecific. When you want concrete suggestions what you could do, you should at least mention the genre of the game you are developing. Also, what do you mean with "feel depth"? What kind of "depth"? Story and backstory depth? Character depth? Gameplay depth?

@Philipp That's great feedback, wish I was thinking that deep 6 years ago as a 15-yo minecraft adventure map builder XD

The usual expectation of a player is that while they progress in the game that everything turns better. Their character becomes more powerful, they gain new tools and abilities, the game world around them grows and flourishes thank to their actions and they gain the trust and friendship of NPCs they interact with.
Turn that around:

Take away tools and abilities from the player-character to make it permanently less powerful.
Have the game world change for the worse, caused directly or indirectly due to the player-characters actions.
NPCs who reacted positive to them start to loathe the player-character for their actions.

The tricky part is to make all of them feel as if it was the direct consequence of the choices or mistakes the player made while it actually was all prescripted and there wasn't a way to avoid it. Some techniques you can use:

The hopeless boss fight: Have a fight which looks possible at first but actually can not be won. When the player loses, punish them but progress with the story.
Unwinable dexterity test. Example: Have the player jump over a chasm, and when they land on the other side it breaks off, they fall down and end up at the bottom of the chasm with barely any health left. Foolish player, should have seen the other side was crumbly. But it actually was impossible to jump far enough. You expect the player to continue from the bottom of the cliff. Other situation where you can cheat that way are QTEs which don't actually react to the players input or any game mechanics which are usually based on random numbers but in the story-critical situation a critical failure is pre-programmed.
A choice where all options are wrong: Have the player decide between two options, but then have friendly NPCs tell them the choice was bad and they should have taken the other choice no matter which was chosen. This was, for example, used in Mass Effect 2. At one point the player is asked if they want to exterminate the last survivors of a dangerous alien species or let them live. If the player choses to let them live, their superiors tell them "How could you!?! They are dangerous and will kill us all!". If the player kills them they say "How could you!?! That's genocide!". During the first playthrough the player won't know that both choices would lead to a negative reaction, so they felt like they made a bad mistake no matter which one they picked.

Teach the player what success is first
In a traditional game, like a platformer, you would first need to teach the player the difference between doing it right, and doing it wrong. You teach the player that jumping over gaps is good and touching spikes is bad -force them to jump over a spike-pit.
Now that the player knows what they should be doing, you can start to bully them. Give them a gap that is slightly too large to jump across, but still looks doable. Failing the jump causes you land on a button which closes-off a door with a big prize behind it.
Congratulations! You've just made the player fail, and it's all their fault.

What about if I want them to believe that they're failing when they really aren't at all?

Like most things, the easiest way to create other ways to achieve an effect is to examine and find what aspect of the original example causes that effect. In this case, the player feels as if they are failing because they are primed to have the expectation that bad things in video games are their fault. This is because most games reward good performance with good results. Unfortunately, and as you guessed, this is a rather short-term (or cheap) method of evoking the feeling of failure because it relies on our cultural expectations of games, which could change at any moment.
Instead, you can use the most basic function of the brain to help you: Association. Whenever two event occur simultaneously or even just temporally close together, a brain immediately attempts to find which caused the other, unless prior knowledge says something else did. Here is an example...
In Generic game 2015, the main protagonist Bob shoots his generic spaceship at generic aliens. If the player gets over 20,000 points in a level (a somewhat difficult feat), then the attack is successfully repelled. On the other hand, if Bob acquires less than 15,000 points, the aliens will destroy a building located in the background. If the player does poorly, they know by the loss of a building. This is a successful priming.
What this means is that in player's mind, any time a building falls, the player is not doing well enough. You now have a tool to toy with their mind because, any time the event of a building falling is triggered, the player and their association will trigger the feeling of failure whether or not it is justified. (stifled evil laugh) Its probably useless at this point to say you can make building start destroying themselves and still achieve the same illusion of failure.
But there are two last things to take note of.
1
The first is about player knowledge. If you want the player to feel like they failed without them actually failing, the mechanics have to include that. When the mechanics include the fake fail, it gets put on a wiki. Finally, the player reads the wiki, and no longer feel any failure at all. But their is a partial solution to this.
While security through obscurity is completely hopeless, you can utilize randomness so that even if the player knows all your algorithms to a T, the game can generate a situation that the player is still unsure whether or not the failure queue is their fault or not. Maybe the game has chosen to drop buildings even when you gain enough points, or maybe it actually is that your failing.
2
The exact example I have given is a somewhat weak one. Ideally, the failure trigger should be woven into the narrative for greater effect (because that is where the characters and other objects are that carry emotional attachments). Eg: If each building being destroyed contains an important member of the story-line.

This is similar to real life: use peer pressure on your character.
In order to tell them they are failing, I would make the action (that it NOT a failure) sound bad:
1. NPCs calling this action dirty, etc.
2. having the character be PUNISHED for doing this. For example, if you buy a X, you get banned from doing Y for Z days. [I would recommend a reward if they are stubborn enough to continue this by the 5th-10th time]. You could also lose friends, achievement points, etc.
You could also teach the user to do one way half of his life then make a change (for example new teacher) that does this another way. Suddenly, the player has to decide whether or not to listen to the first or second way.
If you feel like it, you could implement a way to fool users that they are doing wrong by making them experience a messagebox or warning of some sort. For example, if you were playing COD and the people on your team [bots] tell you to stop shooting player X as he is on your team (when in reality not true). If this was GTA, then you could implement a feature where every time you went over 30 mph a tank spawns behind you (not sure if that would be that persuasive, however). In other words, just put pressure on the player in order to tilt him to the direction you are aiming at.

An extremely helpful answer, for which I have given a +1, and well thought out, however not exactly the kind I was looking for. What I want specifically is for a player to be brought into the depths of despair while they're playing everything perfectly. But if I could give +5s I would.


text:
numeric identifiers associative array
edit: clarified my question. I also realized that I didn't pick a very conclusive question title, which unfortunately I cannot change anymore, sorry.
Hey everyone,
to improve my programming skills a little and getting familiar with good design patterns, I'm trying to program a litte turn based strategy game, and I am at the point to choose a good data structure for the configuration of different terraintypes and unittypes etc. which do exist.
What I have implemented so far is a big "Game Object" with knowledge about everything in the game, and many of its properties are big associative arrays (I'm using PHP, but my question doesn't really have to do much with the language), for example an arrays of units, a map array.... What my array structure is comparable to is the type object pattern mentioned here.
Example: A single unit is of a certain type, say 'Infantry', and shares many data with all the other infantry untis on the field. Instead of copying all these values, I give every unit a "type" so it can look up the details there. Similar with terraintypes. Example:
terraintypes = array()
terraintypes[0] = array()
terraintypes[0]['name'] = 'Forest'
terraintypes[0]['capturable'] = false

unittypes = array()
unittypes[0] = array()
unittypes[0]['name'] = 'Infantry'
unittypes[0]['movecost'] = array()
unittypes[0]['movecost'][0] = 5 //Movementpoints needed for forest
unittypes[0]['movecost'][1] = 7 //Movementpoints needed for terraintype 1

A specific unit or tile on the map wouldn't know its movement costs or name, but would be able to look that up in the unittypes array. Example:
sometile = array();
sometile['owner'] = whatever
sometile['type'] = 0; //this tile is a forest

someunit = array()
someunit['type'] = 0 //This is an "Infantry".

The problem is that getting any kind of information will produce very verbose code, for example finding out how much it costs for a unit to move onto a tile will be
unittypes[unit['type']]['movecost'][tile['type']]

I am trying right now to move to using more objects and classes, so if I give a unit a reference to its unittype, it can lookup information itself, for example
terraintypes[0] = new Terraintype('Forest')
unittypes[0] = new Unittype('Infantry')
someunit = new Unit(unittypes[0])

Now, if I ask a unit something only its unittype would now, the unit can look it up itself, e.g. someunit.getName() will be implemented in the unit like this.unittype.getName().
So far so good. However, how could a unittype store its movecost on the different terrains? Basically I would need an array indexed with terraintypes, but as that is not possible, I will have to swhich back to translate everything to numeric keys, and have a movecost value for every pair (terraintype, unittype).
Who assigns these numeric keys and where? Will every single unittype need to store some kind of identifier which is unique among all the unittypes?
Should I use some constants like const FOREST = 0; const ROAD = 1; const INFANTRY = 0; const VEHICLES = 1 etc?
Another of my problems for finding a good data structure is that if I don't give the game all the data directly, but break everything down to smaller parts, then many parts will need to know about the same objects.
For example, if the Map object knows about all tiles of the map and the units on it, then the game doesn't really know anything about the units, it only knows about the map, and every command in the game which affects a unit needs to be passed to the map, even though its not actually a "map task", like healing units.
This seems like breaking the single responsibility pattern. However, storing references to all the units in several places (so both the Map and something else store references to units) seems to be troublesome with bookkeeping.
To sum it up a little, can you hint me to data structure which are suitable to represent what I am describing? Thanks in advance!

Which programming language and/or engine are you using?

I'm not using any engine right now. Language is PHP (and later I will have to do some implementation in JavaScript as well for the client side)

I do not think that level of verbosity is a bad thing. As long as your code is well documented and you choose clear variable names, accessing data structures like that is quite readable.

First your organization of data is pretty good. Using arrays or objects does not really matter much although an object is cleaner, as it provides a clean interface and avoids simple problems like unset properties. I don't think that verbosity of yours a bad thing. unittypes[unit['type']]['movecost'][tile['type']] can easily be encapsulated, so you need it only once. And for that it's ok.
@Draco18s answer only changes where you store the data. In your case you store the instances in global arrays. Storing them in the class itself as static data might be cleaner. Storing them in an array might actually be the better option, as this allows iterating and hence searching them. So you could do TerrainType::GetTerrain("Forest") or the like. You could also store integer references by doing something like:
public class TerrainType {
    public static FOREST = AddTerrain("Forest",false,0.25f);
    public static PLAINS = AddTerrain("Plains",true,0.75f);
    public static ROAD = AddTerrain("Road",false,1.5f);

    public static terrains = array();
    private AddTerrain(params...){
        idx = len(terrains);
        terrains[idx] = TerrainType(params...);
        return idx;
    }
}

Or store the ID in the TerrainType itself.
As for the mapping from Units to Movement speeds I'd note that this is a mapping: f(Unit, Terrain): speed. You could store this in either the Terrain or the unit or in both. Easiest way would be: Store a unit "base" speed and a terrain "multiplier". Then when unit x is on terrain y you multiply them to get the actual speed (at that point you do have access to both the UnitType and the TerrainType or something is wrong ;-) )
Otherwise you would need to maintain a table and I'd make it a table: Speed[UnitType][TerrainType] however maintaining/creating this might be quite cumbersome due to the NxM relationship here which easily explodes as you add more units/terrains. Note that you have integer keys which you can use as indices into that table if you use the above code. Of course the mapping needs to be done with the constants assigned during TerrainType/UnitType initalization. If you have arrays, you could have a GetIdx method that scans the array and returns the index. As this would also need to be done when accessing a speed, you want to encapsulate this into GetSpeed(UnitType, TerrainType)
Last about passing messages from Game->World->Unit: Nothing bad about this either. Just make it layered. E.g. Game.MoveUnit(unitId, X, Y) -> World.MoveUnit(unitId, X, Y) -> Unit.Move(X, Y)
Or more abstract messages. Each message has an ID and data. Like UnitMessage("Move", X, Y). The game passes all messages it does not understand to the world, which would then pass it to the unit.

I'm still not completely certain how I will handle it, but I will let your answer sink and reflect the problem a little more. Thanks.

I would create a custom data type (a "class") for your terrains.  You'd end up with something like this:
public class TerrainType {
    public static FOREST = new TerrainType("Forest",false,0.25f);
    public static PLAINS = new TerrainType("Plains",true,0.75f);
    public static ROAD = new TerrainType("Road",false,1.5f);

    //I am not sure how PHP handles readonly fields
    public final string name;
    public final bool capturable;
    public final float move_cost;

    private TerrainType(string name, bool capture, float move_speed) {
        this.name = name;
        this.capturable = capture;
        this.move_cost = move_speed;
    }
}

This gives you a singleton-like structure that holds your terrain types and their associated properties without making your code stringly typed.
Then your map object can consist of a 2D array where each position holds a reference to its terrain type.  e.g. mapArr[x][y] = TerrainType.FOREST; although your map might be another class as well, holding the terrain type, who owns the tile, and the units there.

Thanks for your answer. Yes, I can link to a terraintype within my Map array, but that's also possible without the Singleton-like structure. For example I could write mapArr[x][y] = new Tile(forest)
My problem is that a single Terraintype does not just have one move_speed value, but the movespeed on that terrain is different for each unittype, e.g. movecost[INFANTRY] = 5 and movecost[VEHICLES] = 8 to care about the fact that using vehicles may be slower in a forest than walking.
I will probably need to clarify my question a bit.

You can apply any properties that you need, the movement speed was simply an example. The point was that you don't need two separate Forest objects if they're both going to be identical with the same values (the float value I'd used was as a multiplier, eg. infantry that normally move 4 would move 3 on terrain with most_cost 0.75f).


text:
(GLSL) Lighting code outputting a black quad
So, ive been transitioning to modern opengl recently and it's going rather well. But alas, something must go wrong. As the titel says, all I'm getting is a completely black quad. (Ive double checked my C++ code and I'm pretty sure it has nothing to do  with that.)
#version 330 core

//Vertex shader

layout(location = 0) in vec3 vertexPosition_modelspace;
layout(location = 1) in vec3 vertexColor;
layout(location = 2) in vec2 vertexUV;
layout(location = 3) in vec3 vertexNormal;

out vec3 vertNorm;
out vec3 fragmentColor;
out vec3 vertPos;
out vec2 UV;

uniform mat4 MVP;

void main(){
    gl_Position =  MVP * vec4(vertexPosition_modelspace,1.0f);
    UV = vertexUV;
    fragmentColor = vertexColor;
    vertPos = vertexPosition_modelspace;
    vertNorm = vertexNormal;
}

//Fragment shader
#version 330 core

in vec3 Normal;
in vec3 fragmentColor;
in vec3 vertPos;
in vec2 UV;

out vec3 color;

uniform sampler2D textureSampler;
uniform mat4 Model;

void main(){
    vec3 lightPos = vec3(0, 0, 0);
    mat3 normalMatrix = transpose(inverse(mat3(Model)));
    vec3 normal = normalize(normalMatrix * Normal);
    vec3 fragPosition = vec3(Model * vec4(vertPos, 1));
    vec3 surfaceToLight = lightPos - fragPosition;

    float brightness = dot(normal, surfaceToLight) / (length(surfaceToLight) * length(normal));
    brightness = clamp(brightness, 0, 1);

    color = vec3(brightness * 1 * (texture(textureSampler, UV).rgb * fragmentColor));
}

But if you require my c++ code, say so and ill edit.

Note that out vec3 vertNorm; in your vertex shader does not match your corresponding input variable in the fragment shader in vec3 Normal;.
Since Normal in your fragment shader doesn't have any input it defaults to vec3(0, 0, 0). So your end up with a lot of unspecified behavior since you are normalizing a zero-vector which in this case probably returns another zero-vector. I don't know if there is an OpenGL standard there, at least it did for me. Then when calculating brightness you divide by zero again. Your math teacher would be furious at your dividing by zero twice in just a little bit of your code.
The end result is that brightness is 0 which is multiplied with the colors making all of the output colors vec3(0, 0, 0) or black.


text:
Transforming normals along with vertex? (GLSL)
So, I got a model matrix (Via uniform variable) in the shader, is there any way to use the model matrix to transform the normal of a vertex that has been transformed with glm::transform/rotate?
If you want, here is the code:
VERTEX SHADER:
#version 330 core

layout(location = 0) in vec3 vertexPosition_modelspace;
layout(location = 1) in vec3 vertexColor;
layout(location = 2) in vec2 vertexUV;
layout(location = 3) in vec3 vertexNormal;

out vec3 Normal;
out vec3 fragmentColor;
out vec3 vertPos;
out vec2 UV;

uniform mat4 MVP;

void main(){
    gl_Position =  MVP * vec4(vertexPosition_modelspace,1.0f);
    UV = vertexUV;
    fragmentColor = vertexColor;
    vertPos = vertexPosition_modelspace;
    Normal = vertexNormal;
}

FRAGMENT SHADER:
#version 330 core

in vec3 Normal;
in vec3 fragmentColor;
in vec3 vertPos;
in vec2 UV;

out vec3 color;

uniform sampler2D textureSampler;
uniform mat4 Model;

void main(){
    vec3 lightPos = vec3(1, 1, 1);
    mat3 normalMatrix = transpose(inverse(mat3(Model))); // I think this line could do it, but it doesn't seem to work.
    vec3 normal = normalize(normalMatrix * Normal);
    vec3 fragPosition = vec3(Model * vec4(vertPos, 1));
    vec3 surfaceToLight = lightPos - fragPosition;

    float brightness = dot(normal, surfaceToLight) / (length(surfaceToLight) * length(normal));
    brightness = clamp(brightness, 0.2, 1);

    color = vec3(brightness * 1 * (texture(textureSampler, UV).rgb * fragmentColor));

}

You say it doesn't seem to work, how doesn't it work? Also * length(normal) when calculating brightness is pretty redundant since the normal is always normalized meaning its length is 1.

Ive managed to fix the normals by using the mvp, but now if I translate(not rotate) the quad, the light seems to follow it. Ive given the light its own model matrix, but it has the same issue.

Managed to fix it:
VERTEX SHADER:
#version 330 core

layout(location = 0) in vec3 vertexPosition_modelspace;
layout(location = 1) in vec3 vertexColor;
layout(location = 2) in vec2 vertexUV;
layout(location = 3) in vec3 vertexNormal;

out vec3 Normal;
out vec3 fragmentColor;
out vec4 vertPos;
out vec2 UV;
out mat4 mvp;

uniform mat4 MVP;

void main(){
    gl_Position =  MVP * vec4(vertexPosition_modelspace,1.0f);
    UV = vertexUV;
    fragmentColor = vertexColor;
    vertPos = MVP * vec4(vertexPosition_modelspace,1.0f);
    Normal = vertexNormal;
    mvp = MVP;
}

FRAGMENT SHADER:
#version 330 core

in vec3 Normal;
in vec3 fragmentColor;
in vec4 vertPos;
in vec2 UV;
in mat4 mvp;

out vec3 color;

uniform sampler2D textureSampler;
uniform mat4 Model;
uniform mat4 lmvp;

void main(){
    vec4 lightPos = lmvp * vec4(-0.5, 0.5, -0.5, 1);
    mat3 normalMatrix = transpose(inverse(mat3(Model)));
    vec3 normal = normalize(normalMatrix * Normal);
    vec3 fragPosition = vec3(Model * vec4(vertPos.xyz, 1));
    vec3 surfaceToLight = lightPos.xyz - fragPosition;

    float brightness = dot(normal, surfaceToLight) / (length(surfaceToLight) * length(normal));
    brightness = clamp(brightness, 0.2, 1);

    color = vec3(brightness * 1 * (texture(textureSampler, UV).rgb * fragmentColor));
}

Well it seems you have solved your own problem. Honestly I don't think the normals ever really was your problem. Also try giving some time to figuring it out yourself before asking questions. Problem solving skills is one of the most important skills to learn.

And a tips transpose(inverse(mat3(Model))); is maybe redundant and a bit expensive. The inverse and the transpose cancel out if the model matrix consist only of translation, rotation and uniform scaling, leaving only mat3(Model). Second, inverse can be a costly operation and you are doing it for every pixel. I recommend moving it to the vertex shader and passing the normal to the fragment shader after transformation with the model matrix.

Thanks for the tip, but I probably don't have to worry about that right now. (Since I'm at 3000 fps :D)

I agree, you should rather worry about these small optimizations later. Especially if it gets in the way of your programming. Also even though 3000 fps sounds pretty cool, don't become this guy. http://gamedev.stackexchange.com/q/112166/75055 , use milliseconds ;)

This code dump "answer" doesn't say what the problem was without very careful source reading and trying to guess what it is. Please try to condense the things you believe were the problem into text instead, so it reads like a real answer.

I suggest do worry about it right now.  This isn't "optimization", this is "engineering for performance" and there is a difference.


text:
Vector out of range (Batch rendering & opengl)
So ive (tried to) implement a batch rendering system, and at the for loop the error pops up and I'm not shure what ive done wrong. Any suggestions to improve the system would be much appreciated. (It's my first time trying to implement this)
#include "masterRenderer.h"

masterRenderer::masterRenderer() {
    quad = vector<Quad>(1000);
    numOf = 0;
}

void masterRenderer::addQuad(Quad quad) {
    masterRenderer::quad[numOf] = quad;
    numOf++;
}

void masterRenderer::init(GLuint shader, string texPath) {
    vector<GLfloat> vertex((3 * 4) * (numOf + 1));
    vector<GLfloat> normals((3 * 4) * (numOf + 1));
    vector<GLfloat> color((3 * 4) * (numOf + 1));
    vector<GLfloat> uv((2 * 4) * (numOf + 1));

    int nv = 0, nn = 0, nc = 0, nu = 0;

    GLfloat sizeV = 0, sizeN = 0, sizeC = 0, sizeUv = 0;

    for (int i = 0; i < numOf; i++) {      // The error seems to pop up over here.
        for (int j = 0; j < 3 * 4; j++) {
            vertex[nv] = quad[i].g_vertex_buffer_data[j];
            sizeV += quad[i].g_vertex_buffer_data[j];
            nv++;
            normals[nn] = quad[i].g_normal_buffer_bata[j];
            sizeN += quad[i].g_normal_buffer_bata[j];
            nn++;
            color[nc] = quad[i].g_color_buffer_data[j];
            sizeC += quad[i].g_color_buffer_data[j];
            nc++;
        }

        for (int j = 0; j < 2 * 4; j++) {
            uv[nc] = quad[i].g_uv_buffer_data[j];
            sizeUv += quad[i].g_uv_buffer_data[j];
            nc++;
        }
    }

    TextureID = glGetUniformLocation(shader, "textureSampler");
    texture_handle = Util::loadTexture("test.png");

    glGenBuffers(1, &normalbuffer);
    glBindBuffer(GL_ARRAY_BUFFER, normalbuffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(sizeN), &normals[0], GL_STATIC_DRAW);

    glGenBuffers(1, &colorbuffer);
    glBindBuffer(GL_ARRAY_BUFFER, colorbuffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(sizeC), &color[0], GL_STATIC_DRAW);

    glGenBuffers(1, &uvbuffer);
    glBindBuffer(GL_ARRAY_BUFFER, uvbuffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(sizeUv), &uv[0], GL_STATIC_DRAW);

    glGenBuffers(1, &vertexbuffer);
    glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(sizeV), &vertex[0], GL_STATIC_DRAW);
}

void masterRenderer::draw(glm::mat4 Model, glm::mat4 View, glm::mat4 Projection, GLuint MatrixID) {
    glPushMatrix();
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, texture_handle);
    glUniform1i(TextureID, 0);
    glEnableVertexAttribArray(0);
    glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);
    glEnableVertexAttribArray(1);
    glBindBuffer(GL_ARRAY_BUFFER, colorbuffer);
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);
    glEnableVertexAttribArray(2);
    glBindBuffer(GL_ARRAY_BUFFER, uvbuffer);
    glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 0, (void*)0);
    glEnableVertexAttribArray(3);
    glBindBuffer(GL_ARRAY_BUFFER, normalbuffer);
    glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);
    for (int i = 0; i < numOf + 1; i++) {
        Model = glm::translate(glm::mat4(1.0f), glm::vec3(quad[i - 1].pos.x, quad[i - 1].pos.y, quad[i - 1].pos.z));
        Model = glm::rotate(Model, glm::radians(quad[i-1].yrot), glm::vec3(0.0f, 1.0f, 0.0f));

        glm::mat4 mvp = Projection * View * Model;
        glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &mvp[0][0]);
        glDrawArrays(GL_QUADS, 4 * i - 1, 4 * i);
    }
    glDisableVertexAttribArray(0);
    glDisableVertexAttribArray(1);
    glDisableVertexAttribArray(2);
    glDisableVertexAttribArray(3);
    glPopMatrix();
}

masterRenderer::~masterRenderer() { }

where and how do you call masterRenderer::AddQuad()? Is it before calling init or after?

Add quad after the quads are initialized then init.

probably not related, but what for do you do sums like sizeV += quad[i].g_vertex_buffer_data[j];? Also, is sizeV ever used?

There is an error in lines copying data to buffers, you give it incorrect size - not taking in account actual size of data. The second parameter should be size of data in bytes, the sizeof(sizeN) will always return 4 (=the size of GLfloat). For example, instead of
glBufferData(GL_ARRAY_BUFFER, sizeof(sizeN), &normals[0], GL_STATIC_DRAW);

you probably meant
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * sizeN, &normals[0], GL_STATIC_DRAW);

the size of one GLfloat times number of GLfloats. Moreover, there is no need to keep incrementing the sizeN(also it should not be floating point type if you count integer number of elements) because you can get the element count directly from vector:
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * normals.size(), &normals[0], GL_STATIC_DRAW);

same applies to all buffers.
For the out of range problem I suggest you use push_back() and reserve() instead, this should avoid any of these problems completely. Summing it up:
void masterRenderer::init(GLuint shader, string texPath) {
vector<GLfloat> vertex;
vector<GLfloat> normals;
vector<GLfloat> color;
vector<GLfloat> uv;

vertex.reserve((3 * 4) * (numOf + 1));
normals.reserve((3 * 4) * (numOf + 1));
color.reserve((3 * 4) * (numOf + 1));
uv.reserve((2 * 4) * (numOf + 1));

for (int i = 0; i < numOf; i++) {
    for (int j = 0; j < 3 * 4; j++) {
        vertex.push_back(quad[i].g_vertex_buffer_data[j]);
        normals.push_back(quad[i].g_normal_buffer_bata[j]);
        color.push_back(quad[i].g_color_buffer_data[j]);
    }

    for (int j = 0; j < 2 * 4; j++)
        uv.push_back(quad[i].g_uv_buffer_data[j]);
}

TextureID = glGetUniformLocation(shader, "textureSampler");
texture_handle = Util::loadTexture("test.png");

glGenBuffers(1, &normalbuffer);
glBindBuffer(GL_ARRAY_BUFFER, normalbuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * normals.size(), &normals[0], GL_STATIC_DRAW);

glGenBuffers(1, &colorbuffer);
glBindBuffer(GL_ARRAY_BUFFER, colorbuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * color.size(), &color[0], GL_STATIC_DRAW);

glGenBuffers(1, &uvbuffer);
glBindBuffer(GL_ARRAY_BUFFER, uvbuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * uv.size(), &uv[0], GL_STATIC_DRAW);

glGenBuffers(1, &vertexbuffer);
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * vertex.size(), &vertex[0], GL_STATIC_DRAW);
}

...I am not sure if this is the only error in you code but hope it helps, be sure to comment/expand your question.


text:
How to justify friendly shopkeeper in the cave of doom among millions of mobs?
I am exploring the forbidden example cave of doom. I find, among squillions of baddies, a shopkeeper, who just happens to sell stuff inside a deadly cave where nobody goes. Weird. I accidentally cause him to be angry, and he turns out to be more powerful than literally every monster in the game. Messed up.
So here's two questions for you: How can you justify a shopkeeper in the example cave of doom just happening to be there waiting for random adventurers to buy stuff,
and,
Is there a better way to discourage stealing stuff or killing the shop-keep' than just making them pummel you with ridiculous power?
Side note: Bonus points for linking these, explain both why and how he would be down there, in the example cave of doom, surviving without a monster sword or magic to pwn things with, and why it would be a bad idea without him possessing those things, to fight him.

This is an idea generation question more suitable for worldbuilding.

Are you talking about Spelunky?

http://worldbuilding.stackexchange.com/

I think a better question is how you justify a "Cave of Doom" to begin with. If you're just going to throw a random cave at the player and say "go beat this", then sticking an equally random traveling merchant isn't going to raise that much more of an eyebrow.

@Anko  It's a trope of Roguelikes

The shopkeeper is actually the final boss, the center of all evil, hidden under a mask of his table and potions. He does this stuff for business - as you know - demand creates supply so he probably spawns the monsters himself so he can sell his stuff to naive travellers searching for an adventure.

I'm on worldbuilding, and their meta says ask here.

@lukasz1985 add that as an answer! 'Tis good!

@CalebWoodman Haha, no - that was supposed to be a satire :P

@congusbongus yeah, in worldbuilding, my favorite site, it would be closed and Monica Ciello or someone would tell me to come here.

The cave is where the player is in the game.  If we want the player to have access to a shopkeeper, we either have to put the shopkeeper right there, or else we have to build somewhere else for the shopkeeper to be, and building that somewhere else will probably be expensive (in terms of new art required, etc).  Additionally, making the player go somewhere else just to find a shopkeeper probably doesn't make the game better;  it just adds a bunch of backtracking, or requires that we create Scrolls of Town Portal or something.  (If you were asking for an in-game-world reason to justify why a shopkeeper is in the cave, I'll point out that we're talking about "caves of doom", and so a realistic world with internally-consistent lore which will stand up to any trivial amount of scrutiny is pretty much off the table to begin with)
If the goal is to stop the player from killing the shopkeeper or stealing shop contents, then make the shopkeeper not be a valid combat target and not allow the player to pick up his shop's contents without paying for them.  This seems a little obvious -- almost tautological, in fact.  But you asked.

Bonus points:  He's down here because (according to point #1) he has to be here in order for the player to meet him, and it's presumably important for the game that the player meet him.  And he's survived down here for the same reason:  because he has to have survived in order for the player to meet him, and it's important for the player to meet him because if it wasn't important, we wouldn't have gone to the bother and expense of creating artwork for him.
Within the game fiction, he's survived because our world's mechanics are so thin that characters don't age, don't exercise, don't play Scrabble, don't sleep, and mostly don't eat (except occasionally in order to instantly repair themselves after being hit by a sword too often, often while the combat is still in progress).  Characters don't require companionship to avoid becoming lonely, they don't require an occasional vacation, and they're happy standing stock-still on a single tile for eternity.  Additionally, characters other than monsters and the player (and sometimes the player's companions) never even die, except in expensively-produced cutscenes with orchestral music.
And there's no space for an orchestra down here in the caves of doom.
Which, when you come to think of it, is actually a pretty good reason for the shopkeeper to want to live down here.

This might work in a tongue-in-cheek parody game, but not elsewhere. In a fictional world, the rule is usually "it's like reality unless noted". This means that in a medieval-ish fantasy world the NPCs should have similar motivations as real life humans had in that time period, unless we can find a good justification or backstory to make it different.

"And there's no space for an orchestra down here in the caves of doom.", how could your answer be more perfect ?

@vsz The original question didn't specify that it wanted realistic motivations. It also didn't specify a medieval-ish fantasy world (not sure where you got that from). It actually didn't specify much of anything, so my answer here was entirely mechanical in nature, apart from the silly quip in the last two sentences, which I just thought was funny and didn't think anyone would take seriously.

Make the shopkeep a monster too
Being a freebooter, he holds no particular allegiance to one side (the cave dwelling monsters) or the other (you, the player).  But for a bit of coin, he'll sell you whatever he's got.  He's been hawking his wares to the other monsters in the cave for years, but you're nothing more than a walking coin pouch to him.  He knows that no matter how many of his 'compatriots' you kill, more will show up eventually and his business will continue.
Or maybe monsters don't respawn in your game, in which case, after the player leaves (the cave devoid of monsters), he despawns too: he closed up shop and went off to find somewhere else to pawn his goods.  Maybe you'll run across him again later somewhere else...

I have seen exactly this in fallout 3, smiling jack is a raider but isn't hostile to the player (even when the player is shooting at all the other raiders) because cash is king... or caps anyway


text:
MonoGame does not generate xnb from png
I am coming straight from XNA and I installed the latest version of MonoGame today (2015-12-22) for Visual Studio 2015 Community. I created a project from the windows Project template.

I right click the content folder and add a png-file. I compile without error but it stops during runtime because it can't find the content file. My solution look like this

Game1.cs look like this:
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

namespace homer
{
    public class Game1 : Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        private Texture2D simpson;

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

        protected override void Initialize()
        {
            base.Initialize();
        }

        protected override void LoadContent()
        {
            spriteBatch = new SpriteBatch(GraphicsDevice);
            simpson = Content.Load<Texture2D>(@"Images/Homer");
        }

        protected override void UnloadContent(){ }

        protected override void Update(GameTime gameTime)
        {
            if (Keyboard.GetState().IsKeyDown(Keys.Escape))
                Exit();
            base.Update(gameTime);
        }

        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);
            spriteBatch.Begin(SpriteSortMode.FrontToBack, BlendState.AlphaBlend);
            spriteBatch.Draw(simpson, new Vector2(200, 100), Color.White);
            spriteBatch.End();
            base.Draw(gameTime);
        }
    }
}

The problem I encounter is that MonoGame do not make xnb-files from the png and put it in my output folder. I tried to copy the file manually from a compiled XNA project to my MonoGame debug folder and it worked. I have done nothing but create a project from the template and trying to load an image. What do I need to do to make MonoGame compile xnb-files for me. It also runs if I change "Do not copy" to "Copy always" but that is not optimal for runtime as I understand it. Also, I don't want it to be too easy for the users to doodle in the graphics.
Content.mgcb look like this
#----------------------------- Global Properties ----------------------------#

/outputDir:bin/Windows
/intermediateDir:obj/Windows
/platform:Windows
/config:
/profile:Reach
/compress:False

#-------------------------------- References --------------------------------#

#---------------------------------- Content ---------------------------------#

Open the Content.mgcb file with the ContentPipeline tool. From there you can add the .png file and the content will be build for you.
The content pipeline tool is located on my machine in:
"C:\Program Files (x86)\MSBuild\MonoGame\v3.0\Tools\Pipeline.exe"

Worked like a charm. Do I need to do this for every single file in a project? It feels a little redundant to having to add every file twice, first in visual studio and then in the pipeline editor.

You can add files in the pipeline tool (even create folders to organise content). So instead of adding them to your project, add them here in stead.

I tried to add things just in the Pipeline editor but that do not work for me. I must add it both in the project and in Pipeline for it to get to the output folder.

That's weird. The pipeline builds the content. The only thing I could think of is that the builder otherwise has no access to the files. When you add something in the pipeline tool that is not in your project folder, it should ask if the pipeline needs to copy the content to the folder. Does that happen in your case?

The Pipeline asks me if it should, and does, copy to the project folder. But it do not show up in the project explorer until I add it in visual studio. It works if I add things in both places.

You don't need to add it also to Visual Studio (unless you keep those files under source control as well). It should work if the files are just copied there.

Then something must be wrong with my installation. Anyway, I actually think it is convenient to have images in the solution explorer so I can double click them for editing.


text:
OpenGL Face Order
i have written a simple OBJ-file loader to render meshes using OpenGL.
But there is a problem displaying the loaded mesh. It seems that faces that from the background (far) are displayed above the front faces.
To illustrate the problem i have rendered a little example picture (Blender monkey).

I am using really simple shaders:
Vertex shader
#version 330

layout (location = 0) in vec3 vert;
layout (location = 1) in vec2 uv;

uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;

out vec2 frag_uv;
out vec3 frag_vert;

void main()
{
    gl_Position  = vec4(vert, 1);
    gl_Position *= model;
    gl_Position *= view;
    gl_Position *= projection;

    frag_vert = vec3(vec4(vert, 1) * model);
    frag_uv = uv;
}

Fragment shader
#version 330

in vec2 frag_uv;
in vec3 frag_vert;

out vec4 color;

void main()
{
    color = vec4(frag_vert.x, frag_vert.y, frag_vert.z, 1.0);
}

The mesh is rendered using a VBO and a VAO.
I have no clue ehat i am doing wrong.
Thank you, and a nice christmas :)

How did you set up your depth buffer?

I did not set up a depth buffer

Is Your near plane set to 0?

I forgot to enable depth testing.
This is solved. Thank you.
`glEnable(GL_DEPTH_TEST)`

was missing.

@Johannes If you have solved your problem please consider answering your own question instead of just commenting.

Solved
Depth testing was not enabled:
glEnable(GL_DEPTH_TEST);

... fixed the Problem.


text:
How would I implement a realistic stock market?
I'm making a corporation simulator, and it contains stocks. In the game you can buy and sell stocks, but I can't implement a realistic change in the price for them. How do I make them change up/down in a realistic way?

Rather unspecific to the programming language or the platform mentioned, but I would probably go for a greater change as a primary depiction of important stock change, and then generate a small fast change upon that to depict the hooky part of the stock graphs.
So basically:

You start at time T1. You're going towards time T2. Price at time T1 is P1. P2 is end price.

You generate a random number (probably based on some events, maybe?) for P2. This is your larger number target price.

You iterate towards it with a timestep. If you update a couple of times (denoted as Tt) between those timesteps, you do

(T2 - T1)/Tt = Your time step

To get the price at this time, you do

P1 + (P2 - P1)/Tt * AmountOfTimeStepsPassed

This will get you a pretty straight line, so you could look into something like Bezier or something to make a curve. But to get those hooks, you need to add a very small totally random deviation upon it. This needs to go from a small negative number to a small positive number!

P1 + (P2 - P1)/Tt * AmountsOfTimeStepsPassed + SmallRandomNumber