texts: How do I render a PNG with transparency in LibGDX?

texts:
I'm building a simple tic-tac-toe example with LibGDX. I have simple images: cross, circle and board, all pngs created with GIMP with a transparent background.

How can I render them as a Texture with transparency?

I've tried with GL10 enable feature, but it seems not to work.


texts: Clipping Sprite Sheets with Variable Placement

texts:
I was looking at some sprite sheets at sprite sheet database. I noticed that some of the sprite sheets had several different objects placed together in one file. Some of the sprites, such as movement animations were placed next to each other so that they were of the same height. However, sometimes next to them are larger sprite objects that take up a different amount of space.

These sprite sheets have no apparent information such as cell width and height. It seems like you would have to clip them through trial and error. Is there some sort of algorithm to figure out how to clip them without external sprite grid information?

http://sdb.drshnaps.com/display.php?object=7604


texts:
I understand that a 4x4 matrix holds rotation and position data.

The rotation data is held in the 3x3 sub-matrix at the top left of the matrix.

The position data is held in the last column of the matrix.

e.g.

glm::vec3 vParentPos(
    mParent[3][0],
    mParent[3][1],
    mParent[3][2]
);

My question is - am I accessing the parent matrix correctly in the example above?  I know that opengl uses a different matrix ordering that directx, (row order instead of column order or something), so, should the mParent be accessed as follows instead?

glm::vec3 vParentPos(
    mParent[0][3],
    mParent[1][3],
    mParent[2][3]
);

thanks!


texts: Is Apple Game Center Multiplayer Online?

texts:
I'm trying to build a real-time multiplayer game on Unity. I was thinking of using services such as PUN or UNet, but then I ran into Game Center's multiplayer API.

I've read that Apple doesn't give servers and only provides matchmaking services. Is that true? How does that work? Would I still need PUN/UNet with Game Center?

I guess what I'm trying to ask is, will Apple host my game's multiplayer instance, where position of players is synced across, and replace PUN/UNet?

Any help is appreciated. Thank you. Also, if you can provide a source with your answer, that'd be great.


texts: Why is my model flickering when translating

texts:
I have several models here. When they stand still during gameTime, there's no flickering.
But as soon as I move them across the x-axis, they flicker on some places.

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

    Matrix[] transforms = new Matrix[myModel.Bones.Count];
    myModel.CopyAbsoluteBoneTransformsTo(transforms);

    foreach (ModelMesh mesh in myModel.Meshes)
    {
        foreach (BasicEffect effect in mesh.Effects)
        {
            effect.EnableDefaultLighting();
            effect.World = transforms[mesh.ParentBone.Index] *
                Matrix.CreateRotationY(modelRotation)
                * Matrix.CreateTranslation(modelPosition);
            effect.View = Matrix.CreateLookAt(cameraPosition,
                Vector3.Zero, Vector3.Up);
            effect.Projection = Matrix.CreatePerspectiveFieldOfView(
                MathHelper.ToRadians(45.0f), aspectRatio,
                1.0f, 10000.0f);
        }
        mesh.Draw();
    }
    base.Draw(gameTime);
}

Why is that happening and what could I do to prevent it?


texts: A cool way of doing Z-index for XNA components?

texts:
I am trying to render some elements in my game. First, I render the textures (the textures of the textboxes themselves etc). Then I render the primitives (borders around controls etc). Then I render the text.

However, by doing so, this gives a weird result in my user-interface when showing tooltips (by hovering over a textfield), as seen in the screenshot below.

Due to the order of drawing, borders around the window are drawn after textures, which (for the tooltip that appears when my mouse is over the textfield) makes it look weird.


texts: Find the largest empty space inside a cube populated with a point cloud?

texts:
Lets say we have a set of points (x, y, z) where we know 0 < x < 1 (same for y and z).
Now that 3d space is populated with monsters, players or what not. The points represent their location. We want to find the largest vacant 3d space. What would be an effective algorithm to find, let's say, the k largest disjoint empty boxes inside that space?

I was thinking of using Voronoi Diagram and measuring the space near each seed (the points being the seeds) and looking for pairs of neighbors that have a large space.


texts: How is AI most commonly implemented in popular games?

texts:
I'm no gamedev, I'm just a curious coder of not-games. I wonder, how does AI work in popular modern games, say, FPSs? Is it based on hard-coded rules? How much does it have in common with other kinds of AI (like the one which powers autonomous cars etc)? How do developers ensure the AI behaves naturally and is fun to play against?

Stuff I've googled mentioned different derivatives of MinMax but failed to answer how AI deals with continuous, changeable world, for what actions/states AI is rewarded and how it figures out its chance for success of different actions. I've also seen Machine Learning mentioned here and there but it seems it's not used in any serious game?


texts:
I am currently working on a cube engine and am experiencing some issues with CPU optimization.

I store all my quad VBO data inside a Block (at x,y,z of a chunk) class, which is stored inside an array with a length of 6 (the maximum number of cube faces). I would prefer to merge it all inside one VBO. The only issue I am having with this is that I cannot find a way to render 6 different textures on each face.

    GL11.glPushMatrix();
    GL11.glTranslatef(LENGTH.x * origin.x, LENGTH.y * origin.y, LENGTH.z * origin.z);
    for (int z = 0; z < LENGTH.z; z++) {
        for (int y = 0; y < LENGTH.y; y++) {
            for (int x = 0; x < LENGTH.x; x++) {
                Block b = get(x, y, z);
                if (b.getBlockType().isTransparent() || b.getVisibleFaces() == 0)
                    continue;
                GL11.glEnableClientState(GL11.GL_VERTEX_ARRAY);
                GL11.glEnableClientState(GL11.GL_TEXTURE_COORD_ARRAY);
                for (int i=0; i < b.getVertexBuffers().length; i++) {
                    QuadVBO q = b.getVertexBuffers()[i];
                    if (q == null || !q.isValid())
                        continue;
                    Game.GRASS.bind(i);
                    GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, QuadVBO.faceHandles[i].get(0));
                    GL11.glTexCoordPointer(2, GL11.GL_FLOAT, 0, 0);
                    GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, q.getVertexHandle());
                    GL11.glVertexPointer(3, GL11.GL_FLOAT, 0, 0);
                    GL11.glNormalPointer(GL11.GL_FLOAT, 0, q.getPointerVerticesBytes());
                    GL11.glDrawArrays(GL11.GL_QUADS, 0, q.getVerticesCount());
                    GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
                }
                GL11.glDisableClientState(GL11.GL_VERTEX_ARRAY);
                GL11.glDisableClientState(GL11.GL_TEXTURE_COORD_ARRAY);
            }
        }
    }
    GL11.glPopMatrix();

I am aware that this is a horrible way to do it but I cannot seem to find a better way to render these cubes on a screen, any help would be extremely appreciated!


texts: How to compute a heightmap and use as 3d voxel floating point

texts:
When you want to compute a heightmap and use for 3d voxel binary, it's easy.

solid are maybe 1, and air are 0, easy.

But in my case I would like to have a smooth terrain, so the solution is the floating point value. But now I cannot say "Hey, it's 1 so it's solid !" because when I use 1 or -1 with a threshold to 0. It's will work, sure, but look like blocky, not smooth.

When you compute a 3d noise, it's easy you just have to set the computed value (scaled from -1 to 1, threshold to 0). It's will look nice. But for 2d noise...

Let's say, 0 is the minHeight and 500 maxHeight. The 2d noise function is scaled between 0 and 1.

At x:0, y:0, let's say the final value of the height is 250, that the middle. (noise output 0.5 scaled from 0/1 to 0/500)

But for each height, what I am supposed to set ? In binary case, solid are 1, air 0. But in floating point case, what should be the value ?

I tried to apply the noise result (0 to 1), and where y > computedHeight (computedHeight=250) the value is -1.

It's look blocky (That normal) but I don't have the right solution.

So what I am supposed to set to each y voxel ?

Ok my question look confusing, sorry for that.

I can easily get a smooth terrain based on heightmap value. Here is a screenshot.

As you can see, when I combine it with 3d layer, there is a problem, cave is blocky.

Why this problem, I guess it because the cave value are between -1 to 0, nice. But the ground layer that computeNoise*maxHeight-y which give nice result but the value is wrong ! And I'm looking for a better way to compute the heightmap (ground layer) to have correct value and get a smooth cave. :)

Here is my pseudo code of how I generate my voxel array.

for (var x = 0; x < sizeXz + 1; x++) {
    for (var z = 0; z < sizeXz + 1; z++) {
        var compute = Biome.ComputeXz(voxelX, voxelZ);
        for (var y = 0; y < sizeY + 1; y++) {
            data[x, y, z] = Biome.GetY(compute, voxelX, voxelY, voxelZ);
        }
    }
}

Then

public ... GetY(...){
    var computedHeight = Scale(compute.value, 0, maxHeight, 0, 1); //Scale noise 0-1 to 0-MaxHeight
    var currentValue = computedHeight-pos.y;
    var currentType = BlockType.Rock;
    if(pos.y > computedHeight)
        currentType = BlockType.Air;
    return new Block(currentType, currentValue);
}

This work, this look nice (see ground layer image), but the value are wrong because if you lower, you'll get some value like -82.28389, because of the -y to the currentValue which means further you are from the threshold further from 0 the value will be.

And the cave layer which is a raw output from the noise function (so a value between -1 and 1).

As you know Marching cube do a interpolation between each voxel so I let you imagine why the result is so blocky between the cave which output value like 0.0x and ground output like xx.x

Sorry for the long post.


texts:
I've been looking for articles or tutorials on this and I can't seem to find any, so I thought I'd ask here. I've created a bullet class in my game that is added and removed through a list. If I'm going to make these bullets work the way I want them to I need to be able to do two things:

One, I need to check if the bullets are colliding with each other and then remove the two bullets that are colliding. I've tried doing it by updating the bullet list with a for statement and then checking for collision with another for statement, but that occasionally crashes the game.

Two, I need to be able to check how far away every other bullet in the list is from the current one.

So how can I go about doing this?


texts:
I have a non-released game, and currently it's only possible to play with another human being. As the game rules are made up by me, I think it would be great if new players could learn basic game play by playing against an AI opponent. I mean it's not like Tennis, where the majority knows at least the fundamental rules.

On the other hand, I'm a bit concerned that this AI implementation can be quite complex. I hope you can help me with an complexity estimation. I've tried to summarize the gameplay below. Is this defense AI very hard to do?

Basic Defense Game Play

Player Defender can move within his land, i.e. inside a random, non-convex, polygon. This land will also contain obstacles modeled as polygons, that Defender has to move around. Player Attacker has also a land, modeled as another such polygon.

Assume that Defender shall defend against Attacker. Attacker will then throw a thingy towards Defender's land. To be rewarded, Attacker wants to hit Defender's land, and Defender will want to strike away the thingy from his land before it stops to prevent Attacker from scoring.

To feint Defender, Attacker might run around within his land before the throw, and based on these attacker movements Defender shall then continuously move to the best defense position within his land.


