texts: libgdx : Scrolling background from spritesheet causes lag when sprite is repositioned... am I doing something wrong?

texts:
So, I use a sprite from a spritesheet to draw the background and repeat it. (I am drawing it twice) However, the moment that the background is re-positioned to make it look infinite, it causes a lag.

What's the right way to do this without having the background image in a separate file?

BetterSprite sprite = new BetterSprite(new TextureRegion(sprites_texture), spritedef.x, spritedef.y, spritedef.width, spritedef.height);

// BetterSprite is just my extended class that returns .scaledWidth and scaledHeight for scaled sprites

this is how I draw the background

    //initial scrollingX = 0

    floor.setScale(textureScale);
    floor.setY(0);
    floor.setX(scrollingX);
    floor.draw(batch);

    // fill screen
    floor.setX(scrollingX + floor.getScaledWidth());
    floor.draw(batch);

    //fill screen
    floor.setX(scrollingX + ( floor.getScaledWidth() *2) );
    floor.draw(batch);

    if(scrollingX < -floor.getScaledWidth() ){
        scrollingX += floor.getScaledWidth();
    }

The 'scrollingX' gets updated in the doUpdate() method.

It's pretty good when scrolling, but when scrollingx<-floor.getScaledWidth() happens, I get lag.

What's the correct way to do this?


texts: Vertical alignment of a padded font generated by Hiero in libgdx

texts:
I've generated bitmap fonts for libgdx using Hiero. I've got several distance field fonts that require a lot of padding, unfortunately they don't seem to align correctly.

Below is a font with a bounding box drawn to the values returned from getBounds().

I've just changed to distance field fonts and all my logic that handles vertical positioning is broken because of this. If I use a font without any padding above or below then fonts are drawn aligned correctly.

My padding is 10 on all sides. Playing with a couple of characters, if I increase the y by 10 and decrease the height by 10 in the .fnt file I get the image below instead, which looks far more accurate.

If someone can tell me how I can resolve this issue, or a good way to work around it then that would be appreciated.


texts: How do I get mouse x / y of the world plane in Unity?

texts:
I am trying to make a tiled landscape. The terrain itself is not made from tiles but the world has a grid which I define.

I would like to place boxes/rectangles which snap to this grid, at runtime, but in order for me to do that I must get a projection from the user screen to the real-world coordinates.

I have tried various examples using the Ray class but nothing worked. It compiles and outputs a constant value no matter where I put the mouse. I have tried to add some tiles and try to detect them but no luck. I also tried with one plane as big as my world but still no luck.

I am using C# but even a JS version would be helpful.

This technique involves calculating which tile the mouse is under by the x and y positions. Perhaps detecting which tile itself is being pointed to would be a simpler task, at which point I can just retrieve its i/j properties.


texts: Dual Currency vs. One Currency in social games economics and monetization

texts:
Not a programming question but game development related.

I am creating an iPhone online game which I wish to be free-to-play where in-app purchase is used for monetization. The important point is to make sure that this does not break the game-play, my priority is gameplay first, monetization second.

One popular way of monetizing the player base is to sell your in-game currency, however there are 2 ways to go about this:

One Currency: This currency can buy anything within the game, it can be earned through normal play at a limited rate. Players can, however, choose to buy this currency directly to speed up the acquisition of the currency.
Dual Currency: One currency can be earned through normal play and it can be used to buy a limited set of items that is required for normal enjoyment of the game. The second currency is 'premium' and must be purchased using real world money. This second currency can be used to purchase 'premium items' that gives extra abilities such as increase EXP gain, etc. The 2 currencies can be traded between players to give non-paying players to exchange their time for the 'premium' currency.

Both methods do not break gameplay and allows players who does not wish to pay enjoy the entire contents of the game if they put in enough time and effort.

My question is, is there any reason why you would pick one over another? What are the pros and cons that I should pay attention to when implementing each alternative?

Thank you.


texts: Automatically zoom out the camera to show all players

texts:
I am building a game in XNA that takes place in a rectangular arena. The game is multiplayer and each player may go where they like within the arena. The camera is a perspective camera that looks directly downwards.

The camera should be automatically repositioned based on the game state. Currently, the xy position is a weighted sum of the xy positions of important entities.

I would like the camera's z position to be calculated from the xy coordinates so that it zooms out to the point where all important entities are visible.

My current approach is to:

hw = the greatest x distance from the camera to an important entity
hh = the greatest y distance from the camera to an important entity
Calculate z = max(hw / tan(FoVx), hh / tan(FoVy))

My code seems to almost work as it should, but the resulting z values are always too low by a factor of about 4.

Any ideas?


texts: Correcting different dash distances depending on frame rate when using deltaTime

texts:
I'm trying to make a character do a short hop or dash. The player doesn't have control of the character for the duration of the dash, which is supposed to be about .4 seconds.

I tried several ways of doing this... I made a different state that the player is in for that amount of time by creating a float like targetTime and checked when Time.time became bigger than targetTime to give back control to the player. Or I could make a float variable like stateTimer and subtract Time.deltaTime each time.

What I noticed is that depending on whether I test the game in the window or maximized, the distance of the dash changes. The game runs noticeably smoother in maximized mode, and depending on the way I calculate movement, the dash goes further or shorter.

The smoother the game runs, the smaller Time.deltaTime becomes, so in an optimal case, targetTime and Time.time would line up exactly. But the larger deltaTime is, the more it can "overshoot" the targetTime and lead to different results, especially when the time frame is only half a second...

When the game runs in windowed mode, deltaTime ranges from around 0.03 to 0.06, which can overshoot quite a bit, but when it's maximized it's around 0.007, around 10 times smaller.

Is there a way to circumvent this? I have no idea how else I'd measure a time frame as short as .4 seconds. Or should I just not bother because the compiled game should run smoothly anyhow (not planning on making it very demanding hardware wise)

I tried around with fixedDeltaTime but that didn't lead to any good results...


texts: Difference in Shading Using Eye Space or Model Space Coordinates

texts:
While reading on shading, I came across a section in which the artist provides 2 different kinds of fragment shading:

Coloring using model space and eye space.

The result is as illustrated in the following image:

The author goes on with a brief explanation claiming that the image on the left is a result of shading in model space coordinates because the stripes follow the vx value running from the tip of the spout to the handle while the image on the right is based in eye space coordinates, with the stripes following the vx value from right to left.

My questions are as follow:

I have been spending hours trying to understand why and how the effects would be different in both cases (why are the stripes different in both cases?). In addition, is there any particular case when we need to perform shading in the model space coordinates and likewise only in eye space coordinates?

Thanks.


texts: Animating a texture growing & fading with a Unity 2D particle system

texts:
I've created texture which could represent a lightning orb.
Is it possible to animate scaling of the texture to simulate this lighting burst? Like the orb is growing and than fades away.

Or do I need to make sequence of similar images and then animate it as particle system in Unity?


texts: Best pathfinding for a 2D world made by CPU Perlin Noise, with random start- and destinationpoints?

texts:
I have a world made by Perlin Noise. It's created on the CPU for consistency between several devices (yes, I know it takes time - I have my techniques that make it fast enough).

Now, in my game you play as a fighter-ship-thingy-blob or whatever it's going to be. What matters is that this "thing" that you play as, is placed in the middle of the screen, and moves along with the camera.

The white stuff in my world are walls. The black stuff is freely movable.

