texts:
Im using modern opengl and c++.

How do I draw a number of triangles each one having a different texture in one draw call when I only have 32 texture units on my graphics card and the max texture size is 1024? My video card has 2gb of memory yet it can only hold 32 texture at a time?

Why do graphics cards have this limitation? I'm a c++ programmer and in c++ you don't have restrictions like that. The only restriction that you have is how much RAM you have which is fine.


texts: Positions are the same but appear in different locations

texts:
I have a procedurally generated tile that is a part of a turn-based hex tile game. When I try to have the tile instantiate a prefab that is the placeholder for a unit, I used the tile's transform.position as the position part of GameObject.Instantiate(Object, Location, Rotation). Unfortunately, this is the result:

A similar thing happens no matter which tile I use.

More information: I tried placing a cube on where the hex is, supposedly. Its transform is very different. So what it appears to be is that the tile is being placed in the wrong place, not the cube.

Further experimentation shows that the cube is appearing at exactly half the hex's apparent transform (I added a multiplier of 2 to the cube's position and it appeared in the right spot). I still have no idea why.


texts: Everything black except where there's a light

texts:
I have a camera in my scene with a map created at runtime:

As you can see everything can be seen. Now I want the map to be invisible (black as the background) except where there are lights. How can this be achieved in Unity3D?


texts: Server Client position information exchanging

texts: I am doing small game in xna client/server, there can be 50f per seconds, but i don't belive that each client has to sent 50 mesagges about only their position, and then get back from server, regular ping is 50ms so even if 20 messages per second then success, so how it is made that everyone see immediately that someone else changed its position?


texts: How to re-calculate orientation vectors when one of them is being changed?

texts:
I want to implement a Unity-like API for my transforms, with the ability to set forward, right, up vectors directly and change object's rotation quaternion accordingly.
I got stuck at the math behind it, though. What algorithm should we use to change the other 2 vectors?
I feel that the function should have 2 if branches and check which of the other two vectors to use to compute a cross product with the new vector, to decide which vector to use as the first and which is the second, and vice-versa in another branch.
I came up with something like this so far:
void Transform::SetForward(const glm::vec3& v) {
    mForward = glm::normalize(v);
    if (abs(abs(glm::dot(mForward, mUp)) - 1.0f) <= 1e-5) {
        // dot is either -1 or 1 (straight up or down)
        mUp = glm::cross(mRight, mForward);
        mRight = glm::cross(mForward, mUp);
    }
    else {
        mRight = glm::cross(mForward, mUp);
        mUp = glm::cross(mRight, mForward);
    }
    FixRotationQuat();
}


texts: Improving performance of a particle system (OpenGL ES)

texts:
I'm in the process of implementing a simple particle system for a 2D mobile game (using OpenGL ES 2.0).  It's working, but it's pretty slow.  I start getting frame rate battering after about 400 particles, which I think is pretty low.

Here's a summary of my approach:

I start with point sprites (GL_POINTS) rendered in a batch just using a native float buffer (I'm in Java-land on Android, so that translates as a java.nio.FloatBuffer).

On GL context init, the following are set:

GLES20.glViewport(0, 0, width, height);
GLES20.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
GLES20.glEnable(GLES20.GL_CULL_FACE);
GLES20.glDisable(GLES20.GL_DEPTH_TEST);

Each draw frame sets the following:

GLES20.glEnable(GLES20.GL_BLEND);
GLES20.glBlendFunc(GLES20.GL_ONE, GLES20.GL_ONE_MINUS_SRC_ALPHA);

And I bind a single texture:

GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureHandle);
GLES20.glUniform1i(mUniformTextureHandle, 0);

Which is just a simple circle with some blur (and hence some transparency)

http://cl.ly/image/0K2V2p2L1H2x

Then there are a bunch of glVertexAttribPointer calls:

mBuffer.position(position);
mGlEs20.glVertexAttribPointer(mAttributeRGBHandle, valsPerRGB, GLES20.GL_FLOAT, false, stride, mBuffer);

...4 more of these

Then I'm drawing:

GLES20.glUniformMatrix4fv(mUniformProjectionMatrixHandle, 1, false, Camera.mProjectionMatrix, 0);
GLES20.glDrawArrays(GLES20.GL_POINTS, 0, drawCalls);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0);

My vertex shader does have some computation in it, but given that they're point sprites (with only 2 coordinate values) I'm not sure this is the problem:

#ifdef GL_ES
// Set the default precision to low.
    precision lowp float;
#endif

uniform mat4 u_ProjectionMatrix;

attribute vec4 a_Position;
attribute float a_PointSize;
attribute vec3 a_RGB;
attribute float a_Alpha;
attribute float a_Burn;

varying vec4 v_Color;

void main()
{
vec3 v_FGC = a_RGB * a_Alpha;
v_Color = vec4(v_FGC.x, v_FGC.y, v_FGC.z, a_Alpha * (1.0 - a_Burn));
    gl_PointSize = a_PointSize;
    gl_Position = u_ProjectionMatrix * a_Position;
}

My fragment shader couldn't really be simpler:

#ifdef GL_ES
    // Set the default precision to low.
    precision lowp float;
#endif

uniform sampler2D u_Texture;
varying vec4 v_Color;

void main() {
    gl_FragColor = texture2D(u_Texture, gl_PointCoord) * v_Color;
}

That's about it.  I had read that transparent pixels in point sprites can cause issues, but surely not at only 400 points?

I'm running on a fairly new device (12 month old Galaxy Nexus).

My question is less about my approach (although I'm open to suggestion) but more about whether there are any specific OpenGL "no no's" that have leaked into my code.

I'm sure there's GL master out there facepalming right now... I'd love to hear any critique.


texts: Unity UI issue trying to make a button work while held down

texts:
Pretty simple, have a rotate up button and I want it to rotate while held down.

using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class cannonController : MonoBehaviour, IPointerDownHandler, IPointerUpHandler {
public Vector3  force;
Rigidbody2D rg;
Vector3 up;
public bool pointerDown = true;
Vector3 down;
// Use this for initialization
void Start () {
    rg = GetComponent<Rigidbody2D>();
    up = new Vector3(0f, 0f, 20f);
    down = new Vector3(0f, 0f, -3f);
}

/// <summary>
///  all of the rotation stuff
/// </summary>
    public void RotateSTOP()
    {
        rg.transform.Rotate(Vector3.zero);
    }
    public void RotateDown()
    {
    rg.transform.Rotate(down);
    }
    public void RotateUp()
    {
    while(pointerDown == true)
    {
        rg.transform.Rotate(up, Time.deltaTime);
    }

    }
/// <summary>
/// sets pointerDown to check if button is held down
/// </summary>
/// <param name="eventData">Event data.</param>
public void OnPointerDown(PointerEventData eventData)
{
    pointerDown = true;
}

public void OnPointerUp(PointerEventData eventData)
{
    pointerDown = false;
}

}


texts:
I see that modern OpenGL related code uses EGL, i can't get good resources for this so i ask here:

what exactly is EGL ?
if a platform supports OpenGL ES 2.0+ or OpenGL 3.0+ i can presume that will support EGL too ?
when is convenient to use EGL and when it's not?

for what i can tell by now it's something similar to FreeGLUT to me, but looks much more portable and standardized.


texts: Is it safe to set Lua Table data from multiple C++ threads?

texts:
As the title states. I'm curious if it's safe to set data in different Lua tables that exist in the same lua state. From multiple C++ threads.

I'm asking this because my current system actually has a separating between Lua's data, and C++'s data, with Lua driving the majority of the game's update and loop - and C++ handling lower level details such as math, rendering, resources, and physics.

After the physics update, I have to waste time in having an entire phase for Lua to update it's own internals for Serialization and grabbing references.


texts: Monogame: Texture anti-aliasing result in transparent edges

texts:
This is a follow-up question on a previous issue I faced with a game I'm trying to make. It's in a 2D isometric perspective and the levels are created from individual tiles. A simple 3x3 map can be seen here:

The tiles are individually added to the sprite batch, and (at least, this is what I think is happening) each one get anti-aliased on their edges, resulting in a small blur which creates the thin edges that you can see in the picture.

To make matters worse, I actually want to provide a bit more complex tiles in my game than what is displayed above. For example, I want to be able to show roads. To do so, I wanted to layer multiple sprites on top of each other, resulting in the picture below:

I think you can see where I'm going here. The same problem that I described with the aliasing is now occuring aroud each texture. So sad.

I know I can use Point sampling to make the textures align pixel perfect, but even though this does work, the (relatively) high resolution textures really do not seem fit for such a setting:

I mean, these edges simply need to be anti-aliased.

So, my question to you all is: Is there a way to stitch my tiles (and tile-pieces) together in a way so that anti-aliasing does not ruin it with those annoying edges, while still being able to produce a nicely anti-aliased result?

I hope there is, and that someone here can show me how :)

Thanks,

Rutger

Edit 1: Changed the title to be more representative to the problem (I hope?)


texts: How can I use gpu to crop unnecessary pixels from an image?

texts: I would like to keep only the color and x,y coordinates of the pixels that are touching a pixel that is a different color than itself (basically the edges) and remove the rest so that the gpu can compare two edge pixels without needing to read through all the pixels that fill the shape. I want to process this more afterwards but I am trying to do this to limit how many gpu cores the edge detection need so that I can use those cores for other processing at the same time. I am not planning on this as a shader or any graphic thing I’m using it as an AI vision for a game character. I know that they have machine learning for this but I want to avoid that if possible. Not for any reason except I want to know what is going on in there. How can I do this without using the cpu?


texts: sharing preferences between two apps on android with libgdx

texts:
I am making an android game with both a demo version and a paid version. I want users who decide to buy the paid version to continue from where they left off, with all their old data and settings.

I've set a shared user id between both applications, and now I'm wondering if it's possible to use libgdx preferences across both versions.

I am also open to other ideas on how to implement this.


texts:
I'm experimenting with 2d physics, and the problem is this: The IsTouchingLayers function reveals that the object is touching a layer, but only if I use the-1 parameter which is equivalent to Physics2D.AllLayers.

These are the tests done on Visual Studio in debug in the immediate control window:

?Physics2D.AllLayers
-1

?GroundCheck.IsTouchingLayers(-1)
true