texts: How can I make the player(transform) to rotate once each time the player exist the collider and to rotate him slowly smooth?

texts:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerSpaceshipAreaColliding : MonoBehaviour
{
    private float timeElapsed = 0;
    private float lerpDuration = 3;
    private float startValue = 1;
    private float endValue = 0;
    private float valueToLerp = 0;
    private Animator playerAnimator;
    private bool exitSpaceShipSurroundingArea = false;

    // Start is called before the first frame update
    void Start()
    {
        playerAnimator = GetComponent<Animator>();
    }

    // Update is called once per frame
    void Update()
    {
        if (exitSpaceShipSurroundingArea)
        {
            SlowDown();

            if (playerAnimator.GetFloat("Forward") == 0)
            {
                transform.rotation = Quaternion.Inverse(transform.rotation);
            }
        }
    }

    private void OnTriggerEnter(Collider other)
    {
        if (other.name == "CrashLandedShipUpDown")
        {
            exitSpaceShipSurroundingArea = false;
            Debug.Log("Entered Spaceship Area !");
        }
    }

    private void OnTriggerExit(Collider other)
    {
        if (other.name == "CrashLandedShipUpDown")
        {
            exitSpaceShipSurroundingArea = true;
            Debug.Log("Exited Spaceship Area !");
        }
    }

    private void SlowDown()
    {
        if (timeElapsed < lerpDuration)
        {
            valueToLerp = Mathf.Lerp(startValue, endValue, timeElapsed / lerpDuration);
            playerAnimator.SetFloat("Forward", valueToLerp);
            timeElapsed += Time.deltaTime;
        }
        playerAnimator.SetFloat("Forward", valueToLerp);

        valueToLerp = 0;
    }
}

When the player exit the collider area he slow down then stop. at this point I want the player to start rotating and start moving back inside the colliding area.
The exit and the slow down are working but the rotation is not working and not sure how to make him start moving again slowly to max speed when entering back.
The main goal is to prevent the player to leave the marked colliding area with some slow down and rotation.
For the rotation I did :
transform.rotation = Quaternion.Inverse(transform.rotation);

but it keep rotating non stop and not slowly smooth like using Lerp.


texts:
I use Unity 5 and I have an issue with my game, when I click on the Pause button my character jumps before the game is paused. My script detects the click for jump before the pause button so for that I add gameObject.tag but doesn't work:

void Update () {
    if (Input.GetKeyDown (KeyCode.Space) && Time.timeScale == 1 || Input.GetMouseButtonDown (0) && Time.timeScale == 1 && gameObject.tag != "Pause") {
        GetComponent<Rigidbody2D> ().AddForce (Vector2.up * force);
    }

http://makeagif.com/i/bmCKQ3:

Look when I click on the pause button it jumps and pauses directly.
How can I click on the Pause button without making my player jump?


texts: Issue whith transparent textures when loading a prefab in Unity

texts:
I'm trying to implement Asset Bundles in my Unity game.

I used to instantiate a prefab with Instantiate<GameObject>(gameRootPrefab), which worked fine.

Now this prefab is in a Asset Bundle, so I'm loading this Asset Bundle with AssetBundle.LoadFromFile(), and get the prefab to instantiate with LoadAsset<GameObject>(prefabName). I instantiate the prefab the same way as before.

However, I'm now getting an issue with some transparent textures:

This white square is supposed to be a texture with some transparent parts.
I tried tweaking the material and the texture associated to this GameObject, but I'm still getting the same result. Here's the material and texture:


texts: Algorithm for texture blending modification

texts:
Im currently writing a terrain editor for my game (for the record: no commercial intentions) and after having implemented the terrain morphing to my liking im now working on the texturing of said terrain. One chunk of terrain can consist of up to 4 different layers of textures which are blended together using a 4-byte rgba texture with alpha values. The alpha values are 0-255 and together add up to 255, so the blending on the gpu happens like this:

float4 finalColor = color0 * alpha.r + color1 * alpha.g + color2 * alpha.b + color3 * alpha.a;

In a first approach ive been doing very simple modification of that blending (pseudocode):

selectedLayer.alpha += amount;
allOtherLayers.alpha -= (amount / numOtherLayers);

This doesnt work all too bad but it creates a lot of artifacts or sharp lines between chunks. Here is an example image:

Now im looking for different, better algorithms. The brush currently consists of an inner and an outer radius (as seen in the image). Inside the inner radius no interpolation depending on the distance to the center happens, between inner and outer radius linear interpolation between the pressure on the inside and 0 is created.

I hope my question is clear enough, please leave a comment if there has to be more information. Thank you in advance.


texts: Direct3D11 + Assimp imported model corrupted/failed

texts:
I use Assimp library to import vertex and index data from model file.

I don't know how to correctly create index buffer from mFaces array of aiMesh. Or something wrong, because i my model is incorrect.

I have already experienced successful mesh rendering, if verticies and indicies are defined manually in code (x5 vertices triangle and indicies).

Here is my code.

// Loading TRIANGULATED vertex/index buffers:

// Load verticies:
m_uVertexCount = pMesh->mNumVertices;
CBasicEffect::sVertex * verticies = new CBasicEffect::sVertex[m_uVertexCount];
for(UINT i = 0; i < m_uVertexCount; i++)
{
    CBasicEffect::sVertex v;
    v.Pos = Vector3FromAi(pMesh->mVertices[i]);
    v.Color = XMFLOAT4(1,1,0,1);//test
    verticies[i] = v;
}

D3D11_BUFFER_DESC bd;
ZeroMemory( &bd, sizeof(bd) );
D3D11_SUBRESOURCE_DATA InitData;

// Create vertex buffer:
bd.Usage = D3D11_USAGE_DEFAULT;
bd.ByteWidth = sizeof( CBasicEffect::sVertex ) * m_uVertexCount;
bd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
bd.CPUAccessFlags = 0;
InitData.pSysMem = verticies;
if( FAILED(pModelOf->GetDevice()->GetDevice()->CreateBuffer(&bd, &InitData, &m_pVertexBuffer)) )
    ;//...

// Load indicies:
m_uIndexCount = pMesh->mNumFaces * 3;
UINT* indices = new UINT[m_uIndexCount];
for (UINT face = 0; face < pMesh->mNumFaces; face++)
    for (UINT idx = 0; idx < 3; idx++)
        *indices++ = pMesh->mFaces[face].mIndices[idx];

// Create index buffer:
bd.Usage = D3D11_USAGE_DEFAULT;
bd.ByteWidth = sizeof( UINT ) * m_uIndexCount;
bd.BindFlags = D3D11_BIND_INDEX_BUFFER;
bd.CPUAccessFlags = 0;
InitData.pSysMem = &indices;
if( FAILED(pModelOf->GetDevice()->GetDevice()->CreateBuffer(&bd, &InitData, &m_pIndexBuffer)) )
    ;//...

UPDATE: Now i see my model. But it is loaded incorrecty: http://i.stack.imgur.com/Z9liR.jpg (originally it is scene with 5 primitives).

My render code:

// <Clean render target view and depth stencil view>

ID3D11Buffer* pVertexBuffer = pMesh->GetVerticiesBuffer();
    ID3D11Buffer* pIndexBuffer = pMesh->GetIndexesBuffer();

    // Set buffers and topology mode
    UINT stride = sizeof( sVertex ), offset = 0;
    m_pDevice->GetContext()->IASetVertexBuffers( 0, 1, &pVertexBuffer, &stride, &offset );
    m_pDevice->GetContext()->IASetIndexBuffer(pIndexBuffer, DXGI_FORMAT_R32_UINT, 0);
    m_pDevice->GetContext()->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST );

    // Shaders:
    m_pDevice->GetContext()->IASetInputLayout( m_pVertexLayout );
    m_pDevice->GetContext()->VSSetShader( m_pVertexShader, NULL, 0 );
    m_pDevice->GetContext()->VSSetConstantBuffers( 0, 1, &m_pConstantBuffer );
    m_pDevice->GetContext()->PSSetShader( m_pPixelShader, NULL, 0 );
    //m_pDevice->GetContext()->PSSetConstantBuffers( 0, 1, &m_pConstantBuffer );

    // Draw:
    //m_pDevice->GetContext()->Draw( pMesh->GetVertexCount(), 0 );
    m_pDevice->GetContext()->DrawIndexed( pMesh->GetIndexCount(), 0, 0 );

//


texts: Can I have a fixed-angle sprite with a non-fixed-angle CircleCollider2D?

texts:
In Unity2D, can I have a fixed-angle sprite with a non-fixed-angle CircleCollider2D?

I would like to move my character using the circle physics (without fixed-angle), but display him always as if he wasn't rotated (as if he had fixed-angle).

I thought I could just let the collider rotate, and then rotate-back the sprite in the LateUpdate, however since the collider's center isn't 0,0, it "rotates sideway" and doesn't end up in the "original" position.

My knowledge on matrices and quaterions is null, and trigonometry is only slightly above zero, so I'm a bit at a loss... how can I achieve the desired effect?

In order to prevent a X/Y problem, I want to do that since with box colliders sometimes the characters got stuck: if a platform had even just 1 pixel step, the character couldn't walk over it. Also, slopes were a big problem. Changing the collider to a Circle was the obvious consequence; I also tried to detect and add a small vertical speed but it didn't work very well and was becoming a mess.


texts: How do I manually accelerate the rotation of a sphere in Unity 3D?

texts:
I'm a little new to this so any help will be appreciated.

Context:
I'm creating a VR billiard/pool game and trying to get the physics as realistic as possible. I have a cue ball being hit with a cue across a surface with accurate friction values calculated from real world trials.

Problem:
The angular acceleration of the balls isn't realistic at all. Therefore the angular velocity is off (this is due to how Unity calculates physics of interaction as a point of contact rather than an area of contact and therefore friction calculation is done at one point causing it to rotate slower).

Question:
How can I manually set the angular acceleration to a value in code until the angular acceleration is greater than or equals to horizontal velocity, then the angular acceleration is set to 0? Thanks in advance.


texts: Box2dWeb positioning relative to HTML5 Canvas

texts: I'm new with HTML5 canvas and Box2DWeb and I'm trying to make an Asteroids game. So far I think I'm doing okay, but one thing I'm struggling to comprehend is how positioning works in relation to the canvas. I understand that Box2DWeb is only made to deal with physical simulation, but I don't know how to deal with positioning on the canvas. The canvas is 100% viewport and thus can vary size. I want to fill the screen with some asteroids, but if I hardcore certain values such as bodyDef.position.x = Math.random() * 50; the asteroid may appear off canvas for someone with a smaller screen? Can anybody help me understand how I can deal with relative positioning on the canvas?


texts: How to optimize Floor Meshes with different material in unity

texts:
I have several meshes (floor tiles) that consist of unique materials as they have different textures. I see that it is taking too many batches and it has around 100m vertexes.
Is there any way to improve it through programming? The long way, it should be ported to 3d modeling and combine.
I also see the mesh combine but it requires the same material.
Edit:

Around 17k Floor tiles (LoD 9) with details
around 5 or 6 large tiles (Floor LoD 7) with fewer details that are placed beneath the LoD 9 tiles
lod9 tiles are display-based camera culling otherwise LoD7 floor shows all the time.

Here are some of the screenshots:
Lod 7 Tile example (there total 16 tiles)


texts: How to load a terrain of connected caves into bullet-phisics engine?

texts:
I have a terrain that can not be represented as height map. Say a mountain with caves. I  have it in one large .obj file. How do I load such a terrain into bullet-phisics engine?

Or I shall generate height map, load it as a terrain and then load my caves as a seprate obj file somehow cutting it out from generated terrain?


texts: How can I locate empty space next to polygon regions?

texts:
Let's say I have the following area in a top-down map:

The circle is the player, the black square is an obstacle, and the grey polygons with red borders are walk-able areas that will be used as a navigation mesh for enemies.  Obstacles and grey polygons are always convex.

The grey regions were defined using an algorithm when the world was generated at runtime.

Notice the little white column.  I need to figure out where any empty space like this is, if at all, after the algorithm builds the grey regions, so that I can fill the space with another region.

Basically what I'm hoping for is an algorithm that can detect empty space next to a polygon.


texts:
I have a lot of spritesheets that are poorly formatted that I want to decompose, or split out into many small images, one for each sprite.
If I can do that, I can use my custom texture packer tool to build my game assets with.

My development tools are XNA and C# targetting Windows.
How can I decompose the images?


texts:
I developed a browser-based game. It's a Multiplayer Business Strategy Game. Currently I am unable to find a place where I can advertise my game. My main requirements are :

I can only pay via Credit Card. No Paypal. Just tell me which ad company accepts credit cards.
I also have quite a limited budget.

Also, I want to know is their is any rating / review website for my type of game?


texts: Can't give my pictures the right location in libGDX

texts:
I have this code here

 sb.draw(title, (PPlane.WIDTH / 2) - (title.getWidth() / 2), (float) (PPlane.HEIGHT / 10));
 sb.draw(playBtn, (PPlane.WIDTH / 2) - (playBtn.getWidth() / 2), PPlane.HEIGHT / 2);

This gives me a picture in the middle (playBtn) and a picture beneath it (title). But I want the picture title to be above picture playBtn. So what i did was:

 sb.draw(title, (PPlane.WIDTH / 2) - (title.getWidth() / 2), (float) (PPlane.HEIGHT / 1.2));
 sb.draw(playBtn, (PPlane.WIDTH / 2) - (playBtn.getWidth() / 2), PPlane.HEIGHT / 2);

I changed the number that divide PPlane.HEIGHT in draw.title so it would appear above playBtn, but instead it just dissapeared.

I also tried to change the cam.setOrtho to True with the first code but that didn't work either.

What should I do to fix this?


texts: How to do collision detection for fluids in 3D?

texts:
Is there an algorithm or a technique which can detect the collision between 3D fluids?

I currently treat my fluids as dynamic meshes. Is it possible to find collisions with these, or will I need a different representation?

I have considered traditional collision detection techniques like bounding boxes and 'trees' of bounding boxes, but they seem to be more accurate for rigid/solid objects, not for fluids.


texts: Why my Edit Collider in Unity2D has no point to adjust size?

texts: Why when I clicked to Edit Collider of Box Collider 2D component, is not showing points for me resize the collide box?


texts: Bringing a Box2D, Physics Enabled game Online?

texts:
Lets say, to simplify the problem of online games a bit, my goal would be to run a near identical simulation on multiple computers in sync. Would sending commands be a good idea?

Now if only sending commands is not good, should all the physics entities be sent every half second or so?

I'm wondering this because my game will essentially be a Box2D fighting game. Players can also spawn items, which must be added to the Box2D world.

What I'm wondering is how much and what kind of information should I send over the server?

Should I simply send key presses, and every half second snap back dynamic object positions to where the server thinks they should be?

Any helpful tips / articles regarding this would be a great help!

Thanks


texts:
I'm trying to write some code to do post processing in OpenGL ES2 on the iPhone. All is fine an dandy, except I am having trouble working out how to scale the texture rendered in the rendering step, such that it ends up pixel-aligned to the final image displayed on the screen.

I'm using a 512x512 texture, as provided by Apple's Texture2D class, to store my off screen rendering, and then mapping that onto a quad and rendering to cover the whole screen. The thing ends up taking up half of the screen vertically, more than the width of the screen, and is positioned about 2/3rds of the way down.
Here's my setup:

        // Create render to texture targets
        for (int i = 0; i < 2; i++)
        {
            textures[i] = [[Texture2D alloc] initWithData:0
                                     pixelFormat:kTexture2DPixelFormat_RGBA8888
                                     pixelsWide:512
                                     pixelsHigh:512
                                     contentSize:CGSizeMake(512, 512)];

            // create framebuffer
            glGenFramebuffers(1, &textureFrameBuffers[i]);
            glBindFramebuffer(GL_FRAMEBUFFER, textureFrameBuffers[i]);

            // attach renderbuffer
            glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, textures[i].name, 0);

            // unbind frame buffer
            glBindFramebuffer(GL_FRAMEBUFFER, 0);
        }
        // Setup our render to texture quad
        // Screen bounds are usually -1 to 1 on both axis, but we
        // multiply 'y' coords by (2.0/3.0) in the vertex shader so that we
        // get to use a square coordinate system that matches the screen ratio.
        float xSize = 1.0f;
        float ySize = 1.5f;
        quadPoints[0] = -xSize;
        quadPoints[1] = -ySize;
        quadPoints[2] = -xSize;
        quadPoints[3] = ySize;
        quadPoints[4] = xSize;
        quadPoints[5] = -ySize;
        quadPoints[6] = xSize;
        quadPoints[7] = ySize;

I'm doing ping pong rendering, hence the 2 offscreen targets. I've tried fiddling with xSize and ySize to make the thing stretch out beyond the bounds of the screen, such that the texture aligns properly, but can't seem to get it right.

To render with a single post processing step, I do

// Bind to first offscreen framebuffer
glBindFramebuffer(GL_FRAMEBUFFER, textureFrameBuffers[0]);
glViewport(0, 0, backingWidth, backingHeight);

// Render scene

// Bind to the screen framebuffer, and render the previously generated texture through our
// post processing shaders.
GLuint currentProgram = [[postProcessPrograms objectAtIndex:i] intValue];
glUseProgram(currentProgram);
GLuint sourceTexture = (i % 2 == 0)? textures[0].name : textures[1].name;
// Render the texture
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glEnableVertexAttribArray(ATTRIB_VERTEX);
glVertexAttribPointer(ATTRIB_VERTEX, 2, GL_FLOAT, 0, 0, quadPoints);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

// Show our buffer
glBindRenderbuffer(GL_RENDERBUFFER, colorRenderbuffer);
[context presentRenderbuffer:GL_RENDERBUFFER];

Any help would be great - I feel like i'm missing something obvious!


texts:
A customer of mine asked me to develop a Poker Game for him where they play poker with his friends online.

I have been looking for a good reason to start programming with XNA.  Would you implement it with XNA if you were developing a game like this ?

Is there any ebook/online tutorials/video trainings which has some similar sample applications?


texts: Controlling the draw order (z-index) through instancing?

texts:
Is there any way that I can control in which order elements are drawn with instancing?

Do all elements get drawn in the same order they are added to the instance buffer?

Edit: What about the Z coordinate! Since I am drawing my GUI through this, I should be able to just put elements in front of others, right? I am not at home to try this out yet. I will keep the thread updated.


texts:
I wanted to add a ground so I can know the position of a helicopter in the world. But the ground appeared in a weird way:

The ground had the following texture:

This is the code:

public class ImportModel
{
    public Vector3 Position { get; set; }
    public Vector3 Rotation { get; set; }
    public Vector3 Scale { get; set; }
    Model Model;
    Matrix[] modeltransforms;
    GraphicsDevice GraphicDevice;
    ContentManager Content;
    BoundingSphere sphere;
    bool boundingimplemented = false;
    public ImportModel(string model, GraphicsDevice gd, ContentManager cm, Vector3 position, Vector3 rot, Vector3 sca)
    {
        GraphicDevice = gd;
        Content = cm;
        Position = position;
        Rotation = rot;
        Scale = sca;
        Model = Content.Load<Model>(model);
        modeltransforms = new Matrix[Model.Bones.Count];
        Model.CopyAbsoluteBoneTransformsTo(modeltransforms);
    }
    public void Draw(Camera camera)
    {
        Matrix baseworld = Matrix.CreateScale(Scale) * Matrix.CreateFromYawPitchRoll(Rotation.Y, Rotation.X, Rotation.Z) * Matrix.CreateTranslation(Position);
        foreach (ModelMesh mesh in Model.Meshes)
        {
            Matrix localworld = modeltransforms[mesh.ParentBone.Index] * baseworld;
            foreach (ModelMeshPart meshpart in mesh.MeshParts)
            {
                BasicEffect effect = (BasicEffect)meshpart.Effect;
                effect.World = localworld;
                effect.View = camera.View;
                effect.Projection = camera.Projection;
                effect.EnableDefaultLighting();
            }
            mesh.Draw();
        }
    }
    public BoundingSphere BoundingSphere
    {
        get
        {
            if (!boundingimplemented)
            {
                foreach (ModelMesh mesh in Model.Meshes)
                {
                    BoundingSphere transformed = mesh.BoundingSphere.Transform(
                    modeltransforms[mesh.ParentBone.Index]);
                    sphere = BoundingSphere.CreateMerged(sphere, transformed);
                }
                Matrix worldTransform = Matrix.CreateScale(Scale) * Matrix.CreateTranslation(Position);
                BoundingSphere transforme = sphere;
                transforme = transforme.Transform(worldTransform);
                return transforme;
            }
            else
            {
                Matrix worldTransform = Matrix.CreateScale(Scale) * Matrix.CreateTranslation(Position);
                BoundingSphere transformed = sphere;
                transformed = transformed.Transform(worldTransform);
                return transformed;
            }
        }
    }
}

Then I call the class from the Game1 class:

ImportModel ground = new ImportModel("ground", GraphicsDevice, Content, Vector3.Zero, Vector3.Zero, new Vector3(20f));

This is how the scene looks from top:


texts: Better animation of elements in SFML/C++

texts:
This is not about animating individual characters or elements, I'm happy with spritesheets for that. What I'm looking for is the animation of elements on screen.

For example my game starts and the logo comes in flying from a random direction, then rotates or something and stops in one position, then a game character (one or more) comes from the side and does some action.

I haven't done many projects yet, I have written just one complete game, so I don't know whether I've correctly worded the question.

What I've been doing is giving the element an initial and final position and make it move accordingly and using status flags to check its state. The problem is when I want to move it in more than one way. Of course, I can just use the state variables and make it move, but I've been thinking there's got to be an elegant method for it