Now, as the player moves around he will constantly see "monsters" spawning around him in a circle (a circle that's larger than the screen though). These monsters move inwards and try to collide with the player.

This is the part that's tricky. I want these monsters to constantly spawn, moving towards the player, but avoid walls entirely.

I've added a screenshot below that kind of makes it easier to understand (excuse me for my bad drawing - I was using Paint for this).

In the image above, the following rules apply.

The red dot in the middle is the player itself.
The light-green rectangle is the boundaries of the screen (in other words, what the player sees). These boundaries move with the player.
The blue circle is the spawning circle. At the circumference of this circle, monsters will spawn constantly. This spawncircle moves with the player and the boundaries of the screen.
Each monster spawned (shown as yellow triangles) wants to collide with the player.
The pink lines shows the path that I want the monsters to move along (or something similar). What matters is that they reach the player without colliding with the walls.

The map itself (the one that is Perlin Noise generated on the CPU) is saved in memory as two-dimensional bit-arrays. A 1 means a wall, and a 0 means an open walkable space. The current tile size is pretty small. I could easily make it a lot larger for increased performance.

I've done some path algorithms before such as A*. I don't think that's entirely optimal here though.


texts: Is it possible (from the vertex shader) to always draw at specific pixels?

texts:
I am wondering if I can (if possible) make a vertex shader that will always make the pixel shader draw everything in 1 pixel, at position 0,0.

I know this sounds crazy, but it's needed in the situation I'm in right now.

Let's say that I am drawing a line with 2 vertices that each have the color blue. For every vertex, I tried attaching a TEXCOORD that specifies what pixel I want this vertex to be drawn in. However, I can't get this to work.

The reason I am doing this is that I am making experiments where the physics of my game (which is very intensive) is drawn onto a texture, and handled by the GPU.


texts:
i made a terrain on unity. I haven't write scripts yet. But i am getting really big render difference between standalone version and editor verison. Please help me, have nice day.

In Editor:

After build (standalone version):


texts:
This is how I'm creating my player. Is there any way to start fading in and fading out for an amount of time when I get hit?

private Texture tex = Game.res.getTexture("player");

public Player(Body body) {
   TextureRegion[] sprites = new TextureRegion[1];
   sprites[0] = new TextureRegion(tex, 0, 0, 70, 96);
   sprites[1] = new TextureRegion(tex, 69, 193, 68, 93);
   animation.setFrames(sprites, 1 / 6f);
}


texts: Is it possible with DirectX11 to have pixel shader output an integer rather than float4?

texts:
I am trying to implement object picking via a shaders.  My intent is to create a texture2d that I would write out ID values describing individual objects.

Following drawing the objects, I would query back the pixel value at the focus point and read out the ID of the object.

I've created my texture2d as follows:

// Create a very tiny selection texture.
// This will record the color ID as unique identifier of a selectable object.
D3D11_TEXTURE2D_DESC desc;
desc.Width = 1;
desc.Height = 1;
desc.MipLevels = 1;
desc.ArraySize = 1;
desc.Format = DXGI_FORMAT_R32_UINT;  // 16 bit integer, hold up to 65536 possible unique IDs.
desc.SampleDesc.Count = 1;
desc.SampleDesc.Quality = 0;
desc.Usage = D3D11_USAGE_STAGING; // We will write via GPU and read to CPU!
desc.BindFlags = D3D11_BIND_RENDER_TARGET;
desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
desc.MiscFlags = 0;

HRESULT result = m_deviceResources->GetD3DDevice()->CreateTexture2D(&desc, 0, &m_colorRenderTarget);
if (FAILED(result)) {
    OutputDebugString(L"PickRenderer: Unable to create Texture2D");
}

Is it possible to then to make a pixel shader that would write out an R32 integer value, rather than the float values for RGBA?  If so, how would I best do this?

My pixel shader currently writes float RGB values out as follows:

// A constant buffer that stores the model transform.
cbuffer ModelConstantBuffer : register(b0)
{
    float4x4    modelToWorld;
    float3      color;  // Instead use unsigned int32 here if possible?
};

// Per-vertex data used as input to the vertex shader.
struct PixelShaderInput
{
    min16float4 pos     : POSITION;
};

// Can this use a different return value for uint?
min16float4 main(PixelShaderInput IN) : SV_TARGET
{
    return min16float4(color, 1.f);
}

Thanks, I've been trying to find an answer to this, but it seems very unusual to write out non-float values if it is possible.


texts:
Goal: Render distance lines between two points on the surface of a mesh-based primitive (i.e. sphere, cube, etc).

Current Solution: Iteratively traverse distance line between two end points and "reverse" raycast through this point somehow. Since the distance line directly connects both vertices through the mesh, the according points on the mesh surface are required.

Ray ray = new Ray();
RaycastHit raycastHit;
ray.origin = posOnDistanceLine;
ray.direction = raycastNormal.normalized;
// Reverse ray since we can't raycast from inside the mesh
ray.origin = ray.GetPoint(1);
ray.direction = -ray.direction;

Lines are then drawn using Unity's LineRenderer which is being populated with positions of vertices whenever a change in normals (to previous raycast) is identified.

Issues:

Horrible performance (as 100 rays are cast whenever the end points move).
Solution doesn't always work and produces unexpected, jagged lines / points.

Question:
Is there a better approach to implement this?


texts: 2D map/plane with nodes overlayed that supports panning, scaling and clicking on nodes

texts:
I'm trying my hand at Android development and seem to be running into an invisible ceiling in trying to get what I want accomplished. Basically I'm trying to create an app that renders a 2D surface map that I can (pinch) zoom and pan. I'll have to place nodes on the surface of the map that will scale/zoom and pan in relation to the surface.

I started out with a 2D ImageView approach and got as far as pinch zoom, pan and laying nodes as relative ImageViews, but all the methods I tried to get X,Y,W,H for the 2D surface were always off for some reason. Additionally, I was never able to scale the node ImageViews correctly, and as a result never got far enough to try and work out their X,Y scaled offset.

So I decided to get back to 3D rendering. Conceptually pan/zoom is camera manipulation, so I don't have to mess with how to scale the 2D map or the nodes. But I need a starting point or sample to get me going that's close to what I'm trying to achieve. A sample on a translucent spinning cube isn't helping as much as I need it to.

Any tips? Links, insults and sympathy are all welcome!


texts:
I'm importing arms from blender for my first person controller but when I make the player the Arms' parent it turns 2d. I have no idea why this is happening so if anyone could help it would be very appreciated.

I'm very confused lol


texts: procedural generation - deterministic or not? (No man's sky)

texts:
Here is a link of Sean Murray talking about the game No Man's Sky:

https://www.youtube.com/watch?v=h-kifCYToAU

Starting at around 4:00 in the video, he is talking about how the environment is procedurally generated.

At first, I thought it meant that they ran some incredibly complex algorithms to generate the entire universe and then stored it.

But as he explains, the world doesn't really exist as stored 3d data and what have you, but it really is just the output of a very complex function that takes your position (3d coordinates, and I guess time as well) as input and always generates the exact same environment around you based on that, no matter where you are in this gigantic universe.

This is incredibly smart and interesting but there are a few things that I don't understand:

How can you interact with the environment and have any effect on it if it is the result of a deterministic function? You would have to "update" that function every time you interact, don't you?

How can multiple players interact with the environment and see the same changes?

How can only a single player blow out a piece of rock and then expect it to stay blown apart? Does it change the "world-generating function" ?


texts: Reference a single 2d Rectangle in an array

texts:
What I am attempting to do probably has a very simple answer but I can't make heads or tails of it no matter how hard I try.  Provided I'm a newb.

What I am trying to do is after I create a grid of rectangles, when the cursor moves into the grid, it changes the color of the rectangle the cursor is currently in (or highlights it), then changes back when the cursor leaves.  Here's what I've coded so far:

namespace MapGenie
{
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        Rectangle[,] gameGrid;

        MouseState currentMouseState;
        MouseState previousMouseState;

        bool colorChange = false;

        Color color;
        Color previousColor;

    protected override void Initialize()
    {
        //Creates the array
        gameGrid = new Rectangle[10, 10];

        color = Color.Black;

        base.Initialize();
    }

    protected override void LoadContent()
    {
        spriteBatch = new SpriteBatch(GraphicsDevice);
        this.IsMouseVisible = true;

        int Gridsize = 20;

        //Creates the grid
        for(int x = 0;x <10;x++)
            for (int y = 0; y < 10; y++)
            {
                gameGrid[x, y] = new Rectangle(x * Gridsize, y * Gridsize, Gridsize, Gridsize);
            }
    }

    protected override void Update(GameTime gameTime)
    {
        currentMouseState = Mouse.GetState();
        var mousePoint = new Point(currentMouseState.X, currentMouseState.Y);
        previousMouseState = currentMouseState;

        //Checks each rectangle in the gameGrid array to see if cursor is there?
        foreach (Rectangle grid in gameGrid)
        {
            if (grid.Contains(mousePoint))
            {
                previousColor = color;
                color = Color.Blue;
                colorChange = true;
            }
            if (colorChange == true)
                color = previousColor;
        }

        base.Update(gameTime);
    }

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

        spriteBatch.Begin();

        var t = new Texture2D(GraphicsDevice, 1, 1);
        t.SetData(new[] { Color.White });

        foreach (Rectangle grid in gameGrid)
            spriteBatch.Draw(t, grid, color);

        spriteBatch.End();

        base.Draw(gameTime);
    }
}
}

Before I added the else statement (Which I am also aware does not work, but I am working to fix that after asking this), the entire grid would turn blue.  So, I am not sure if it is the right question or not, but how do you get just the one the cursor is in to change color?


texts: I'm trying to make a 3D tour for cardboard. I'm putting my 3d image inside a sphere with a shader but I've noticed this problem. And the middle of the image is looking kinda wavey and distorted.


texts: Unity: How can I control a Shadergraph effect on multiple enemies with the same prefab?

texts:
So I made a simple White Flash -> Dissolve effect with shader graph 2D, it's my 1st time using shaders.
I'm controlling the effect using a float inside the shader, with:

Material.SetFloat("FLOAT_NAME", 0-1f);

And I'm wandering how can a control only a single instance of my Shader without affecting all my enemies.

Example:
I have 20 enemies, all from the same prefab with the same material.
I want to be able to make 1 enemy dissolve whenever I shoot at him.


texts: Generating random values, keep trying till value within bounds are generated

texts:
Sorry for the strange topic name, couldn´t think of a good way to describe it.
I´m basically trying to achieve the following:

I'm placing items randomly on the screen, but these items shouldn't be placed near eachother at a given distance.
This is the process I have in my head right now:

generate a random location
check if this location is not near any other objects
it is near -> start the process over to generate a new item (till it is not near anymore)

I've run into this scenario multiple times but could never think of a way to efficiently do this, while I do feel that there is a simple way to do it. Here is the implementation I have right now. I feel like I should use a while loop but I can't get my around how to do it.
The code is in AS3 but that shouldn't matter.

public function generatePlanetsFromXML(xml:XML):void
    {
        planets = new Array();

        for (var i:int = 0; i < xml.projects.project.length(); i++) {

            var planet:Planet = new Planet();
            planet.data = xml.projects.project[i];
            planet.radius = (Math.random() * 20) + 20;
            addChild(planet);
            addObject(planet);

            planets.push(planet);

            calculatePlanetLocation(planet, i);
        }

    }

    private function calculatePlanetLocation(planet:Planet, i:int):void
    {
        var randomX:int = (Math.random() * (worldwidth - planet.width)) + 20;
        var randomY:int = (Math.random() * (worldheight - planet.height)) + 20;

            //get a location that isn't close to another planet
            //keep looping till the distance is higher than minimum distance
            for (var j:int = 0; j < planets.length; j++) {

                if (i != j) {

                    var dx:int = planets[j].x - randomX;
                    var dy:int = planets[j].y - randomY;
                    var distance:int = Math.sqrt((dx * dx) + (dy * dy));

                    if (distance < minPlanetDistance) {

                        trace("retry getting location..");
                        planet.alpha = 0.3;
                        calculatePlanetLocation(planet, i);

                    }else {

                        //distance is fine, planet can be placed!
                        planet.x = randomX;
                        planet.y = randomY;
                    }

                }else if (i == 0) {

                    //first planet should always be placed
                    planet.x = randomX;
                    planet.y = randomY;
                }

            }
    }


texts: File saved to IndexedDB lost unless we change scenes

texts:
Our game includes an in-game level editor. When the user saves a custom level, the level is serialized and written to a file:
public void SaveFile<T>(T obj, string path) {
    if (!typeof(T).IsSerializable) {
        throw new ArgumentException("Tried to save non-serializable type " + typeof(T).Name);
    }

    FileStream fs = null;
    try {
        fs = new FileStream(path, FileMode.Create);
        DataContractJsonSerializer serializer = GetSerializer();
        serializer.WriteObject(fs, obj);
    } catch (Exception ex) {
        Debug.LogException(ex);
    } finally {
        if (fs != null) fs.Close();
    }
}

Serialized files can be loaded like this:
public T LoadFile<T>(string path) {
    if (!typeof(T).IsSerializable) {
        throw new ArgumentException("Tried to deserialize non-serializable type " + typeof(T).Name);
    }

    if (!File.Exists(path)) return default(T);

    FileStream fs = null;
    T result;
    try {
        fs = new FileStream(path, FileMode.Open);
        DataContractJsonSerializer serializer = GetSerializer();
        var result = (T)serializer.ReadObject(fs);
    } catch (Exception ex) {
        Debug.LogException(ex);
        throw ex;
    } finally {
        if (fs != null) fs.Close();
    }

    return result;
}

When displaying a "Load" menu, we enumerate the saved files like this:
public List<T> LoadFiles() {
    if (!Directory.Exists(path)) {
        Debug.Log("No save files found");
        return new List<T>();
    }

    var files = Directory.EnumerateFiles(path);
    Debug.Log("Found " + files.Count() + " files");

    List<T> result = new List<T>(files.Count());
    foreach (string file in files) {
        Debug.Log(file);
        T obj = LoadFile<T>(file);
        if (obj == null) Debug.Log("File at " + file + " loaded null");
        if (obj != null) result.Add(obj);
    }
    return result;
}

I have omitted a lot of code for brevity, but what is shown above should cover the important parts.
In the Editor, everything works perfectly. However, in WebGL builds (where files are saved to/loaded from the browser IndexedDB), there is a strange quirk: the file doesn't remain in IndexedDB unless the user changes to a different scene after saving.
Scenario 1:

In the level Editor, Bob presses "Save"
The file is saved, and the browser console shows the log entry File saved to /idbfs/abc123/CustomLevels//FileName
Bob refreshes the webpage
Bob clicks "Load"
The game searches IndexedDB but does not find the file saved in step 2

Scenario 2:

In the level Editor, Alice presses "Save"
The file is saved, and the browser console shows the log entry File saved to /idbfs/abc123/CustomLevels//FileName
Alice returns to the main menu scene
Alice refreshes the webpage
Alice clicks "Load"
The game searches IndexedDB and does find the file saved in step 2

The browser console log suggests that after Bob refreshes the page in Scenario 1, the file no longer exists. If this was the only scenario that Bob had saved, we see the message "No save files found". If Bob had previously saved other scenarios and used the workaround of returning to the main menu scene, those previously saved files will appear in the console and save list, but the most recent file is missing.
Why would the save file disappear from the IndexedDB if the user leaves the webpage without changing scenes, but remain in the IndexedDB if the user returns to the main menu scene before leaving the webpage?


texts: Draw selected instances of VAO (glDrawArraysInstanced)

texts:
I'm using glDrawArraysInstanced to draw multiple instances of a tree at different positions to generate a forest.

Is there a way to draw selected instances?
For example:
I got 100 trees with different attributes.
Due to culling I only want to draw instance 3, 65, 89 and 95.


texts:
In many common AAA titles (Source engine games especially), when the player reaches an area 'un-catered' for, such as out of bounds, or noclipping under the map; a strange effect occurs on the screen (buffer tearing?).

It can be described as being similar to the trail of windows that Windows XP may leave behind a window being dragged whilst theres a system hang.

I can only postulate that the developers do not clear the color buffer when refreshing the screen?

Is that correct? If so, why?


texts: In Pygame, how can I check if an object is touching a color?

texts: Is there a way to tell if a sprite is touching a specific color on the screen, maybe given as a hex code. I know you can do pygame.sprite.collide for sprites, but how can you do this for a specific color on the whole screen?


texts:
Can anyone please help me to understand the proper use of the dispose().
Does dispose() get called automatically or do I have to make a call to it?

In a game I'm writing, I use a texture atlas and an asset manager for all of the textures I use.  I have an abstract class called Enemy and every type of enemy extends it.
I have an arraylist that holds all of my enemies, and when an enemy is dead, I remove it from the arraylist.  Do I need to make a call to the dispose() method in the individual enemy classes to remove the textures from memory before removing it from the arraylist or does it happen automatically or is that not how dispose() gets used period?  (Each individual type of enemy class sets its own textures by using a TextureRegion)


texts:
I'm following the "3D game programming with DirectX 11" book (Frank Luna) and i'm having this issue.
There is no valid constructor to convert from (const float*) to DirectX::XMFLOAT4

namespace Colors {

    XMGLOBALCONST XMVECTORF32 White = { 1.0f, 1.0f, 1.0f, 1.0f };
    XMGLOBALCONST XMVECTORF32 Black = { 0.0f, 0.0f, 0.0f, 1.0f };
    XMGLOBALCONST XMVECTORF32 Red = { 1.0f, 0.0f, 0.0f, 1.0f };
    XMGLOBALCONST XMVECTORF32 Green = { 0.0f, 1.0f, 0.0f, 1.0f };
    XMGLOBALCONST XMVECTORF32 Blue = { 0.0f, 0.0f, 1.0f, 1.0f };
    XMGLOBALCONST XMVECTORF32 Yellow = { 1.0f, 1.0f, 0.0f, 1.0f };
    XMGLOBALCONST XMVECTORF32 Cyan = { 0.0f, 1.0f, 1.0f, 1.0f };
    XMGLOBALCONST XMVECTORF32 Magenta = { 1.0f, 0.0f, 1.0f, 1.0f };

    XMGLOBALCONST XMVECTORF32 Silver = { 0.75f, 0.75f, 0.75f, 1.0f };
    XMGLOBALCONST XMVECTORF32 LightSteelBlue = { 0.69f, 0.77f, 0.87f, 1.0f };
}

The error is here

Vertex vertices[] = {
    { XMFLOAT3(-1.0f, -1.0f, -1.0f), (const float*)&Colors::White },
    {XMFLOAT3(-1.0f, +1.0f, -1.0f), (const float*)&Colors::Black },
    {XMFLOAT3(+1.0f, +1.0f, -1.0f), (const float*)&Colors::Red },
    {XMFLOAT3(+1.0f, -1.0f, -1.0f), (const float*)&Colors::Green},
    {XMFLOAT3(-1.0f, -1.0f, +1.0f), (const float*)&Colors::Blue},
    {XMFLOAT3 (-1.0f, +1.0f, +1.0f), (const float*)&Colors::Yellow},
    {XMFLOAT3 (+1.0f, +1.0f, +1.0f), (const float*)&Colors::Cyan},
    {XMFLOAT3 (+1.0f, -1.0f, +1.0f), (const float*)&Colors::Magenta}
};

and this is the struct Vertex

struct Vertex {
        XMFLOAT3 Pos; XMFLOAT4 Color;
    };


texts:
I'm trying to make a grid like, light up floor using Unity's Shader Graph. However, I am having an issue where the lines are flicking after a really short distance when the camera is moving.

The shader graph is below.

How can this issue be prevented and what is causing it?


texts: multipass shadow mapping renderer in XNA

texts:
I am wanting to implement a multipass renderer in XNA (additive blending combines the contributions from each light).  I have the renderer working without any shadows, but when I try to add shadow mapping support I run into an issue with switching render targets to draw the shadow maps.  When I switch render targets, I lose the contents of the backbuffer which ruins the whole additive blending idea.

For example:

Draw()
{
    DrawAmbientLighting()
    foreach (DirectionalLight)
    {
        DrawDirectionalShadowMap() // <-- I lose all previous lighting contributions when I switch to the shadow map render target here
        DrawDirectionalLighting()
    }
}

Is there any way around my issue?  (I could render all the shadow maps first, but then I have to make and hold onto a render target for each light that casts a shadow--is this the only way?)


texts: In Android, is it possible to get the first version of the app the user installed from the Play store?

texts:
I have an app currently in alpha, and I am thinking of moving to beta soon.
Once I do this step, I want to re-initialize local files as the game changed quite a bit (local scores, etc.), and display a "Thank you for testing the alpha-version"-message and whatnot.

To do this, I would like to check whether the first time the user installed my app from the app-store was during the alpha, i.e. whether the version corresponds to one of the version of alpha.
I found that it is possible to get the time the app was first installed, but haven't found a way to retrieve the version.

Short story long: is there a way to get the version of the app the user installed it for the first time?

P.S.
If possible, I would like to achieve this in Unity


texts: For my RTS game's physics engine, I'm trying to find out a clever way to make a unit face the direction it's moving in. Given a Vector2d direction of movement (its normalized velocity), how can I calculate the unit's rotation? If possible, I'd rather not use inverse trig functions because I only have a lookup table for Sine.


texts: What are the hidden cost while deploying game with Unity3D?

texts:
I just started learning Unity3D. I created a small 2D game, and I want to host for Windows, iPhone, iPad, Android, Windows 8, Xbox and even on websites.

I created it using free Unity3D editor. Now I want to host all these game on my website.

I will purchase iPhone, Android, and Windows 8 developer accounts. Apart from that, do I need to purchase any license in order to deploy the game on my website?

I can lots of license here: https://store.unity3d.com/

If I later purchase Unity Pro, then do I need to purchase any extra licenses?

And will that Unity logo always appear while starting the game?


texts: XNA 4.0 - Strange edges with multilight shader

texts:
I am generating a light, a depth and a normalmap to calculate the lightning at each pixel with multiple lights.

On both rendertargets, i set the preferredMultiSampleCount parameter to 16 samples because I want smooth edges.
It seems to work well on the first picture (normalmap).
In the second picture (lightmap), multisampling works great, too.
But somehow there are flickering edges at the end of each model.

I think it may have to do something with the depthmap because due to using Surfaceformat.Single I have to use

minfilter = point;
magfilter = point;
mipfilter = point;

for the Texture filter and I think AA doesnt work with filter type point.

Is this a known newbie problem or should I upload the source of my shader files for a better understanding of my problem?

EDIT:
If I turn multisampling off, I dont get these edges:

(Take a look at the bottom of the square in the middle.. )


texts:
I have been working on an implementation of gpu-based geo clip maps, but there is a section of the GPU Gems 2 article that I just can't seem to understand, specifically this paragraph, and more precisely the bolded part:

  The choice of grid size n = 2k−1 has the further advantage that the
  finer level is never exactly centered with respect to its parent
  next-coarser level. In other words, it is always offset by 1 grid unit
  either left or right, as well as either top or bottom (see Figure
  2-4), depending on the position of the viewpoint. In fact, it is
  necessary to allow a finer level to shift while its next-coarser level
  stays fixed, and therefore the finer level must sometimes be
  off-center with respect to the next-coarser level. An alternative
  choice of grid size, such as n = 2k−3, would provide the possibility
  for exact centering

Let's take an example image from the article:

My "understanding" of the way the clip maps were updated was that you floor the position of the viewpoint to an int, and as such get the center vertex point. If this is not the same as the previous center point, you update the entire map. Now, this obviously is not the case.  What I am failing to understand is this:

If you look at the image above, if the viewpoint was to move one unit to the right, then the inner ring (the one just around the view point + white center square) would end up getting a 1 unit space on both the left and right side of itself. But there is nothing in the paper that deals with this. What I mean is that it would end up looking like this:(excuse my crummy cut-and-paste editing of the above image):

This is obviously not a valid state. So, would the solution be that a clip ring (layer) can only move in increments of the ring/layer it's contained within? Wouldn't this end up being very restrictive? I feel like I am missing some crucial understanding of parts of the algorithm, but I have been over both this paper and the original paper from 2004 and I just can't see what I am not getting.


texts: How can I start the race from a checkpoint with GTA 5 Map Editor?

texts:
When I use the official Map Editor from GTA V then it seems that you are only able to test the Map from the Start Point all the time. This is very annoying when you build a hardcore difficult Map and you don´t want to start all the time again from the Start Point.

Is there a way to start the Race from as example Checkpoint #3 instead of always from the Start Point? I think there must be a way because I can´t imagine that hardcore difficult Map Builders always restart the Map from the Start Point..

Btw I can't ask the question at rockstar forum because you need to be 1 month online with your account before you can ask questions.


texts: How do I prevent camera jitter when rotating the player - Unreal?

texts:
This is a problem that seems to have no reasonable answer anywhere around, yet is a commonly needed aspect of developing game mechanics.

Context

I'm developing a traditional 3rd person character controller esque thing, you know, camera controlled by mouse/joystick all that jazz.