?GroundCheck.IsTouchingLayers(0)
false
?GroundCheck.IsTouchingLayers(1)
false
?GroundCheck.IsTouchingLayers(2)
false
?GroundCheck.IsTouchingLayers(3)
false
?GroundCheck.IsTouchingLayers(4)
false
?GroundCheck.IsTouchingLayers(5)
false
?GroundCheck.IsTouchingLayers(6)
false
?GroundCheck.IsTouchingLayers(7)
false
?GroundCheck.IsTouchingLayers(8)
false
?GroundCheck.IsTouchingLayers(9)
false
?GroundCheck.IsTouchingLayers(10)
false
?GroundCheck.IsTouchingLayers(11)
false
?GroundCheck.IsTouchingLayers(12)
false
?GroundCheck.IsTouchingLayers(13)
false
?GroundCheck.IsTouchingLayers(14)
false
?GroundCheck.IsTouchingLayers(15)
false
?GroundCheck.IsTouchingLayers(16)
false
?GroundCheck.IsTouchingLayers(17)
false

These are the layers I have in the project:

If I use the -1 parameter it works correctly, the character jumps when it touches the ground and does not jump when it is in the air, but it will definitely jump by touching any layers.  And anyway I want to understand why.

What am I doing wrong ?

Thank you


texts: Implementing fog of war in opengl es 2.0 game

texts:
Hi game development community, this is my first question here! ;)

I'm developing a tactics/strategy real time android game and I've been wondering for some time what's the best way to implement an efficient and somewhat nice looking fog of war to incorporate in it.

The style of fog of war i'm looking for is to darken the areas where there is no visibility  at a certain moment. [not the solid black, unexplored area, kind of fog of war]
Note that this has nothing to do with which units are visible to the player. This is merely a visual effect.

My experience with OpenGL or Android is not vast by any means, but I think it is sufficient for what I'm asking here.

So far I have thought in some solutions:

Draw white circles to a dark background, corresponding to the units
visibility, then render to a texture, and then drawing a quad with
that texture with blend mode set to multiply. Will this approach be
efficient? Will it take too much memory? (I don't know how to render
to texture and then use the texture. Is it too messy?)
Have a grid object with a vertex shader which has an array of
uniforms having the coordinates of all units, and another array
which has their visibility range. The number of units will very
probably never be bigger then 100. The vertex shader needs to test
for each considered vertex, if there is some unit which can see it.
In order to do this it, will have to loop the array with the coordinates and do
some calculations based on distance. The efficiency of this is
inversely proportional to the looks of it. A more dense grid will
result in a more beautiful fog of war... but will require a greater
amount of vertexes to be checked. Is it possible to find a nice
compromise or is this a bad solution from the start?

Which solution is the best? Are there better alternatives? Which ones?

Thank you for your time.

Edit

I have (kinda) tried the second option with only one unit, and the shadows were getting too pixelated.. If I increased the number of vertexes, the fps started to drop. I tried doing the tests in the fragment shader and the results were better in terms of smoothness (that was expected) but also in terms of performance (comparing to the denser grid), which got me a little surprised. But I don't know if testing each pixel against 50 units might be viable to do in the fragment shader. Probably not!

I'm gonna bring a third option that I don't know if is valid, but maybe you people can enlighten me:

3.Use the stencil buffer in some way to draw the invisible areas in white (this would be done by having the stencil buffer initialized in
white, and then draw black circle textured quads on it corresponding to units visibility) and then use
that to make a kinda "clipping mask" effect on a full black somewhat
transparent quad that would darken the invisible areas.

I don't even know if this is possible, and I'm not 100% sure that every android with opengl 2.0 supports stencil buffer. I also don't know very well what is the stencil buffer or when it is used... But apparently this might be a perfect solution. Does anyone have an idea?


texts:
I am trying to build a game based on Advance Wars in XNA.
I am so far where the tiles are placed on the screen, except here starts my problem. During the game, I ofcourse want to move the camera around over the map.

Except I got no idea on how to do this. I hope there is a way of just moving a camera around and not reposition every object on the map (thus all the tiles and units), since that is currently to only thing I might get to work, with my current knowledge.

Sorry for the short post, please let me know if I need to provide code or anything else.


texts: give a prefab clones a script from another prefab in Unity3d

texts:
I have the following :

TurretBallmanager :

using UnityEngine;
using System.Collections;

public class TurretBallManager : MonoBehaviour {

// Use this for initialization
public GameObject BallPrefab;
public GameObject TurretPrefab;
public static TurretBallManager instance;
public int turretSpawnTime=35;
public int LastTurretTime=0;
Vector2 v;
void Start () {
    instance = this;
    v = new Vector2(TurretPrefab.transform.position.x,TurretPrefab.transform.position.y);
}

// Update is called once per frame
void Update () {
    if (Time.time > LastTurretTime + turretSpawnTime) {
        GameObject T = Instantiate(TurretPrefab,v,Quaternion.identity) as GameObject;
        //T.AddComponent<Turret>();
        v.x=T.transform.position.x+2;
    }
  }
}

Turret class :

using UnityEngine;
using System.Collections;

public class Turret : MonoBehaviour {

// Use this for initialization
double LastBallTime=0.0;
double LastTurretTime=0.0;
public decimal spawnballTime=1.5;
Vector2 v ;
void Start () {

}

// Update is called once per frame
void Update () {
    if (Time.time > LastBallTime + spawnballTime) {
        LastBallTime=Time.time;
        Debug.Log (transform.position);
        GameObject B = Instantiate(TurretBallManager.instance.BallPrefab, transform.position, transform.rotation) as GameObject;
        //B.AddComponent<Ball>();
    }

  }
}

Ball class :

using UnityEngine;
using System.Collections;

public class Ball : MonoBehaviour {

// Use this for initialization
void Start () {

}
void OnMouseDown() {
    Object.Destroy (gameObject);
}
// Update is called once per frame
void Update () {

}

void OnBecameInvisible ()
{
    Debug.Log ("destroyed");
    Destroy(gameObject);
}
}

I have a turret wish fire a ball every 1 sec ,the ball is a prefab wish have the Ball class ( when the ball is out of bounds or is touched it should be destroyed ) what i'm trying to do is creating a another turret every 35 sec wish also should fire a ball every 1 sec ..
what i am facing is the fallowing problem :

the turret is being created after 35 sec but it's ball are not implementing the ball script and they are not being destroyed
An overflow is occurring due to the number of balls created and the whole project is freezing

Image 1 : as soon as the game begin
Image 2 : When 35 seconds ends
Image 3 : you can see that millions of turrets are created at the same time as soon as 35 sec ends

The turretballmanager is a class given for the Maincamera


texts: How can I render 3d pictures synched frame by frame to a keyed video?

texts:
I'm developing a software that aims to combine a keyed video with a 3D rendered one, synchronously frame by frame.

Each frame of video should be combined with a timely corresponding frame of 3D picture using a matching camera position parameter.

How can I perform this rendering and ensure it stays in synch?


texts: Sorting sprite's layers in isometric view

texts:
I'm making a strategy game with isometric view and I'm having some problems with deciding which sprite should be drawn first (I'm using SFML 2.2 as graphic library).
I'm using std::sort to sort sprites in array by their Y position in a window (Floor and walls aren't sorted, they are stored in different arrays).
This code works well in an RPG game where there aren't more than 100 sprites on the map at the same time, but this is going to be a strategy game and when there are 13000 or more sprites on the map, FPS is dropping below 30 and game is becoming unplayable. So, is there any faster way to sort these sprites?


texts: Converting normalized device coordinates to world space coordinates flipping my sprites

texts:
I'm trying to convert my game's camera system to use world space coordinates rather than OpenGL's default normalized device coordinates, however in doing so my sprites are being rendered improperly as you will see in the image below. Using GLM as my math library I have created a 4x4 orthographic matrix with the following code:

m_orthoMatrix = glm::ortho(0.0f, (float) m_screenWidth, (float) m_screenHeight, 0.0f);

I am then performing some translations (and scaling if by chance that is messing with anything) with the following code (m_cameraMatrix is a 4x4 matrix)

vec3 translation(-m_position.x, -m_position.y, 0.0f);
    m_cameraMatrix = glm::translate(m_orthoMatrix, translation);
vec3 scale(m_scale, m_scale, 0.0f);
    m_cameraMatrix = glm::scale(mat4(1.0f), scale) * m_cameraMatrix;

m_scale is a float currently with my testing at value 1.0f. m_position is a vec2 where in the image, the sprite on the right has values (0, 0) and the sprite on the left as values (screen width / 2, 20).

The issue, as you will notice, is that the sprites are rendered upside down, and I can't seem to fix it without getting rid of my translation math and going back to normalized coordinates.


texts: Extrude only vertices where the assigned texture is transparent?

texts:
I am looking at implementing a water surface on my spherical object and have created a texture with transparent pixels where the water should be. However, I am currently confused on how I can extrude only vertices where the texture is transparent. Do I have to test the texture at the appropriate position prior to assigning the vertex and just assign a Color.Transparent value to that vertex or am I thinking about this all wrong?

Special thanks to @Bram for helping me to answer some questions that could help clarify my specific situation.

What geometry do you extrude?

Individual vertices with a geometry, fragment, or hull shader.

What is the extrusion for?

To make waves in the water.

When I mention testing texels and then assigning colors to a vertex, I mean doing so beforehand when creating the Vertex[] object. This would be easy enough to do I suppose; I'd have to look into some samples of how to test the texture on the C# side, which is why I'd love to do it in a shader that has a similar flow as below:

Vertex Shader

Create the sphere.

Pixel Shader

Grab only vertices that have transparent pixels via TEXCOORD0.

Geometry/Fragment/Hull Shader

Extrude those vertices.


texts: How should I structure the layout and saving system of my game concept?

texts:
I am a huge fan of Minecraft and (to an extent) Terraria. I’ve always wanted to make my own version of that type of Creative sandbox game, and recently I’ve been thinking of so many things I could add to it.

The game I’m imagining is a very different style from these two games. It’s 3D, and cartoony to a point but not too cartoony to not be realistic. I’m talking more realistic than Fortnite’s style but I definitely do not want to attempt to make a photo-realistic game.

I want my games world to be more fluid than the worlds of Minecraft and Terraria. I don’t want the player to be necessarily limited to a grid of blocks, though that should maybe be implemented at some points, like when the player is placing pieces of a structure down (blocks).

Generated structures such as trees, rocks, and the terrain I don’t really want to be blocky or constrained to a set grid.

The things that I see players being able to place into the world are things like wood columns to form the base of a house, wall blocks for a house, tables and chairs, doors, and different blocks required to create different items.