EDIT: I'm looking at animations such as in World of Goo etc.


texts: How to check audio quality after changing import settings

texts:
I have changed the quality of an audio clip from 100 to 10 in the import settings. But when I played the clip from the inspector, I didn't hear any noticeable difference

The compression format of the audio clip is set to 'Vorbis'

So I wonder if it's the original file or the compressed file that is being played by the Unity Editor?


texts: How do I output a webcam stream to a 2D canvas with SharpDX in C#?

texts:
I'm writing an application for the Oculus Rift using the SharpOVR library to access HMD position data. I decided it is reasonable to use SharpDX to also output webcamera streams.

Unfortunately, all SharpDX documentation is basically a copy paste from C++ documention and I only know basic C++. C# uses a different style, class names, etc.
The MediaFoundation samples are also C++-only.

I'm trying to write a pretty simple part that renders 2 videos from 2 webcams.
I've managed to get webcameras list with this code, but I'm failing to init one— it currently fails at source.Start(descriptor, null, time);

According to the exception, I need to bind all Stream events first. Or I am missing something I need to init?

Can one help with further actions from camera start till outputting to monitor? I know the code shouldn't be too hard, problem is adapting it to C#.


texts: Direct3D11 Reading from (Static) Index Buffer

texts:
Good morning,

I have an Indexbuffer created with usage D3D11_USAGE_DEFAULT and CPUAccessFlags 0. Now I want to read data from this buffer regularly (it is a terrain index buffer). But the problem is that I am not allowed to read data from the buffer, because the buffer is not created with the flag D3D11_CPU_ACCESS_READ.

Even if I make the buffer dynamic, I still am not allowed to read from the buffer. This is because the CPUAccessFlag D3D11_CPU_ACCESS_READ is not allowed to be used together with usage D3D11_USAGE_DYNAMIC.

Could anyone please give me advice on how to properly read data from a vertex or index buffer in Direct3D11. In my case I want to read data from it frequently.


texts: How can I exclude a range of values when generating random numbers?

texts: If you are using Random.range to generate values, is there any way to exclude some values within the range (for example: pick a number between 1 and 20, but not 6 through 8)?


texts:
I am making glyphs on a wall "glow", by changing how much of the overlay textures light intensity is blended into the diffuse map. The basic approach is to capture the diffuse map into a render target, and then spritebatch.draw(additive) the light intensity texture on top of it.

This worked great for smaller textures. Now I want to do the same for a larger scene that has massive texture maps. It doesn't make sense to capture all of that just to make some portions "glow".

Is there a better way than to use render targets for a "glowing" effect?


texts:
I'm trying to draw an arc out of dots that previews a KinematicBody2D's trajectory after a jump but said preview always falls short of the body's actual jump and I cannot figure out why. Below is an example gif of what I'm talking about.

And this is the code I used in the example.
extends Node2D

var arcPoints = 40
var pointsPerSec = 12
var startYvelocity = -500
var velocity = Vector2(200, startYvelocity)
var gravity = 300

var startPosition = Vector2(96, 544)

func _draw():

    var totalY = startPosition.y
    var velY = startYvelocity
    var calcGravity = gravity/pointsPerSec

    for p in range(arcPoints):
        velY += calcGravity
        totalY += velY/pointsPerSec

        var point = Vector2(startPosition.x+(velocity.x/pointsPerSec)*(p+1), totalY)
        draw_circle(point, 2, 'fafafa')

func _ready():
    pass

func _physics_process(delta):
    velocity.y += gravity*delta
    get_child(0).move_and_slide_with_snap(velocity, Vector2(0.0, 1.0), Vector2(0.0, -1.0))


texts: OpenGL Depth Buffer/Coordinate issue with SFML

texts:
For some reason, my coordinate system in OpenGL is getting all messed up with depth.  When I put something more than 1 unit away from zero (in terms of the Z coordinate), I can't see the object.  Furthermore, it seems as if the GL coordinate (-1, -1, 0) is in the lower left corner no matter what I do (and (1, 1, 0) is upper right).  I've used OpenGL in Java and in C++ with GLUT before and am now trying out SFML, and haven't had these issues before, so maybe someone can tell me what I'm doing wrong?

A minimal example as best I can do:

#include <SFML/Graphics.hpp>
#include <SFML/OpenGL.hpp>

#include <iostream>

int main()
{
    sf::ContextSettings settings;
    sf::RenderWindow window(sf::VideoMode(800, 600), "OpenGL Test", sf::Style::Default, sf::ContextSettings(24));

    settings = window.getSettings();

    std::cout << "depth bits:" << settings.depthBits << std::endl;
    std::cout << "stencil bits:" << settings.stencilBits << std::endl;
    std::cout << "antialiasing level:" << settings.antialiasingLevel << std::endl;
    std::cout << "version:" << settings.majorVersion << "." << settings.minorVersion << std::endl;

    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);    // Black Background
    glDepthRange(-1, 1000);

    // run the main loop
    bool running = true;
    while (running)
    {
        sf::Event event;
        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
            {
                // end the program
                running = false;
            }
            else if (event.type == sf::Event::Resized)
            {
                // adjust the viewport when the window is resized
                glViewport(0, 0, event.size.width, event.size.height);
            }
        }
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        glLoadIdentity();

        // Comment this line to fix it!!?
        glTranslatef(-1.5f,0.0f,-6.0f);

        glBegin(GL_TRIANGLES);                      // Drawing Using Triangles
            glVertex3f( 0.0f, 1.0f, 0.0f);              // Top
            glVertex3f(-1.0f,-1.0f, 0.0f);              // Bottom Left
            glVertex3f( 1.0f,-1.0f, 0.0f);              // Bottom Right
        glEnd();                            // Finished Drawing The Triangle

        window.display();
    }

    return 0;
}

Update:
The glDepthRange() call was to make sure that wasn't the source of the problem.  Also I added the following code to the initialization, and I haven't seen any change in behavior:

glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glViewport(0, 0, 800, 600);

glMatrixMode(GL_MODELVIEW);
...

Also, I'm using the 2.0RC version of SFML, and my OpenGL version is 4.3 (running on an ATI card).


texts:
In XNA, I have created a new VertexType, called it VertexPositionTextureLight which inherts the IVertexType Interface, but apparently I need to implement the member of VertexDeclartion which I cleary have:

struct VertexPositionTextureLight : IVertexType  {
    Vector3 position;
    Vector2 textureCoordinates;
    float light;

    public readonly static VertexDeclaration VertexDeclaration = new VertexDeclaration(new VertexElement(0, VertexElementFormat.Vector3, VertexElementUsage.Position, 0), new VertexElement(sizeof(float) * 3, VertexElementFormat.Vector2, VertexElementUsage.TextureCoordinate, 0), new VertexElement(sizeof(float) * 5, VertexElementFormat.Single, VertexElementUsage.TextureCoordinate, 1));

    public VertexPositionTextureLight(Vector3 position, Vector3 normal, Vector2 textureCoordinate, float light)  {
        // TODO: Use normal data
        this.position = position;
        this.textureCoordinates = textureCoordinate;
        this.light = light;
    }
}

I used to use this struct without inheriting the interface but since I need to call the device.DrawUserIndexedPrimitives that function wants the struct to inherit IVertexType.


texts: Pre game loading time vs. in game loading time

texts:
I'm developing a game in which a random maze is included.
There are some AI creatures, lurking the maze. And I want them to go in some path according to the mazes shape.

Now there are two possibilities for me to implement that, the first way (which I used) is by calculating several wanted lurking paths once the maze is created.
The second, is by calculating a path once needed to be calculated, when a creature starts lurking it.

My main concern is loading times. If I calculate many paths at the creating of the maze, the pre loading time is a bit long, so I thought about calculating them when needed.
At the moment the game is not 'heavy' so calculating paths in mid game is not noticeable, but I'm afraid it will once it will get more complicated.

Any suggestions, comments, opinions, will be of help.

Edit:

As for now, let p be the number of pre-calculated paths, a creatures has the probability of 1/p to take a new path (which means a path calculation) instead of an existing one.
A creature does not start its patrol until the path is fully calculated of course, so no need to worry about him getting killed in the process.


texts: How to get an game object to instantiate lower than where It's created?

texts:
When I press the collider where my allies spawn I want for them to spawn a little bit lower when I instantiate. I have tried to use Vector 3 and GetComponent, but It gives this error:

'Assets/Scripts/PlaceMonster.cs(26,33): error CS0131: The left-hand side of an assignment must be a variable, a property or an indexer'

I just want for my allies to spawn a little bit lower than the collider, but I'm stumped on what's the problem.

void OnMouseUp () {
    theAllyMenu.gameObject.SetActive (false);
    if (canPlaceAlly ()) {
        ally = (GameObject)
            //GetComponent<Transform>().transformPic = transformPic;
            transform.position = new Vector3(transform.position.x, transform.position.y - -5, transform.position.z);
            Instantiate (allyPrefab, transform.position, Quaternion.identity);
    }

}


texts: How should I structure VBOs for my 2d world data?

texts:
My game is played on a fixed-size hex based arena, where each hex can be of a different type, and possibly contain some creatures/items/anything on it.

When I started out, I got the advice to have a VBO per entity, which I took quite literally and ended up creating a VBO per-hex per-frame, which got real slow. This lead me to restructure the data in a way that I pre-calculate all of the VBO data for the "background" hex grid just once, and just repeatedly draw it.

The problem is that now I can't simply rely on changing the model and having everything be updated, as the whole "map" is pre-calculated. Following this I created a separate VBO which is filled just with "dynamic" objects that change on each frame, and first render the static background, and then the dynamic part that changes.

But this leads me to a question. What if I need to change the background at runtime? For example, what if a "wall" gets torn down every once in a while, and I need to update the world data? Currently I can think of only a few options:

Change the VBO in place during the frame. This would only work if the change is small enough to not lag the frame.
Keep a separate VBO that just has the "changes" and is drawn over the original one. I don't really like this approach, as it doesn't really feel flexible.
Build a new VBO in a separate thread and atomically swap them once done. While this would allow me to do a larger update without sacrificing framerate, it could also introduce a weird kind of latency, when the user would still see the old thing for a few frames until the new VBO is calculated.

Ideally I'd just change my "model" and re-build the whole VBO from it, but that's about as slow as it gets, so I'm not really sure if I should even keep thinking this way?

How do larger and more complicated games handle updating geometry on the fly? Is everything just pre-calculated animations that simply get swapped around?


texts: OBB vs rectangle/quad/plane with bounds collision detection/response

texts:
I am able to resolve collision between an OBB and a plane but can't get it to work when I introduce some bounds on the plane size. I want to have the plane of width and height dimensions defined by a normal and a position.
The code for detecting/resolving is fairly simple if the plane doesn't have any bounds:
function obbIntersectsPlane( obb, plane ) {
  let r = obb.size.x / 2 * Math.abs( dot( obb.right, plane.normal ) ) +
          obb.size.y / 2 * Math.abs( dot( obb.up, plane.normal ) ) +
          obb.size.z / 2 * Math.abs( dot( obb.forward, plane.normal ) );

  let s = dot( plane.normal, obb.position ) - dot( plane.normal, plane.position );

  if ( Math.abs( s ) < r ) {
    return {
      overlap: r - s,
      vector: plane.normal
    };
  }

  return false;
}