The issue comes when I'm developing a climbing system:

I have to develop a climbing system, and when I 'attach' the player to a climbing ledge, they could be at any angle relative to this ledge, up to perpendicular.
When the player jumps up, and the ledge detection runs, the player attaches to the ledge, and needs to rotate to be facing the ledge dead on.
I need a method for the camera movement to be completely independent of this capsule collider rotation change, as currently I have this problem:...

Problem

When I rotate my player's capsule collider, the attached camera boom rotates with it.

Specific Problem

When I set my actor's rotation directly, the camera orients itself immediately with the player's direction, then immediately returns itself to the previous view, creating a massive camera jitter, especially at lower framerates.

The question

How do I prevent this behaviour

OR

How do I reapproach problems of rotating the player character?


texts: Loss of texture detail in XNA (Banding 16 bit issue)

texts:
I'm loading in a background texture for my game, it's not vert detailed, it's just there too add some variance. The problem is that there looks like a large reduction in detail. I've included images below so you can see what I'm talking about. What would cause this to happen and how can I get my detail back?

More info:
 Verticies are VertexPositionTexture
 Load method Texture2D.FromStream
 Effect BasicEffect

Also the project is a Silverlight/XNA mix

Source Image:

Image from game:

Note: the images don't match up completely but you should get the idea.


texts:
I'm wondering how one could implement an HUD in LWJGL. I've seen tutorials on this, but they don't seem to work. I know the basic structure goes like this:

init3d();
// 3d code
init2d();
// HUD

To which, of course, init3d and init2d are the GL Initialization codes. And also, how would you draw the images for the HUD (or should I ask that in a separate question)?

If this is too vague, let me know and I'll update the question.


texts:
... or better yet, removing the need to search the map altogether.

I'm either looking for suggestions on how to optimize my code, or a change in design.

In my component-based entity system, the Entity is comprised of Attribute and Behavior objects. The Behavior objects are just stored in an std::vector; they are no issue, I just call their update function.

Attributes, I store in a map of <std::string, Attribute> and they represent the path of communication between Behaviors (Behaviors never interact directly). When a Behavior needs an attribute it searches its Entity's map.

That's a bit problematic for Behaviors that access that information a few times a second, like the Rendering behavior (draws the Entity on-screen). Rendering needs to read the Position, the Orientation, and a few other things, and it needs to do that a few times a second.

How can I solve this issue? It should also be noted that the base classes Entity, Attribute, and Behavior are written in C++, but their implementations in Python.


texts: Calculate slope for linear interpolated movement

texts:
I want to move rectangles to their targets the "smooth" way with linear interpolation. I hope this is right.

float slope(float x1, float x2, float y1, float y2) {
    return std::abs((y2 - y1)) / std::abs((x2 - x1));
}

int s = slope(x, target->x, y, target->y);

if(x > target->x) {
    x -= s * speed * delta;
} else if(x < target->x) {
    x += s * speed * delta;
}

if(y > target->y) {
    y -= s * speed * delta;
} else if(y < target->y) {
    y += s * speed * delta;
}

The result is that they barely move. But when they move it is very slow or fast as hell.
I would also apreciate any suggestions on how to reach the target better.
Thanks in advance.


texts:
I have a game, and I have a level editor where you can build your level from blocks. Blocks positioned in cells. So blocks can have no neighbours or have one or few neighbours. My problem is that I need to put appropriate texture to block, based on block position related to another blocks. Is there some specific algorithms or methods that can help me?

I want it to update textures after adding/moving/deleting each block so it should be fast.

Levels can look like

- - - - - - - - - - - - - - -
|                            |
|             |- - - |       |
|             |- - - |       |
|                            |
|         - - - - -          |
|         |       |          |
- - - - - |       | - - - - -|


texts:
I would like to provide support for switching between both OpenGL and Vulkan in my game (and potentially DX12 later).  Currently I only know OpenGL so I am working on that.
I have read a lot of posts about supporting multiple apis.  Thus far I have been creating a non-specific interface with virtual functions for which I then create a .h/.cpp for the the OpenGL specific implementation.  For example, I have a GraphicsDevice.h and a GLGraphicsDevice.h and GLGraphicsDevice.cpp.  I then have this in my initialisation code:
GLGraphicsDevice gl_graphics_device = GLGraphicsDevice(&gl_window);
GraphicsDevice* graphics_device = &gl_graphics_device;

Using the above approach I would have to determine somehow whether graphics_device would be GLGraphicsDevice or VKGraphicsDevice which I would most likely do using a configuration file.
I recently came across a different approach of handling multiple apis suggesting the use of macros:

Have a base class with the common data e.g., IndexBufferBase.
Each API class (e.g. GLIndexBuffer) inherits from the base class and handles API-specific functionality, such as creating the index buffer and drawing with it.
IndexBuffer inherits from one of the API classes depending on which macro is set.

I'm not sure how I would set the macros for the above approach.
I've read that macros should be avoided but I've also read that virtual function calls are costly, so which is the better approach?  Or perhaps there is another option?
Edit: Based on helpful feedback in the comments I have narrowed my goal to providing compile-time support for multiple apis.


texts:
For a game that updates a board every frame I am calculating the next arrangement of board, updating pixel array data and render board as 2D texture to quad the size of the screen using OpenGL.
I use:

glTexImage2d(GL_TEXTURE_2D,0,GL_RGBA,tex_width,tex_height,0,GL_BGRA,GL_UNSIGNED_INT_8_8_8_8_REV, &pixel_data.front())

to initialize the texture object and

glTexSubImage2d(GL_TEXTURE_2D,0,0,0,tex_width,tex_height, BGRA,GL_UNSIGNED_INT_8_8_8_8_REV, &pixel_data.front())

to update the texture.

The slowest part of the code is update_pixels() (below) Taking  256x128 elements input array and creating four component pixel array based on that. This function is very slow(45ms) and it seems it should be done differently. What would be the proper way to implement this function?

Update pixel data per frame:

void  update_pixels() {
//update pixels
//std::vector <unsigned char> pixel_data
float state = 0;
size_t it = 0;

for (size_t y = 0; y < board.getWorldHeight(); ++y) {
    for (size_t x = 0; x < board.getWorldWidth(); ++x) {
        state = board.get_state(y * golf_board.getWorldWidth() + x);

        pixel_data[y * board.getWorldWidth() + x + it ] = static_cast<unsigned char>(state * 255);
        ++it;
        pixel_data[y * board.getWorldWidth() + x + it] = static_cast<unsigned char>(state * 255);
        ++it;
        pixel_data[y * board.getWorldWidth() + x + it] = static_cast<unsigned char>(state * 255);
        ++it;
        pixel_data[y * board.getWorldWidth() + x + it] = static_cast<unsigned char>(1 * 255);

    }

}
return;
}

Time measurement:

void render(){
render_frame() //glDrawElements() for quad and scale uniform update takes 0.2ms
generate_states() //new states for board takes 1.3ms
auto t1 = std::chrono::high_resolution_clock::now();
update_pixels(); // create new pixel array, takes 32 ms
auto t2 - std::chrono::high_resolution_clock::now();
float update_time = std::chrono::duration_cast<std::chrono::microseconds>(t2-t1).count() /1000.0f;
//cout <<updae_time
glfwSwapBuffers() //from update pixels to swap takes 13ms
}


texts: Are there shaders or at least shader like things in Swing?

texts: Is there? Because I'm wondering if it supports GLSL, HLSL, or it's own shading language? I don't know much about Swing graphics. Does anyone know?


texts: What should a game have in order to keep humans playing it?

texts:
In many entertainment professions there suggestions, loose rules, or general frameworks one follows that appeal to humans in one way or another.  For instance, many movies and books follow the monomyth.

In video games I find many types of games that attract people in different ways.  Some are addicted to facebook gem matching games.  Others can't get enough of FPS games.

Once in awhile, though, you find a game that seems to transcend stereotypes and appeals almost immediately to everyone that plays it.  For instance, Plants Versus Zombies seems to have a very, very large demographic of players.  There are other games similar in reach.

I'm curious what books, blogs, etc there are that explore these game types and styles, and tries to suss out one or more popular frameworks/styles that satisfy people, while keeping them coming back for more.


texts: glsl shader to allow color change of skydome ogre3d

texts:
I'm still very new to all this but learning a lot. I'm putting together an application using Ogre3d as the rendering engine. So far I've got it running, with a simple scene, a day/night cycle system which is working okay.

I'm now moving on to looking at changing the color of the skydome material based on the time of day. What I've done so far is to create a struct to hold the ColourValues for the different aspects of the scene.

struct todColors {
    Ogre::ColourValue sky;
    Ogre::ColourValue ambient;
    Ogre::ColourValue sun;
};

I created an array to store all the colours

todColors   sceneColours [4];

I populated the array with the colours I want to use for the various times of the day. For instance DayTime (when the sun is high in the sky)

sceneColours[2].sky = Ogre::ColourValue(135/255, 206/255, 235/255, 255);
sceneColours[2].ambient = Ogre::ColourValue(135/255, 206/255, 235/255, 255);
sceneColours[2].sun = Ogre::ColourValue(135/255, 206/255, 235/255, 255);

I've got code to work out the time of the day using a float currentHours to store the current hour of the day 10.5 = 10:30 am. This updates constantly and updates the sun as required.

I am then calculating the appropriate colours for the time of day when relevant using

else if( currentHour >= 4 && currentHour < 7) {

    // Lerp from night to morning
    Ogre::ColourValue lerp = Ogre::Math::lerp<Ogre::ColourValue, float>(sceneColours[GT_TOD_NIGHT].sky , sceneColours[GT_TOD_MORNING].sky, (currentHour - 4) / (7 - 4));

}

My original attempt to get this to work was to dynamically generate a material with the new colour and apply that material to the skydome. This, as you can probably guess... didn't go well.

I know it's possible to use shaders where you can pass information such as colour to the shader from the code but I am unsure if there is an existing simple shader to change a colour like this or if I need to create one.

What is involved in creating a shader and material definition that would allow me to change the colour of a material without the overheads of dynamically generating materials all the time?

EDIT :
I've created a glsl vertex and fragment shaders as follows.

Vertex

uniform vec4 newColor;

void main()
{
gl_FrontColor = newColor;
gl_Position = ftransform();
}

Fragment

void main()
{
gl_FragColor = gl_Color;
}

I can pass a colour to it using ShaderDesigner and it seems to work. I now need to investigate how to use it within Ogre as a material.

EDIT :

I created a material file like this :

vertex_program colour_vs_test glsl
{
source test.vert
default_params
{
    param_named newColor float4 0.0 0.0 0.0 1
}
}

fragment_program colour_fs_glsl glsl
{
source test.frag
}

material Test/SkyColor
{
technique
{
    pass
    {
        lighting off

        fragment_program_ref colour_fs_glsl
        {
        }
        vertex_program_ref colour_vs_test
        {
        }
    }
}
}