I like how the Minecraft and Terraria worlds are generated and saved. It’s simple: each coordinate is a block and that can be stored away very easily. I still haven’t figured out how I can save the type of world I want in my game, though.

So my question is: how should I structure the terrain, structures, and player-placed blocks layout/saving system so that I can save it efficiently and write it relatively simply as well?

Something I’ve thought about: there is a mod for Minecraft called the no cubes mod which essentially removes all the cubes from the game and seamlessly blends blocks together. That might be a good way to make this game since the blocks are still stored the same way but they are not actual blocks, and terrain can be made more realistic through this method.


texts:
Please let's avoid the discussion of creating/using a game framework or not.

I would like to create a small framework for card games or use one if it exists. Does anyone knows one?

Preferably written in Java or C#.

Thanks in advance,


texts: What term is used to refer to iPhone and Android games?

texts: What do you call games developed for Android or iPhone to differentiate them from games developed for other platforms?


texts: Why does Forge not find my texture for my custom background?

texts:
I am creating a minecraft mod that improves the main menu for my minecraft server. At first I wanted to create the background, but somehow when I try to start minecraft it closes and I get a nullpointerexception because minecraft didn't find my background.

public class ThundrialMenu extends GuiScreen {

    @Override
    public void initGui() {

    }

    @Override
    public void drawScreen(int mouseX, int mouseY, float partialTicks) {
        Random rnd = new Random();
        int background = rnd.nextInt(3)+1;
        String backgroundLocation = "/assets/thundrial/gui/Background"+background+".png";
        this.drawBackground(mc.renderEngine.getTexture(new ResourceLocation(backgroundLocation)).getGlTextureId());
        super.drawScreen(mouseX, mouseY, partialTicks);
    }

    @Override
    public void updateScreen() {
        super.updateScreen();
    }
}

This is the folder where the pictures are located:

Why does Minecraft not find those pictures?


texts: Can I use fictional city/country names from public domain/fiction etc. in a potentially monetized browser game?

texts:
I'm currently developing a browser game with a focus on economy, trading and industry. For that I'm building a fictional world with countries and cities. To avoid political drama within the games player interactions, I'd like to avoid using real countries that currently exist/are recognized. I tried to come up with several fictional country names, but I'm reaching the limitations of my creativity where they are still OK-sounding...
My questions are now...

Can I use fictional countries e.g. from movies/comics etc (e.g. Sokovia from the Marvel universe)? Maybe with slight adjustments?
Can I use older country or empire names (e.g. Babylonia)? Maybe also with slight adjustments.
Can I use city names from the real world? I need a lot of them, so coming up with thousands brings me to my limit and there may probably be overlaps without me knowing. Based on the following question that should be fine, also since they have nothing to do with the real-life equivalents. Do I need licensing to use real city names in my game?
What about using planet or galaxy names which are public domain (or how are they protected, if at all)?

I found some generators in the internet which are helpful to a certain degree, but I'd rather write my own to be honest.
Since the game might be monetized, are there any licensing issues involved? I'm pretty new to this from a legal perspective.

Another thing are the fictional company names the users can choose. I guess I can set certain restrictions there to exclude real world companies and provide a "report" button for real companies to request the removal/change to be on the safe side.

Thanks in advance

PS: Since I also needed flags, I already found a nice generator, in case someone is interested:
https://www.reddit.com/r/vexillology/comments/4ha19q/flagmaker_20/?st=jb6e4qyk&sh=c1544079


texts: (GLSL) Lighting code outputting a black quad

texts:
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.


texts: C# Monogame Enemy shooting at random intervals

texts:
I am currently coding a simple Monogame Space Shooter.

I have almost finished my enemy shooting behaviour,
but I spent a long time on fixing it and got to the point
where I wanted somebody to help me out.

Okay so basiclly I have my 9 enemies (instances of Enemy class) in my
Level class, and in level update I do stuff like checking if enemy has been hit by player, if they are Dead so I can remove them from the list etc.

I made a simple Timer class that has only 1 function, uses

var timer += GameTime.ElpasedGameTime.TotalMiliseconds

and simply checks if timer is bigger or equal than function input parameter(or argument?), and func is a bool so it then returns T or F.

Now inside my Enemy.cs claas I have this function:

public bool IsShooting()
        {
            if (enemyTimer.Wait(randomFloat))
            {
                shot = true;
                return true;
            }
            else
            {
                shot = false;
                return false;
            }
        }

enemyTimer = new Timer() & randomFloat = field(variable at the top of the class)
in my Enemy class.

And now last but not least(actually the problem here) is this, so now in my Level class I got this little update function:

public void Update(Weapon weapon)
        {
            if (enemies.Count == 0)
                isFinished = true;

            if(!isFinished)
            {
                for (int i = 0; i < enemies.Count; ++i)
                {
                    if (enemies[i].shot)
                    {
                        seconds = rand.Next(1, 10);
                        randMiliseconds = 1000f * seconds;
                    }

                    enemies[i].randomFloat = randMiliseconds;
                    enemies[i].Update();

                    if (enemies[i].isDead == true) // If enemy is dead, remove it from level
                    {
                        enemies.RemoveAt(i);
                        --i;
                    }

                    foreach (Bullet bullet in weapon.bullets)
                    {
                        if ( !(i < 0) && weapon.ShotEnemy(bullet, enemies[i])) // If not enemies count == 0 and if
                        {                                                      // enemy has been shot decrease its health
                            enemies[i].Health -= weapon.Damage;                          // and set bullet visibility to false;
                            bullet.isVisible = false;
                        }
                    }

                }

            }

        }

This for loop goes through all the enemies, first if block is used for checking that
if the enemy has shot the bullet, then set random value again to something different, if shot has not yet been fired then use the old value and wether it has been changed or not it sets randomFloat field in Enemy class to that value.

Now this is how it works: First all of 9 enemies shoot 1 bullet at the same time (Just about when I open the window, cause I putted randomFloat = 1000f; in my Enemy CTOR), and then randomFloat value is set in Level class to something different, I have message output and FOR EVERY DAMN ENEMY randomFloat is the same.... now that is a problem, I want the rand value to be different for all of them, and it should, right?
Becouse those 9 enemies are all different instances of that class and if in each for(;;) loop cycle in my Level.Update() if it gets positive value that enemies[index] has fired a shot it should change it to some number that is very unlikly to be the same for all 9 enemies (seconds = rand.Next(1,20); randomFloat = 1000 * seconds; ). So basiclly randomFloat get random, but it is the same every time for all enemies, and they all shot and will shot at the same random Time

Expected result: Every enemy shooting at different random time


texts: BSPs, Octrees and modern graphics hardware

texts:
I have read a lot of literature on BSPs, Octrees and like. Problem is that it is all old literature from software rendering time. Nobody describes how it is implemented today. So here is my idea how to do it and my question.

Let's say that I use some partitioning algorithm, it does not matter which one. I subdivide my level mesh into multiple partitions and store it in RAM. Should I simply create vertex buffers for each node so I can render my scene faster or what?

How do you do it, is there any better way today?

Thank you


texts: How to construct a octree density from SDF for MC

texts:
It very clear how it works with a regular grid. 3 inner loops - x, y, z over some size. The smaller the cells, so will be the mesh more detailed.
But how about octree. I know i can stich different levels with transvoxel (not sure with what max difference), but no idea how to construct the tree from SDF. It kind of needs to know if a cell is occupied and then split and so on? But how?
Or maybe octrees are bad idea for marching cubes and isn't practiced (then what about ray cast)?


texts: How to avoid entities flying far away when tabbing out and then tabbing back in?

texts:
I'm developing a game which uses a standard Entity-Component-System.
Every frame, the PhysicsSystem runs, which, among other things, updates the position of entities based on their velocity. Something like this:
execute(delta: number, elapsed: number) {
  for (let entity of this.scene.query(CT.Transform, CT.Physics)) {
    let transform = entity.get(CT.Transform);
    let physics = entity.get(CT.Physics);

    let movementIncrement = physics.direction.multiply(delta * physics.friction * physics.speed);

    physics.velocity = physics.velocity.multiply(1 - delta * physics.friction).add(movementIncrement);
    transform.pos = transform.pos.add(physics.velocity.multiply(delta));
  }
}

This works fine, except there's an issue. When the user switches to another tab, waits some time (let's say 5 seconds), and then tabs back in, sometimes the entities instantly fly away so far that they fly off the map and out of bounds.
I'm not sure why this would happen, as it never happens during normal gameplay. Something to do with the tab becoming inactive for a time, and then active, seems to cause this issue.
I suppose a possible solution is to "pause" the game if the tab loses focus, but I rather the game keep running in the background unless the user manually pauses by hitting escape.
Does anyone know why this is happening? The rest of the game continues functioning normally, it's just the entity positions fly away for some reason.


texts: How is background of 2.5d games developed

texts:
When I say 2.5d games, I mean like this:

Bloodstained Ritual of the Night DEMO gameplay

My question is, I know the characters and platforms are 3d but are the backgrounds all 3d as well? Even if its not interacted on in any way? Like for example, at 10:45, did the developer(s) make models of the cannons at the background? Or 48:30, did they model the houses?

For context, I'm starting a hobby project game in 2.5d and I'm trying to get an idea on how I would develop the backgrounds.


texts:
I have just started making a mod for minecraft, I learned how to make items and import custom png's and have gotten all of that to work. I have been searching around the code trying to find a way to make an item being held or in the inventory give off light around the player. I do have experience coding in java, but I am not well acquainted with the minecraft code.

(This is using mcp 5.6 with modloader in minecraft 1.1 with eclipse)


texts: How to disable camera moves (mouse drag) in an Unreal Engine editor plugin?

texts:
I tried to override FEdMode:

virtual bool DisallowMouseDeltaTracking() const override
{
    UE_LOG(LogTemp, Warning, TEXT("do not allow mouse delta tracking!"));
    return true; // I also tried to return false
}

but the problem is that the cursor stops moving (and gets invisible).

Is it possible to change the camera moves (to make it like in 3Ds max or sketchup)?


texts:
I want to run my code multiple times without using the Update() method, now, I could use a coroutine or an Invoke(), but since the Invoke() is not very performance friendly as a coroutine, my best option is to use a coroutine instead.

Now, my problem is, when my coroutine is completed and I want to restart it, how exactly should I do it?

Here is what I've done, but it doesn't work:

private void Start()
{
    StartCoroutine(DoSomething());
}