texts:
What is "render path"? Who invented this term?

I can suppose that this thing mean something one from the list below:

The thing which shows which rendering technique should be used (e.g. forward/deffered rendering)
Module for rendering lines and curves
Description how shaders should be connected in mutlipass render to reach the goal of some render FX.

For what this term is stand for? Thanks


texts: How to change a variable in the spawnpoint from another prefab

texts:
I refer the website for proper way of referencing the script How to call a public function from another script in Unity? but it does not work, still return a nullreference exception in the example below. Not sure how to fix it.Apart from that I also consider using
 int a;
public int A
{ get; set; }

and in HPscript using spawnpoint.A = spawnpoint.A - 1;
but it come out the content is for read only.
Below is the codes I using.
I attach this code to a capsule gameobject that is use to spawn prefab gameobject,drag and drop prefab to  the enemy GameObject inspector window, this part working correctly.
using System;
using UnityEngine;

public class Spawnpoint: MonoBehaviour
{ public GameObject Enemy;

  public int a;
  int currentstate = 0;
  int previousstate = 0;

   void Counting()
{//the below if statement is to ensure the Gameobject only spawn once when condition become true
 //in every 10seconds
    var d = DateTime.Now.Second % 10;
    if(d==0)
    {
        currentstate = 1;

    }
    else
    {
        currentstate = 0;
    }
}

void Spawn()
{//Stop spawning when Gameobject equal 5

    if (d==0&&currentstate!=previousstate)
        if(a<5)
    {
        Instantiate(Enemy, new Vector3(UnityEngine.Random.Range(0, 4), 1, UnityEngine.Random.Range(0, 4)),Quaternion.identity);
        a = a+1;
    }
}

 void Update()
{
    Counting();
    Spawn();
    previousstate = currentstate;
}

}
The script below is not working. I want the HPscript to deduct the value "a",in Spawnpoint script so the script will continue spawn enemy when number less than 5.This script is attached to the prefab gameobject that is place in asset folder.
 using System;
 using UnityEngine;

public class HPScript : MonoBehaviour
{ Spawnpoint spawnpoint;

void Start()
{
    spawnpoint = GetComponent<Spawnpoint>();
}
public void counting()
{

    var c = DateTime.Now.Second % 30;
    if(c==0)

    {

        spawnpoint.a = spawnpoint.a - 1;

        Destroy(gameObject); }
}

void Update()
{
    counting();

}

}


texts:
I'm facing a problem with a game I'm making.
Currently I can select an enemy and mark it as shown on the image:

But now I want to show the position of the selected enemy on the screen when it's off camera.
So my questions are:

How do I know when an enemy is off camera.
How can I show in GUI an arrow on the edge of the screen that points to the position of that enemy. Perhaps something related to what I did to point towards the crosshair?

Vector3 positionOnScreen = Camera.main.ScreenToWorldPoint(mousePos + Vector3.forward * range);
Vector3 targetDir = positionOnScreen - transform.position;

Thanks!


texts: Why does the projection matrix transform object points into a unit cube in computer graphics?

texts:
This semester I both took a computer vision and a computer graphics seminar. But only now before the exams I realize that there seems to be a fundamental difference between projection in both topics.

In computer vision we learned the math to map an object point from 3D to a plane using a 4x3 matrix, which seems logical to me:

|u|   |p_11 p_12 p_13 p_14|   |X|
|v| = |p_21 p_22 p_23 p_24| x |Y|
|w|   |p_31 p_32 p_33 p_34|   |Z|
                              |1|

However in computer graphics one usually uses a 4x4-matrix. The very nice explanation on Coding Labs has a picture depicting the outcome of said transformation: it depicts a unit-cube containing the transformed objects (distorted according to the projection).

But a unit-cube certainly isn't what is rendered on to the flat 2D screen. Is there something going on internally that just isn't mentioned? Why is this done?


texts: Is it possible to work with a dedicated server in XNA?

texts:
Hi I want to release my XNA game to the XBOX platform, but I'm worried about the networking limitations. Basically, I want to have a dedicated (authoritative) server, but it sounds like that is not possible.

Which is why I'm wondering about:

Using port 80 web calls to php-driven database
Using an xbox as a master-server (is that possible?)

I like the sound of #1, because I could write my own application to run on the xbox, and I would assume other users could connect to it similar to the p2p architecture.
Anyone able to expand on theory #2 above? or #1 as worst-case scenario?


texts: Managing different types of Actors/Entities in a rendering engine