In the code I have tried :

Ogre::MaterialPtr material = Ogre::MaterialManager::getSingleton().getByName("Test/SkyColor");
Ogre::GpuProgramParametersSharedPtr params = material->getTechnique(0)->getPass(0)->getVertexProgramParameters();
params->setNamedConstant("newcolor", Ogre::Vector4(0.7, 0.5, 0.3, 1));

I've set that as the Skydome material which seems to work initially. I am doing the same with the code that is attempting to lerp between colours, but when I include it there, it all goes black.

Seems like there is now a problem with my colour lerping.


texts: How to deal with players having too much money (or any large numbers)?

texts:
I'm working on a browser MMORPG in PHP and MySQL and today got a bug report about int32 overflow, due to the player having too much money. When I was designing the core system, I completely forgot about the integer 2,147,483,647 limit, so now I'm trying to come up with some way to fix this without breaking everything apart.

How to better handle in-game currency (or basically any number that's going to increase indefinitely)? I have couple of ideas, but would like to ask for help choosing as this is the first time I'm dealing with this kind of stuff (int overflow and large numbers.)

Fix the current mechanics so that players won't ever have that much money. Doesn't really address the integer problem, but it still needs to be done.
Use float instead of int. This seems like an easy option, but I'm not sure if there would be any potential side-effects. Also, I read somewhere that you shouldn't compare floats, so I'm not sure how I would handle basic hasEnoughMoney? type of conditions. Also, is float the same in PHP and MySQL?
Have some sort of higher currency, like bronze/silver/gold coins and automatically convert it at certain threshold (ie. 1,000,000 would become 1M or something like that.) The downside here is more apparent than with the floats - more complexity and more room for mistakes to happen.
Straight out cap the amount of money player can have few points below the overflow limit. Straight forward and effective, but I don't really like the idea of having a limit on money - though I just realized, GTA (and many more I'm sure) has it if I'm not mistaken, so maybe it could work?

Any help would be much appreciated. I searched for hours, but couldn't find much. I read this How do idle games handle such large numbers? among other things, but it doesn't really help as what I'm doing is multiplayer, so not every player will have either too much (and not need precision, so to use floats) or too little (and need precision), and it needs to be unified for all players.

Thanks!


texts: Unity - 2D - Scaling to fit between two objects

texts:
The game is a top down 2d shooter and I'm facing trouble in doing this :
- I got a player 2D ship
- The player fires laser, which is a long thin image with box collider attached.
- What I want is that when the laser hit the enemy ship, the laser's length (Height) should be equal to the distance between the player and the enemy. (That is the laser shouldn't go through the enemy)

So what I have done is this :
In the Laser's script :

Vector3 scale = new Vector3(1, 1, 1);

void OnCollisionStay2D(Collision2D col) {
  If (col.gameObject.layer == 12) //ENEMY
     {
          scale.y = (col.gameObject.transform.position.y - Info.PlayerPosition.y) / this.gameObject.renderer.bounds.size.y;
          this.transform.localScale = scale;
     }

void OnCollisionExit2D(Collision2D col)
     {
          scale.y = 10 / this.gameObject.renderer.bounds.size.y; // 10 is the height of the screen;
          this.transform.localScale = scale;
     }

That's it. So when I run it, things go crazy, the scale.y value kind of oscillates between some low value and high value and withing 2-3 seconds, scale.y becomes infinity (as of Unity Console)

I can't make anything out of it :( Been like 1.5months with unity.
Thanks in advance :)


texts:
I have a character composed of five bodies which are tied together by a lot of joints. On of them is the overall chassis, to which all forces and impulses are applied to move the whole Character.

All in all that works very fine, except one thing: I need to set the Position of the Character so that it get Beamed from one place to the other in one single frame.

Unfortunately I cannot get this to work. I tried the following code, without any success…

playerbodies.forEach(function (bd) {
    bd.SetLinearVelocity(new b2.Vec2());
    var t = bd.GetTransform();
    t.p.x -= 10;
    bd.SetTransform(t, bd.GetAngle());
});

How can I make that happen?


texts: Animate a 3D boss with some parts that become independant

texts:
I would like to create a boss but first, I want the player to fight the head. Then the head flies to the body and becomes attached to it.

Later, the boss will throw an arm to the player and the arm will chase the player, becoming independent with its own AI.

Do I have to render 3 models separatly? (The head + one arm + the body)
If I do this, how am I supposed to animate the complete body when everything is attached together?

Do I have to render the 3 models (The head + one arm + the body) + 1 model without the arm (Head + body) + 1 model with everything attached?
If so, how do I handle animations with these 5 models?


texts: Mixing XNA and Silverlight gives wierd graphics

texts:
I making a small 3dgame which is made as a Silverlight and XNA app, but when I draw the sprites the graphics becomes all wierd.

All my primitive types are rendered correctly, but my 3d models are just wierd

My Draw is like this when silverlight is set to draw

private void OnDraw(object sender, GameTimerEventArgs e)
{
    // Render the Silverlight controls using the UIElementRenderer
    elementRenderer.Render();

    // Clear the screen to a solid color
    SharedGraphicsDeviceManager.Current.GraphicsDevice.Clear(Color.CornflowerBlue);

    switch (gameState)
    {
        case GameState.ChooseStarter:
            TextBlockStatus.Text = "Find Starting Player";
            break;
        case GameState.PlaceBrick:
            TextBlockPlayer.Text = (playerTurn == PlayerTurn.PlayerOne) ? "Player One" : "Player Two";
            TextBlockState.Text = "Place Brick";
            foreach (IGraphicObject obj in _3dObjects)
            {
                obj.Draw(cameraPosition, e);
            }
            break;
        case GameState.GiveBrick:
            TextBlockState.Text = "Give Brick";
            break;
    }

    spriteBatch.Begin();
    // Using the texture from the UIElementRenderer,
    // draw the Silverlight controls to the screen
    spriteBatch.Draw(elementRenderer.Texture, cameraProjection, Color.White);
    spriteBatch.End();
}

This gives me this output

If I comment the spritebatch lines out I get the correct output, except the silverlight text is of course not shown

I am not entirely sure what to look for except that zero vector I am giving to the spritebatch, but if thats the source I have no idea what I am supposed to set it as epspecially when its a 2d vector


texts: what's the best way of panning in a 2D scene