private IEnumerator DoSomething()
{
    //Does something
    yield return new WaitForSeconds(20f);
    //Does another thing
    yield return new WaitForSeconds(20f);
    StartCoroutine(DoSomething());
}


texts: In the new InputSystem of Unity, how to detect the keyboard and the mouse "as the same input device"?

texts:
I'm trying to use the PlayerInputManager of the new InputSystem (preview 7) and my keyboard and mouse are being detected as separate devices. I'm not saying that it is wrong, but it is not useful at all and I would like to know how to fix it.

As shown in this video, the PlayerInputManager has the ability of Instantiating new players when they press a button of their controller. This is almost exactly what I need, but it is not perfect.

All works fine using controllers but if someone wants to join using the keyboard/mouse, "they won't be able".

When a key is pressed in the keyboard, a player joins, and when the mouse is used, another player joins (despite the fact that in that game youn need both to control a character and neither one of the spawned characters would be playable).

So my question is: how can I configure the InputSystem so that only one player joins when either a keyboard or mouse is used and it reads the input from both devices?

Maybe it is simply a missing feature, but I think that it would be nice if you could achieve what I want because a lot of times the keyboard is used alongside a mouse.

Thanks in advance!


texts: A friend and I are doing a 2D XNA game. Thus far, the API seems really cool and performance is acceptable.  My question is more towards the release of it though.  As other developers how have done games, how well have they done for you on PC (as far as downloads, sales, etc)?  I know the statistics about the Xbox360 from seeing it personally but, I was curious as to how successful these were on PC?


texts: Story and news-feed ideas for social network games

texts:
I am currently working on a educational and fun 2-in-1 game. As I am not a professional, I need advice on story and news-feed. The goal is simple-get richer, the story is about a worker who is trying to get over his/her financial problems and become rich.

During the whole gaming process there is a news-feed (every day there are a couple of fresh news about what is going on). The news are fresh and individual so I need to write about 2000 pieces of news for 2 year gaming, maybe more.

The problem is that I am not sure whether repetitive news can interest in this game. What can be done to make the news-making process easier but not boring from the point of view of the player?


texts: How does one make a 3D background in a 2D game?

texts:
I am trying to figure out how to make a background that looks 3D in a game that is 2D.
Below there is a video of the game "Under The Lotus." I am trying to get a background with similar effect (it looks like a 3D environment, while the game runs basically in the X and Y axis).

http://www.youtube.com/watch?v=3GsTwsx5aWo

Can anyone give me an idea how to do that? Or point me in some direction on what to read to be able to figure this out?

I am planning on using SDL for this game. If I could avoid using OpenGL that would be better, but it is not a real requirement.


texts:
Greetings

I'm in the process of making a Scoreboard for a game (Starcraft II). This scoreboard is being made as a WPF Application with a C# code-behind. I already have a version which works for 90% in WinForms but I lacked the support to easily make it look a lot nicer which are available in WPF.

The point of this application will be to form a kind of overlay on top of a running game.
In this overlay people can see the Score, Map, Players, Colors, etc. Basically all the info they need.

Since the main look of the app in WPF is based on an image with a transparent background I have set most Background values to Transparent. However when I do this the entire application does not get registered by streaming software. For example it just shows my Desktop or the game I'm playing but not my application even though it IS there. I can see it with my own eyes but the audience on the stream cannot.

Does anyone have any experience with this matter because it's really doing my head in. My entire application will be useless if it is not visible on streams. If I have to put the background on a color rather than transparent the UI will be completely demolished as well in terms of looks.

I'm basically trying to make a game-overlay in C# & WPF which is able to update with little hassle for the viewer. I have little to no knowledge regarding C++ and DirectX so I would not know where to start in that regard. This project currently holds 1 Developer and 1 Graphic Designer so it isn't a big scaled project, it will also be distributed for free once/if it gets finished. Any tips are welcome!

Thank you for your time reading and your possible insights.


texts:
I am creating a GUI for my game, so I use some buttons like
. So you can see it is only text surrounded by a rectangle. But I currently use a huge png image with all the buttons I need arranged as I want it, it is really inefficient, so how can I  upload a single smaller image of the rectangle, a sample of the gradient I want and use SDL_tff to create a surface. Say: I copy the rectangle and the text in an SDL_Surface, it should have two colors (black and white), now make white pixel transparent and black pixels to be replaced with the gradient to create the buttons and place them using SDL_Rects.


texts: How do I slow down my character while running?

texts:
void Movement()
{
    transform.Translate(Vector3.forward * 10 * Time.deltaTime);

    if(Input.GetKey(KeyCode.S))
    {
        transform.Translate(Vector3.forward * 3 * Time.deltaTime);
    }

    if(Input.GetKeyUp(KeyCode.S))
    {
        transform.Translate(Vector3.forward * 10 * Time.deltaTime);
    }
}

I tried this code but seems to me, it didn't work as I expected it to.

What I expect:

my character moves along at a speed of 10 automatically
when the S key is held, the character slows down to a speed of 3 instead
when the S key is released, the character goes back to their default speed of 10

What I observe:

the character does not slow down when the S key is pressed

How can I fix this?


texts: How to access variables of uninitialized class?

texts:
So I've gone with a somewhat singleton approach to my game class:

#include "myGame.h"

int main () {
    myGame game;
    return game.Execute();
}

But now I need to define a class that accesses variables in the instance of myGame.

class MotionState {
    public:
    virtual void setWorldTransform (...) {
        VariableFromMyGameClass++;            //<-- !?
        ...}
};

I'm trying to integrate this class into my project from an example that just uses globals.  How can I access variables of myGame class in the definition of new classes?  Should I give up on my singleton approach?


texts: What algorithm to use for random terrain?

texts:
(Please note, I am aware that the generation is not truly random and relies on mathematical equations, and that my language of choice is C++)

So I've been learning programming for a while now and I'm looking to make a top down 2D game. I want this game to generate random terrain pretty much like Dwarf Fortress but with sprites, however for this question let's just say that there just ASCII characters. I want it to generate mountains,  rivers, inland lakes etc. I know of algorithms but have not been able to find a list of them all. The ones i know of are:

Perlin Noise,
Diamond Square,
Midpoint Displacement
and some other minor ones.

However I don't know which one to use and struggle to find a good article on any of them. Is there one right for the job, or does it just come down to personal opinion? And if you can find a list of all the algorithms and maybe a good article on one it would really help. Thanks!


texts: How do I check user's unlocked achievement and leaderboard scores via GPG plugin

texts:
I need to load user's achievement and their scores from leaderboard in my game. But the Social.LoadScore() and Social.LoadAchievements() both returns a 0 size array in callback.

When I checked the implementation in Google Play Gaming's PlayGamePlatform.cs, both the method has this summary -

Not implemented yet. Calls the callback with an empty list.

So my question is How do I get this data in Unity? Has anyone tried any other method to get the data?


texts:
I'm building the inside of a space ship in Unity as POC. I need info on scene lighting.
Rooms, corridors or just in general how to make an enclosed scene look great with lights.

Keep in mind this is indoors and I can't really use the Directional Light and have to
rely on realistic light sources.

Thanks!


texts: Translate the ModelView matrix, or change vertex coordinates?

texts:
If I have a simple 2D scene and I want to move the objects inside the scene on the X and Y axis, should I send OpenGL the original vertex coordinates with each move and apply a ModelView matrix transform, or should I simply send the updated coordinates?

Since the scene is simple and there are really not that many vertices, I'm not using vertex buffers.


texts: How can I simulate a magnet that attracts a ball in a 2D enviroment?

texts:
I am making a top-down game where you have to move a ball from point A to point B. You are attracting the ball using magnets that are standing still. The ball needs to get pulled by multiple magnets.

How can I make this happen?


texts: What can I do to make sure that I have the energy to work on my game while working full-time?

texts:
I work as a software engineer 40+ hours a week and I find that between balancing my personal life and family responsibilities that I have literally no energy to work on game development.

What can I do to make more time for my hobby without burning myself out in front of the computer? I am sure there must be someone here successfully developing a game while working as a programmer on the side.


texts:
I would have thought that if the object is on-screen that this function should return screen coordinates. When used in conjunction with the directX draw text function, it works fine. Textual overlays track the 3D objects perfectly, however consider the following code:

D3DXVec3Project(&xyCoords, &HeadPosition(), &viewport, &matProjection, &matView, &matFinal);//for thought bubble

D3DXVECTOR2 origin = D3DXVECTOR2(
    (0.0f / SCREEN_WIDTH) * 2.0f - 1.0f,
    (0.0f / SCREEN_HEIGHT) * 2.0f - 1.0f);

D3DXVECTOR2 headPos = D3DXVECTOR2(
    (xyCoords.x / SCREEN_WIDTH) * 2.0f - 1.0f,
    (xyCoords.y / SCREEN_HEIGHT) * 2.0f - 1.0f);

lineRenderer.Draw2DLine(origin, headPos, D3DXCOLOR(1, 0, 0, 1), D3DXCOLOR(1, 1, 0, 1));

origin has a value of -1, -1 which is fine (texture coords for the screen go from -1 to 1 in each axis) but headPos has the value of -1.#IND000 in both the x and y. I think this may be because D3DXVec3Project is returning MASSIVE numbers, although I could be wrong.

Who knows what's going on under the hood of DrawText_A in the following code, but it clearly compensates for whatevers not working with the above code.

D3DXVec3Project(&xyCoords, &HeadPosition(), &viewport, &matProjection, &matView, &matFinal);

    rct.left   = xyCoords.x;
    rct.right  = xyCoords.x;
    rct.top    = xyCoords.y;
    rct.bottom = xyCoords.y;

    m_font->DrawTextA(NULL, stateStream.str().c_str(), -1, &rct, DT_LEFT|DT_NOCLIP ,   D3DXCOLOR(1,0,0,1));

This all works perfectly. Where am I going wrong with the first bit of code?

EDIT - the code below gives me the following values (also listed below)

D3DXVECTOR2 origin = D3DXVECTOR2(
    (0.0f / 1280.0f) * 2.0f - 1.0f,
    (0.0f / 720.0f) * 2.0f - 1.0f);

D3DXVECTOR2 headPos = D3DXVECTOR2(
    (xyCoords.x / 1280.0f) * 2.0f - 1.0f,
    (xyCoords.y / 720.0f) * 2.0f - 1.0f);