texts:
I'm coding a simple game engine using DirectX11, and I'm stuck on how to implement a kind of ECS. Now my rendering system look like this (sorry if the diagram is not real UML, it's just for description):

The architecture is really naive, I wanted to keep things as simple as possible, for learning purposes:

Every entity is modeled as a new class (no, inheritance, no composition), and is added to a master Renderer class with a AddEntityXXX() method, which adds it to a vector of that kind of entity.
Every ShaderXXX inherits from a base Shader class, which takes care of the common functionality of a shader (compiling the bytecode, binding the shader program, seting the input layout ecc..), while every subclass defines some type members (struct XXXConstantBuffer {...};) that contain shader parameters (constant buffers) to be uploaded/updated before rendering (UpdateXXXConstantBuffer() method).
The renderer keeps a reference to a camera object, which contains the view and projection matrices, and uses some instances of a FrameBuffer class for offscreen rendering (shadow mapping, water reflections/refractions, postprocessing).
Finally, the renderer renders each EntityXXX by calling a specific RenderXXX() member function and performing the appropriate work for each type of game object, like binding the specific shader, updating the constant buffers and issuing a draw call.

Now, since my engine will be more than a showcase of graphics features, I want to make each entity abstract, and I tried inheritance, but since each entity has its own "identity" it's not  viable approach:
an entity representing a player needs a Move() method, position and velocity state variables, while a terrain entity doesn't move ecc..
So I learned about the Component pattern and Entity Component System architecture / Game Actors.
What I find most difficult in abstracting the various kinds of entities is how to manage the rendering: How can a renderer differentiate between them and update the shader parameters (constant buffers) accordingly? In some cases I need to pass to the UpdateXXXConstantBuffer() method a WorldViewProjection matrix only, in others (shadow mapping) I need to pass a LightViewprojection matrix as well, or an array of bone tranform matrices for animation.

How can a rendering engine be structured to address these issues?
Please, don't give general pattern advices, I know the existence of the Component pattern, and the Entity Component System, but I'd like to learn some practical implementation for it. I mean how should an entity be structured so that a rendering process can be performed abstracting away the specific implementation of an entity/actor?

EDIT
maybe my uber-question could be rephrased like this:
how can I structure a simple but efficient RENDERING ENGINE? I know that there's no such thing as a generic rendering engine, but which are the guidelines (and by that I mean a foundation for an architecture/patterns) to implement one and how does this translate to a component based GAME ENGINE?


texts:
How can I make an 2d image using World space coords with a shape? Like a circle instead of a quad.In 3d you can modify the vertices but if I want a smooth circle there will be too much vertices. What I want to achieve is something like a cirle mask that will be move over the global texture at runtime.
So has anyone done something similar?
I've tried combining some shaders with two uv's one for world space and one for alpha uv mesh but it gives some weird artifacts.

This is the how the shader looks on the right:

Shader "Unlit/WorldspaceTiling"
 {
     Properties
     {
         _MainTex ("Texture", 2D) = "white" {}

 }
 SubShader
 {
      Tags {"Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent"}
 LOD 100

 ZWrite Off
 Blend SrcAlpha OneMinusSrcAlpha
 Cull Off
     Lighting Off
     ZWrite Off
     Fog{ Mode Off }
     Pass
     {
         CGPROGRAM
         #pragma vertex vert
         #pragma fragment frag
         #include "UnityCG.cginc"

         struct appdata
         {
             float4 vertex : POSITION;
             float2 uv : TEXCOORD0;
         };

         struct v2f
         {
             float2 uv : TEXCOORD0;
             float4 vertex : SV_POSITION;
         };

         sampler2D _MainTex;
         float4 _MainTex_ST;

         v2f vert (appdata v)
         {
             v2f o;
             o.vertex = mul(UNITY_MATRIX_MVP, v.vertex);

             // Gets the xy position of the vertex in worldspace.
             float2 worldXY = mul(_Object2World, v.vertex).xy;
             // Use the worldspace coords instead of the mesh's UVs.
             o.uv = TRANSFORM_TEX(worldXY, _MainTex);

             return o;
         }

         fixed4 frag (v2f i) : SV_Target
         {
             fixed4 col = tex2D(_MainTex, i.uv);
             return col;
         }
         ENDCG
     }
 }

}


texts:
I startded to make an assimp only opengl skeletal animation demo. For that I used this: http://sourceforge.net/p/assimp/discussion/817654/thread/5462cbf5
And something is not correct in bone matrices.

and my standerd bob_with_lamp model(.md5) looks like this. its moving its parts but not in correct way.This is the code:

    for( size_t a = 0; a < anim->mNumChannels; ++a)
{
  const aiNodeAnim* channel = anim->mChannels[a];
  aiVector3D curPosition(0,0,0);
  aiQuaternion curRotation(1,0,0,0);
  aiNode* targetNode = scene->mRootNode->FindNode(channel->mNodeName);
  while((int)time >channel->mNumPositionKeys) time-=channel->mNumPositionKeys;
  curPosition = channel->mPositionKeys[(int)time].mValue;
  curRotation = channel->mRotationKeys[(int)time].mValue;
  aiMatrix4x4 trafo = aiMatrix4x4(curRotation.GetMatrix());
  trafo.a4 = curPosition.x; trafo.b4 = curPosition.y; trafo.c4 = curPosition.z;
  targetNode->mTransformation = trafo;
}
for (unsigned int n = 0; n < scene->mNumMeshes; ++n)
{
    const aiMesh* mesh = scene->mMeshes[n];
    std::vector<aiMatrix4x4> boneMatrices( mesh->mNumBones);
    for( size_t a = 0; a < mesh->mNumBones; a++)
    {
      const aiBone* bone = mesh->mBones[a];
      aiNode* node = scene->mRootNode->FindNode( bone->mName);
      boneMatrices[a] = bone->mOffsetMatrix;
      const aiNode* tempNode = node;
      while( tempNode)
      {
          aiMatrix4x4 m = tempNode->mTransformation;
          boneMatrices[a] *= tempNode->mTransformation;
          tempNode = tempNode->mParent;
      }
    }

and my render:

    std::vector<aiVector3D> resultPos( mesh->mNumVertices);
    std::vector<aiVector3D> resultNorm( mesh->mNumVertices);

    for( size_t a = 0; a < mesh->mNumBones; ++a)
    {
      const aiBone* bone = mesh->mBones[a];
      const aiMatrix4x4& posTrafo = boneMatrices[a];
      aiMatrix3x3 normTrafo = aiMatrix3x3( posTrafo);
      for( size_t b = 0; b < bone->mNumWeights; ++b)
      {
        const aiVertexWeight& weight = bone->mWeights[b];
        size_t vertexId = weight.mVertexId;
        const aiVector3D& srcPos = mesh->mVertices[vertexId];
        const aiVector3D& srcNorm = mesh->mNormals[vertexId];
        resultPos[vertexId] += weight.mWeight * (posTrafo *srcPos);
        resultNorm[vertexId] += weight.mWeight * (normTrafo * srcNorm);
      }
    }
    //And rendering the vertices from the pos vector

what should I change to made this to get correct positions?


texts:
I am developing an mobile application (in HTML5) that will run on multiple platforms and will eventually have both single and multiplayer options. The current issue I have is the best method for storing many rows of data so that the user can access it either in single (no internet) or multiplayer.

I have a relational database for the multiplayer users to access the data, however I'm concerned about performance (keep trying to access to the server). I was wondering if there is any reasonable method (apart from localstorage and websql - as I understand, localstorage can't hold a lot of data and websql is only available on certain platforms) to store a lot of data locally on a mobile device so that any non-internet users can still access their data and do so quickly?


texts: Rotating a child shape relative to its parent's orientation

texts:
When rotating a shape using a quaternion value I also wish rotate its child shape.

The parent and child shapes both start with different orientations but their relative orientations should always be the same.

How can I use the difference between the previous and current quaternions of the parent shape in order to transform the child segment and rotate it relative to its parent shape?

    public Quaternion Orientation
    {
        get { return entity.Orientation; }
        set
        {
            Quaternion previousValue = entity.Orientation;
            entity.Orientation = value;

            // Use the difference between the quaternion values to update child orientation
        }
    }

EDIT:

If I have understood teodron correctly then this is what I must do

// Qc' = Qp' * Inv(Qp) * Qc
//
// Where:
// Qp   = Parent orientation last frame
// Qp'  = Parent orientation this frame
// Qc   = Child orientation last frame
// Qc'  = Child orientation this frame

set
{
    Quaternion previousValue = entity.Orientation;

    entity.Orientation = value;

    Quaternion childOrienation = value * Quaternion.Inverse(previousValue) * childOrientationPrev;
    //Quaternion childOrienation = childOrientationPrev * Quaternion.Inverse(previousValue) * value;
}

I have tried both multiplication orders but neither method rotates the child object correctly and instead it spins very quickly.


texts: Processing large multi layered images with SharpDX

texts:
I'm currently working on an image processing project that pans and zooms on multi-layer high resolution images.

The goal is colorize (including color, gain and noise) n layers (n having a minimum of 5) and merge them via shaders. On top of that, there are 5–6 layers of 2D geometry each colored and merged as well.

The normal image size is 7440 x 7440.

These are then merged and rendered on a single Quad. I've been able to get this working very well and the results are good.

This is being processed on a Xeon based workstation with a M4000 Nvidia Quadro or a Xeon based Lenovo p51 with M2200 Nvidia Quadro.

The issue comes when I need to process a very large image (34,992 x 34,992) that requires splitting the image over 9 quads on the same systems.

These images must go through the same process of colorization and merging. The images are 11,664 x 11,664 per quad.

When zoomed in, we are still processing areas we can't see—can I apply some form of frustum culling here?

And, when zoomed out, is there a way to process a lower resolution image so the GPU is not pegged and none responsive?


texts: OpenGL 4D textures with bilinear interpolation

texts:
I want to use and interpolated 4D texture in OpenGL, i.e. a texture that is accessed with a texture coordinate vector (s, t, p, q) and interpolated linearly in every texture coordinate.

The extension GL_SGIS_texture4D does exactly this. However, it is unsupported on literally every GPU I have access to.

If the was a GL_TEXTURE_3D_ARRAY, I guess I could sample the appropriate 2 layers of a 3D array texture with the (s, t, p) coordinates and then manually interpolate in the q coordinate. However, there are only "ordinary" GL_TEXTURE_2D_ARRAY texture arrays. A possible solution is to treat the texture array as 2D array of 2D texture, sample the appropriate 4 layers with (s, t) and then manually interpolate in p and q. This method is somewhat constrained by GL_MAX_ARRAY_TEXTURE_LAYERS. I am also afraid of the relatively large number of 2D texture fetches required to fetch a single 4D texture value.

Is there a simpler way of achieving 4D interpolated textures?


texts:
This isn't exactly a game development question, but I am planning on using Unity as my engine and modeling in Maya so I was hoping folks on here might have some experience with this.

I want your advice or examples of modeling real-world buildings (inside and outside) ensuring accuracy but not necessarily detail.

The breakdown:

I am doing a project in which I want to make a 3d interactive,
explorable map of my university's campus.
I am starting small with making one single building as my prototype.
My plan is/was to model the building in Maya then import it into Unity to make the application.
So far I have been able to access floor plans, however they lack measurements/dimensions (width, length, height, etc)
I am in the process of attempting to get more resources but am unsure of what I will be able to acquire
I have access to the building in question
As a legitimate school project, I can try to get permission for various related needs

I wanted to know if anyone has any experience related to what I am doing or if anyone may be able to point me in a good direction for any resources that may help me.


texts: Facebook data exchange for mobile games (multiplayer)

texts:
A multiplayer mobile game that we are working on connects players through Google Play and Game Center but we would also like to add an option to play with your Facebook friends and here's the question:

Is there a way to exchange the data between Facebook users through the FB API so we could exchange Google Play ID / Game Center ID?

Is there a way to do this without having a server which holds Facebook UIDs and stuff?


texts:
The game I'm developing has a simple game server which stores inventory and hero data for each user, as well as deciding the outcome of some random events. The server interacts with PostgreSQL and responds to HTTP queries. It runs on EC2 and Microsoft Azure, but these hosts sometimes become unreachable for a few minutes, and one week the EC2 server froze every day. What are the strategies to make sure a server is always available?

Non-solution: Multiple servers with their own databases, and the client will try to connect to a different server after a timeout. Of course, their data will be absent if it's a different server.

Solution 1: As above, except whenever player data changes, that change is stored, and each player's data is replicated to the other servers (bidirectionally). The disadvantage is that this solution is "home grown" and prone to mistakes.

Solution 2: One primary server (let's leave sharding for later), and one or more backup servers, with the database being replicated. When the primary server becomes unreachable, a backup server is made into the primary server.
Problems: this needs additional technology for directing queries to the right server, and also to decide when a backup server needs to be promoted to primary. Can this "manager" also hang? It sure can if it's on AWS! That would bring the whole system down.

Solution 3: We could pay for database hosting with some guarantee of reliability, and have multiple servers but just one database. We would assume the database is reliable (but still back it up). The user could connect to any reachable server, and the servers would not need to worry about having stale data, since there will be only one database. (Again, sharding is a separate problem, and we could just multiply the whole setup without fundamentally changing its architecture.)

So how is reliability achieved when individual servers aren't reliable? I like solution 3 for its simplicity, if a 3rd party database can be relied upon.


texts:
I am currently porting a game from WP7 using XNA to WP8.1 using MonoGame. I have been putting considerable effort into optimizing my game to be under the 185MB memory limit for low-memory phones.

I was making headway until I discovered a memory spike on startup. I continued to reduce the quality of my assets until the memory usage (while the game is running) is at about 140MB. However, on startup, the memory usage spikes to 205MB, sits there for about 10 seconds, and then drops to standard operating memory usage. It does this every time. Increasing or decreasing the asset sizes only changes how high the spike goes and the usage in general, but it does not change the 10 second delay at all.

One idea I thought about was to delay the user with a longer splash screen, giving me time to load all the assets without blowing the hatch. But this seems to me like detracting from the user experience out of convenience.

Any ideas? Has anyone else had this problem?


texts: Why does my AI Enemy slide towards its target when it is supposed to be idle?

texts:
So using Unity standard assets to get a stage rolling, Ive built a simple terrain and used FPSController as the player and AI ThirdPersonController (Ethan) as the enamy.

Ive built the navmesh and everything was working in its default state, but then I changed the AI script slightly as I wanted Ethan to follow me only if I come within a certain range, so I changed it to the following:

public float dangerRadius = 5f;

        private void Start()
        {
            // get the components on the object we need ( should not be null due to require component so no need to check )
            agent = GetComponentInChildren<UnityEngine.AI.NavMeshAgent>();
            character = GetComponent<ThirdPersonCharacter>();

            agent.updateRotation = false;
            agent.updatePosition = true;
        }

        private void Update()
        {
            if (target != null)
                agent.SetDestination(target.position);

            if (agent.remainingDistance < dangerRadius)
                character.Move(agent.desiredVelocity, false, false);

            else
                character.Move(Vector3.zero, false, false);
        }

        public void SetTarget(Transform target)
        {
            this.target = target;
        }

But the problem is that when the remainingDistance is greater than dangerRadius or when I am out of range, Ethan just slides slowly towards the target in idle state and as the distance becomes lower than the threshold he starts running as expected.

Ive tried adding friction materials to the terrain and the collider on Ethan but he still slides.

Help thanks


texts: How do I keep UI texts in their relative positions at all screen resolutions?

texts:
I need to position several UI texts on the screen.

I do this using a Canvas with Screen Space Overlay.

Also, these UI texts need to stay at their relative positions at different screen sizes.

Here is a screenshot in which the texts are highlighted in green:

One can see that they don't follow a grid-like pattern.

How could I keep them at their relative position at different screen resolutions?

Thank you.


texts: Is there any difference between storing textures and baked lighting for environment meshes?

texts:
I assume that when texturing environments, one or several textures will be used, and the UVs of the environment geometry will likely overlap on these textures, so that e.g. a tiling brick texture can be used by many parts of the environment, rather than UV unwrapping the entire thing, and having several areas of the texture be identical. If my assumption is wrong, please let me know!

Now, when thinking about baking lighting, clearly this can't be done the same way - lighting in general will be unique to every face so the environment must be UV unwrapped without overlap, and lighting must be baked onto unique areas of one or several textures, to give each surface its own texture space to store its lighting.

My questions are:

Have I got this wrong? If so, how?
Isn't baking lighting going to use a lot of texture space?
Will the geometry need two UV sets, one used for the colour/normal texture and one for the lighting texture?
Anything else you'd like to add? :)


texts:
I often hesitate to use friend classes in C++. Since it often does not feel right, or just seems to be an indicator of bad design. Though, in this case I think a friend class might improve the design. Let me explain:

Let us say I have a very simple mesh class:

class Mesh {
    friend class Renderer;
public:
    using Vertices = std::vector<Vertex>;
    Vertices::iterator begin() {
        return vertices_.begin();
    }
    Vertices::iterator end() {
        return vertices_.end();
    }
    void invalidate(){
        valid_ = false;
    }

private:
    Vertices vertices_
    bool valid_;
}

The renderer looks something like this:

class Renderer {
public:
    void render(Mesh & mesh){
        if (!mesh.valid_){
            //The mesh has changed, update internal data.. GL buffers etc.
            mesh.valid_ = true; // Mesh becomes valid again.
        }
        //render...
    }
}

So, this is of course a very simplified example. My question is, if this is a good design in this case? Clients can only call invalidate() on meshes. And only the renderer is allowed to "validate" a mesh again. Without a friend class, A public setter would have to be used in the Mesh class. Hence providing a "leaky" interface. Allowing clients to "validate" meshes, which I do not want.

Edit to clarify

A valid mesh in this sense means that its corresponsing data in other subsystems is the same. The renderer has its own mesh data in its own form (a GL buffer). Therefore, only the renderer should be able to validate, since it knows about its own mesh data. Clients can edit meshes, and invalidate them only.


texts: Is it possible to write a game that doesn't require a GPU?

texts:
I already know many computers today have a GPU that supports DirectX and OpenGL.
But what about computers that don't? Can I write a simple 2D game that does not rely on the GPU, so that it works even on older machines?

Is there a cross-platform C or C++ game library that will let me do this? Ideally, such a library would let me toggle hardware acceleration with very few lines of code.


texts:
I'm making a 2D sidescroller game and want to give the blocks a 3D like effect. This way it looks like the player is walking on 3D blocks while walking on a 2D plane (thus having only x,y coordinates).

I have already written the code to generate the terrain in 2D, but the 3D effect is now baked in. It looks like this:

At this moment the 3D effect is baked into the blocks, but I want to try to generate it.

Is there a common way to achieve this 3D like effect while still staying 2D?
Do I have to convert from 2D to 3D or is it also possible to do this with calculations/shaders?

EDIT; The reason I want the top texture of the block separate of the block is because when the camera would go up, the top should get bigger as the camera sees more of the top of the block and the other way around when the camera goes down.


texts:
I'm new in cocos2d and game dev. I'm still learning in game dev. My goal is to make one game like Doodle Grub. But problem is snake body. I wrote like following

-(void)update:(ccTime)delta
{
    //NSLog(@"%f",[GameScence sharedGameScence].playerVelocity.y);

    CGPoint tmp=self.position;
    float tmprotation;
    self.position=[GameScence sharedGameScence].WormHeadPos;

    [GameScence sharedGameScence].WormHeadPos=tmp;
    tmprotation=self.rotation;

    [self setRotation:[GameScence sharedGameScence].Headrotation];

    [GameScence sharedGameScence].Headrotation=tmprotation;

}

snake is moving but problem is all of the body segments are same position when snake stop. And all of the body segments is so close and can't see segments like Doodle Grub. Any idea or Any suggestion ?


texts: Unity Animator not animating player, but following transitions perfectly in Animator Window

texts:
I am trying to animate a model in my project, and although I have been successful doing the same in other projects, I am not succeeding in this one.
The model does not seem to animate, although in the Animator window, everything looks fine, transitioning from one state to the other and going back.

I have followed the tutorials to import animations from the site where I downloaded the animation, and each animation is the same as other working animations in other projects:

The animations play as expected in the inspector window.
I have tried modifying the "Apply Root Motion" in my character and it does not work either way. My Player model has these properties:

And I have tried adding a Rigid Body but it didn't work neither. I have spend several hours trying to solve this issue and I am running out of ideas to try. How can I make the animation work as expected?
Cheers!


texts: How do I prevent inappropriate ads from appearing in my game?

texts:
My game implements Unity ads, and is designed with a universal audience in mind. As such, I would prefer not to have 18+ ads (or even 13+ ads depending on the circumstances) appearing in it, especially since it would appeal to younger audiences as well. My question is then, how do I prevent age-inappropriate ads from appearing? Is there a way to simply set the age limit or content restrictions on Unity ads? The only setting along those lines that I can find is the COPPA toggle, and that would cause other issues (not to mention that it wouldn't do anything to the ads). I've looked in the dashboard for a while, and I've tried to research it beforehand, but the fact that they've shifted to a centralized services page, redirected all the old links (breaking them in the process), reorganized the settings in the dashboard, and 404d their FAQ post on the topic doesn't help either. Blocking ads based on a rating would work too, as I would have to get one because I am publishing to Google Play.

Edit: The second link only 404s some of the time. I just happened to get it every time before asking this question. Bad luck, I guess.


texts: (How exactly to use EventSystem?) Assigning string Name to UI Button in Unity without CrossPlatformInput?

texts:
I'm trying to make a new game for Android. There is a Jump button i've added as UI button , this works fine as I have a method for Jump() which I can just add to the OnClick() method in the Button's Inspector tab.

However, for my 'Pick Up' button I don't really want a method for pick up. I already have my item pickup handling code inside a OnTriggerEnter() method and what I was hoping to do was have an additional if condition into my code like:

if (Input.GetButtonDown("Pickup")){ //then it ok to pickup! }

This is how i did it in my other projects. But I had been importing the CrossPlatformInput namespace and then just copied and adapted the buttons from the Jump button that came as standard with that.

So now, I can't see how to name my button as 'Pickup'. I tried looking at the code from CrossPlatformInput, it seems it takes the name you provide it, and passes it to VirtualInput (also in the CrossPlatformInput namespace), I couldnt see a copy of this class anywhere, it think its closed source maybe :/

Of course, I could probably manually make a method to add to the OnClick() which just makes a bool true only when it's being clicked. But I feel like there must be a way to just add this UI button as 'Pickup' to the Input system (like you do with "Horizontal", "Vertical" or "Jump" for example).

Again, I tried to read the docs, and also lots of forums and sites like this. I found that the EventSystem will (or should) have the part I need, but i am now stuck.

I tried this:

EventSystem.current.currentSelectedGameObject.name == ??????????

I read that will return the name of the most recent button pressed, but how would that method know that my new Button is called "Pickup", I dont see how I added it to that yet?

Another reason why i'd like to do it this way is for Cross Platform compatibility. If I make it this way, I already now that there is a certain button on the keyboard mapped in Project>Input to the same name (ie. "Pickup" ; Left-Ctrl). And it seems cleaner to use the existing way of doing this if possible, im sure its just that I dont know how yet.

Most options ive seen online involve the OnClick inspector function, or CrossPlatFormInput imported package.

I hope this makes sense to someone, and that there is a way to do it. Thanks for any help as usual very much appreciated.


texts: A* search in hexagonal grid with minimum turn radius

texts:
I need to run an A* search through a hexagonal grid. However, I have one nasty constraint: my vehicle can only turn so sharp. It has a specified minimum turn radius. I can't quite see how to translate this constraint into something I can use with each cell expansion to determine if a neighbor is viable or not. My grid cells are significantly smaller than the minimum turn radius.

I have an initial angle and location of the vehicle; it seems I need to keep a current angle with each cell. With that in mind, I'm not quite sure when I need to reset reference point. It seems that I cannot do that every cell or I will only go in a straight line.

I can translate that turn radius into a polygon (with several hundred sides) where each side length is the distance between my grid cells. I'm not sure how to use this, though.


texts: SDL2 SDL_PollEvent endless polling on key hold

texts:
What is wrong with SDL2 SDL_PollEvent() function? When I press-and-hold a key it enters "while (SDL_PollEvent())" block each frame. If in previous frame event queue was emptied and in new frame I press-and-hold button it should create one event - SDL_KEYDOWN. Run this code. It has macro to compile for SDL2 and SDL1.2. SDL1.2 runs okay, polls keyhold and empies queue. SDL2 seems to pump it back each frame, so SDL_PollEvents grabs the same even next frame.

#define USESDL2

#include <iostream> //cout
using namespace std;

#ifdef USESDL2
//link with -l SDL2
#include <SDL2/SDL.h>
#include <SDL2/SDL_events.h>

#else
//link with -l SDL
#include <SDL/SDL.h>
#include <SDL/SDL_events.h>

#endif // USESDL2

int main(int argc, char **argv)
{
    bool q = true;
    SDL_Event e;

    SDL_Init(SDL_INIT_VIDEO);
#ifdef USESDL2
    SDL_Window *win;
    win = SDL_CreateWindow("SDL2", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, SDL_WINDOW_SHOWN);
#else
    SDL_Surface *buff;
    buff = SDL_SetVideoMode(640, 480, 32, SDL_SWSURFACE);
#endif
    while (q) {
        while (SDL_PollEvent(&e)) {
            cout << "Polling: ";
            switch (e.type) {
            case SDL_QUIT:
                q = false;
            break;
            case SDL_KEYDOWN:
                cout << "Key down: ";
                switch (e.key.keysym.sym) {
                case SDLK_q:
                    q = false;
                break;
                case SDLK_UP:
                    cout << "UP\n";
                break;
                case SDLK_r:
                    cout << "r\n";
                break;
                }
            break;
            }
        }
    }

#ifdef USESDL2
    SDL_DestroyWindow(win);
#endif
    SDL_Quit();
}


texts:
I am trying to see changes of component 'z' from light space. In vertex shader component 'z' divide 'w' is not 0. But after sending float4 with texcoord1 to pixel shader its 0. All matrices are good. Here is the code:

float4x4 MatWorld;
float4x4 MatView;
float4x4 MatProjection;

float4 LightViewMatrix;
float4 LightProjectionMatrix;
float4 LightPosition;

texture tex0;

sampler2D ShadowMap = sampler_state
{
    texture = tex0;
};

struct VertexOut
{
    float4 position : POSITION;
    float2 tex : TEXCOORD0;
    float4 lightViewPosition : TEXCOORD1;
};

struct VertexIn
{
    float4 position : POSITION;
    float2 tex : TEXCOORD0;
};

VertexOut VSLight(VertexIn In)
{
    VertexOut Out;

    In.position.w = 1;
    Out.position = mul(In.position, MatWorld);
    Out.lightViewPosition = Out.position;
    Out.lightViewPosition = mul(Out.lightViewPosition, LightViewMatrix);
    Out.lightViewPosition = mul(Out.lightViewPosition, LightProjectionMatrix);

    Out.position = mul(Out.position, MatView);
    Out.position = mul(Out.position, MatProjection);

    Out.tex = In.tex;
    return Out;
}

float4 PSLight(float4 Color : COLOR, float2 tex : TEXCOORD0, float4 lightViewPosition : TEXCOORD1) : COLOR
{
    float depth = lightViewPosition.z / lightViewPosition.w;
    if (depth == 0)
    {
        return float4(0, 0, 0, 1);
    }
    return float4(depth, 0, 0, 1);
}

technique T1
{
    pass P0
    {
        VertexShader = compile vs_2_0 VSLight();
        PixelShader = compile ps_2_0 PSLight();
    }
};

All objects are black. Sorry my english is slightly poor.


texts:
I'm researching text rendering techniques for 3D applications, and I'm having a hard time finding information on the topic. Do you know of any other methods of text rendering that are actually used in current games or have a historical significance?

So far I have:

Using prerendered bitmaps of glyphs / strings as textures,
converting the glyph vectors to triangle meshes and rendering it as such,
signed distance fields (popularized by Valve's paper),
GLyphy.

I haven't managed to find anything else though.

Does anyone know what large engines, such as Source, Unreal, Unity, etc. use?

Sources would also be greatly appreciated.

Thanks.


texts: I've read this: http://msdn.microsoft.com/en-us/library/windows/desktop/ff476898%28v=vs.85%29.aspx#Shader_Constant_Buffer but there's not much information in it. When creating a constant buffer do I have to worry about what I put in it and in what order? Do I have to stick to a multiplicity of some power of 2 in bytes or something?


texts: Calculate impulse need on object to throw i Y meters into the air, with varying mass

texts:
Say I have an object that has a variable mass. Now I want to apply a vertical impulse (straight up into the air) onto the object, so it always flies up to the same height. How do I calculate this?

So the variables are:

m: mass
Y: height (constant)
If: Impulse force
G: Gravity

The origin is always from a floor, so no mid-air impulses or anything.

(I'm using the Box2D engine, but I think that a solution would be engine independent?)


texts:
I have a worldmap, with different cities on it. The player can choose a city from a menu, or click on an available cities on the world map, and the toon should walk over there.

I want him to follow a predefined path.

Lets say our hero is on the city 1. He clicks on city 4. I want him to follow the path to city 2 and from there to city 4.

I was handling this easily with arrow movement (left right top bottom) since its a single check.

Now I'm not sure how I should do this. Should I loop threw each possible path and check which one leads me to D the fastest ... and if I do how do I avoid running in circle forever with cities 1-5-2  ?


texts: opengl bump mapping (normal mapping) problem with VBO and GLSL

texts:
hi i am beginner i am trying to implement bump mapping with vbo and glsl.
My question is: did i make bump mapping ? if i did why these edges didnt disappear ?

high and low meshes (i used low meshes of course)


texts: What is the "pricing standard" on Windows Phone?

texts:
On iOS, I find it is more usual to see light versions of a game for free (with ads and less features) and a full version for a cost and all the features.

On Android, I see more games that have both a full version for free and one for a cost. One with ads and the other without.

On WP7, how are games usually priced?

Talking about a rather simple and small game here and I'm trying to figure out how to price it. I'm thinking of going for a 1$ app with full features no ads, but I'm not so sure. Would it be more profitable to put it for free with ads instead? How do other developers usually make that choice?


texts: Make a plane to display material from both sides

texts:
I know there is a setting in Cry Engine, which allows you to be able to read materials of the plane from both sides, so I am wondering if there is such a setting in Unity5.

Thanks in advance


texts: How should I approach architecting a data-driven shoot-em-up?

texts:
I'm venturing into Mobile/Tablet based development coming from the world of Web Applications.

I want to write a game similar to 1942/43 video game from the 80's:

...similar in the sense that I have a plane/spaceship that flies vertically "up" the screen and stuff comes down to attack it (otherwise nothing that would violate copyright).

I'm familiar with collision detection, sprites, object pooling, etc. but what I'm spinning my wheels on is how to layout all the code for this game.  e.g. it doesn't fit my normal MVC pattern, I don't have a DB, and the user input will likely be limited to touch based movement around the screen with "auto-fire" on all the time.

What I'm blanking out on is how to do all the "levels" and sequence "waves" of attackers within a level.

Should I just have a "level" file for each level, that queue's up attack waves? if so, based on time? based on some event? based on a position passed by the player?

e.g.

<level id="1">
  <event timeoffset="500" type="attack" name="vConfiguration" position="50"/>
  <event timeoffset="1250" type="attack" name="jConfiguration" position="75"/>
  <event timeoffset="1300" type="bonus" name="quadGunUpgrade" position="10"/>
  ...
</level>

Part of me thinks this would be really easy to setup levels this way, then read in the file to queue up the events for the attacks/bonus/? to occur (where each named "attack" is a bit of configured code to position "N" enemies and start their flight sequences)

The other part of me thinks - whoa! before you even dream of implementing this - determine how others would approach it - no need to re-invent the wheel or create a monster.


texts: How can I do a Metroid like transition between two tilemaps with Monogame Extended?

texts:
I want to do a transition like those in the Metroid games. Here is an example of what i mean: https://www.youtube.com/watch?v=RKJ3MAi0ZI0.
You enter the door, the screen fades to black and the camera scrolls to the next room where the screen fades in again.

I'm using Monogame Extended and i have a TiledMap. I use them like described in the documentation. I have a camera with a view matrix and a projection matrix

   Camera2D camera;

   ...

   public void DrawGame(GameTime gameTime, SpriteBatch spriteBatch)
   {
        var viewMatrix = camera.GetViewMatrix();
        var projectionMatrix = Matrix.CreateOrthographicOffCenter(0, gDevice.Viewport.Width, gDevice.Viewport.Height, 0, 0f, -1f);

        tiledMap.Draw(viewMatrix, projectionMatrix);
   }

My idea is now to create a second tiledMap to placing them directly next to the first one where the transition occurs. Then i just have to move the camera from one map to the next one. My problem now is that i have no clue how to put them next to each other. From my understanding i somehow have to use the view and projection matrix to draw the tiledMap but i can't figure out how it should work with two tiledMaps.


texts: Alternative in-game dev console implementations

texts:
I'm developing a dev console for my game. Currently I have a simple parser which is basically a regex which accepts words with dashes and dots (ie. list, 1.0, list -i) or simplistic arrays and maps (ie. [1,2,3], [x:1.0, y:2.0]). I plan on making an AST parser later on but for now this works well enough.

When these tokens get parsed first token in parsed line is the command token which is used to invoke a registered command. Commands are classes which implement a ConsoleCommand interface which looks like this (basic command pattern):

interface ConsoleCommand {
    val description: String
    val instructions: String
    fun execute(args: Array<Any>): String
}

This works, but I'm not quite satisfied since to actually register any console commands I must do so where I can access the entity. For example if I want to register the player as an interactable console command I must do so either in a custom system only created for the specific console command, or add console specific code into existing systems, basically polluting my codebase with console specific code.

My question here is what are alternative dev console implementations? Is there a way to implement a console which wouldn't affect the rest of the codebase?

I have an inkling of an idea where the console could be some sort of an observer and it itself would register onto entities and stuff, but I don't see a way of implementing that without having the entities implement some sort of special observable interface so that they can actually be observed, as well as the fact that observers usually don't manipulate the entities themselves....


texts: Issues to display a texture loaded with libPNG with opengles 3.0

texts:
I'm trying to load a texture loaded with libPNG on a XY coordinates. I know the width and the height of the texture (32x32).

The texture is already loaded successfully and I have his Id.

Here is my function to print any (32x32) texture on a XY position :

void printTexture(GLuint idTexture, GLfloat x, GLfloat y) {
    glActiveTexture(GL_TEXTURE0);
    glBindVertexArray(this->VAO[0]);
    glUniform1i(this->mTagShaderHandle, 0); //to execute a particular code on the Pixel Shader
    glUniform1i(this->mTextShaderHandle, 0); //the uniform Sampler2D from my Fragment Shader bound to 0.

    GLfloat xpos = x;
    GLfloat ypos = y;

    GLfloat w = 32;
    GLfloat h = 32;

    GLfloat vertices[6][4] = {
            { xpos,     ypos + h,       0.0, 0.0 },
            { xpos,     ypos,           0.0, 1.0 },
            { xpos + w, ypos,           1.0, 1.0 },

            { xpos,     ypos + h,       0.0, 0.0 },
            { xpos + w, ypos,           1.0, 1.0 },
            { xpos + w, ypos + h,       1.0, 0.0 }
    };

    glBindTexture(GL_TEXTURE_2D, idTexture);
    checkGlError("glBindBuffer");

    glBufferSubData(GL_ARRAY_BUFFER, GL_ZERO, sizeof(vertices), vertices);
    glDrawArrays(GL_TRIANGLE_STRIP, GL_ZERO, 6);
    glBindVertexArray(GL_ZERO);
    glBindTexture(GL_TEXTURE_2D, GL_ZERO);
}

Here is how I initialize my VAO and VBO :

glBindVertexArray(this->VAO[0]);
glBindBuffer(GL_ARRAY_BUFFER, this->VBO[0]);
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * 6 * 4, GL_ZERO, GL_DYNAMIC_DRAW);
glEnableVertexAttribArray(GL_ZERO);
glVertexAttribPointer(GL_ZERO, 4, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), GL_ZERO);
glBindVertexArray(GL_ZERO);

Here is how I set up my texture:

glTexImage2D(GL_TEXTURE_2D, GL_ZERO, GL_RGB, temp_width, temp_height, GL_ZERO, GL_RGB, GL_UNSIGNED_BYTE, image_data);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);

And my Vertex Shader :

const char           gVertexShader[] =
        "#version 320 es\n"
        "layout (location = 0) in vec4 vertex;\n"
        "out vec2 TexCoords;\n"
        "uniform mat4 projection;\n"
        "uniform int tag;"
        "void main() {\n"
                "  gl_Position = projection * vec4(vertex.xy, 0.0, 1.0);\n"
        "  if (tag > 0) {\n"
        "      TexCoords = vertex.zw;\n"
        "  } else {\n"
        "      TexCoords = vertex.xy;\n" //here is the code that should be executed by the pixel shader program because Tag = 0.
        "  }\n"
        "}\n";

The texture is not displaying at all. I tried a lot of things but nothing change. I should keep this pixel shader because I have some functions to print texts so that's why I have the if/else statement on my Pixel Shader code.

What's wrong with my code ?

Thanks a lot for help.


texts: Do delays after losing and before restarting serve as a defense against burnout, or are they addiction machines?

texts:
In games like Super Hexagon or even Everwing, there's a very brief but noticeable delay from losing to starting over: waiting for the restart button to appear, pressing it, etc...

Is this a defense against player burnout? If there's no pause that separates one game try from next, the game might feel never-ending and burn out the player quickly.

Or is it a way to keep the player addicted? I often suspected this in Everwing, because that game's hardly shy about its avaricious nature. Perhaps there's a psychological effect in making the player wait before they can play again — like building the craving part of a habit?

Or perhaps a lack of this delay is to keep the flow going, so to speak? Ori and the Blind Forest does something similar in its Ginso Tree level. It has very fast restarts, no button or anything, and deaths do not restart the music that's playing in the BG. The result is that deaths do not break the flow of the game, and despite them the whole level feels seamless.

So, are there any studies on this? Barring those, anecdotes? I couldn't find anything, anywhere.


texts: XAudio2: how to convert seconds to samples

texts:
in the Xaudio2 API you can specify the start and endposition only in samples.

but i require them to be set by seconds.

now i am looking for a way to convert seconds into samples but havent found much information on how to do that so far.

any help on this is highly appreciated!