texts:
Up to know I have used this functions to create a 2D scene (for showing images) and to pan on it ( in fact it's a customization of the class COpenGLControl here in codeguru) :

void COpenGLControl::OnSize(UINT nType, int cx, int cy)
{
wglMakeCurrent(hdc, hrc);
CWnd::OnSize(nType, cx, cy);

if (0 >= cx || 0 >= cy || nType == SIZE_MINIMIZED) return;
oglWindowWidth = cx;
oglWindowHeight = cy;
// Map the OpenGL coordinates.
glViewport(0, 0, oglWindowWidth, oglWindowHeight);

// Projection view
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
// Set our current view perspective
glOrtho(-oglWindowWidth/2, oglWindowWidth/2, oglWindowHeight/2,-oglWindowHeight/2, -1, 1);
// Model view
glMatrixMode(GL_MODELVIEW);
wglMakeCurrent(NULL, NULL);
}

void COpenGLControl::OnDraw(CDC *pDC)
{
wglMakeCurrent(hdc,hrc);
// If the current view is perspective...
glLoadIdentity();
glScalef(m_fZoom,m_fZoom,1.0);
glTranslatef(m_fPosX, m_fPosY, 0.0f);
wglMakeCurrent(NULL, NULL);
}

void COpenGLControl::OnMouseMove(UINT nFlags, CPoint point)
{
// TODO: Add your message handler code here and/or call default
int diffX = (int)(point.x - m_fLastX);
int diffY = (int)(point.y - m_fLastY);
m_fLastX = (float)point.x;
m_fLastY = (float)point.y;
if (nFlags & MK_LBUTTON)
{
    m_fPosX += (float)0.5f * diffX;
    m_fPosY -= (float)0.5f * diffY;
}
OnDraw(NULL);
CWnd::OnMouseMove(nFlags, point);
}

pressing left mouse button and draging on the window, will cause the image to pan
In fact the COpenGLControl class is for 3D scenes and the disadvantage of this way for 2D scenes is that when I zoom in, I feel the speed of pan is more than the time that I zoom out?
I mean zooming in increases the speed of pan while zooming out decreases it.
Do you know of any way better for continuous panning in a 2D OpenGL scene?


texts:
After noticing some timing descrepencies with events in my code, I boiled the problem all the way down to my Windows Message Loop.

Basically, unless I'm doing something strange, I'm experiencing this behaviour:-

MSG message;

while (PeekMessage(&message, _applicationWindow.Handle, 0, 0, PM_REMOVE))
{
    int timestamp = timeGetTime();
    bool strange = message.time > timestamp; //strange == true!!!

    TranslateMessage(&message);
    DispatchMessage(&message);
}

The only rational conclusion I can draw is that MSG::time uses a different timing mechanism then timeGetTime() and therefore is free to produce differing results. Is this the case or am i missing something fundamental?


texts: Is there a terrain generation method where seed data is stored for each chunk instead of surface data?

texts:
I'm a web programmer but I do like the idea of working on games at some point. As an enthusiast, I'm curious:

Is there an accepted terrain building practice in which developers create a generation engine which accepts various seed values to control terrain in a non-random environment?

I'm thinking of a method of, instead of storing gigabytes of map data, just storing a couple of megabytes of seed data, different types of seed data values for each chunk of the map, allowing the client to dynamically generate the map of your desired "design" (Not random gen), with only building and structure component configurations to be saved as map data.

Is there a name for this? It seems like it would be a good method of keeping a game's file size small.


texts:
I'm working on creating an iris wipe transition, like the ones you see in old cartoons - a fully transparent circle closes on a certain point, leaving a full screen of a solid color. Additionally, the background around the circle fades in from full transparency as well. I decided that shaders would be easier than creating vertices to build the iris effect. I may have been wrong.

EDIT: I've made some progress since asking this question - there is now an iris effect, but it opens and closes around a blank CornflowerBlue screen before displaying the screen, and the background around the circle is always full transparency.

Shader:

sampler TextureSampler : register(s0);
float2 irisCenter;
float radius;
float4 backColor;

float4 PixelShaderFunction(float4 pos : SV_POSITION, float4 color1 : COLOR0, float2 coords: TEXCOORD0) : COLOR0
{
    float4 p = pos;
    float2 c = irisCenter;
    float r = radius;

    float alpha = abs(1 - step(pow(p.x - c.x, 2) + pow(p.y - c.y, 2), r * r));
    return float4(backColor.r, backColor.g, backColor.b, alpha * backColor.a);
}

technique Technique1
{
    pass Pass1
    {
        PixelShader = compile ps_3_0 PixelShaderFunction();
    }
}

The alpha variable should be deciding if a pixel is inside the circle and should be transparent, or if the pixel is outside the circle and shouldn't be. irisCenter, radius, and backColor are all set on each frame by:

public void Draw()
{
    if (isInitialized && (isRunning || dir == EffectDirection.Backward))
    {
        float r = color.R; // / 255f;
        float g = color.G; // / 255f;
        float b = color.B; // / 255f;
        float a = (color.A * currentFadeLevel); // / 255f;

        var irisEffect = GameServices.Effects["IrisEffect"];
        irisEffect.Parameters["irisCenter"].SetValue(irisCenter);
        irisEffect.Parameters["radius"].SetValue(irisRadius);
        irisEffect.Parameters["backColor"].SetValue(new Vector4(r, g, b, a));

        quadRenderer.Render(irisEffect);
    }
}

IrisEffect.cs

QuadRenderer.cs

Instead of behaving as an iris wipe, it first draws a full-screen rectangle for half the effect, and then a full-screen Color.CornflowerBlue rectangle (I guess the quad from QuadRenderer isn't drawing with transparency). I'm not sure what's wrong as I'm new to HLSL.

Question 1: How can I get the coordinates of the current pixel being processed by the shader?

Question 2: What am I doing wrong?

Question 3: How do I draw the rest of the quad transparently?


texts:
I've gone about 2 ways for implementing melee attacks however, bboth have major flaws, hoping someone has a simpler answer.
Method 1:
Creating a "projectile" that's using an image, then reducing the transparency of said image. Then offsetting the projectile to be at the end of the character sprite then have it kill itself after 10 milliseconds. This works however it does have a  draw back that the more I make the image of the projectile transparent at a certain % pygame stops reading it as an image, it will show the rect but will not allow for collision with enemies. Also if you use mask collision instead of direct rect collision, you damage yourself.
Method 2:
Much like the first is a rect that is offset in front of the player, if the hit rect of the object collides with the hit rect of the enemy, that's read as a hit. The drawback is if you get too close the mask collision used for the player/enemy sprite is activated and you take damage. Masking cannot be used with this method as it would read the player's sprite as a collision, meaning you hurt yourself to hurt the enemy.


texts: How do I tag a specific build for sorting/filtering in Unity Performance Reporting?

texts:
I am working in a Unity project where there are multiple versions of the app being build from the same code base.  The app being built is determined by a Script Define.  I want to be able to sort Unity Performance Reports based on the app I am building.  The app version can be the same across multiple apps in my case.

Unity Performance Reporting has filters, such as app version, but I cannot figure out how to add a custom filter.  I want to tag a build with the app being made, and then filter by that tag.

I have "Manager" access to the Dashboard.

Adding a custom tag during compile-time, run-time, or in the configuration settings is fine.  I just cannot figure out how.
 This Official Post does not have the information I am looking for.

How can I apply custom filters in Unity Performance Reporting?


texts: Where can I find some "must see" game development portfolios?

texts: I am trying to put together a website/portfolio and it would be great to see what others have done.


texts:
I am using OpenGL 2.1 and GLSL 1.20 .

I am trying to compute the fragment color applying the Phong lighting model.

This is the formula I have (the original formula has a summation, but since the light is only one it's not needed):

  Ip = Ka * Ia + Kd * (Lm • N) * Id + Ks * (Rm • V)^s * Is

With:

  Ka, Kd, Ks, s respectively material's ambient, diffuse, specular and shininess values;
  Ia, Id, Is respectively light ambient, diffuse and specular values;
  N surface normal;
  Lm direction vector point-light;
  Rm= 2.0 * (Lm • N) * N - Lm .

So this is the vertex shader:

#version 120

varying vec3 position; // I'll pass the position and the normal to
varying vec3 normal;   // the fragment shader
varying vec4 diffuse; // I'll compute here the ambient and diffuse
varying vec4 ambient; // values and pass them to the fragment shader

void main()
{
    gl_Position = ftransform();
    position= vec3(gl_Position);
    gl_TexCoord[0] = gl_MultiTexCoord0;

    normal= normalize(gl_NormalMatrix * gl_Normal);
    ambient= gl_FrontMaterial.ambient * gl_LightSource[0].ambient;
    ambient+= gl_LightModel.ambient * gl_FrontMaterial.ambient;
    diffuse= gl_FrontMaterial.diffuse * gl_LightSource[0].diffuse;
}

And this is the fragment shader:

#version 120

varying vec3 position;
varying vec3 normal;
varying vec4 diffuse;
varying vec4 ambient;

void main()
{
    gl_FragColor= ambient+diffuse;
    vec3 Lm= vec3(normalize(position-vec3(gl_LightSource[0].position)));
    vec3 V= vec3(normalize(-position));
    float LdotN= max(dot(Lm,normal),0.0);  // Since I'll use this two times
                                           // I compute it just once and reuse it
    vec3 Rm= 2.0* LdotN * normal-Lm;
    // First part of the formula: Kd * (Lm • N) * Id
    gl_FragColor+= gl_FrontMaterial.diffuse * LdotN * gl_LightSource[0].diffuse;
    // Second part: Ks * (Rm • V)^s * Is
    gl_FragColor+= gl_FrontMaterial.specular* pow(max(dot(Rm,V),0.0),gl_FrontMaterial.shininess)* gl_LightSource[0].specular;
}

The result is unrealistic, it seems like the specular light is not really applied:

I tried with a teapot and this is the result:

After changing the camera position (the teapot was covering the light):

I think it's ok.


texts:
The gerstner wave function is a commonly used method to calculate waves and simulate water in video games and movies or most 3d simulations. It is however quite complex so it is very hard for young developers such as myself to understand and implement it into code.

Would it be possible to simplify the formula:

A = amplitude of wave (Float)
W = wave number (Vector)
D = direction (Vector) how do i know what to set the direction to?
S = Speed
L = wave length
phase-constant = S x 2* pi/L.

According to the article Q = 1/(W * A)

Issues and Questions:

Why are all three lines of the formula seperated by commas?
D refers to a directional vector (i think)
Q = 1/(W * A) but W is a vector and A is a float?
What does this line mean: wiDi.(x,y) is that reffering to w * dot product of(d , (x,y))

sigma returns the sum of what exactly?

Here is my attempt to implement it into java code:

float yPos = (float) ((steepness * amplitude) * direction.y * Math.cos(wavenumber.y * (direction.dot(position)) + phase_const * time));

Dont know if its correct

This may help:

https://github.com/armanuguray/water-surface/blob/master/src/engine/waterengine.cpp


texts: How to remove horizontal black bar at the bottom of the game screen in libgdx?

texts: Here is the screenshot .Here is my Play constructor in Play class.


texts: How do i update opengl lightning equation in my fragment shader to make my texture less glossy and more like a fabric

texts:
I built a model in blender, and am currently trying to import it into my android app using assimp together with opengl, i dont have any issues with the importing but my goal is to make the object look realistic as possible, and this is where my problem lies...I have implemented normal mapping using both the diffuse and normals of my texture but after rendering it the objects looks smooth and glossy, yes the bumps were rendered well and i like it but i need the material to look more like a fabric (cloth/textile), please how can i do this? do i need to update my lighting equation or the issue is with my original diffuse texture?

Here is my original diffuse texture

Here is my rendered model

Here's my fragment shader

    void main()
{
    // obtain normal from normal map in range [0,1]
    vec3 normal = texture2D( normalMap, textureCoords ).xyz;
    // transform normal vector to range [-1,1]
    normal = normalize(normal * 2.0 - 1.0);  // this normal is in tangent space

    // get diffuse color
    vec3 color = texture2D( textureSampler, textureCoords ).xyz;
    // ambient
    vec3 ambient = 0.1 * color;
    // diffuse
    vec3 lightDir = normalize(tangentLightPos - tangentFragPos);
    float diff = max(dot(lightDir, normal), 0.0);
    vec3 diffuse = diff * color;
    // specular
    vec3 viewDir = normalize(tangentViewPos - tangentFragPos);
    vec3 reflectDir = reflect(-lightDir, normal);
    vec3 halfwayDir = normalize(lightDir + viewDir);
    float spec = pow(max(dot(normal, halfwayDir), 0.0), 32.0);
    vec3 specular = vec3(0.2) * spec;

   gl_FragColor  = vec4(ambient + diffuse + specular, 1.0);
}

Here's my vertex shader

mat3 transpose(mat3 m) {
    return mat3(m[0][0], m[1][0], m[2][0],
    m[0][1], m[1][1], m[2][1],
    m[0][2], m[1][2], m[2][2]);
}

void main()
{

    gl_Position     = mvpMat * vec4(vertexPosition, 1.0);

    vec3 fragPos = vec3(model * vec4(vertexPosition,1.0));

    vec3 T = normalize(normalMatrix * tangent);
    vec3 N = normalize(normalMatrix * normal);
    T = normalize(T - dot(T, N) * N);
    vec3 B = cross(N, T);

    mat3 TBN = transpose(mat3(T, B, N));

    //values for fragment shader
    tangentLightPos = TBN * lightPos;
    tangentViewPos  = TBN * viewPos;
    tangentFragPos  = TBN * fragPos;
    textureCoords   = vertexUV;
}


texts: Game loop with fixed timestep gives strange result

texts:
So I've read the famous article at http://www.koonsolo.com/news/dewitters-gameloop/comment-page-2/#comments which describes different methods of implementing a game loop. I've tried to implement the final method that is described in the article in Javascript (ignoring interpolation for the time being):

var Timer = {
        pastTime : 0,
        currentTime : 0,
        started : false,
        //starts the timer
        start: function(){
            if(!this.started){
                this.started = true;
                this.pastTime = new Date().getTime();
            }
        },
        //gets the time in MILLSECONDS
        getTime: function(){
            return new Date().getTime() - this.pastTime;
        },
        //stops the timer but does not reset it (i.e. getTime() can still be
          called to get the time between start() and end())
        end: function(){
            if(this.started){
                this.currentTime = new Date().getTime();
                this.started = false;
                return this.currentTime - this.pastTime;
            }
        },
        //resets the timer
        reset: function(){
            this.pastTime = 0;
            this.currentTime = 0;
            this.started = false;
}

var maxFrameSkip = 5;
var nextTick = new Date().getTime();
var TICKS_PER_SECOND = 25;
var tickTimeMillis = 1000 / TICKS_PER_SECOND;

var ticksPerSecondReal = 0;
var ticksCounter = 0;

var timer = Object.create(Timer);

var loops = 0;

 function gameLoop(){
    loops = 0;

    timer.start();

    while(new Date().getTime() > nextTick && loops < maxFrameSkip){
        update();
        ticksCounter++;
        nextTick += tickTimeMillis;
        loops++;
    }

    draw();

    if(timer.getTime() >= 1000){
        ticksPerSecondReal = ticksCounter;
        ticksCounter = 0;
        timer.reset();
    }

    console.log(ticksPerSecondReal);

    window.requestAnimationFrame(gameLoop);
}

 gameLoop();

So the problem that I'm having is that the console.log(ticksPerSecondReal) should always be giving me 25 because that's the constant ticks per second that I want and have set up. What I end up getting is an alternating number that is 25 and 26. So periodically (~1 second) it will be 25 and then 26 and then 25 and so on. And sometimes (much less frequently) it will even give a result of 27. It keeps switching back and forth when it should be constant at 25. What is the issue here?


texts: Best data structure to store large amount of data

texts:
I am making a minecraft kind of game. In which I have 100s of objects and their crafting recipe.

Now I want to store them inside the program, ie I cannot load external files. Everything must be inside class for now. In future I might be able to use databases, once the game gets more traction.

All these objects will have addition properties like shootable,purchase cost,etc etc.

Some also have array property like

{ research1: unlocks{ object1:50%, object2:100% }},

{ research2: unlocks{ object1:50% }}.

But all these objects will be constant with an exception of "locked" boolean.

If I do a huge database I'll also have to search data using filters on they keys like we do on sql.
Example: "Give me all Researches that are unlocked and that unlocks object1"

What will be the best datastructure to store them?
Thanks.


texts: Why can't I get a bool packed and aligned into a D3D constant buffer?

texts:
Alright, I'm having a hard time getting a bool packed and aligned into a hlsl constant buffer and I'm not sure why.

Here is the buffer in hlsl

cbuffer MaterialBuffer : register(b1) {
    float3 materialDiffuseAlbedo;
    float  materialSpecularExponent;
    float3 materialSpecularAlbedo;
    bool isTextured;
};

And here it is in c++

struct GeometryBufferPass_MaterialBuffer {
    XMFLOAT3 diffuse;
    float specularExponent;
    XMFLOAT3 specular;
    bool isTextured;
};

I've tried moving the bool and padding the struct in all kinds of ways with no luck. What is the correct way to do this?


texts: How can I stop Substance's runtime texture caching?

texts:
Procedural textures with the Substance Engine seem to update very quickly if you turn off caching, modify one exposed variable at a time, modify it frequently, and even then only after you've attempted to modify it 2 or 3 times.

However, I want basically the opposite. For example, units have a "blood" variable that generates blood differently on them as they take damage, as well as a "battle wear" variable that generates scratches and dents, but doesn't revert when they heal.

So to force a variable not to cache, I have to set it to some dummy value, then back to normal, then call RebuildTexturesImmediately.

How can I tell Substance not to cache a variable at runtime, so I can change it once and have the texture regenerate quickly?


texts: render trajectory of particle in forcefield using GLSL shader

texts:
I want to visualize flow of particles in some forcefield e.g. electromagetic, gravitional or potential flow in fluid (streamlines);

I was thinking to use Geometry Shader which would look like this (not tested, just sketch):

#version 330 core
layout (points) in;
layout (line_strip, max_vertices = 64) out;

uniform float dt;

vec3 getForce(in vec3 pos){ /* ... don't care now ... */ }

void main() {
    vec3 pos = gl_in[0].gl_Position;
    for( int i=0; i<64; i++ ){
        pos += getForce(pos) * dt; // it's actually velocity field but who cares
        gl_Position = pos;
        EmitVertex();
    }
    EndPrimitive();
}

However, I read that Geometry shaders are very slow (I did not yet tested). So I wonder if it would be helpful in this situation?

Or would Tesselation shaders or Compute shaders be suitable for this job and achieving better performance?.

background: I have experience with vertex-shaders, fragment-shaders, OpenCL ... but I have never tried geometry-,tesselation- nor compute-shaders.

EDIT: there is my simple example implementation using geometry shader in 2D
https://github.com/ProkopHapala/SimpleSimulationEngine/blob/ca16b6f8d72864a8a572ed2a21ded99c5c2cc3e4/cpp/sketches_SDL/OGL3/test_GeometryShader.cpp

which plots this (for velocity field defined by dipole):


texts: In Unity's Shader Graph how do you access parameters from code?

texts:
I recently rewrote a shared I was using into Shader Graph. As an example I carried out the color as an external parameter.

In my traditional shader to set the color I would call something like

MyMaterial.SetColor("_NewColor", color)

In the new code, I could not figure out the name of the parameter until I looked at the generated code. Turns out my Color parameter was actually named "Color_D027E98" So now my code is

MyMaterial.SetColor("Color_D027E98", color);

Not very pretty and I don't know how constant D027E98 is. Is this the correct way of changing a shader's parameter? Should I be doing something different using Shader Graph - Is this number going to change on me as if I update my shader?


texts: How do I simulate vehicle movement in a non-gravity environment (e.g., space)?

texts:
As a series of small experiments, I've began to tinker with game development, specifically using SpriteKit and Swift. I'm looking to simulate a body moving through a non-gravity environment, specifically space.

My vehicle starts in the middle of the screen and begins to travel horizontal with a constant force vector of (100, 0). When the user touches a new location, I would like for the vehicle to alter course and head to the location of the touch. In addition, I would like to simulate the vehicle "turning" in space. You can imagine that the turn wouldn't be immediate but would resemble something like a car drifting around a corner. This is such an example. I've got a crude version of it working, but there are weird quirks that I'm beginning to wonder if I'm approaching this correctly.

This is what I have so far:

Vehicle construction:

ship = SKShapeNode(rectOfSize: CGSizeMake(40, 20))
ship.fillColor = UIColor.redColor()
ship.strokeColor = UIColor.clearColor()
ship.position = getMiddle()

ship.physicsBody = SKPhysicsBody(rectangleOfSize: ship.frame.size)
ship.physicsBody?.affectedByGravity = false
ship.physicsBody?.velocity = CGVectorMake(Constants.VELOCITY, 0)
ship.physicsBody?.applyForce(CGVectorMake(Constants.VELOCITY, 0))
ship.physicsBody?.dynamic = true

self.addChild(ship)

When the user touches, I simply record the touch location as touchLoc.

In update:

if needUpdate {
    let shipLoc = ship.position

    // Find deltas
    let dx = shipLoc.x - touchLoc.x
    let dy = shipLoc.y - touchLoc.y

    // How much does the ship need to rotate?
    let angle = atan2(dy, dx) + CGFloat(M_PI)
    let rotate = SKAction.rotateToAngle(angle, duration: 0.1, shortestUnitArc: true)
    ship.runAction(rotate)

    /*
     * The deltas are used to create the new velocity vector, if the delta values are too
     * low, it could cause slow down in the ship velocity, so try to "normalize" the deltas
     * into something more similar to the starting velocity so the ship maintains a good speed
     */
    let len = sqrt(pow(dx, 2) + pow(dy, 2))
    let normalFactor = Constants.VELOCITY / len
    let ndx = dx * normalFactor
    let ndy = dy * normalFactor

    // Our enhanced vector
    let toVector = CGVectorMake(-ndx, -ndy)

    let curVelocity = ship.physicsBody!.velocity
    var newX = curVelocity.dx
    var newY = curVelocity.dy

    /*
     * This section is used to simulate the "drifting turn". Instead of turning sharply, add
     * some fudge factor (TURN_DELAY = 1) to make the turn gradual
     */
    if curVelocity.dx > toVector.dx {
        newX -= Constants.TURN_DELAY
    } else {
        newX += Constants.TURN_DELAY
    }

    if curVelocity.dy > toVector.dy {
        newY -= Constants.TURN_DELAY
    } else {
        newY += Constants.TURN_DELAY
    }

    // Set the new velocity vector
    ship.physicsBody?.velocity = CGVectorMake(newX, newY)

    /*
     * Kind of convoluted, but this is to check to see if the ship is within a specified range of the
     * touch location (UPDATE_PADDING = 3). If the ship is, stop trying to run this update function (at least
     * until the next touch) because the ship will constantly try to target the touch location
     */
    if (-UPDATE_PADDING ... UPDATE_PADDING ~= (shipLoc.x - touchLoc.x)) &&
       (-UPDATE_PADDING ... UPDATE_PADDING ~= (shipLoc.y - touchLoc.y)) {
        print("Stopping. Touched \(touchLoc.x), \(touchLoc.y). Ship: \(shipLoc.x), \(shipLoc.y)")
        needUpdate = false
    }
}

Here is a quick video demonstrating how it currently works. As you can see, as the touches happen closer to the vehicle weird things happen. This leads me to believe I'm going about this all wrong. Any advice, suggestions, or resources would be greatly appreciated. Thanks.


texts: Q: 2D cone and rectangle collision detection

texts:
I'm working on a 2D RPG game and now I need to detect if players ability collides with enemy rectangle hitbox. Currently I have this code that detects if a point is in cone, but I need to modify it to find if rectangle is colliding with a cone like in a picture below

float skillAngleTotalWidth = 90f;
int radius = 8, x = 3, y = 4;
float startAngle = skillUsedAtAngle - skillAngleTotalWidth / 2;
float endAngle = skillUsedAtAngle + skillAngleTotalWidth / 2;
// Calculate polar co-ordinates
float polarradius = (float)Math.Sqrt(x * x + y * y);
float Angle = Helpers.RadianToDegree((float)Math.Atan(y / x));
// Check whether polarradius is less then radius of circle or not and Angle is between startAngle and endAngle or not
if (Angle >= startAngle && Angle <= endAngle && polarradius < radius)
{
   Console.WriteLine("Point ({0}, {1}) exist in " + "the circle sector", x, y);
}

Need to find if cone and rectangle collide


texts: Frustum culling with a single large object

texts:
I am helping to optimize performance in a mobile game. The artists who built a particular scene added a wall around the scene. The wall is a single mesh with 100k triangles. Because it goes around the entire scene, at least some of the wall is visible from all angles and is always being rendered.

While running the game in the Editor with the Statistics panel enabled, I can see that hiding the GameObject containing the wall always reduces the current number of tris by 100k regardless of how much of the wall is actually visible. Does this mean that the entire wall is always getting rendered, rather than only the triangles that are actually in front of the camera?

Obviously the artists need to reduce the overall polygon count of the wall, but I'm wondering if they should also break it into several separate pieces so that the entire wall doesn't need to be rendered at once.


texts: How to alter image pixels of a wild life bird?

texts:
Hello so I was hoping someone knew how to move or change color and position actual image pixels and could explain and show the code to do so.

I know how to write pixels on a surface or screen-surface

usigned int *ptr = static_cast <unsigned int *> (screen-pixels);

int offset = y * (screen->pitch / sizeof(unsigned int));

ptr[offset + x] = color;

But I don't know how to alter or manipulate a image pixel of a png image my thoughts on this was

How do I get the values and locations of pixels and what do I have to write to    make it happen?

Then how do I actually change the values or locations of those gotten pixels and how do I make that happen?

any ideas tip suggestions are also welcome!

  int main(int argc , char *argv[])
    {

        SDL_Surface *Screen = SDL_SetVideoMode(640,480,32,SDL_SWSURFACE);

        SDL_Surface *Image;

        Image = IMG_Load("image.png");

        bool done = false;

        SDL_Event event;

        while(!done)
        {

            SDL_FillRect(Screen,NULL,(0,0,0));

            SDL_BlitSurface(Image,NULL,Screen,NULL);

                while(SDL_PollEvent(&event))
                {

                    switch(event.type)
                    {

                            case SDL_QUIT:
                            return 0;
                            break;

                    }

                }

                SDL_Flip(Screen);

        }

    return 0;

}


texts: Trying to understand relatively simple normal map antialiasing paper

texts:
See this paper: ftp://download.nvidia.com/developer/Papers/Mipmapping_Normal_Maps.pdf

They describe the very simple implementation of an algorithm for antialiasing normal maps.

I don't understand exactly how to look up an appropriate value in the lookup table they describe.

A value is accessed with (N_a . N_a, N_a . H).

My specular light for example, is computed with:

        result.Specular += baseIntensity * SpecularColor *
            pow(max(0, dot(H,N)), SpecularExponent);

The H is the same as the H in the paper.
SpecularExponent is the s in the paper.
The N is the vector that results from looking up a normal in the normal map (which is already normalized) and then transforming that normal into world space.

What is N_a then?

It seems that the lookup table is constructed by taking all of the normals (N_a) in a normal map, and then taking all (or many) of the values that H can take, and forming a table from these according to the formula they provide.

However, this doesn't make sense to me, how is the normal that is transformed into world space taken into account in the lookup table then?

That is, the normal in the normal map is rotated to be on the mesh that the normal map is being applied to. So this new rotated normal is what we use to calculate the specular exponent -- how does this fit into the use of the lookup texture?

My best guess right now is that N_a is actually the normal from the normal map that is already transformed into world space. Otherwise, I guess it is just the normal from the normal map, and they ignore the transformation into world space.


texts: Why won't Unity drop objects to the origin position?

texts:
It seems that my objects drop to the middle of the scene, not a global position of (0, 0, 0).

Why is Unity behaving like this?


texts: Having issue having AI move after changing directions

texts:
I've frankenstein'd together an AI script for the enemy to chase the player once the player enters the AI's collider. If the player's X is lower than the enemy's X aka he's on his left the enemy turns and should start chasing the player again. My debug log fires saying the enemy should be chasing left and the enemy turns, but he does not chase the player.

Can someone take a look and see if the solution to the issue I'm having is apparent? I'm assuimg it has something to do with my leftward movement but im not experienced enough to know what it is, when I enter the values in different ways I can get the enemy to move left however so I'm not sure what exactly is wrong.

using UnityEngine;
using System.Collections;

public class EnemyMovement : MonoBehaviour
{

    public float movementspeed;
    public Transform player;
    Renderer enemyRenderer;
    bool engage = false;
    public GameObject enemySprite;
    public bool spriteFacingRight = true;
    Rigidbody2D rigid;

    //Animator enemyAnimator;

    void Start()
    {
        enemyRenderer = GetComponent<Renderer>();
        rigid = GetComponent<Rigidbody2D>();
        //enemyAnimator = GetComponent<Animator>();
    }

    void FixedUpdate()
    {
        if (engage == true)
        {

            if (spriteFacingRight && rigid.transform.position.x < player.position.x)
            {

                chargePlayer();

            }

            if (spriteFacingRight && rigid.transform.position.x > player.position.x)
            {

                turnFacing();
                chargePlayer();

            }
        }
    }

    void OnTriggerEnter2D(Collider2D col)
    {
        if (col.tag == "Player")
        {
            engage = true;
            Debug.Log("player engaged");
        }
    }

    void turnFacing()
    {
        float facingX = enemySprite.transform.localScale.x;
        facingX *= -1f;
        enemySprite.transform.localScale = new Vector3(facingX, enemySprite.transform.localScale.y, enemySprite.transform.localScale.z);
        spriteFacingRight = !spriteFacingRight;
        Debug.Log("facing player");
    }

    void chargePlayer()
    {
        if (!spriteFacingRight)
        {
            rigid.AddForce(new Vector2(-1, 0) * movementspeed);
            Debug.Log("chasing left");
        }

        if (spriteFacingRight)
        {
            rigid.AddForce(new Vector2(1, 0) * movementspeed);
            Debug.Log("chasing right");
        }
        //enemyAnimator.SetBool("isCharging", charging);
        Debug.Log("charging player");
    }
}


texts:
I've looked at some stuff online regarding this specific topic, and a lot of the info that I read involved graphs and path finding.

I really don't want to get involved in something too complex & out of my level, and also I don't need my snake to be that intelligent (it will be a large board with the snake not growing in size on every munch).

How could you structure a simpler AI for the snake that gets the job done relatively well? I would be able to get the snake to move towards the food item correctly, but my issue is that I'm not sure how to deal with the snake colliding with itself. Say the snake has a look ahead, and it finds that its tail is in the way, it could change direction, but what happens next?

Any ideas on how to tackle this? Should the snake build an instruction set from every square, or should it think on the go?


texts:
Getting this error when trying to use SDL_mixer...

SDL_types.h file not found..

I am including all the correct files as far as I can tell and have included the frameworks (both SDL and SDL_mixer) to my /systems/library/frameworks folder and it compiles well until I add SDL_mixer.h to my project. What should I do?

Here is main.cpp

#include <SDL/SDL.h>
#include "SDLMain.h"
#include "SDL_mixer.h"

int main(int argc, char ** argv)
{
    SDL_Init(SDL_INIT_EVERYTHING);
    Mix_Chunk song;
    //Initialize SDL_mixer
    if( Mix_OpenAudio( 22050, MIX_DEFAULT_FORMAT, 2, 4096 ) == -1 )
    {
        return false;
    }

    song = Mix_LoadWAV("song.wav");
    SDL_SetVideoMode(1000, 500, 32, SDL_SWSURFACE);
    SDL_Event event;
    bool done = false;
    while(!done)
    {
        while (SDL_PollEvent(&event))
        {
            if (event.type == SDL_QUIT)
            {
                done = true;
            }
            if (event.type == SDL_KEYDOWN)
            {
                if (event.key.keysym.sym == SDLK_UP)
                {
                    Mix_PlayChannel( -1, song, 0 );
                }
            }
        }
    }
    SDL_Quit();

    return 0;
}

Thanks


texts: GameObject is only rendered when it has a negative z scale

texts:
I have an orthographic camera that looks like this:

I create 2d polygonal meshes that have uniform z values in their vertices. I use Camera.ViewportToWorldPoint() to map these viewpoint vertices to world vertices.
The initial z valueI use for each polygon vertex is 1.0f. When I view my generated polygons, they each have a scale of (1,1,1) and are not being rendered. However, when I set the z value of the scale to any value less than zero, the mesh is rendered.
Could this be an issue with my camera's properties?


texts: GLfloat vs GLfixed vs GLint performance in 2017

texts: Some people claim that floats should be used for rendering vertices in modern graphics cards, because graphics cards are optimized for floating-point arithmetic and therefore, integer calculations are often emulated. I would think that most graphics cards have ALUs, and therefore, an efficient way to process integer vertices. So, are floats actually faster than integers on modern graphics cards?


texts: Homebrew development for 7th gen home consoles

texts:
I'm looking to do some homebrew development for either the Wii, Xbox360 or PS3. I'll be developing from a Linux system. The programming language doesn't matter.

Wii - devkitPPC and libogc look fairly easy and complete
Xbox360 - Mono.XNA looks interesting but not very feature complete
PS3 - psl1ght seems interesting but I haven't been able to find out much

How homebrew friendly are each of these consoles? Is someone able to give a comparison of each of these scenes?


texts:
I'm looking at creating a tablet application (iPad, Nexus, Surface...). I've heard it's possible to create it using HTML5 canvas. I was wondering if it was limited to canvas, if div/input/table can also be used.

Can a normal HTML page be used as an application for the Apple, Microsoft, Android store?


texts: Rotate an object smoothly on the Y axis in Unity

texts:
I am attempting a simple script to swing a door open in Unity.  This requires a smooth rotation of 90 degrees around the Y axis.  I have seen that one way to do this is using Unity's Quanternion object.  I believed that this should work:

public class DoorOpenScript : MonoBehaviour
{

    public float smooth = 20;

    // Use this for initialization
    void Start ()
    {
        SwingOpen ();
    }

    // Update is called once per frame
    void Update ()
    {

    }

    void SwingOpen()
    {
        Quaternion newRotation = new Quaternion(transform.rotation.x,transform.rotation.y,transform.rotation.z,transform.rotation.w);;
        newRotation *= Quaternion.Euler(0, 90, 0); // this add a 90 degrees Y rotation
        transform.rotation= Quaternion.Slerp(transform.rotation, newRotation,20 * Time.deltaTime);

    }

}

However, this just opens the door completely. I have tried playing with the third parameter to Slerp but with no results. What am I doing incorrectly?


texts: What is involved in creating a real-time multiplayer platformer game?

texts:
I'm creating a platformer game that has a "co-operative" feature which I'd like to work over networks / the internet.

Now I've read up on network game programming including articles like What every programmer needs to know about game networking and so I understand the difference between techniques like Peer-to-Peer lockstep and Server-Client prediction architectures:

I've concluded that for any real-time game that is going to be played over the internet, Peer-to-Peer lockstep simply isn't an option.
I'm also concerned that even for a platformer a simple client-server architecture (without some sort of client prediction) would result in degraded gameplay due to the delay between action and reaction caused by a round-trip to a server. (Having said that I want to eliminate the need for a central server, and so only one of the players, the client, will actually experience this lag).

This leaves client prediction, but even for a simple game like a platformer this still sounds pretty complex.

How would I go about creating a working client predictive system for a multiplayer platformer game?


texts: Slow motion of a spherical object on an blunt slant obstacle

texts: In cocos2d environment and box2D when an spherical object falls on a blunt slant obstacle, it moves really slowly, that's nauseating, if you have coded to not to have any interaction with world while object is in motion. Is there any way to get rid of this slow motion of object?


texts: Can I use Unity to edit a prefab created in Blender?

texts:
I've imported a character from Blender. The character is made of metaballs and so doesn't import properly. I'm trying to edit the character within Unity using the rig from the original Blender object.

The problem I'm running into is that I can only access the bones when the object is instantiated. The rig/armature object doesn't unfold in the project resource folder, and double clicking on the top-level object just opens it in Blender. So I can't seem to make edits that can later be instantiated.

Is there a way to use Unity to edit a prefab made in Blender so it can be instantiated? Any other suggestions welcome.

Screenshots for reference:


texts:
I am trying to write a Pixelshader for a curve effect in Direct2d.

A curve effect maps each color channel value to a different value by using a look up table.

For this effect I would need to pass 3 arrays to the effect.
Each array has 256 entries to map the specific color channel.

How can I pass these arrays to a Pixel shader (i.e. Direct2d Effect)?