for origin I get (-1, 1.2) and for headPos I get (0, 1.401e-043#DEN). FYI HeadPosition() will return a vector3 that has a 0 z component and x and y values from about 2 to roughly 33.

Now how on earth can me with a calculator be better than the computer? what am I missing?

0.0f / 720.0f) * 2.0f - 1.0f should clearly = -1, not 1.2! what is going on?

0 / anything = 0, 0 * 2 = 0, 0 - 1 = -1!!!


texts: TLS Allocator ALLOC_TEMP_THREAD error using "Fireworks" and "Explosion" particle systems in Unity 5.5

texts:
I receive a TLS Allocator ALLOC_TEMP_THREAD error whenever I add certain prefab particle system assets, such as "Fireworks" and "Explosion", to my scene.

It also generates a huge amount of log messages, such as

  Allocation of 752 bytes at 0524a60f
  Allocation of 22960 bytes at 0542a6f0
  ...

It also creates a huge amount of lag and, severely drops the frame rate.

Particle systems like "Flare", "Dust Storm" and "AfterBurner" work as expected. The individual simulation of the child particle systems in the "Explosion" and "Fire" prefabs worked perfectly in the scene view, but the same prefabs simulate weirdly in the game.

I am using Unity 5.5, and this error should have been fixed in 5.4.0 b23, but apparently it has not. How do I fix these issues?


texts: How can I make Iridescence material In unity?

texts: One of the characters of the Dota2 that Is called Nyx Assassin has an interesting material effect If you look at the body and feet you can see this effect.It looks like poily/polluted water.I like to know how can I make something like that In unity.


texts: How can I create a "night sky" effect in OpenGL?

texts:
I am creating a game using OpenGL and I want to render the effect of a night sky with a few stars in it.

I want to have a shiny black effect in the sky so that it looks good. Could some one help in how to proceed through it or give a link to a good tutorial?


texts: Abstracting the ability to attack using an ECS

texts:
As the title suggests, my question is how to abstract the concept of 'attacking' using an ECS (entity component system). The "game" I'm working on is a roguelike in real-time, where all enemies/NPCs/player is an Entity (just an Id) with components.

I read this link and it helped clarify some things about an attack system, but I'm still confused how to implement this with an ECS.


texts:
I'm trying to build a radar system like the one in the original X-Wing games. The way it works is that there are two circular radar systems, one for behind the ship, and one for infront.

So, I've written a class to represent the radar, it has a vector representing the direction the radar is facing, and a 3D position of where the radar is. Both of these things will change in realtime as the ship moves and so the radar will need updating each frame.

Now I'm trying to figure out how to transform the position of another ship onto the radar. What I need is a final 2D X/Y coordinate between -1,-1 and 1, 1 for plotting on the 2D radar screen.

Given two vectors (the direction of the ship - which the radar is facing - and the direction to the ship we are plotting), how can I calculate a 2D X-Y position on the radar? Obviously I also have access to the up and right vectors of the ship too.

My instinct says that this should be relatively straightforward, but my math skills suck.


texts: Multiple textures on a mesh created in blender and imported in xna

texts:
I created a cube in blender which has multiple images applied to its faces. I am trying to import the model into xna and get the same results as shown when rendering the model in blender. I go through every mesh (for the cube its only one) and through every part but only the first image used in blender is displayed in every face. The code I am using to fetch the texture looks like that:

foreach (ModelMesh m in model.Meshes)
{
   foreach (Effect e in m.Effects)
   {
      foreach (var part in m.MeshParts)
      {
         e.CurrentTechnique = e.Techniques["Lambert"];
         e.Parameters["view"].SetValue(camera.viewMatrix);
         e.Parameters["projection"].SetValue(camera.projectionMatrix);
         e.Parameters["colorMap"].SetValue(modelTextures[part.GetHashCode()]);

      }
   }
   m.Draw();
}

Am I missing something?

EDIT:

Here is the code for getting the texture from the blender and use it in the XNA:

foreach (ModelMesh mesh in model.Meshes)
            {
                foreach (ModelMeshPart part in mesh.MeshParts)
                {
                    BasicEffect basicEffect = part.Effect as BasicEffect;

                    if (basicEffect != null)
                        modelTextures[part.GetHashCode()] = basicEffect.Texture;

                    part.Effect = material.effect;

                }
            }


texts: Acceptable memory size consumed by mobile game in 2017?

texts:
How do you think, what is the acceptable memory size consumed by mobile game in 2017, taking into account current state of mobile devices hardware performance?
I've made a pack of optimizations using a number of recommendations and managed to reduce memory consumption from 270Mb to 120Mb, but it still seems to me too much.
Anyway, my game looks pretty nice, smooth and fast on iPhone 5s (produced in 2013), also I run it on cheapest no-name android, and it still looks quite good.
So my question can be rephrased this way: is there anything criminal if the game eats about 200Mb of RAM in our reality when 1Gb of ram is not something incredible for the mobile device?


texts:
Say I have an octree and at a certain level I store VBOs in that octree. I know the dimensions of of the nodes that own the vbo so I can do basic frustum culling.  That works nicely because everything outside of the screen is never rendered.

However my world is quite big and I currently also draw things behind already drawn octrees.  What would I use to not draw nodes that are occluded by other nodes and how would I go about that?

I saw some mentions of occlusion culling in the OpenGL superbible but I fail to see how I can utilize that when I don't have a clear distinction between occluders and occludees.


texts: How should I implement lag compensation in my racing game?

texts:
I've looked around and I see a lot of discussion about lag compensation for FPS's, but none for racing games.

I know Mario Kart uses some sort of interpolation for other racers, but it doesn't provide very smooth results a lot of the times, when the simulated kart goes way off course and then teleports back on track with the next server update. I think games like Forza also use interpolation, but the cars in games like that move a lot more predictably, so it doesn't seem noticeable.

If I'm going for a game with the same type of chaotic movement that of Mario Kart, will I just have to accept that there will be sudden visible teleporting when a player has a bad connection to the server?


texts: How can I efficiently update only the entities that matter in a given frame?

texts:
I'm making a RTS, which can potentially have lots of units in one map (think Age of Empires).

I'm looking for a way to update my units. I want to avoid calling a virtual Update() method every frame on every entity. On the other hand, units that are not in view should still be updated and behave "normally."

I'm assuming this is a fairly standard question; what would be a way to handle this situation?


texts:
I have a small problem with converting a bitmap to a Texture2D. The resulted image of the conversion has the red channel switched with the blue channel :/ I don't know why, because the pixel formats are the same. If someone can help me I will be very happy :)

      System.Drawing.Image image =
            System.Drawing.Bitmap.FromFile(ImageFileLoader.filename);
        System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(image);
        Texture2D mapTexture = new Texture2D(Screen.Game.GraphicsDevice, bitmap.Width, bitmap.Height,false,SurfaceFormat.Color);

        System.Drawing.Imaging.BitmapData data =
            bitmap.LockBits(new System.Drawing.Rectangle(
            0, 0, bitmap.Width, bitmap.Height),
            System.Drawing.Imaging.ImageLockMode.ReadOnly,System.Drawing.Imaging.PixelFormat.Format32bppArgb);

        byte[] bytes = new byte[data.Height * data.Width*4];

        System.Runtime.InteropServices.Marshal.Copy(data.Scan0, bytes, 0, bytes.Length);

        mapTexture.SetData<byte>(bytes, 0, data.Height * data.Width * 4);

        bitmap.UnlockBits(data);
        bitmap.Dispose();
        image.Dispose();


texts: How could I generate a document that catalogs a collection of 3D models?

texts:
I have a lot of 3D models (.obj and .fbx) I can re-use in some games, but sometimes I forget them.

So I want to create a (for instance) Word document with the images of all my 3D models.

This can be useful to organize & reuse models from my personal library.

I know I could do this by hand, but that's not efficient; how could I somehow automate some parts of the process to achieve this?


texts: Generating a sprite using a list of points

texts:
I am trying to dynamically generate a sprite in Unity to visualize a list of points.

What I've got so far is creating a small Texture2D object and then trying to override the geometry:

static SpriteRenderer SpriteRendererFromPoints(SpriteRenderer spriteRenderer, List<Vector2> points) {
    var texture = Texture2D.whiteTexture;
    spriteRenderer.sprite = Sprite.Create(texture, new Rect(0.0f, 0.0f, texture.width, texture.height), new Vector2(0.5f, 0.5f));
    Sprite sprite = spriteRenderer.sprite;
    sprite.OverrideGeometry(points.ToArray<Vector2>(), sprite.triangles);
    return spriteRenderer;
}

I am adding this SpriteRenderer and a PolygonCollider2D to my gameobject and the instantiate it like this:

    GameObject meshObject = new GameObject();

    PolygonCollider2D polygonCollider = meshObject.AddComponent<PolygonCollider2D>();
    PolygonCollider2DFromPoints(polygonCollider, points);

    SpriteRenderer spriteRenderer = meshObject.AddComponent<SpriteRenderer>();
    SpriteRendererFromPoints(spriteRenderer, (from point in points select new Vector2(point.x, point.y)).ToList<Vector2>());
    Instantiate(meshObject);

It all runs fine but when running this, the sprite is nowhere to be seen:

Any help as to what I'm missing here or alternative ways of accomplishing this would be much appreciated.


texts:
What's the best way to create a simple moving navmesh agent with animation? (e.g. a human enemy running to player)

I have run animation that moves the enemy

public void Run ()
{
    animator.SetFloat ("Speed", 1f);
}

but I am not sure how to combine it with navmesh.

In one tutorial I saw Standard Assets ThirdPersonController .Move(...) used for that, but I am not sure if I should use it for that purpose, as I understand it was intended only for player characters?

Or should I use animation that runs in place?


texts:
I'm doing a game in which i have a ball which is controlled by the keyboard and the goal is to get is out of a maze without touching the walls.

I've added my ball sprite to GroupSprite

vehicle = pygame.sprite.GroupSingle(Vehicle(70,470))

since at the time, i thought that was the right way of doing it. However, i found that all the interaction always goes with the sprite directlly not with the GroupSingle. So I end with constantly accessing the sprite throug the GroupSingle.sprite:

vehicle.sprite.desired_speed_up_down

Is there a reason why i shouldn't just remove 'GroupSingle' and define:

vehicle = Vehicle(70,470)


texts: Does a successful attempt count as an attempt?

texts:
I'm writing a video game and I'd like to know if I should include the "successful" attempt in the count of "total attempts".

For instance, in a clay shooting game, if the player needs four shots before they hit the target:

bullet one = miss
bullet two = miss
bullet three = miss
bullet four = hit

Does it equate to three attempts, or four attempts? What text do I need to write at the end of the round?

  You needed three attempts to hit the target!

or

  You needed four attempts to hit the target!


texts: Retreive 3d World Map coordinates from touch/click input with LIBGDX?

texts:
Problem: I am trying to create an RTS style interaction. I want to be able to click on the map and have characters move to the click location. I haven't been able to figure this out, even after reveiwing tutorials from the one and only xoppa and several other's inqueries on the same concept. Other's seem to be happy utilizing collision with a near or far plane or a basic collision shape. However, I have a map with variations in height. I can't tell if I'm not creating my complex collision shape correctly or I'm just making things more complicated than need be. The code I think is relevelvant is as follows.

A model is loaded from a G3DB scene in the exact same manner of xoppa loading a 3d scene tutorial. After loading, I call the following method in my ModelInstance class.

private Array<Mesh> modMesh = new Array<~>();
public void createShape() {
    modMesh = model.meshes;
}

When a user clicks the mouse or taps the touch screen, I call this method to check collision of the ray from the camera to presumably the part of the map we were trying to touch.

public Vector3 checkSelection(Ray ray) {
    Vector3 intersection = new Vector3();
    for(int i = 0; i < modMesh.size; i++) {
        mesh = modMesh.get(i);
        float[] v = new float[mesh.getNumIndices() * mesh.getNumVertices() * mesh.getVertexSize()];
        short[] ind = new short[(mesh.getNumIndices() * 6 - 6) * (mesh.getNumVertices() - 1)];
        Intersector.intersectRayTriangles(ray, mesh.getVertices(v), ind, mesh.getVertexSize(), intersection);
    }
    return intersection;
}

So, when I run this code, it returns Vector3 values. They seem to be off though. For instance, my camera is looking at point (0,0,0). If I click where (0,0,0) appears on the screen, it will return a value like (-14.56, -18, -85). I imagine I am not creating a proper collision shape for the map. Which again leads to my question. How do I obtain the collision coordinate on a 3D map with variations in height in LibGDX?

Side Note: My intersecting collisions with normal collision shapes work perfectly. This is the reason I'm assuming I am completely wrong in the way I create a collision shape for the map itself. Thank you in advance for any input and assistance offered.


texts: what is best iap unitypackage (Asset) for support google play+ amazon in unity 2019.1.9?

texts: I need a unitypackage easy and easy for In app purchasing in googleplay and amazon (for Android) Which unitypackage is best in unity 2019.1.9?


texts: Are SharpDX's ContextDirect2D methods different from XNA's SpriteBatch?

texts:
I'm migrating from XNA to SharpDX in Win8. I noticed this DrawBitmap call in one of the samples.

Is this different in some shape, way or form from XNA's SpriteBatch?


texts: .md5mesh - multiple meshes with smooth normals

texts:
I have a .md5mesh which contains multiple meshes and I want to calculate smooth normals. The normals are correct but they don't work with multiple meshes.

My first idea was to merge all meshes, then calculate the normals and then render them seperated again, but I'm afraid that something will go wrong with this.

I already tested merging the meshes with blender and it gives me correct normals, but breaks texturing because each mesh has it's own texture.

I need advice on what to do now.


texts: How to implement dynamic background music?

texts:
Assumption 1: As a game's story progresses, dynamic background music is often used to enhance the player's immersion.

Assumption 2: Background music is probably always streamed due to memory limitation and performance.

What do I need to consider when I'm checking the feasibility of having dynamic(ally changing, adapting) background music? For example when a boss enemy appears the game should not just replace the "wandering music" to "boss combat", it should rather somehow cross-fade the two music scores as it starts playing the new music.

Is it usually possible to stream multiple sounds in parallel? I'm using LibGDX, where -- as far as I'm aware -- only a single streaming music instance can be played at a time, so how can I have such music with this framework?

Do I suspect correctly if I also need to separate a dynamic music into parts like "intro", "loopable part", "loopable part near the climax", "outro", etc., and when a part ends have a music manager code decide which part should be (re)started?

I'm more interested in understanding the theory instead of the actual implementation of the code.


texts: How can I retain the soundtrack state across levels to have continuous play?

texts:
Suppose I have two levels. I want the same soundtrack to play on both of them.

