# Question
Title: I need a book to continue experimenting with ActionScript 3
I am a CS student who finished his third year in school, and I'm interested in game development. This summer, I bought a book named "Foundation Game Design with Flash" by Rex Van Der Spuy. I'm halfway through it. It's a book for beginners, but it still helped me get familiar with Flash interface and AS3 syntax.

After I finish this book, I want to continue learning. I'm going to buy another book soon, and currently I'm considering three different items: Real-World Flash Game Development, AdvancED Game Design with Flash and "Foundation ActionScript 3.0 Animation: Making Things Move!" I want an intermediate level book. I now understand basic concepts of Flash and AS3, and can google my way through if I can't understand a concept in the book I'm going to buy.

Do any of you have a suggestion among these three? I only have budget for one. If you think I can benefit more from a completely different book, that's also good advice. Keep in mind that I will keep buying books as I finish them, so you can suggest an order of books to follow, aswell.

# Answer
I have only read **Foundation ActionScript 3.0 Animation: Making Things Move!** by Keith Peters but it was a good read, covered some interesting topics and the code was good. The author also runs the blog http://www.bit-101.com/blog/. He has also written another book **AdvancED ActionScript 3.0 Animation** which is similar to the first, but with different topics, although I would read his first one to begin with.
> 3 votes

# Answer
The book i used for AS3 was ActionScript 3.0 Game Programming University. Everything is explained very well, and it was fun working with the book.

Its completely based on games tho.
> 1 votes

---
Tags: actionscript-3, books
---


title: Windows Form code not executing?

text:
# Question
Title: Windows Form code not executing?
Ok, I've got a weird one here. I'm trying to make a basic tile engine using a windows form, but some of my code is just...not happening. I'll post the chunks in question.

```
private void MapEditor_Load(object sender, EventArgs e)
    {
        LoadImageList();
        FixScrollBarScales();
        cboCodeValues.Items.Clear();
        cboCodeValues.Items.Add("ENEMY");
        cboCodeValues.Items.Add("CHEST");
        cboCodeValues.Items.Add("NPC");

        for (int x = 0; x < 100; x++)
            cboMapNumber.Items.Add(x.ToString().PadLeft(3, '0'));

        cboMapNumber.SelectedIndex = 0;
        TileMap.EditorMode = true;
        backgroundToolStripMenuItem.Checked = true;
    }

```

This should be called when the form loads, right? The code dives into LoadImageList(), which contains:

```
private void LoadImageList()
    {
        string filepath = Application.StartupPath + @"\Content\Textures\IndoorTileSet.png";
        Bitmap tileSheet = new Bitmap(filepath);
        int tilecount = 0;
        for(int y = 0; y < tileSheet.Height / TileMap.TileHeight; y++)
        {
            for(int x = 0; x < tileSheet.Width / TileMap.TileWidth; x++)
            {
                Bitmap newBitmap = tileSheet.Clone(new System.Drawing.Rectangle(x * TileMap.TileWidth, y * TileMap.TileHeight,
                    TileMap.TileWidth, TileMap.TileHeight), System.Drawing.Imaging.PixelFormat.DontCare);
                imgListTiles.Images.Add(newBitmap);
                string itemName = "";
                if(tilecount == 0)
                    itemName = "Empty";
                if(tilecount == 1)
                    itemName = "Floor";
                listTiles.Items.Add(new ListViewItem(itemName, tilecount++));
            }
        }
    }

```

The bitmap loads correctly, but then the entire MapEditor\_Load method just stops working. tileCount seems to be a local variable in the debugger, and its value is 0, but the debugger never executes the breakpoint on the line which it is assigned. I have absolutely no idea why it would do this, and it's driving me nuts. Any help? Oh, I put the bitmap load in a try/catch block just to see if it was handling an exception in a weird way, but I had no luck. It's not throwing an exception. I began having this problem immediately after replacing my IndoorTileSet with an updated version.

# Answer
Are you running 64-bit Windows? When you say "stop working" do you mean the program just continues, or does the debugger terminate itself and your process? If you answered "yes," this is what may be biting you:

In 64-bit Windows, the kernel will eat any exceptions that reach a managed/native transition. This often presents itself in managed applications and a failure for exceptions to propagate out of delegates for `Load` events on forms and such (but of course, since an exception was raised, not all code in the delegate body was executed). You can find more on this issue here.

Your tileset PNG probably can't be loaded by the bitmap loader somehow. One way to see if this is the case may be to move the code *out* of the load event execution path (just shove it in your main function for a moment) and try to run it, possibly with "Break on Throw" enabled for all exceptions.
> 1 votes

# Answer
MapEditor\_Load would only get called if you have an event wired up to call that function on the Load event. Rather than implementing it as an event, I'd suggest using an override.

```
  // Notice your constructor...
  public MapEditor()
  {
     // InitializeComponent contains this line to hook up the Load event
     // this.Load += new System.EventHandler(this.MapEditor_Load);
     // (or may not contain it if your project is broken.)
     InitializeComponent();
  }

  // The load event (when hooked up) references this function,
  // as you can see in the comment above
  private void MapEditor_Load(object sender, EventArgs e)
  {
     // Your code here
  }

  // This is preferred because it avoids the complexity of events
  protected override void OnLoad(EventArgs e)
  {
     base.OnLoad(e);
     // Your code here
  }

```

Here you can see on the UI where the load event is hooked up:
> 0 votes

---
Tags: windows-forms
---


title: How do I add a custom mob to Minecraft?

text:
# Question
Title: How do I add a custom mob to Minecraft?
Basically decided to make my own mob, I have:

* Created my mob's entity class
* Created my mobs model class
* Drawn the model
* Added the function call for addMapping within the EntityList class

I'm stuck on what to do next. I've tried finding the code that deals with passive animal spawning in the world, however I can't seem to find it.

Help greatly appreciated.

# Answer
> 18 votes
Well I'm not going to write a whole tutorial (because I have limited time right now) but I will link you to some resources and give some tips.

Firstly if you are going to mod Minecraft in any way, you want to go to the modding wiki.

I had a look around the wiki, and found a basic mob creation tutorial.

There is a massive mod creation tutorial here. You should have a skim through that

I picked out some individual tutorials that you might like-

Now on to the model creation, this took me a while to find, but I found 3 modelling programs.

* Techne \- Allows you to create models, which will then be converted into Java code. has alot of user tutorials on how to create replicas of vanilla models (cows, endermen etc.)
* MCModeller \- Quite simple GUI, live preview. Coded in Java
* FMCModeller \- GUI is not as simple, but it looks extremely professional with 2 view, one for the spritesheet and one for displaying the model live (which you can rotate etc.). Coded in Flash.

For the passive animal spawning code, I suggest you download Minecraft Coders Pack MCP, and search through the source files. The way I first found how to mod the terrain generator, was searching the source directory for the blockID I was modding. I suggest you search for terms like "spawn" and "entity".

You must understand however, that when Mojang releases modding support, this will be much easier, so be prepared to change your code. Also with the newest Adventure Updates, Mojang is constantly changing the code.

---
Tags: minecraft-modding, modding
---


# Question
Title: Culling Techniques for 3d OpenGL ES game
I'm developing a 3d flight simulator for Android and am using a relatively large (10k triangles) scene in 3ds format for the scenery. The scene is one polygon soup, not separated into separate objects. Frustum culling per triangle would be time consuming. What techniques could I use to render the triangles that are only visible in the view-port?

# Answer
Per-triangle culling is done by the GPU, so you should only draw entire objects. Some tips:

* Break down your scene into smaller objects, preferably doing it based on their material, so they are drawn in a single batch.
* Calculate a bounding box for each object, and intersect them with the view frustum. Discard or draw them based on this criteria.
* Use VBOs for your data, uploading it once to the GPU and then drawing them directly from VRAM.
* If you have a very large object, like a ground plane, consider implementing a quadtree approach (or octree if it isn't flat).
* Consider using level of detail (LOD) for detailed, distant objects.
> 2 votes

# Answer
You should separate the triangles in groups, as in making separate game objects, then assign a bounding volume to it and check the box geometry against the frustum planes to discard all triangles contained in the bounding volume.

You need to separate objects in order to define a local coordinate space/object center for each triangle group that makes a 3D object. You can't skip groups of triangles if the only information you have are just the vertex position of random triangles, so you need to define a local center for groups or triangles and these triangles' vertices be described relative to the local object center. Then for transforming the vertices' positions to the global coordinates, just add the object's center to each vertex to translate to the global coordinates (but this won't work for rotations, you should build a matrix instead if you want both a rotation and translation transform).

So either you make a file for each object, or parse the single file and separate them on loading, but the later is difficult and you will work better if geometries are already split and have a local origin defined.
> 2 votes

# Answer
Octrees are a good way to organize polygon soup scenes for visibility culling. The idea is similar to other sorts of recursive dividing techniques like BSP or even quicksort, but more 3 dimensional.
> 1 votes

---
Tags: 3d, opengl-es, scene-graph, culling
---


# Question
Title: How do I implement SkyBox in xna 4.0 Reach Profile (for Windows Phone 7)?
I'm trying to Implement SkyBox in my phone game. Most of the samples in the web are for HiDef profile, and they are using custom effects (that not supported on Windows Phone). I've tried to follow this guide. But for some reason my SkyBox is not rendered.

This is my SkyBox class:

```
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Rocuna.Core;
using Rocuna.GameEngine.Graphics;
using Rocuna.GameEngine.Graphics.Components;

namespace Rocuna.GameEngine.Extension.WP7.Graphics
{
    /// <summary>
    /// Sky box element for phone games.
    /// </summary>
    public class SkyBox : SkyBoxBase
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="SkyBoxBase"/> class.
        /// </summary>
        /// <param name="game">The Game that the game component should be attached to.</param>
        public SkyBox(TextureCube cube, Game game)
            : base(game)
        {
            Cube = cube;
            CubeFaces = new Texture2D[6];
            PositionOffset = new Vector3(20, 20, 20);
            CreateGraphic(512);
            StripTexturesFromCube();
            InitializeData(Game.GraphicsDevice);
        }

        #region Properties

        /// <summary>
        /// Gets or sets the position offset.
        /// </summary>
        /// <value>
        /// The position offset.
        /// </value>
        public Vector3 PositionOffset { get; set; }

        /// <summary>
        /// Gets or sets the position.
        /// </summary>
        /// <value>
        /// The position.
        /// </value>
        public Vector3 Position { get; set; }

        /// <summary>
        /// Gets or sets the cube.
        /// </summary>
        /// <value>
        /// The cube.
        /// </value>
        public TextureCube Cube { get; set; }

        /// <summary>
        /// Gets or sets the pixel array.
        /// </summary>
        /// <value>
        /// The pixel array.
        /// </value>
        public Color[] PixelArray { get; set; }

        /// <summary>
        /// Gets or sets the cube faces.
        /// </summary>
        /// <value>
        /// The cube faces.
        /// </value>
        public Texture2D[] CubeFaces { get; set; }

        /// <summary>
        /// Gets or sets the vertex buffer.
        /// </summary>
        /// <value>
        /// The vertex buffer.
        /// </value>
        public VertexBuffer VertexBuffer { get; set; }

        /// <summary>
        /// Gets or sets the index buffer.
        /// </summary>
        /// <value>
        /// The index buffer.
        /// </value>
        public IndexBuffer IndexBuffer { get; set; }

        /// <summary>
        /// Gets or sets the effect.
        /// </summary>
        /// <value>
        /// The effect.
        /// </value>
        public BasicEffect Effect { get; set; }

        #endregion

        protected override void LoadContent()
        {
        }

        public override void Update(GameTime gameTime)
        {
            var camera = Game.GetService<GraphicManager>().CurrentCamera;
            this.Position = camera.Position + PositionOffset;
            base.Update(gameTime);
        }

        public override void Draw(GameTime gameTime)
        {
            DrawOrder = int.MaxValue;
            var graphics = Effect.GraphicsDevice;
            graphics.DepthStencilState = new DepthStencilState() { DepthBufferEnable = false };
            graphics.RasterizerState = new RasterizerState() { CullMode = CullMode.None };
            graphics.BlendState = new BlendState();
            graphics.SamplerStates[0] = SamplerState.AnisotropicClamp;

            graphics.SetVertexBuffer(VertexBuffer);
            graphics.Indices = IndexBuffer;

            Effect.Texture = CubeFaces[0];
            Effect.CurrentTechnique.Passes[0].Apply();
            graphics.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, _vertices.Count, 0, 2);

            Effect.Texture = CubeFaces[1];
            Effect.CurrentTechnique.Passes[0].Apply();
            graphics.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, _vertices.Count, 6, 2);

            Effect.Texture = CubeFaces[2];
            Effect.CurrentTechnique.Passes[0].Apply();
            graphics.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, _vertices.Count, 12, 2);

            Effect.Texture = CubeFaces[3];
            Effect.CurrentTechnique.Passes[0].Apply();
            graphics.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, _vertices.Count, 18, 2);

            Effect.Texture = CubeFaces[4];
            Effect.CurrentTechnique.Passes[0].Apply();
            graphics.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, _vertices.Count, 24, 2);

            Effect.Texture = CubeFaces[5];
            Effect.CurrentTechnique.Passes[0].Apply();
            graphics.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, _vertices.Count, 30, 2);
            base.Draw(gameTime);
        }

        #region Fields

        private List<VertexPositionNormalTexture> _vertices = new List<VertexPositionNormalTexture>();

        private List<ushort> _indices = new List<ushort>();

        #endregion

        #region Private methods

        private void InitializeData(GraphicsDevice graphicsDevice)
        {
            VertexBuffer = new VertexBuffer(graphicsDevice, typeof(VertexPositionNormalTexture), _vertices.Count,
                BufferUsage.None);
            VertexBuffer.SetData<VertexPositionNormalTexture>(_vertices.ToArray());

            // Create an index buffer, and copy our index data into it.
            IndexBuffer = new IndexBuffer(graphicsDevice, typeof(ushort),
                                          _indices.Count, BufferUsage.None);

            IndexBuffer.SetData<ushort>(_indices.ToArray());

            // Create a BasicEffect, which will be used to render the primitive.
            Effect = new BasicEffect(graphicsDevice);

            Effect.TextureEnabled = true;

            Effect.EnableDefaultLighting();
        }

        private void CreateGraphic(float size)
        {
            Vector3[] normals = {
                                    Vector3.Right,
                                    Vector3.Left,
                                    Vector3.Up,
                                    Vector3.Down,
                                    Vector3.Backward,
                                    Vector3.Forward,
                                };
            Vector2[] textureCoordinates = {
                                               Vector2.One, Vector2.UnitY, Vector2.Zero, Vector2.UnitX,
                                               Vector2.Zero, Vector2.UnitX, Vector2.One, Vector2.UnitY,
                                               Vector2.Zero, Vector2.UnitX, Vector2.One, Vector2.UnitY,
                                               Vector2.Zero, Vector2.UnitX, Vector2.One, Vector2.UnitY,
                                               Vector2.UnitY, Vector2.Zero, Vector2.UnitX, Vector2.One,
                                               Vector2.UnitY, Vector2.Zero, Vector2.UnitX, Vector2.One,
                                           };
            var index = 0;
            foreach (var normal in normals)
            {
                var side1 = new Vector3(normal.Z, normal.X, normal.Y);
                var side2 = Vector3.Cross(normal, side1);

                AddIndex(CurrentVertex + 0);
                AddIndex(CurrentVertex + 1);
                AddIndex(CurrentVertex + 2);

                AddIndex(CurrentVertex + 0);
                AddIndex(CurrentVertex + 2);
                AddIndex(CurrentVertex + 3);

                AddVertex((normal - side1 - side2) * size / 2, normal, textureCoordinates[index++]);
                AddVertex((normal - side1 + side2) * size / 2, normal, textureCoordinates[index++]);
                AddVertex((normal + side1 + side2) * size / 2, normal, textureCoordinates[index++]);
                AddVertex((normal + side1 - side2) * size / 2, normal, textureCoordinates[index++]);
            }
        }

        protected void StripTexturesFromCube()
        {
            PixelArray = new Color[Cube.Size * Cube.Size];

            for (int s = 0; s < CubeFaces.Length; s++)
            {
                CubeFaces[s] = new Texture2D(Game.GraphicsDevice, Cube.Size, Cube.Size, false, SurfaceFormat.Color);
                switch (s)
                {
                    case 0:
                        Cube.GetData<Color>(CubeMapFace.PositiveX, PixelArray);
                        CubeFaces[s].SetData<Color>(PixelArray);
                        break;
                    case 1:
                        Cube.GetData(CubeMapFace.NegativeX, PixelArray);
                        CubeFaces[s].SetData(PixelArray);
                        break;
                    case 2:
                        Cube.GetData(CubeMapFace.PositiveY, PixelArray);
                        CubeFaces[s].SetData(PixelArray);
                        break;
                    case 3:
                        Cube.GetData(CubeMapFace.NegativeY, PixelArray);
                        CubeFaces[s].SetData(PixelArray);
                        break;
                    case 4:
                        Cube.GetData(CubeMapFace.PositiveZ, PixelArray);
                        CubeFaces[s].SetData(PixelArray);
                        break;
                    case 5:
                        Cube.GetData(CubeMapFace.NegativeZ, PixelArray);
                        CubeFaces[s].SetData(PixelArray);
                        break;
                }
            }
        }

        protected void AddVertex(Vector3 position, Vector3 normal, Vector2 textureCoordinates)
        {
            _vertices.Add(new VertexPositionNormalTexture(position, normal, textureCoordinates));
        }

        protected void AddIndex(int index)
        {
            if (index > ushort.MaxValue)
                throw new ArgumentOutOfRangeException("index");

            _indices.Add((ushort)index);
        }

        protected int CurrentVertex
        {
            get { return _vertices.Count; }
        }

        #endregion
    }
}

```

# Answer
You don't have set View/Projection/World of the effect. Try something like this in the draw method :

```
        Effect.View = xxxx.m_viewMatrix;
        Effect.Projection = xxxx..m_projMatrix;
        Effect.World = Matrix.Identity;

```
> 2 votes

---
Tags: xna, c#, windows-phone-7
---


# Question
Title: What is the "DirectX for Managed Code Update"?
I came upon this site while looking for information about working with DX in managed code and saw that MS released something containing a 'DirectX for Managed Code Update'. This sounds promising but I can't find much information about it.

Is this an out of date update referring to what was formerly *Managed DirectX*, or something new\*?

If new, has anyone used it? How does it compare to SlimDX?

(\*as new as it can be from June last year)

# Answer
> 4 votes
The description is somewhat misleading; even though the SDK link you've posted is for the June 2010 version of the SDK, the DirectX for Managed Code Update is from a much older version of the SDK (whenever they last updated MDX, which was years and years ago as MDX is a deprecated product). The latest SDK still contains the old MDX assemblies, but they are dead.

Microsoft's "official" means of accessing DirectX through managed code is the Windows API code pack, which is somewhat of a bastard child and unlikely to get any more support or iteration than MDX ever did.

XNA or SlimDX are better choices, depending on the level of abstraction you want (XNA for a high level view, SlimDX for a close, low-level mapping to the native D3D API).

# Answer
> 1 votes
As far as I know, the only officially supported way of using managed code and DirectX is XNA. However there have been some rumors that Windows 8 might change this again.

Anyway in 2010 there was only XNA and legacy Managed DirectX. Either this is a bug fix for legacy Managed Direct X or they meant XNA. (Or it is something completely else).

As for using 'managed Direct X' when you don't want to use the XNA framework, you can use cool 3rd party frameworks like SlimDX (which you tagged already).

If you haven't made up your mind yet at all then I would go with XNA since it offers both high-level features and low-level bit-tweaking when you want it!

---
Tags: c#, directx, slimdx, microsoft
---


title: Trying to implement Render to Texture

text:
# Question
Title: Trying to implement Render to Texture
I'm having trouble implementing render to texture with OpenGL 3.

My issue is that after rendering to the frame buffer, it appears the rendered object becomes deformed, which may imply a bad transformation has occurred somewhere. Which doesn't make sense as the object renders fine when **not** using my frame buffer (see bottom of post).

**The current result is such:**

Current result http://k.minus.com/jZVgUuLYRtapv.jpg

**And the expected result was this (or something similar, this has just been GIMP'd):** Expected http://k.minus.com/jA5rLM8lmXQYL.jpg

It therefore implies that I'm doing something wrong in my frame buffer set up code, or elsewhere. But I can't see what.

---

The FBO is set up through the following function:

```
unsigned int fbo_id;
unsigned int depth_buffer;
int m_FBOWidth, m_FBOHeight;
unsigned int m_TextureID;

void initFBO() {
    m_FBOWidth = screen_width;
    m_FBOHeight = screen_height;

    glGenRenderbuffers(1, &depth_buffer);
    glBindRenderbuffer(GL_RENDERBUFFER, depth_buffer);
    glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, m_FBOWidth, m_FBOHeight);

    glGenTextures(1, &m_TextureID);
    glBindTexture(GL_TEXTURE_2D, m_TextureID);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, m_FBOWidth, m_FBOHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
    glBindTexture(GL_TEXTURE_2D, 0);

    glGenFramebuffers(1, &fbo_id);
    glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo_id);

    glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depth_buffer);
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_TextureID, 0);

    assert(glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE);
    glBindFramebuffer(GL_FRAMEBUFFER, 0);
}

```

Here is my drawing box code, which just takes a transformation matrix and calls the appropriate functions. The current values of P is a projection matrix, and an identity matrix for the view matrix (V).

```
void drawBox(const Matrix4& M) {
    const Matrix4 MVP = M * V * P;

    if (boundshader) {
        glUniformMatrix4fv((*boundshader)("MVP"), 1, GL_FALSE, &MVP[0]);
    }

    glBindVertexArray(vaoID);
    glDrawElements(GL_TRIANGLES, sizeof(cube.polygon)/sizeof(cube.polygon[0]), GL_UNSIGNED_INT, 0);
}

void drawStaticBox() {
    Matrix4 M(1);
    translate(M, Vector3(0,0,-50));

    drawBox(M);
}

void drawRotatingBox() {
    Matrix4 M(1);
    rotate(M, rotation(Vector3(1, 0, 0), rotation_x));
    rotate(M, rotation(Vector3(0, 1, 0), rotation_y));
    rotate(M, rotation(Vector3(0, 0, 1), rotation_z));
    translate(M, Vector3(0,0,-50));

    drawBox(M);
}

```

And the display function called by GLUT.

```
void OnRender() {
    /////////////////////////////////////////
    // Render to FBO

    glClearColor(0, 0, 0.2f,0);

    glBindFramebuffer(GL_FRAMEBUFFER, fbo_id);
    glViewport(0, 0, m_FBOWidth, m_FBOHeight);
    glClear(GL_COLOR_BUFFER_BIT| GL_DEPTH_BUFFER_BIT);
    GL_CHECK_ERRORS

    colorshader.Use();
    boundshader = &colorshader;

    drawRotatingBox();

    colorshader.UnUse();

    /////////////////////////////////////////
    // Render to Window

    glClearColor(0, 0, 0, 0);

    glBindFramebuffer(GL_FRAMEBUFFER, 0);
    glViewport(0, 0, screen_width, screen_height);
    glClear(GL_COLOR_BUFFER_BIT| GL_DEPTH_BUFFER_BIT);
    GL_CHECK_ERRORS

    texshader.Use();
    boundshader = &texshader;

    glBindTexture(GL_TEXTURE_2D, m_TextureID);
    drawStaticBox();

    texshader.UnUse();

    // Swap le buffers
    glutSwapBuffers();
}

```

---

And... the obligatory texture shader code

**vertex**

```
#version 330

in vec2 vUV;
in vec3 vVertex;
smooth out vec2 vTexCoord;

uniform mat4 MVP;
void main()
{
   vTexCoord = vUV;
   gl_Position = MVP*vec4(vVertex,1);
}

```

**fragment**

```
#version 330
smooth in vec2 vTexCoord;
out vec4 vFragColor;

uniform sampler2D textureMap;

void main(void)
{
   vFragColor = texture(textureMap, vTexCoord);
}

```

---

**The following is what is rendered when not using the FBO logic:** What is rendered to the FBO http://k.minus.com/jiP7kTOSLLvHk.jpg

---

... Help?

Any ideas on what I may be doing wrong? Further source available on request.

# Answer
Offhand looks like your UV coordinates are messed up. Try rendering the textured cube with just a static test image?
> 1 votes

# Answer
It looks as if part of the cube is getting near-clipped in the FBO version, which leads me to suspect something wrong with the projection matrix and/or viewport. Double-check those, maybe try explicitly setting glDepthRange(0, 1)?
> 0 votes

---
Tags: c++, opengl, c, deferred-rendering
---


title: Rendering tiles on 3/4 perspective

text:
# Question
Title: Rendering tiles on 3/4 perspective
Using a 3/4th perspective, I'm trying to create a way to render cliffs where nothing is overlapped, and it creates an accurate representation of the elevation. This is a rough mockup of how it might look in-game:

The way the tile data is organized is by layer. Each elevation has a layer class which holds all of the ground data for that specific layer, and all unoccupied space is simply null in the array. I can't seem to come up with a way to render the data so it would look something like this. I've thought about rendering from highest to lowest elevation, the other way around, etc. All entailed a situation where something is getting overlapped that shouldn't be.

What's the best way to do this?

# Answer
> 2 votes
I suggest that you draw the top rows \[on the screen\] first, and build up from the ground, overwriting the higher rows as you draw those tiles (you'll have to traverse the upper layers as you do this, but that should be easy as the X and Y will remain unchanged), and do so until all rows are completely drawn for you.

You can even loop beyond the bottom and just draw other things that are higher up even though their corresponding ground tiles are off the screen (creating a sense of even more depth for your scenes as your players navigate in any direction).

Additionally, if alpha-blending (transparency) mode is support, and if your character is always positioned in the centre of the screen (e.g., because the background scrolls when the player's character moves), you could also use transparency effects (with alpha-blending) when drawing the tiles that would block the view of the character (so the player can see what's going on), and gradually reduce this transparency effect with each tile that is further away from the character (80% transparency for the blocking tile, 60% for the next ones, 40% for the ones outside of that, then 20% outside of that, and finally 0% for all the rest).

# Answer
> 5 votes
I don't know if it's important to how your game works to actually make the tile have depth information or just APPEAR to have depth. If appearing to have depth is ok, then here's the way I addressed this in my tile engine:

Each map has a two-dimensional array of `MapCell` objects. A `MapCell` can be thought of as a "tile slot" in that it represents an area on the map where a tile would be drawn.

Now, each `MapCell` has two (it could be more, but I only use two) `MapCellLayer` objects. The first `MapCellLayer` object is always defined, but the second one is optional (i.e. often `== null`).

A `MapCellLayer` can have up to five `Tile` objects. `Tile` objects represent the actual tiles being drawn to the screen and hold a reference to the tile index from the tilesheet. The reason there are five `Tile` objects is because of how they're drawn and used. They're set up like this:

1. Ground - This is the base tile, it's drawn on the screen first and appears below all other tiles in the `MapCell` and the players.
2. Mask 1 - This tile is drawn second (if it exists) and provides a way to add tiles with alpha transparency over top of the ground tile. It's drawn below the player.
3. Mask 2 - This is exactly the same as the Mask 1 tile except it's drawn after to allow for even more control of the map by overlaying more tiles.
4. Fringe 1 - This tile is drawn after Mask 2 and is effectively the same as Mask 1 with the only exception being that it is drawn OVER the player. Players get drawn between Mask 2 and Fringe 1.
5. Fringe 2 - You may have guessed it already, but this is the same as Fringe 1, but drawn over it.

My draw call works like this:

```
Loop through all the MapCells within the camera's view.
   Loop through all MapCellLayers for the current MapCell
      If the layer exists
         Draw the Ground tile if it exists
         Draw the Mask 1 tile if it exists
         Draw the Mask 2 tile if it exists
         Draw the Player on the tile if any
         Draw the Fringe 1 tile if it exists
         Draw the Fringe 2 tile if it exists
      End if layer exists
   End MapCellLayer loop
End MapCell loop
```

A few notes:

* If you you build your maps with this system, you can create some advanced looking terrain features with the right tileset. See my example pictures below.
* The point of the MapCellLayer is so that I can have areas where two players occupy the same cell but one is above another one such as on bridges or inside houses (i.e. first and second floor, although inside houses I only draw the MapCellLayer that the player is on).
* I don't actually draw the players in the tile loop, I just wanted to make it simple. I actually make use of `SpriteSortMode.FrontToBack` so that each layer has it's own values and gets drawn in the correct order. The player/npc loop is then done separately. I recommend this method especially if your players/npcs are larger than a single tile.

Here's some example pictures from one of the maps in my game. I've taken screenshots working up from drawing only Ground tiles to all tiles up to Fringe 2. The player is stationary.

**Ground**

**\+ Mask 1** (Note the use of transparency on the bushes and tree roots.)

**\+ Mask 2** (Note the ladder being drawn over the rock wall from Mask 1.)

**\+ Fringe 1** (Note that the player is being drawn *behind* the tree.)

**\+ Fringe 2** (Note how the branches of the pink tree on the right now overlap the ones from the tree on the left.)

I hope this helps you. Let me know if you have any questions.

# Answer
> 0 votes
I would calculate the visible portion when rendering each block so that you only ever render each screen block once.

I would implement it something like this:

```
TileImage GetTileImage(int screenx, int screeny)
{
  for(int height = layers.count - 1; height >= 0; height--)
  {
    //translate height down the screen to get the correct block
    TileImage image = layers[height].GetTile(screenx,screeny-height);
    if(image != NULL)
    {
      return image;
    }
  }
  //If we got here no tile makes up this screen tile, handle accordingly
}

```

So what this code does, is start off at the max height layer, and looks for a tile at X: ScreenX Y: ScreenY - Height

As the block that shows at screen position 5,5 at height 3 is actually at word position 5,2

So the loop will search from the top height until it finds a block for that screen coord.

Hope this makes sense.

So in your rendering loop you would loop over x and y in screen coords and call GetTileImage() once per image square.

---
Tags: xna, c#, tiles
---


# Question
Title: Does OGRE do hardware skinning by default?
I am trying to understand how OGRE works at a lower level, and from what I have read so far, I believe OGRE generates shaders from material scripts using its RTShader system, on the loading of each scene (based on the contents).

My questions are:

1. Is this correct? (i.e. does OGRE 1.7.1 by default generate shaders at runtime by default?)
2. If 'yes', do the generated shaders support hardware skeletal animation by default?
3. In either case, if 'yes' to (1), when I extend a material script specifying a fragment program, is this incorporated into the generated script or does it completely replace it?

**EDIT:**

OK, so I got PIX to debug a scene with a model with skeletal animation, and it turns out the fixed-function pipeline was in use (no vertex or pixel shaders were available for PIX to debug even as assembly).

I then looked with the debugger for the properties referenced in the skeletal animation example file SkeletalAnimation.h:

```
    // change the value if hardware skinning is enabled
Pass* pass = ent->getSubEntity(0)->getMaterial()->getBestTechnique()->getPass(0);
    if (pass->hasVertexProgram() && pass->getVertexProgram()->isSkeletalAnimationIncluded()) value = "Hardware";

```

And found that there was no vertex or fragment program to speak of, hence I can assume the answer to (2) at least is 'no'.

Looking further at OGRE's documentation it seems I can combine shaders with the FFP, but only replacing specific stages. (i.e. I can't use the FFP vertex processing and then add a vertex shader)

*I am still unsure though about RTShader: Is it an established part of OGRE, or still in development? Do I have to turn it on? Or do I have to invoke it manually?*

# Answer
On much further reading, in case anyone is interested, the answer to my edited question is:

RTShader is part of the core OGRE system but is a recent addition (1.7). It works as asserted above, by generating a shader based on the requirements of the scene, but the user invokes it explicitly themselves and applies the result to their models.
> 2 votes

---
Tags: shaders, rendering, ogre, mogre
---


title: Blend Modes in Cocos2D with glBlendFunc

text:
# Question
Title: Blend Modes in Cocos2D with glBlendFunc
We've been trying to replicate the **most common blending modes** that are available in Photoshop and Quartz 2D, but we've only come up with 3 and that's after some long searching online.

For anyone interested, here they are:

> * **Multiply** = GL\_DST\_COLOR, GL\_ONE\_MINUS\_SRC\_ALPHA
> * **Screen** = GL\_MINUS\_DST\_COLOR, GL\_ONE
> * **Linear Dodge** = GL\_ONE, GL\_ONE

You can try these and other such modes in action online, at this very useful website: http://www.andersriggelsen.dk/glblendfunc.php

Now, we would appreciate it if anyone could provide us with additional blending modes that we can recreate inside Cocos2D, since our Open GL experience is really, really limited.

Thank you in advance!

Argiris

# Answer
> 4 votes
Bad news is that you can't implement all of photoshop's blend modes with glBlendFunc, even though there are a bazillion of combinations that you can use.

Good news is, when you move to shaders, the orange book (OpenGL Shading Language, http://www.amazon.com/exec/obidos/ASIN/0321637631/khongrou-20 ) contains a chapter with shaders to emulate the photoshop's blend modes.

Luckily all you'll probably ever need in pre-shader world are the three most common blend modes;

* Add: GL\_ONE, GL\_ONE
* Blend: GL\_SRC\_ALPHA, GL\_ONE\_MINUS\_SRC\_ALPHA
* Multiply: various, such as the one you mentioned: GL\_DST\_COLOR, GL\_ONE\_MINUS\_SRC\_ALPHA

**EDIT**:

Related (almost duplicate) question on stackoverflow: https://stackoverflow.com/questions/818230/photoshop-blending-mode-to-opengl-es-without-shaders

Photoshop blending shaders: http://mouaif.wordpress.com/2009/01/05/photoshop-math-with-glsl-shaders/

---
Tags: opengl-es, cocos2d-iphone, ios, blending
---


# Question
Title: Should I go with SpriteBatch or just 3D with Z component always zero?
I'm designing a platformer and beginning to code the viewing engine of the game. Now, I have to make a key decision: Should I just use SpriteBatch to draw all the 2D stuff, as there is no 3D, or should I just go with making camera-facing polygons with Z set to zero? What are the good sides and drawbacks of both? Performance? Extensibility?

Performance is a key factor as I'll be having lots of texttures/objects/effects/animations etc, and I'll be targetting high resolutions like 1920x1200 (if available on client's computer), so I need things to go smooth. On the other hand, I also need some extensibility, as I want to have great control over the drawing methods. Seems like I'd be going with 3D/polygon method, but I was wondering if it has any side-effects?

# Answer
Sprite batch is implemented with 'camera-facing polygons with Z set to zero'. IIRC it even has rotation, and if it doesn't, you can supply your own transformation matrix. Your choices are equivalent. Ask yourself how much work you want to do duplicating spritebatch instead.
> 5 votes

---
Tags: xna, platformer, spritebatch
---


# Question
Title: differences between opengl 3 and opengl 4
I'm just getting started with game programming and I want to start learning opengl. I found a very great tutorial from scratch to get started with opengl 3 and I'm wondering if there is a big difference between openGL 3 and openGl 4. Or I should ask, does openGL 4 make openGL 3 obsolete, or I can start with openGL 3 and then I can move to openGL 4?

# Answer
I'll start this off by linking to an explanation of how OpenGL versions work. In short, OpenGL (generally) is backwards compatible, so all GL 3 code works just fine on GL 4 implementations.

The 4.x series of OpenGL versions represents what you might call "Direct3D 11"-class hardware. It exposes functionality of that hardware. D3D10 hardware is represented by the 3.x versions of OpenGL. So "moving to openGL 4" means abandoning lower hardware, or having multiple rendering pathways.

A detailed breakdown of the actual feature changes between 3.3 and 4.2 can be found in the 4.2 specification. Do note that many features (separate\_shader\_objects, shading\_language\_420pack, texture\_storage) are not restricted to 4.x hardware; they are API changes and you can access them on 3.x hardware via extensions.

The most salient question is this: what does GL 4.x allow me to do that I can't with 3.x hardware?

Tessellation is probably the most well-known feature. It is also probably the least generally useful. That's not to say that it's useless; proper use of tessellation can enhance detail in models. But to me at least, it's not really the best thing GL 4 has going for it.

Shader subroutines are an interesting idea. This basically allows you to dynamically piece together different fragments of shaders. You can more or less attach a function to a specific bind point in a program. The specification is a bit hard to follow, but it's good functionality.

I'd say that image load/store is probably the most overlooked and yet most powerful bit of GL 4 functionality. With it, you have the ability to implement order-independent transparency with performance that's about as good as OIT is going to get. There are probably many other uses for image load/store, but it will take cleverer people to figure them out.

There are some odds and ends in GL 4. Stuff like double-precision support and indirect rendering. These are more GPGPU-style stuff, so it probably won't be of much use in a game.

But generally, GL 4 doesn't radically change how you implement feature X from GL 3.
> 14 votes

---
Tags: opengl
---


title: Shape editor with custom format?

text:
# Question
Title: Shape editor with custom format?
I'm trying to determine what format the shapes in my 2D game should be stored in and also what software I should use to aid in making the actual shapes.

Up until now I used PhysicsEditor from code'n'web, which saves shape information in XML format. The problem is that the way the file is layed out, it will require a lot of parsing to extract the actual information I'm interested in.

I've made my own "format" for storing shape information (see below). I used JSON instead of XML since it's a lot less verbose. Layed out like this, I require minimal parsing to get the actual information.

```
{
    "polygons":
    [
        {
            "density" : 1.2,
            "vertices": [
                [0.0, 8.9], [5.6, 7.8], [3.5, 0.0], [3.6, 9.9]
            ]
        }
    ]
}

```

My question:
Can I configure PhysicsEditor so that it saves shapes in this format automatically? If not, is there some software that allows that kind of configuration?

# Answer
Can you "configure" it? No. You can write an exporter plugin for it however.
> 3 votes

---
Tags: tools, editors
---


title: Loading Bitmap by name in Android

text:
# Question
Title: Loading Bitmap by name in Android
Currently, I'm loading images as follows:

```
sampleimage= BitmapFactory.decodeResource(context.getResources(), R.drawable.sampleimage);

```

This automatically chooses the correct image from the drawable-hdpi, drawable-mdpi or drawable-ldpi folders.

How can I load the bitmap using the image name as the string "sampleimage.png"?

# Answer
If you want to access bitmaps by full file name you can store them in `assets` folder. Then obtain *AssetManager* from your *Activity* by calling `getAssets()` and use `AssetManager.open(String fileName)` or `AssetManager.openFd(...)` method.

If you only want to force Android to not get bitmap from mdpi, ldpi and hdpi folders (depending on device parameters) then store your resources in `res/drawable` folder (without "-\*dpi" suffix). You can also provide bitmaps in `res/raw` folder and then they wouldn't be scaled (what may occure in res/drawable folder).

There is one more difference between assets and res/drawable or res/raw folder. In assets resources can be put in subfolders in your way of organizing thins.

Look for more info at http://developer.android.com/guide/topics/resources/providing-resources.html and http://developer.android.com/reference/android/content/res/AssetManager.html
> 3 votes

---
Tags: android, java
---


# Question
Title: 2D physics performance on iPhone/Android using Unity 3D?
I've been looking into making 2D games with Unity. One thing which concerns me is the performance of the physics engine. Since Unity is a 3D game engine I'm going to have to assume it uses a 3D physics engine. Obviously I can turn this 3D engine into a 2D one by locking off various axis such that objects only move physically in 2D space.

However this worries me, for example Box2D being a specialized 2D physics engine is optimized for 2D. Would the physics in Unity3D be fast enough to say, duplicate the sorts of physics we see in games like Angry Birds on a handheld device?

# Answer
> 1 votes
Yes. I've used box2d before and right now I'm using unity. I'd say it's just as fast box2d and good enough for Angry Birds.

---
Tags: android, iphone, physics, unity, box2d
---


# Question
Title: How does pixeljunk shooter simulate its liquids?
I am really impressed by the liquids in pixeljunk shooter. I would love to know how they do it.

# Answer
> 14 votes
There is an excellent SIGGRAPH presentation on PixelJunk Shooter 2's lighting and physics simulation, including fluid mechanics, available on youtube.

---
Tags: physics, rendering, simulations, particles
---


title: Enemy class architecture

text:
# Question
Title: Enemy class architecture
I'm developing a game for Android in Java. I would like to know how a good Enemy class architecture could be implemented.

I've created an abstract class called Enemy. It stores common properties like Health and Animation data. It has methods like LoadContent, Update and Draw.

I want to inherit this class and implement different enemy classes. I want to be able to store all my active enemies in some sort of collection. Then in my Update function of my game loop, I'll do something like:

```
for each Enemy in Enemies
{
Enemy.Update()
}

```

And the Update method of the correct child class would be called.

How can this be achieved?

# Answer
I would consider making an enemy factory. Every time you make a new enemy of any sort, add it to a list inside your factory instance. This means that you can update all of your enemies from your enemy factory, and you know that every enemy is in the list.
> 2 votes

# Answer
If Update is abstract in your base class then all you have to do is override it in your child classes and the relevant update function will be called on each one.
> 4 votes

---
Tags: architecture, android, java
---


title: install unity package in to iphone?

text:
# Question
Title: install unity package in to iphone?
HI All, what is the steps of to install the unity package in to iphone and create a build (app file )that my client can also able to install in his iphone .

Thanks, balraj.

# Answer
Here are some tutorials that you might find useful from UnifyCommunity.

Then there's this presentation over on Scribd regarding "Unity iPhone Newbie Guide"; maybe that's something you would like to read.

Then there's the iPhone Publishing page directly from the horses mouth over at Unity.
> 2 votes

# Answer
Without putting your application in the iStore, you will need to configure a team environment set up with your developer account where you have both your device and your clients device added as a development devices. That being said, your client may need a developer account? Keep in mind that this might not be something the client really wants to do and their phone may need to be updated/synchronized/reformatted.

In any event, I think you will have to transfer your xcode files to the client and walk them through the deployment process if you don't have physical access to the device...

It gets a little hairy at this point, I am working on a project where were just trying to get all our developers and testers able to deploy to their iDevices it becomes a bit of a process for a simple development deploy.

Let us know how it works out...
> 0 votes

---
Tags: iphone, unity
---


title: Out of bounds in AAA games

text:
# Question
Title: Out of bounds in AAA games
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?

# Answer
> 36 votes
Once upon a time, clearing the color and depth buffers actually took time. Doing a clear meant that the graphics card would have to walk every pixel of the framebuffer and write a value to it.

Because of this, game developers found that it would be more efficient to simply assume that, every frame, you would write to every pixel. They developed many techniques for taking advantage of this.

The color buffer is the easiest to ignore. Less easy is the depth buffer, because it would be polluted with old data. So what they did was simple.

On frame 0, they would render with a `glDepthRange` (or the D3D equivalent) of (0, 0.5), and they would use a `glDepthFunc` of `GL_LESS` (or `GL_LEQUAL`). This means that the farthest depth value you would ever get in the depth buffer is 0.5. So the largest value in the depth buffer at the end of frame 0 is 0.5 (assuming you wrote to every pixel).

On frame 1, they would change the depth range to (1, 0.5). Notice that in this case, the near depth value is *larger* than the far depth. But they would also change the depth func to `GL_GREATER` (or `GL_GEQUAL`), which reverses the meaning of the depth test. Because the largest value in the depth buffer at this point is 0.5, everything you write will have a value *larger* than this. Since the depth test was reversed, this effectively means that whatever was written on frame 0 is now farther away than everything that frame 1 will write. At the end of frame 1, the *smallest* value in the depth buffer is now 0.5.

And then they repeat.

On any hardware made since around 2003, this is no longer an optimization. Indeed, it is a *negative optimization*. Clearing the depth buffer actually makes hardware *faster*. No, really.

Basically, what happens is that clearing buffers doesn't actually write anything. They store some bits in the GPU's caches that let the system know what are the color/depth values they have been cleared to. When the system tries to write to a cache line of the framebuffer, it doesn't bother to read what's there, because it already knows that it is a blank field of the clear color/depth value. If you try to blend with what's there or do a depth test, again, no need to read: it knows what value to blend/test with/against.

So every first read/modify/write that you do on each cache line after a clear is just a write. It's *free*.

Plus, having a jagged depth buffer can work against Hyper-Z/Hierarchial-Z/any Z-culling optimizations in hardware. Yes, your scene will work against those eventually as you add detail. But if your depth buffer is jagged from previous renderings, even if those background objects are in the background, it can affect the efficiency of Z-culling techniques. And that's not going to help performance.

So you should *never* do this depth reversal technique in modern games.

Note: Jari makes a good point on tile-based rendering architectures (as found in most mobile platforms). Not clearing the depth can make things unpleasant there too.

# Answer
> 6 votes
Yes, you're right that the back buffer isn't being cleared.

Why is because (mostly) that it's faster to use a custom shader that ping-pongs depth values in opposite directions each frame and rely on the fact that your game always renders every pixel on the screen.

So for zero cost you save one buffer clear per frame.

---
Tags: rendering
---


title: Hide game data from player?

text:
# Question
Title: Hide game data from player?
I'm working on my first (C++) game, and I want to use a component based design. I've read a lot about this lately and yesterday I decided I wanted to store object data in external JSON files, to allow for more flexibility and ease of access.

Then it dawned on me that leaving these files in the game's directory tree would allow the players to modify anything they want very easily.

I'm not worried about showing the code to developers, because the game will be open source, but I'm afraid an inexperienced gamer might break the game or at least ruin the fun.

Am I missing something? What's the policy about hiding game data (in open source games)? Is it normal to leave everything plainly accessible to anyone?

If not, what is a good way to hide the data?

# Answer
If players tinker and ruin the fun I would say that's their problem. For tinkerers half the fun is seeing what breaks.

It's like getting worried that players would use a god mode cheat code and being worried that the player isn't challenged.

I wouldn't do anything more than putting those config files in a zip file (which you should probably do anyway for loading times) and making sure your code can handle corrupted data gracefully.
> 33 votes

# Answer
> I'm afraid an inexperienced gamer might break the game or at least ruin the fun.

If they're meddling with the game data, then that is what they consider 'fun'. You don't need to protect them from this. Entity component data is hardly a spoiler, after all. Maybe if you had dialogue or quest data in there, it would be a problem, but probably not. Most gamers don't even know where to look for this sort of thing, never mind deliberately searching through it or editing it.

My advice is to zip it up and rename the file extension. This will keep out the casual looker but won't be difficult for you to work with. You can use something like PhysicsFS to work with the files.
> 19 votes

# Answer
You could store the data **encrypted**, using a symmetric encryption scheme (AES), but this is pointless: the software is *opensource*, so everyone can read the key and therefore decrypt the data. This would just "stop" the casual gamer from cheating.

And it would be kind of pointless even in closed source projects, since it is quite easy to find the key into the game binary.

So, you have two possibilities:

1. just leave the stuff unencrypted (but at least collect the md5 hash of every file, so that you can check it at runtime against any damage in the distribution of your game);
2. **go closed-source**, scramble the data (with a secret reversible multi-step algorithm like string reverse + byte swapping + xor with a constant string, etc...) and then crypt everything with AES. It will be harder for anybody to recover the data. A lot harder.
> 3 votes

# Answer
I would leave it. There is a huge mod community and players like changing/modding games. If they break something, it's on them. They could always reinstall.

Also makes it easier for other developers to work with.
> 3 votes

---
Tags: c++, data
---


# Question
Title: Can an iOS application have an explicit quit button?
I've heard a rumor that you cannot have an explicit quit button on your app when it goes to the Apple App Store, can anyone verify this? It seems that most applications do not have one, and there is no explicit quit. How to developers handle quitting in general on iOS applications?

Note: I am using Unity, C#, and Xcode to develop my game for the iPad.

# Answer
> 5 votes
There is no mention of such in the app store review guidelines; however you are strongly encouraged to comply with the iOS HIG which, among other things, suggests never quitting programmatically and always being ready to stop in response to the Home button (iOS Developer account required to view those links, I think).

Because of the above, I would not be surprised if Apple rejected an app with an explicit "quit" button. Even if they didn't I would suggest not implementing one: it's redundant UI, and UI space is at a premium on such a small screen. I've never seen an application with a quit button, and would probably be annoyed by it, because it would suggest to me a lazy developer who did not take the time to understand his or her platform properly.

Users quit an application via the Home button. iOS will send your application delegate various "about to become inactive" messages, as well as "about to terminate" messages when the OS is going to kill your app for good (as a result of multitasking load balancing, for example). The default templates created by Xcode for iOS applications already implement some of these message selectors.

Since you're using Unity, you may not have direct access to these selectors. You may need to hook something from Unity's scripting API to find out when you are being suspended, or Unity may just expose this via's it's normal "application is quitting" code path -- whatever that is. Unity's got a section in their documentation detailing some iOS specifics.

# Answer
> 1 votes
Sure, any application can have one. But the real question is, *should* it have one? And the iOS Human Interface Guidelines (as mentioned earlier), suggest that no, it shouldn't have this ability.

That said, you will have to manage the game's state when the user switches to another app, turns off the phone, or it just dies. Obviously you don't want to touch and resume a game, and have it throw you directly into active gameplay.

My own approach would be to detect when the game is no longer active, and then to have it automatically pause the game, complete with a "Game paused, touch to continue" prompt on screen.

I also would spend a lot of time checking out iOS apps and games that were similar to what I had in mind, and look at how they handle this case. I think you'll find few (if any) apps have an explicit "quit" option which ought to tell you a) what users are used to, and b) what makes an app fit Apple's acceptance standards.

# Answer
> 0 votes
No.

There are no built in programmatic mechanisms to exit an application by design. I think this is Apple's way of creating a consistent experience across apps.

That said if you have to do it in your app you can do so by causing a crash for example by calling.

```
free(1);

```

To the user the app just closes as this is Apple's way of controlling user experience for crashes.

---
Tags: unity, ios, gui, ipad, user-experience
---


# Question
Title: What are the disadvantages of marking every edge as a seam when unwrapping a mesh?
I'm a programmer who's trying to learn a little basic 3D modelling. I'm reasonably comfortable with basic geometry modelling, and can unwrap and texture simple models. But I have a question...

When it comes to unwrapping models, all the tutorials emphasise the need to mark as few seams as possible when unwrapping a mesh. My question is, why? I'm guessing this is super-obvious to people with modelling experience, but not to me (given that my texturing efforts mostly are constrained to the generation of AO or normal maps).

I’m guessing that it’s purely to do with preserving the model’s shape when it comes to editing the diffuse texture? Is that the only reason you don’t want to simply cut every edge and lay all faces out individually?

I realise I’m displaying my utter ignorance of the subject matter when asking this question, so apologies, but sometimes the super-obvious things are the hardest to find answers to .

# Answer
> 10 votes
Every "UV seam" in your model - that is, every place where the model's faces are continuous while the UV map for the same edge is cut up - is a problem both for the artists and for the hardware.

* It makes it harder to texture the model properly. This is especially true when the editing is done on the texture directly, in 2D, not in a 3D painting program. The fewer such seams, the easier it is to mentally wrap the texture around the model.
* While simple blending can work for the diffuse texture and some other texture types, you have to be very careful with things like a tangent space normal map. For these, you can't just linearly blend (interpolate) between the X and Y (usually mapped to R and B in texture viewers) values without the resulting normal vector becoming de-normalised and the seam becoming visible (usually as a slightly darker "line") under some lighting conditions. On the other hand, trying to fix it in texture and making the values on both UV edges close to each other or the same can result in the seam becoming visible because it's unnaturally *flat* compared to the rest of the model.
* The pixel shaders have to do more work at every discontinuity (even if that's usually abstracted in the hardware nowadays), and get to hit different memory places to fetch the texture data from (which is usually the less optimised "code path" in hardware), as opposed to usually working with spatially close texture values.
* Automatic mipmapping (and very few shops can afford to touch up the generated lower-resolution textures manually) will break all the hard work you and your artists did to make a seam invisible at the default resolution.

That said: If your art style dictates that the model faces are clearly distinct from each other and they only ever will have "hard", explicit edges, none of it is a problem.

# Answer
> 6 votes
Two big reasons are **making sense of the unwrapped texture** and **edge artifacts**.

As you mentioned, it can be very difficult for an artist to make sense of how their 2D edits will wrap around the 3D model if the seams don't make sense. In the case where every face was separated and optimally placed with some kind of bin packing algorithm, it would be nearly impossible to edit the texture by hand. Hopefully they're using some kind of 3D painting tool these days, but it's still nice (and necessary!) to make edits directly on the 2D texture.

The other problem (edge artifacts) can show up due to floating point precision limitations with texture sampling. Let's say the faces are all laid out disconnected on top of a black background. Due to floating point error in your texture coords or during sampling on the video card, it's pretty likely those black edge pixels are going to occasionally show up or be blended in when the texture is filtered. Because this affects each face, you'll have this weird background-artifact-wireframe effect going on. The only way to combat this would be to artificially shrink your texture coords ever so slightly, but then each face would look weird because it won't quite line up with its neighbors texture-wise.

The nice thing about minimizing seams is that there are fewer edges in your model where the face is adjacent to the (unused) background, so there are fewer places for those artifacts to creep in. Most faces are immediately adjacent to their neighboring faces in the actual model, so the edge artifacts are actually adjacent pixels in the texture and you'll never notice them.

---
Tags: models, blender
---


# Question
Title: Is 3DS Max the sofware used to design all game contents?
Please tell me what is the software which persons or companies use it to design the graphics of games (2D and/or 3D), is it 3DS Max? Is there any other software or any more simple software?

# Answer
> 2 votes
There's quite a huge list of softwares that can be used. The ones I'm listing here are the most popular ones, but you could do all your assets using paint and notepad

### 3D Models

* 3DS Max is often used for low poly models.
* ZBrush is often used for high poly, and sculpting
* Photoshop/Any other image manipulation tool is used for texturing

### 2D Assets

* Photoshop/Fireworks/Any image manipulation tool.

There is also XSI for animation and modeling, but it is less used.

# Answer
> 2 votes
No, Max is not used to design *all* game content. *Some* studios may use it to design *some* content, but there are many options for building content.

Some studios use Max, some use Maya, some use proprietary tools. Max and Maya are both 3D modelling programs, so some studios that do primarily 2D artwork probably use something like Photoshop (or again, something custom-written).

---
Tags: 3d, 3dsmax
---


title: ID3D10Device Pointer Problem

text:
# Question
Title: ID3D10Device Pointer Problem
Basically when placed in the same file this works fine, but if placed in separate files (and I have tested this) just after Init() is called, the pointer to ID3D10\* device's value is suddenly 0x00000000. If it's all in the same file, the device pointer has a memory address all the way through. I'm really stumped here. Also wasn't quite sure whether this was a gamedev or stackoverflow question so sorry if it's in the wrong place. SORRY IN ADVANCE FOR THE AMOUNT OF CODE!

file that makes the calls:

```
#include <d3d10.h>
#include <d3dx10.h>
#include "direct3D.h"
#include "game.h"
#include "cube.h"

Cube* cube1;
void test();
//called once
void Initialise(HWND hWnd)
{
    initD3D(hWnd);
    init_pipeline();
    test();
    //cube1->Init();
    Init();
}

```

Direc3D.cpp

```
// include the basic windows header files and the Direct3D header files
#include <d3d10.h>
#include <d3dx10.h>
#include "direct3D.h"
#include "Globals.h"

// this function initializes and prepares Direct3D for use
void initD3D(HWND hWnd)
{
DXGI_SWAP_CHAIN_DESC scd;

ZeroMemory(&scd, sizeof(DXGI_SWAP_CHAIN_DESC));

scd.BufferCount = 1;
scd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
scd.BufferDesc.Width = SCREEN_WIDTH;
scd.BufferDesc.Height = SCREEN_HEIGHT;
scd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
scd.OutputWindow = hWnd;
scd.SampleDesc.Count = 1;
scd.SampleDesc.Quality = 0;
scd.Windowed = TRUE;
scd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;

// create a device class and swap chain class using the information in the scd struct
D3D10CreateDeviceAndSwapChain(NULL,
                              D3D10_DRIVER_TYPE_HARDWARE,
                              NULL,
                              0,
                              D3D10_SDK_VERSION,
                              &scd,
                              &swapchain,
                              &device);

// create a texture for the depth buffer
D3D10_TEXTURE2D_DESC zbd;
ZeroMemory(&zbd, sizeof(zbd));
zbd.Width = SCREEN_WIDTH;    // set the width of the depth buffer
zbd.Height = SCREEN_HEIGHT;    // set the height of the depth buffer
zbd.ArraySize = 1;    // we are only creating one texture
zbd.SampleDesc.Count = 1;    // no multi-sampling
zbd.Format = DXGI_FORMAT_D32_FLOAT;    // one 32-bit float per pixel
zbd.BindFlags = D3D10_BIND_DEPTH_STENCIL;    // texture is to be used as a depth buffer
ID3D10Texture2D* pDepthBuffer;
device->CreateTexture2D(&zbd, NULL, &pDepthBuffer);    // create the texture

// create the depth buffer
D3D10_DEPTH_STENCIL_VIEW_DESC dsvd;
ZeroMemory(&dsvd, sizeof(dsvd));
dsvd.Format = DXGI_FORMAT_D32_FLOAT;    // one 32-bit float per pixel
dsvd.ViewDimension = D3D10_DSV_DIMENSION_TEXTURE2D;    // depth buffer is a 2D texture
device->CreateDepthStencilView(pDepthBuffer, &dsvd, &dsv);    // create the depth buffer
pDepthBuffer->Release();    // release the texture once the depth buffer is made

// get the address of the back buffer and use it to create the render target
ID3D10Texture2D* pBackBuffer;
swapchain->GetBuffer(0, __uuidof(ID3D10Texture2D), (LPVOID*)&pBackBuffer);
device->CreateRenderTargetView(pBackBuffer, NULL, &rtv);
pBackBuffer->Release();

// set the back buffer as the render target
device->OMSetRenderTargets(1, &rtv, dsv);

D3D10_VIEWPORT viewport;    // create a struct to hold the viewport data

ZeroMemory(&viewport, sizeof(D3D10_VIEWPORT));    // clear out the struct for use

viewport.TopLeftX = 0;    // set the left to 0
viewport.TopLeftY = 0;    // set the top to 0
viewport.Width = SCREEN_WIDTH;    // set the width to the window's width
viewport.Height = SCREEN_HEIGHT;    // set the height to the window's height
viewport.MinDepth = 0;    // the closest an object can be on the depth buffer is 0.0
viewport.MaxDepth = 1;    // the farthest an object can be on the depth buffer is 1.0

device->RSSetViewports(1, &viewport);    // set the viewport
}

// this is the function used to render a single frame
void render_frame()
{
// clear the window to a deep blue and clear the depth buffer to 1.0f
device->ClearRenderTargetView(rtv, D3DXCOLOR(0.0f, 0.2f, 0.4f, 1.0f));
device->ClearDepthStencilView(dsv, D3D10_CLEAR_DEPTH, 1.0f, 0);

    // select which input layout we are using
    device->IASetInputLayout(pVertexLayout);

    // select which primtive type we are using
    device->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

    // select which vertex buffer and index buffer to display
    UINT stride = sizeof(VERTEX);
    UINT offset = 0;
    device->IASetVertexBuffers(0, 1, &pBuffer, &stride, &offset);
    device->IASetIndexBuffer(iBuffer, DXGI_FORMAT_R32_UINT, 0);

    D3DXMATRIX matRotate, matView, matProjection, matFinal;

    // increase the time varaible and send to the effect
    static float Time = 0.0f; Time += 0.001f;

    // create a rotation matrix
    D3DXMatrixRotationY(&matRotate, Time);

    // create a view matrix
    D3DXMatrixLookAtLH(&matView,
                       &D3DXVECTOR3(0.0f, 9.0f, 24.0f),    // the camera position
                       &D3DXVECTOR3(0.0f, 0.0f, 0.0f),    // the look-at position
                       &D3DXVECTOR3(0.0f, 1.0f, 0.0f));    // the up direction

    // create a projection matrix
    D3DXMatrixPerspectiveFovLH(&matProjection,
                           (float)D3DXToRadian(45),    // the horizontal field of view
                           (FLOAT)SCREEN_WIDTH / (FLOAT)SCREEN_HEIGHT, // aspect ratio
                           1.0f,    // the near view-plane
                           100.0f);    // the far view-plane

    // combine the matrices and render
    matFinal = matRotate * matView * matProjection;
    pTransform->SetMatrix(&matFinal._11);
    pPass->Apply(0);
    device->DrawIndexed(36, 0, 0);

// display the rendered frame
swapchain->Present(0, 0);
}

// this function sets up the pipeline for rendering
void init_pipeline()
{
// load the effect file
D3DX10CreateEffectFromFile(L"effect.fx", 0, 0,
                           "fx_4_0", 0, 0,
                           device, 0, 0,
                           &pEffect, 0, 0);

// get the technique and the pass
pTechnique = pEffect->GetTechniqueByIndex(0);
pPass = pTechnique->GetPassByIndex(0);
pPass->GetDesc(&PassDesc);

// get the Transform effect variable
pTransform = pEffect->GetVariableByName("Transform")->AsMatrix();

// create the input element descriptions
D3D10_INPUT_ELEMENT_DESC Layout[] =
{
    // first input element: position
    {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D10_APPEND_ALIGNED_ELEMENT,
        D3D10_INPUT_PER_VERTEX_DATA, 0},

    // second input element: color
    {"COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, D3D10_APPEND_ALIGNED_ELEMENT,
        D3D10_INPUT_PER_VERTEX_DATA, 0}
};

// use the input element descriptions to create the input layout
device->CreateInputLayout(Layout,
                          2,
                          PassDesc.pIAInputSignature,
                          PassDesc.IAInputSignatureSize,
                          &pVertexLayout);
}

// this is the function that cleans up Direct3D and COM
void cleanD3D()
{
swapchain->SetFullscreenState(FALSE, NULL);    // switch to windowed mode

//pBuffer->Release();    // close and release the vertex buffer
pVertexLayout->Release();    // close and release the input layout object
swapchain->Release();    // close and release the swap chain
rtv->Release();    // close and release the render target view
device->Release();    // close and release the 3D device
}

void Init()
{
// create eight vertices to represent the corners of the cube
VERTEX OurVertices[] =
{
    {D3DXVECTOR3(-1.0f, 1.0f, -1.0f), D3DXCOLOR(1.0f, 0.0f, 0.0f, 1.0f)},
    {D3DXVECTOR3(1.0f, 1.0f, -1.0f), D3DXCOLOR(1.0f, 0.0f, 0.0f, 1.0f)},
    {D3DXVECTOR3(-1.0f, -1.0f, -1.0f), D3DXCOLOR(1.0f, 0.0f, 0.0f, 1.0f)},
    {D3DXVECTOR3(1.0f, -1.0f, -1.0f), D3DXCOLOR(1.0f, 0.0f, 0.0f, 1.0f)},
    {D3DXVECTOR3(-1.0f, 1.0f, 1.0f), D3DXCOLOR(1.0f, 0.0f, 0.0f, 1.0f)},
    {D3DXVECTOR3(1.0f, 1.0f, 1.0f), D3DXCOLOR(1.0f, 0.0f, 0.0f, 1.0f)},
    {D3DXVECTOR3(-1.0f, -1.0f, 1.0f), D3DXCOLOR(1.0f, 0.0f, 0.0f, 1.0f)},
    {D3DXVECTOR3(1.0f, -1.0f, 1.0f), D3DXCOLOR(1.0f, 0.0f, 0.0f, 1.0f)},
};

// create the vertex buffer
D3D10_BUFFER_DESC bd;
bd.Usage = D3D10_USAGE_DYNAMIC;
bd.ByteWidth = sizeof(VERTEX) * 8;
bd.BindFlags = D3D10_BIND_VERTEX_BUFFER;
bd.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE;
bd.MiscFlags = 0;

device->CreateBuffer(&bd, NULL, &pBuffer);

void* pVoid;    // the void pointer

pBuffer->Map(D3D10_MAP_WRITE_DISCARD, 0, &pVoid);    // map the vertex buffer
memcpy(pVoid, OurVertices, sizeof(OurVertices));    // copy the vertices to the buffer
pBuffer->Unmap();

// create the index buffer out of DWORDs
DWORD OurIndices[] =
{
    0, 1, 2,    // side 1
    2, 1, 3,
    4, 0, 6,    // side 2
    6, 0, 2,
    7, 5, 6,    // side 3
    6, 5, 4,
    3, 1, 7,    // side 4
    7, 1, 5,
    4, 5, 0,    // side 5
    0, 5, 1,
    3, 7, 2,    // side 6
    2, 7, 6,
};

// create the index buffer
// D3D10_BUFFER_DESC bd;    // redefinition
bd.Usage = D3D10_USAGE_DYNAMIC;
bd.ByteWidth = sizeof(DWORD) * 36;
bd.BindFlags = D3D10_BIND_INDEX_BUFFER;
bd.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE;
bd.MiscFlags = 0;

device->CreateBuffer(&bd, NULL, &iBuffer);

// void* pVoid;    // redefinition

iBuffer->Map(D3D10_MAP_WRITE_DISCARD, 0, &pVoid);    // map the index buffer
memcpy(pVoid, OurIndices, sizeof(OurIndices));    // copy the indices to the buffer
iBuffer->Unmap();
}

```

Direct3D.h

```
#ifndef DIRECT3D_H
#define DIRECT3D_H

// global declarations
static ID3D10Device* device;
static ID3D10Buffer* pBuffer;
static ID3D10Buffer* iBuffer;    // the pointer to the index buffer
static ID3D10RenderTargetView* rtv;    // the pointer to the render target view
static ID3D10DepthStencilView* dsv;    // the pointer to the depth stencil view
static IDXGISwapChain* swapchain;    // the pointer to the swap chain class
static ID3D10Effect* pEffect;
static ID3D10EffectTechnique* pTechnique;
static ID3D10EffectPass* pPass;
static ID3D10InputLayout* pVertexLayout;
static ID3D10EffectMatrixVariable* pTransform;    // the pointer to the effect variable interface
static D3D10_PASS_DESC PassDesc;

// function prototypes
void initD3D(HWND hWnd);
void render_frame();
void init_pipeline();
void cleanD3D();
void Init();

#endif

```

cube.cpp

```
#include "cube.h"
#include "globals.h"
#include "Direct3D.h"

// include the Direct3D Library file
#pragma comment (lib, "d3d10.lib")
#pragma comment (lib, "d3dx10.lib")

Cube::Cube() : GameObject()
{

}

Cube::~Cube()
{
pBuffer->Release(); // why does this only work when put here? because it's    created here? I thnk so, why not iBuffer though?
}

void Cube::Draw()
{
render_frame();
}

void Cube::Init()
{
// create eight vertices to represent the corners of the cube
VERTEX OurVertices[] =
{
    {D3DXVECTOR3(-1.0f, 1.0f, -1.0f), D3DXCOLOR(1.0f, 0.0f, 0.0f, 1.0f)},
    {D3DXVECTOR3(1.0f, 1.0f, -1.0f), D3DXCOLOR(1.0f, 0.0f, 0.0f, 1.0f)},
    {D3DXVECTOR3(-1.0f, -1.0f, -1.0f), D3DXCOLOR(1.0f, 0.0f, 0.0f, 1.0f)},
    {D3DXVECTOR3(1.0f, -1.0f, -1.0f), D3DXCOLOR(1.0f, 0.0f, 0.0f, 1.0f)},
    {D3DXVECTOR3(-1.0f, 1.0f, 1.0f), D3DXCOLOR(1.0f, 0.0f, 0.0f, 1.0f)},
    {D3DXVECTOR3(1.0f, 1.0f, 1.0f), D3DXCOLOR(1.0f, 0.0f, 0.0f, 1.0f)},
    {D3DXVECTOR3(-1.0f, -1.0f, 1.0f), D3DXCOLOR(1.0f, 0.0f, 0.0f, 1.0f)},
    {D3DXVECTOR3(1.0f, -1.0f, 1.0f), D3DXCOLOR(1.0f, 0.0f, 0.0f, 1.0f)},
};

// create the vertex buffer
D3D10_BUFFER_DESC bd;
bd.Usage = D3D10_USAGE_DYNAMIC;
bd.ByteWidth = sizeof(VERTEX) * 8;
bd.BindFlags = D3D10_BIND_VERTEX_BUFFER;
bd.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE;
bd.MiscFlags = 0;

device->CreateBuffer(&bd, NULL, &pBuffer);

void* pVoid;    // the void pointer

pBuffer->Map(D3D10_MAP_WRITE_DISCARD, 0, &pVoid);    // map the vertex buffer
memcpy(pVoid, OurVertices, sizeof(OurVertices));    // copy the vertices to the buffer
pBuffer->Unmap();

// create the index buffer out of DWORDs
DWORD OurIndices[] =
{
    0, 1, 2,    // side 1
    2, 1, 3,
    4, 0, 6,    // side 2
    6, 0, 2,
    7, 5, 6,    // side 3
    6, 5, 4,
    3, 1, 7,    // side 4
    7, 1, 5,
    4, 5, 0,    // side 5
    0, 5, 1,
    3, 7, 2,    // side 6
    2, 7, 6,
};

// create the index buffer
// D3D10_BUFFER_DESC bd;    // redefinition
bd.Usage = D3D10_USAGE_DYNAMIC;
bd.ByteWidth = sizeof(DWORD) * 36;
bd.BindFlags = D3D10_BIND_INDEX_BUFFER;
bd.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE;
bd.MiscFlags = 0;

device->CreateBuffer(&bd, NULL, &iBuffer);

// void* pVoid;    // redefinition

iBuffer->Map(D3D10_MAP_WRITE_DISCARD, 0, &pVoid);    // map the index buffer
memcpy(pVoid, OurIndices, sizeof(OurIndices));    // copy the indices to the buffer
iBuffer->Unmap();
}

```

cube.h

```
#ifndef CUBE_H
#define CUBE_H

#include "gameObject.h"

class Cube : GameObject
{
private:
//VERTEX* OurVertices;
public:
Cube();
~Cube();
void Draw();
void Init();
};

#endif

```

If I call Init() from game.cpp, the code works fine, if I call cube-\>init(), just as this function is entered (not when the other one is left), the device pointer suddenly has an address of 0x00000000. Thanks in advance for any help you can give.

Both functions are identical - copy pasted.

# Answer
At first glance, I would say it's because you have `static`s in your Direct3D.h header file.

`static` in a header file has the effect of creating a **distinct copy per translation unit** (i.e. in your case, one for game.cpp, one for cube.cpp), each of which is initialised to zero.

Instead, you should remove the `static` keyword to make them extern, add the definitions to a .cpp file, and initialise them properly.
> 3 votes

# Answer
But are you creating the cube instance somewhere? such as `cube1 = new Cube()` and there could be another `device` variable defined with the same name, such as a protected member of GameObject?

Try removing "static" from `static ID3D10Device* device;` and see if that fixes the problem. Not sure about this though

Like this:

```
void Initialise(HWND hWnd)
{
    cube1 = new Cube();
    initD3D(hWnd);
    init_pipeline();
    test();
    cube1->Init();

```

// Init(); }
> 0 votes

---
Tags: c++, directx, directx10
---


# Question
Title: Is it possible to integrate Action Script 3.0 with Java Script and PHP for an online browser game?
My client wants a browser based online game, languages which are known to me are Java Script PHP and Action Script and also My Sql.

Game is quite like Farmvile as far as functionality is concerned.I would like to know how to combine these technologies to make a full fledged browser game, also do i have to use all of these languages or AS 3.0 with PHP and MySql will be enough?

Lastly i would like to know is there any book,link or tutorial about architectures and framework of games like farmvile?

Thank You

# Answer
> 1 votes
I've written a game that uses a Flash/AS3 front end and a communicates with a backend PHP/MySQL Server through dynamic XML sheets (might not be the best way) on a shared server through a local hosting company.

In general: 1. Load ActionScript with configurations variables using JavaScript (swfObject.js) 2. Have AS3 game connect by writing and reading XML (contacting per-specified pages) 3. Use PHP pages to act as intermediary, take in values passed from Flash/AS front end and perform database operations. 4. PHP code generates XML response. 5. AS3 reads XML File and processes data ...now you have a possible two-player/transactional game

Facebook has a pretty easy PHP API to use for integrating games and pulling in user data (name, friends, etc...). Check out the Facebook Developers areas.

# Answer
> 0 votes
You could use either ActionScript/Flash or JavaScript/HTML for the front-end. You'll be doing pretty much the same in either case, that is using HTTP connections for interacting with the back-end.

For the back-end you can use pretty much any language and database that you like. This could be PHP and MySQL, which is an easy to use choice, though with a pretty bad performance.

Other obvious choices for programming could be Node.js or .NET/C#. But really, anything where you can get a good HTTP library is within scope. For database you can choose anything that has an interface in the chosen language.

---
Tags: architecture, actionscript-3, javascript, php
---


# Question
Title: How to make a customizable 3D character with maya for a flash game
i'm working in a 3d flash role-playing game with alternativa 3d engine.

My game requires the main character to be customizable, for example, the player must be able to add a mustache, a hat, a tie, change colors of sking, clothing, etc, to the character.

How am i able to do that?.

(I'm using maya for modeling.)

Thanks in advance.

# Answer
If your 3d engine supports a scene graph, some scene graphs will have a node called a switch node. This can be used to switch between different types of geometry. So, you could put a switch node above the lip and switch between a mustache and no geometry (an empty node in the switch). For clothing and skin tone, you might be able to do something similar with switch nodes at the texture level. Not sure though.
> 1 votes

---
Tags: 3d, flash, character, maya, editors
---


title: Getting the angle between two objects?

text:
# Question
Title: Getting the angle between two objects?
I have a set of boxes which create a sort of path, they don't intersect very smoothy and to help that process I'm trying ot find a way to get an angle between them that can make it easier to generate another box between the intersection points.

Here's a pic of what I mean, the crudely drawn yellow arrows are basiclaly the angles I'm trying to find to put boxes there:

# Answer
> 6 votes
That vector can be obtained simply by summing up the normals of the boxes faces and normalize. The normal vector even point outside the box so the sum vector points toward the direction where the boxes exit from the intersection. along with the vector you need the intersection segment too (if you still don't have it)

# Answer
> 3 votes
you can use atan2. for example:

```
float radians = Math.atan2(object2.y - object1.y, object2.x - object1.x);

```

and then if you want the degrees its like this:

```
float degrees = radians * 180 / PI

```

# Answer
> 0 votes
Since I can't comment yet, I'll just put it as an answer:

As stas said, use Atan2, but be careful. Atan2 returns 0 to PI like a normal angle, BUT it returns 0 to -PI for the lower half of the 'circle'.

And remember that in the computer, angles start at 3 o'clock for 0, 12 noon for (PI/2), 9 for PI, and 6 for (3PI/2) or -PI in this case. You'll need to convert anything that you receive as a negative.

To convert: if(radians \< 0) { radians = (2 * PI) - radians; }

From there, convert to degrees if you so desire.

I'm doing this from memory, but I had 'fun' learning this on my own a couple years ago. If you need any more help, just ask.

---
Tags: xna, c#, mathematics, angles
---


# Question
Title: C# (Mono)/Java 3D Game Engine recommendation
Can you recommend a good C# game engine for cross platform (Win/Mac/Linux, I don't care about consoles) development?

I've got some experience with raw OpenGL and I played around with Java bindings and the JMonkeyEngine. However I'm somewhat disappointed those solutions and I tried Ogre3D which seemed really promising but I would rather not have to develop with the PITA that is C++.

I've had a look at this list but it is pretty overwhelming. I'm not looking for a all-in-one solution, i.e. I don't really require support for networking, audio and all that jazz but it wouldn't hurt if it's supported.

Maybe there's also an awesome Java solution out there that I don't know about?

# Answer
> 14 votes
Unity is actually using Mono in its back end. Though a lot of its scripting tutorials use JavaScript, you can actually program Unity completely in C# / Mono.

# Answer
> 3 votes
JMonkeyEngine is really the most recommended 3D engine for Java. Xith3D is sometimes recommended as an alternative, as it is also a scenegraph style graphics engine.

You could go with LWJGL or JOGL but those aren't engines so much as libraries, and you'd be writing raw OpenGL.

I don't recommend Java3D though, I think it's all but abandoned.

I think LWJGL is the best you're going to get, but again, it's a game library, not a graphics engine. OGRE is a scenegraph graphics engine like JMonkeyEngine; LWJGL is to Java what SDL is to C++. It provides functions for OpenGL, audio and input, and you are expected to run with that. I personally like that kind of power.

# Answer
> 3 votes
I would look at Ardor3D and have another look at JMonkeyEngine.

---

## Ardor3D

Created by the original JMonkeyEngine developer(s) who decided a clean break was required so they could start over and use all the experienced gained developing it to create a better API and platform.

The people I know to have used Ardor3D have very positive things to say about its design and API. It is under active development and has a good community and good API documentation, although tutorials are a little short in supply and generally you'll have to be familiar with 3D programming concepts to be able to pick it up.

---

## JMonkeyEngine

A community-lead takeover of the JMonkeyEngine the Ardor3D devs left behind, it has gone from strength to strength since the release of JME3 which addressed a number of shortcomings in the design of JME2.

There is ample documentation including tutorials and plenty of projects using it. If you had issues with JMonkeyEngine 2 or earlier, it is well worth another look at version 3.

---

## Others

# Answer
> 1 votes
The Axiom 3D Engine is based on a C# port of Ogre. It has DirectX, OpenGL and XNA renderers, so is very portable, though some platforms are not very actively maintained.

# Answer
> 1 votes
take a look at Ploobs Engine, right now it supports XNA 4, it is opensource and has a lot of cool features:

# Answer
> 0 votes
Look at http://www.devmaster.net/engines/search.php and also check out the XNA framework.

# Answer
> 0 votes
SDL plus the .NET Wrapper?

# Answer
> 0 votes
OpenTK is being used for MonoGame. MonoGame only supports the 2D api of XNA at the moment unfortunately, but you mentioned you had some OpenGL experience so you can use the OpenTK wrapper to do 3d graphics. You could also probably find a few scene graph libraries that are implemented in C# or in C++ with C# wrappers.

For audio, OpenTK wraps OpenAL, or if you want something more robust and plan on releasing the game as freeware, then FMOD doesn't cost anything to use. It gets pricy if you want to charge for your game. A cheaper alternative would be BASS.

---
Tags: c#, java, cross-platform, mono
---


# Question
Title: OpenGL ES Faces appear to be transparent when alpha is 1.0?
I am working on an object (OBJ File) loader for my app on iOS, currently I have successfully read the vertices and the faces of the object, and I am now just adding colours to the imported models.

I am coming across a major problem now. Out of a cube with six faces, all coloured red apart from two opposite faces which are coloured blue. This cube is set to rotate so I can see all sides, but the colours do not appear correctly as shown in the video below:

http://youtu.be/0L2AIFkd2Qk

The blue faces only shows when the two blue sections overlap, I cannot figure out why - I am used to OpenGL for PC, is there something I am missing which is causing this strange colouring?

The colouring is achieved by sending a large float array of the format RGBA RGBA RGBA etc for each vertex;

```
// colours is the name of the array of floats
glColorPointer(colorStride, GL_FLOAT, 0, colors);
glEnableClientState(GL_COLOR_ARRAY);
glDrawArrays(renderStyle, 0, vertexCount);

```

Any help you can offer would be great,

\[EDIT\]

Even if you don't know the problem, but have seen this before and know what it may be that would help as I have no idea where to even start looking as it is!

Many thanks

# Answer
> 1 votes
It looks like your face normals are pointing to the wrong side. Change the triangle winding order on your loader or set a different glCullMode when rendering.

---
Tags: opengl-es, ios, objective-c, transparency, color
---


# Question
Title: Fading to transparent with premultiplied alpha
I'm fading an object from fully visible to transparent, but the fade darkens the object.

```
this.Color = Color.Lerp(Color.White, Color.Transparent, weight);

```

The object does fade to transparent, but.. It becomes darker and more transparent. There used to be a Color.TransparentWhite and Color.TransparentBlack in the non-premultiplied alpha xna world. How can I make the fade to transparent make the object fade through white to transparent with premultiplied alpha?

We are drawing sprites as quads using GraphicsDevice.DrawUserIndexedPrivitives and BlendState set to BlendState.AlphaBlend. This is supposed to do premultiplied alpha blending in XNA4.

Also, how the color is used in the rendering:

```
effect.Alpha = this.Color.A / 255f;
effect.DiffuseColor = new Vector3(this.Color.R / 255f, this.Color.G / 255f, this.Color.B / 255f)

```

I suspect I should not use premultiplied alpha when using Alpha and DiffuseColor to make sprites/texts transparent. However when I use Color.Lerp to fade to new Color(1,1,1,0) it still darkens.

# Answer
> 1 votes
When using effect.DiffuseColor and effect.Opacity you should not use premultiplied color space.

The problem is that I used Color.Lerp:

```
Color.Lerp(new Color(1,1,1,1), new Color(1,1,1,0), .5f);
color : {R:127 G:127 B:127 A:127}

```

What I did to solve this is by setting the color to:

```
effect.Opacity = this.Color.A / 255f;
if (effect.Opacity > 0)
{
    effect.DiffuseColor = new Vector3(this.Color.R / 255f, this.Color.G / 255f, this.Color.B / 255f) / Opacity;
}
else
{
    effect.DiffuseColor = Vector3.Zero;
}

```

Note the `/ Opacity` to return from premultiplied color space to normal color space.

# Answer
> 2 votes
If the color is in premultiplied-alpha form, you'll need to lerp both the RGB and the alpha to zero. Lerping only the alpha to zero would result in an additive blend. I don't know how Color.Transparent is defined, but maybe it's not (0, 0, 0, 0).

If lerping everything to zero still causes the darkening effect, then the color isn't being used as premultiplied-alpha.

# Answer
> 2 votes
If you want to use the "old ways" of alpha fading, you can disable premultiplied alpha for the specific texture. I doubt there is a noticeable difference between the new and old approaches, but new one may be a little bit darker indeed.

Check your fading texture in the "Properties" tab and set "Premultiply Alpha" to false under "Content Processor" group. If you're using a sprite batch, set it to BlendState.NonPremultiplied before drawing. Then do your interpolation: `this.Color = new Color(this.Color.R, this.Color.G, this.Color.B, alphaFade);`

# Answer
> 1 votes
Don't lerp the colour components, just set the alpha:

```
this.Color.A = weight;

```

(where weight = 255 if opaque and 0 when transparent)

---
Tags: xna-4.0, color
---


title: Designing Levels For any Odd Games

text:
# Question
Title: Designing Levels For any Odd Games
What advice, methods, practices, etc. can be given to help me design levels for any odd game, and also know if that game should have levels?

**Update**: For 3d Games I found this: Level Design Tips

But it doesn't really get into 2D games.

I am having trouble designing levels. I do want to keep this general since I could design any 2D game and be face with this problem of designing levels. It breaks down to two things, how do you know a particular game should have levels when it isn't obvious ( like platform games )? And, how do you go about designing levels?

Just to give you an example, and it is an example, I built a classic Breakout clone and I feel I can build levels for it, since others have done so. But I can't get my head round to design a good level.

# Answer
> 2 votes
Level design boils down to setting up decisions for the player to make. Thus, your first step when designing a level is planning out what decisions you want the player to make. Once you've planned out what decisions the player will make in your level, then you can more deliberately lay out elements in order to support those decisions.

Note that the decisions aren't always complicated, and in simpler games it may even be the same decisions in a bunch of levels, in which case all those levels are just different permutations of the same set of decisions. Breakout is an example of the latter: in every level you want the player to make decisions about whether to chase after the falling power-up or stay under the ball.

In a more complex game you'll be setting up decisions about which path to take, decisions about how to engage each enemy, decisions about when you use various resources, etc.

---

This is of course a very broad overview of how to design levels (level designers tend to just have this in the back of their subconscious rather than think about it deliberately) but then this is a very broad overview question.

# Answer
> 2 votes
> I built a classic Breakout clone and I feel I can build levels for it, since others have done so. But I can't get my head round to design a good level.

Making levels is an artform into itself. What makes a good level? That completely depends on the game in question. Play the game. What's fun? Make more of it. What's not fun? Remove it. Can't remove it? How to make it less bad? And so on, and so forth.

I made a simple game for mobile devices over a decade ago, and it had certain number of features. In the hands of great level designers (from AAA game world), they managed to use the set of features in ways I would never have imagined, and the game was much better for it.

(This was a demo game for mobile game tech, and I don't think we ever released it to the public. Which is a pity).

---
Tags: level-design
---