At the moment I have an audio source in each level, playing the soundtrack. However, when you move from one level to the other, the soundtrack will of course restart over (because it's a different audio source).

How can I "resume" the soundtrack? Or rather, how can I retain the soundtrack state across levels to have continuous play?


texts: Technique for objects following each other in complete movement?

texts:
I'm wondering how objects follow each other where they move over the previous position of the object in front of them. When the leading object stops, all that are following should stop at their position. So how is this achieved?

Like so:

Edit:
What I want to achieve is that all the following objects "walk" the path the leading object in front is taking. All the other objects just move at the speed of the leading object ( this would be by passing the velocity vector to all the following objects). But how do I let all the objects move/pause over the path while maintaining their distance from each other as well.


texts: How to keep player in the center of the screen but let him move to the edge of the map without moving camera there?

texts: In my rpg-styled (top-down perspective) 2d game, I want my player to be at the center of the screen, while the entire world moves, giving the effect of player movement. I can make that, but my problem is at the edges of the game-world, I want the world to stop moving and the player to move.


texts: How should I structure an extensible asset loading system?

texts:
For a hobby game engine in Java, I want to code a simple but flexible asset/resource manager. Assets are sounds, images, animation, models, textures, et cetera. After a few hours of browsing and some code experiments I'm still not sure how to design this thing.

Specifically, I'm looking for how I can design the manager in a way so that it abstracts away how specific asset types are loaded and where assets are being loaded from. I would like to be able to support both file system and RDBMS storage without the rest of the program needing to know about it. Similarly, I would like to add an animation description asset (FPS, frames to render, reference to the sprite image, et cetera) that's XML. I should be able to write a class for this with the functionality to find and read an XML file and create and return an AnimationAsset class with that information. I'm looking for a data-driven design.

I can find a lot of information on what an asset manager should do, but not on how to do it. The generics involved seem to result in some form of cascading of classes, or some form of helper classes. However I haven't seen a clear example that didn't look like a personal hack, or a point of consensus.


texts: How do I convert from Cartesian to spherical coordinates?

texts: This seems like a fairly basic and common problem. Is there a builtin way to achieve it or do I have to write the algorithm on my own? If I do, how should it work?


texts: Effective Methods to utilize 3d Scanners to produce game development resources

texts:
Once upon a time I was quite passionate about game development.  About four years ago at the height of my game development aspirations, I was involved in a number of activities. I worked with a team of students at my college to build a game using XNA.  I wrote a basic cross platform 3d engine using OpenGL/GLUT, and I wrote a simple tank game for Android using OpenGL ES 2.0.

For better or worse, since that time I've been swept up in the winds of corporate profit, and for the past few years I've been mostly preoccupied with building corporate applications and websites and I've done very well by it.

Even so, I've been trying to build games on the side, and one of the major limiting factors has always been the acquisition of quality resources (models, textures, sprites, audio) to support the game itself.

Basically what I am trying to say is that given an individual whose greatest strength is the programming, and is mediocre at best at developing graphical and media assets, what do you think some techniques I could use in conjunction with a 3d scanner to help me produce realistic or at least decent 3d models and/or 2d renders of scanned objects?

The catalyst for this thread is that I recently came across a kickstarter for a relatively affordable high quality scanner called 'Robocular'.  Aside from being excited about the project as a huge nerd, I am quite frankly intrigued by the possibilities introduced by having the ability to cheaply manipulate a medium and subsequently scan it as a model.  Although a device like this seems most suited to scanning terrain assets, I can't help but wonder whether it may be feasible to utilize multiple scanner runs to produce model animations, or perhaps scan individual body parts and cobble them together, applying animations later by manipulating the pieces in Blender.  Or perhaps simply using a physical object as the initial base for the model manipulation.

Either way it seems way to potentially save a huge amount of time compared to how long it would have taken me to produce a model myself.  I know there are a lot of free or affordable resource packs online, but one problem I've always had with them is that they don't necessarily combine with each other well.  I.E.  That cheap pack of humanoid models just doesn't quite work with the vehicle pack I purchased, or the free weapon pack I found, etc.  It's often the case that the art style or level of detail from one pack to another just doesn't match up... But like I said I haven't been very active in the game dev scene for a while, so I'm not sure if a 3d scanner is necessarily going to provide as much of a shortcut as simply purchasing model packs...

It's just that the concept is so cool and open ended that it's difficult not to be excited about it.

Basically I was hoping to spark a discussion on the practical applications of such a tool.  Given the high precision of the scanner and the fact that it supports color, it seems like you could do a lot with it.

Some of the initial ideas I had are:

Play Doh or clay + Paint
Wooden models + Paint
Soap models + Paint
Construction Paper or paper mache' + glue/tape
Purchasing toys as base models, then augmenting the toy with clay or play doh to produce something unique
Casting objects in wax, then carving details in the wax shape

I'm confident that some of these techniques could be significantly faster than using the actual 3d modeling tools, at least to start off.  Anyone have some killer ideas on how to utilize a 3d scanner to create assets?


texts: Is Kip R. Irvine's claim of Assembly being practical for game development accurate?

texts:
Kip R. Irvine's book, Assembly Language for x86 Processors, sixth edition, begins by comparing the Assembly language against high-level languages. One of the pros for Assembly, was game development:

  Game programmers are experts at writing code that takes full advantage
  of hardware features in a target system. They use assembly language
  as their tool of choice because it permits direct access to computer
  hardware, and code can be hand optimized for speed.

Whereas a high-level language:

  Produces too much executable code, and may not run efficiently.

This caught my attention. While I do realize that Assembly can optimize your programs, perhaps even significantly, I wonder if, at this point, it is at all practical?

My skepticism comes from:

Assembly seems to be difficult to maintain.
High-level languages aren't so slow.
I'm pretty sure that we have a handful of cutting-edge games based solely on high-level languages.
A particular interest in game development is to make your product cross-platform. I can only think of this as a significant obstacle for anyone using Assembly.
How much is "too much" executable code? I'm not entirely sure how reliable can this measure be.

Even if he meant to use Assembly for specific portions of your game, it still seems (to me) somewhat unpractical.

I'm not particularly advanced in Assembly, so I'm not sure. Are these claims accurate?


texts: Unity: Game objects in scene load incrementally and not at the same time

texts:
I am using Unity in my Android app. When the app opens, I show the user data in the Unity scene. User data contains texts and images.

In order to load this data in the scene, I make a lot of
UnityPlayer.UnitySendMessage(GameObject,Function,Params)
calls to many C# scripts in Unity from Android. Each of these calls performs a specific task like loading an image, creating a text, applying the text font etc.

Problem is that the loading of this data right now looks incremental (if that's the right word). So the text is visible first and after a fraction of a second the image shows. Some text effects show later. This looks ugly.

How can I make all the UI elements load at the same time even if it takes some time? Is there a way to freeze the scene before each game object is ready to be drawn?


texts: How to do collision resolution with 2d rectangles?

texts:
I am trying to create a basic side scroll 2D game. There are lots of documentation on collision detection but I find the easiest to use at the moment is just basic AABB Collision. This is my basic outline
Rect old_position = player->rect;
if(key == a) {
    player.x += 5; // move 5 px to right
}
if ... // same for up and left

if(key == s) {
    player.y += 5; // move 5 px down
}

player.y += 4; // move player down, gravity

if(collision_detection(player->rect, rectangle->rect)) { // rect = {x pos, y pos, w idth h eight}
    if(player->rect.y - old_position.y > 0) {
        player->rect.y = rectangle->rect.y - player->rect.h; // if player moved down and collided, move the player to the same pos as object + its own height to get directly above the object.
    } else if(player->rect.y - old_position.y < 0) {
        player->rect.y = rectangle->rect.y + rectangle->rect.h; // move to directly under collided object.
    }
     ...
}

this does not work since if I come from the side, falling down, I get teleported up above the object! There are people who write about things such as roleback / moving back before the collision happened, etc. but there is not straight forward way of doing collision resolution. When I try different methods they might work but I always slide into them if I walk straight into a wall or if I jump and move into a wall in the air while jumping I glitch inside the rectangle, etc, etc.
Does anyone have a blueprint for different 2D collision resolution? I am curious what types there are and what pros and cons there is. The above code is just sample dummy code, so there is no need to critique it. Thanks!


texts:
I'm writing a game engine using OpenGL 4.3 using gcc 5, mainly to teach myself graphics programming.

Initial development was on my Surface Pro 3 using mingw-w64 and worked like a charm.

I've decided to move to my desktop, which is running two GTX 670s, and both Windows and Arch Linux. I've made sure that I have the latest NVIDIA drivers installed on both operating systems, but am having issues with my vertex and fragment shaders. All I know is that neither system compiles the shaders, but the OpenGL Reference Compiler simply issues a warning saying that OpenGL 4.3 might not be fully implemented. I've also tried downgrading all the way to OpenGL 4.0, but this doesn't seem to fix the issue.

Below are the shaders that I'm currently trying out. Hoping someone more experienced than I can lend a hand?

shader.vert:

#version 430

layout (location = 0) in vec3 vertex_position;
layout (location = 1) in vec2 vt;

uniform mat4 cam_view, cam_proj, sprite_matrix;

out vec2 texture_coordinates;

void main()
{
   texture_coordinates = vt;
   gl_Position = cam_proj * cam_view * sprite_matrix * vec4(vertex_position, 1.0);
}

shader.frag:

#version 430

in vec2 texture_coordinates;
layout (binding = 0) uniform sampler2D tex;

out vec4 frag_colour;

void main()
{
   vec4 texel = texture(tex, texture_coordinates);
   frag_colour = texel;
}

Thanks in advance :)


texts:
I currently have islands that look like this:

And I want to procedurally subdivide it into regions, like this:

What algorithm does what I'm looking for? Do you have suggestions on how to create coherent regions like in the bottom picture. Your help is appreciated.


texts: Is there a simple way to draw only the tiles I need?

texts:
I am working on a platformer that is going to have a map that is randomly generated and infinite in 3 directions: left, right, and down.

I've figured out that I will need to separate this world into chunks, as otherwise it will be impossible to pull off. Each chunk currently consists of 512x512 tiles. (This may change in the future.) There will be set points on each chunk where the game will check whether or not a chunk exists in the direction the player is heading. If there isn't, one (or a few more) will be generated. If there is, it will be loaded into memory.

Now, my problem is, say I have a chunk and I am near the bottom left corner of it. If the camera moves diagonally down and to the left, I will be intersecting 3 additional chunks. Is my only option to calculate the tiles from each chunk and determine where they need to be drawn on screen? It seems like this will be a little nuisance of a problem to deal with. If this is the only way to do it, I guess I will have no choice but to tackle it, but I'm wondering if there's an alternative solution to this.


texts: What is a proper way to handle player inputs based on different states?

texts:
So, I have two ideas how to do that:

Use enum to define current state and check current state value before running certain method group in Update. Code:

void Update()
{switch(currentState){
    case 1:
        InputGroup1();
        break;
    case 2:
        InputGroup2();
        break;
    <...>
}

And so on. I don't think that this is a good idea because of possible performance drops.
Same concept about current state, but instead of checking it and running method groups, "head" script will check current state and activate corresponding script, disabling others. For me it looks like best way in terms of performance and usability.

And also, is it better to keep all input checks in one giant script/component and call functions you need from it? Essentially creating centralized Input Manager.


texts: Is std::deque the best option for storing my graphics objects?

texts:
I am currently implementing an object buffer, which stores all the objects used in the game at one place. All other components of the game, like the user interface, the level loader, etc, add objects to this buffer and then the objects are accessed by the rendering engine to render them all at once.

I need to store the graphics object in the object buffer contiguously in memory, so that  i can take advantage of cpu caching while rendering. I also need to have stable pointers to the objects stored in the buffer as they have to be editable by their pointers by the components that created them, like the user interface must be able to access the graphics it put into the buffer in response to mouse movement with a pointer to that graphic.

These are the reasons i could not use either std::lists, which are not contiguous, or std::vectors, which invalidate all pointers when they reallocate. One data container i found useful was the std::deque, which though doesn't have complete contiguity, does allow some and keeps pointers valid, but what i wanted to ask was is

is there any other data structure out there which is better at what i want?

As far as i understand deques, they are implemented as vectors of arrays of all definite sizes. Is there a data structure that is able to allocate arrays with increasing size, like vector does?


texts: Advantages and disadvantages of LWJGL for a beginner?

texts:
I am starting a 2D side scroller, tile based RPG sort of game in Java. I do have lots of knowledge in Java, so that's not a problem, but I have NO experience in game development, at all. I had found a couple of books / tutorials and I am trying to decide between using LWJGL or doing everything myself. What do you guys suggest?

Thanks!


texts: Does P2P Matchmaking can make an online game without any cost?

texts:
I’m planning on making an online game. I’ve used Unity (with Photon’s PUN2), but after some research, I had the idea of instead of using a server, with ccu limit and charge fees, i could make a P2P multiplayer game, so that way, the server would be one of the two players, without having any cost on me.
I don’t know If this is possible, and indeed, a good idea. I did a research on this but I couldn’t find a clear explanation or tutorial.
PS: It’s not a big game (2d game) think of it as the size of an online version of PONG, where two players fight until one wins, it could have or not a time limit.


texts: How to avoid the GameManager god object?

texts:
I just read an answer to a question about structuring game code. It made me wonder about the ubiquitous GameManager class, and how it often becomes an issue in a production environment. Let me describe this.

First, there's prototyping. Nobody cares about writing great code, we just try to get something running to see if the gameplay adds up.

Then there's a greenlight, and in an effort to clean things up, somebody writes a GameManager. Probably to hold a bunch of GameStates, maybe to store a few GameObjects, nothing big, really. A cute, little, manager.

In the peaceful realm of pre-production, the game is shaping up nicely. Coders have proper nights of sleep and plenty of ideas to architecture the thing with Great Design Patterns.

Then production starts and soon, of course, there is crunch time. Balanced diet is long gone, the bug tracker is cracking with issues, people are stressed and the game has to be released yesterday.

At that point, usually, the GameManager is a real big mess (to stay polite).

The reason for that is simple. After all, when writing a game, well... all the source code is actually here to manage the game. It's easy to just add this little extra feature or bugfix in the GameManager, where everything else is already stored anyway. When time becomes an issue, no way to write a separate class, or to split this giant manager into sub-managers.

Of course this is a classical anti-pattern: the god object. It's a bad thing, a pain to merge, a pain to maintain, a pain to understand, a pain to transform.

What would you suggest to prevent this from happening?

EDIT

I know it's tempting to blame the naming. Of course creating a GameManager class ain't such a great idea. But the same thing can happen to a clean GameApplication or GameStateMachine or GameSystem that ends up being the duct-tape-favorite by the end of a project. No matter the naming, you have that class somewhere in your game code, it's just an embryo for now: you just don't know yet what monster it will become. So I'm not expecting "blame the naming" answers. I want a way to prevent this from happening, a coding architure and/or a process a team can follow knowing that this will happen at some point in production. It's just too bad to throw away say, one month of bugfixes and last-minute features, just because all of them are now in one huge unmaintainable manager.


texts:
For my Maths unit at university, we have to manually calculate if a sphere is colliding with a capsule collider.

The information I have to go with is this;

You have the following Sphere:

LadyBird3 - CentrePoint = (0, 0, 0), Radius = 18.0

And the following capsule

Sanic - BottomPoint = (0,2,6), TopPoint = (0, 12, 6), Radius = 5.0

Determine if the following pair-wise collision occurs:

Sanic & LadyBird3

In our lecture, we are told the following;

NOTE: Normalizing at this step is unimportant

First, we are going to check the Dot Product of AC and AB

If this Dot Product is less than 0, that means the closest point from the line segment to C is A
So we can just return the squared length of AC and stop any further calculations
Now we perform the same test with the Dot Product of BA and BC
Once again, if the Dot Product is less than 0, B would be the closest point on the line segment to C, so we would just return the length of BC and stop any further calculations.

Projection...
If the dot product returned > 0 for both points of the line segment, we need to project C onto AB to get the distance.
There's an efficient way to get the squared distance if this is all we care about:

SquaredDistance = AC.LengthSq - (AC . AB) * (AC . AB) / AB.LengthSq
When performing the dot product here, we need to make sure that it is NOT normalized.

And the final step is to use this squared distance and compare it to the sum of both radii squared to determine if there is an intersection.

So, I'm trying to calculate if they are intersecting or not using the information from above.

All I've managed to come up with is this
(Taking away the LadyBird3 positions from Sanics position (TP, BP))

AC = (0, 2, 6)

AB = (0, -10, 0)

Dot Product = -20

BA = (0, 10, 0)

BC = (0, 12, 6)

Dot Product = 120

It feels like with the values I'm getting are not correct, or the process I'm doing is wrong... Is anyone able to point me in the right direction?


texts: Unity: What's the difference between SRP batching & GPU Instancing?

texts:
I've been researching a lot about Draw calls and how to reduce them, i'm using GPU Instancing and it's amazing, but i did not succeed in making SRP batching work.

What's the difference between the two and when to use which?

can we use them together?


texts: What concepts are there for interactive water?

texts:
I want water to be a gameplay object in my game. The player should be able to take in in a bucket and tip it out somewhere in the world. Water should flow in some way so that it can be used to build rivers and transport game objects or to create particular apparatuses. It's comparable to the game Minecraft where you can build cool things involving water or just create just some small waterfalls. However, there my game isn't made out of blocks so there is smooth terrain.

In most games water is simply placed at a given height. That works well for lakes and Oceans, but for flowing rivers and usage in apparatuses this concept is to limited. In Minecraft water is implemented as a block which spreads inside the blocky grid, too. That approach is a bit more what I need to realize my idea but I don't use these blocks and therefore such water simulation would look very misplaced.

What concepts of representing water which the player can interact with in the mentioned manners are there? How can I realize oceans, rivers, buckets and so on with one general approach? There shouldn't be an infinite amount of water. If you fill your bucket, the volume of the lake the water was taken from should decrease unnoticeable. Moreover if the player would place water somewhere that volume of water should never go missing.


texts: How can you procedurally place objects in a non-gridded game?

texts:
This is a follow-up question to this question. I mistakenly worded the question, but got a good answer before I could correct myself, so I didn't want to delete it. Sorry!

Now that I know that it is possible, I'd like to implement procedural world generation, but I don't want it to look gridded or blocky, where everything is obviously placed on an integer grid.

I know that you can do this in gridded worlds by inputting a square's x and y into a noise function, or similar, but how can I generate a more natural looking object placement using procedural methods?

This is in the context of an adventure game, if it matters.


texts: How can I modify the UV co-ordinates on a texture so they converge to a point?

texts:
I'm building a roof visualiser app, where someone can take a picture of their roof, define its outline, then visualise a new roof texture on it.

I'm generating a 3D plane that matches the roof outline points, but I'd like the 3D planes material's UV's to match the perspective of the existing roof (i.e the lines converge into the distance as they move away from the user.

Is this possible?

The alternative solution is to figure out how to rotate the generated 3D plane to match the roof outline points, while matching the perspective too, but I'm thinking this may be more complicated.

Step 1 - Define roof oultine with points

Step 2 - Texture 3D plane with UV's mapped to maintain roof perspective based on slant defined in the 4 points

Any tips on how to solve this?


texts: How to save and update modifications done by the player in my procedurally generated JavaScript game?

texts:
I am making a game and I need the world to be generated and saved. I used Perlin noise to generate the terrain (and other stuff like trees), but cannot figure out the best way to save and recall actions done by the player, e.i. if a tree is cut down or a mineshaft is used I want that entity to either be updated or deleted.

How could I accomplish this?

More info: I am making this in JavaScript and eventually want to implement Node.js to implement multiplayer features in the future. The player also has a very limited view and this is a 2D top down kind of game. I am also making this basically from scratch.

Any and all help is appreciated!


texts: How can I create the illusion of a 3D object moving around in a static background?

texts:
I'm designing a Resident Evil clone using OpenGL. I'm curious how the older Resident Evil games used a static pre-rendered background with 3D models roaming around:

(source: spong.com)
Here, if the main player (Claire) moved a few steps back, she will overlap with the pay phone booth. But if she keeps moving alongside the phone booths, she'll still be overlapping them until she is adjacent to the second phone booth.
Conceptually, how is this done and how can I replicate it? I'm not interested in the implementation technicalities on any particular platform. Just the concepts.


texts: Rotate model to face direction it's traveling in 3d with scenekit and swift - Boids implementation

texts:
I am implementing a boids simulation using Swift and Scenekit. Implementing the simulation itself has been fairly straight forward however I have been unable to make my models faces the direction they are flying (at least all the time and correctly) To see the full project, you can get it here (https://github.com/kingreza/Swift-Boids)

Here is a link to a video that shows the behavior I'm getting right now:
https://www.youtube.com/watch?v=9k07wxod3yI

Here is what I am doing to rotate the models to face the direction they are going:

func rotateShipToFaceForward(ship: Ship, positionToBe: SCNVector3)
  {
    var source = (ship.node.position - ship.velocity).normalized();

    // positionToBe is ship.node.position + ship.velocity which is assigned to ship.position at the end of this call
    var destination = (positionToBe - ship.node.position).normalized();

    var dot = source.dot(destination)

    var rotAngle = GLKMathDegreesToRadians(acos(dot));
    var rotAxis = source.cross(destination);

    rotAxis.normalize();

    var q = GLKQuaternionMakeWithAngleAndAxis(Float(rotAngle), Float(rotAxis.x), Float(rotAxis.y), Float(rotAxis.z))

    ship.node.rotation = SCNVector4(x: CGFloat(q.x), y: CGFloat(q.y), z: CGFloat(q.z), w: CGFloat(q.w))

}


texts: How to replace if/else/switch with polymorphisim

texts:
For a long time Robert Martin has been advising against if/else/switch branching logic and instead rely on the polymorphic behavior of different types. if/else/switch should only be used in the factory creating the types with different behaviours. He describes the approach in a recent blog post. I feel I understand the thrust of his argument as applied in his example situation and I really like the concept as it pushes decision making to a single location, DRY & OCP.
However, I'm finding it difficult to apply the principle is some basic game dev situations.
e.g. consider this pseudo-code controlling a ball bouncing around a box (think 'Breakout')
void ball::update(){
  if(collideswith(leftWall))
    velocity.x= +speed;
  else if(collideswith(rightWall))
    velocity.x = -speed;
  else if(collideswith(topWall))
    velocity.y = -speed;
  else if(collideswith(bottomWall))
    velocity.x = +speed;
}

I am unsure what kind of polymorphic class I could build to replace the branching logic here.
Replacing the above code with an Uncle Bob solution might be over-engineering, but am interested in learning more about applying the principle in these kinds of contexts.


texts:
I'm new in DirectX and I'm making a 2D game.
I want to use a particle system to simulate a 3D starfield, so each star has to set its own constant buffer for the vertexshader es. to set it's world matrix.
So if i have 500 stars (that move every frame) i need to call 500 times VSsetconstantbuffer, and map/unmap each buffer.
with 500 stars i have an average of 220 fps and that's quite good.
My bottelneck is Vs/PsSetconstantbuffer.
If i dont call  this function i have 400 fps(obliviously nothing is display, since i dont set the position of the stars).
So is there a method to speed up the render of the particle system??

Ps.
I'm using intel integrate graphic (hd 2000-3000). with a nvidia (or amd) gpu will i have the same bottleneck??
If, for example, i dont call setshaderresource i have 10-20 fps more (for 500 objcets), that is not 180.Why does SetConstantBuffer take so long??

LPVOID VSdataPtr = VSmappedResource.pData;
memcpy(VSdataPtr, VSdata, CszVSdata);
context->Unmap(VertexBuffer, 0);

result = context->Map(PixelBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &PSmappedResource);
if (FAILED(result))
{
    outputResult.OutputErrorMessage(TITLE, L"Cannot map the PixelBuffer", &result, OUTPUT_ERROR_FILE);
    return;
}
LPVOID PSdataPtr = PSmappedResource.pData;
memcpy(PSdataPtr, PSdata, CszPSdata);
context->Unmap(PixelBuffer, 0);

context->VSSetConstantBuffers(0, 1, &VertexBuffer);
context->PSSetConstantBuffers(0, 1, &PixelBuffer);

this update and set the buffer.
It's part of the render method of a sprite class that contains a the vertex buffer and the texture to apply to the quads(it's a 2d game) too.
I have an array of 500 stars (sprite setup with a star texture).
Every frame:
      clear back buffer;
      draw the array of stars;
      present the backbuffer;

draw also call the function update( which calculate the position of the sprite on screen based on a "camera class")

Ok, create a vertex buffer with the vertices of each quads(stars) seems to be good, since the stars don't change their "virtual" position; so....
In a particle system (where particles move) it's better to have all the object in only one vertices array, rather then an array of different sprite/object in order to update all the vertices' position with a single setbuffer call.
In this case i have to use a dynamic vertex buffer with the vertices positions like this:

verticesForQuad={{ XMFLOAT3((float)halfDImensions.x-1+pos.x, (float)halfDImensions.y-1+pos.y, 1.0f), XMFLOAT2(1.0f, 0.0f) },
    { XMFLOAT3((float)halfDImensions.x-1+pos.x, -(float)halfDImensions.y-1+pos.y, 1.0f), XMFLOAT2(1.0f, 1.0f) },
    { XMFLOAT3(-(float)halfDImensions.x-1+pos.x, (float)halfDImensions.y-1.pos.y, 1.0f), XMFLOAT2(0.0f, 0.0f) },
    { XMFLOAT3(-(float)halfDImensions.x-1.pos.x, -(float)halfDImensions.y-1+pos.y, 1.0f), XMFLOAT2(0.0f, 1.0f) },

....other quads}

where halfDimensions is the halfsize in pixel of a texture and pos the virtual position of a star.
than create an array of verticesForQuad and create the vertex buffer

ZeroMemory(&vertexDesc, sizeof(vertexDesc));
vertexDesc.Usage =      D3D11_USAGE_DEFAULT;
vertexDesc.BindFlags =  D3D11_BIND_VERTEX_BUFFER;
vertexDesc.ByteWidth =  sizeof(VertexType)* 4*numStars;

ZeroMemory(&resourceData, sizeof(resourceData));
resourceData.pSysMem =  verticesForQuad;

result = device->CreateBuffer(&vertexDesc, &resourceData, &CvertexBuffer);

and
call each frame Context->IASetVertexBuffers(0, 1, &CvertexBuffer, &stride, &offset);

But if i want to add and remove obj i have to recreate the buffer each time, havent i??
There is a faster way? I think i can create a vertex buffer with a max size (es. 10000 objs) and when i update it set only the 250 position (for 250 onjs for example) and pass this number as the vertexCount to the draw function (numObjs*4), or i'm worng