# Question
Title: Setting up a cross-platform Ogre project on a Git repository
I'm looking to start a cross platform game project using Ogre, and I want to host it on a git repository. I'm collaborating with a friend on this: I'm on a Mac using Xcode, and he's on a PC using Visual Studio.

I've looked around on the Ogre site, and it seems CMake is what I should be using, but I'm not sure how to set it up with a Git repository. Would you be able to give me any pointers on where to start on this – tutorials and guides etc?

# Answer
First off, setting up a cross-platform Ogre and using a Git repository do not have any direct relationship.

The Source Control Management (whether it's Git or not) is used to synchronize multiple computers no matter if all the team use the same OS or different OS’s.

If you want to use Source Control Management with your friend, you will need a place to host it. The most famous one if you choose Git is probably github.

However, you can also use Mercurial in conjunction of bitbucket as host.

The duo Mercurial / bitbucket is often used by Indies and students because bitbucket offers the ability to create a free 5 user account and to keep your project private, whereas the free account on github is limited to open-source project and require paid account to get it private.

---

Now let's talk about CMake.

I'm working on a cross-platform project (Linux, OSX, Windows) using Ogre, and here is why and how I use CMake.

CMake is useful, because it offers the ability to supplant the Makefiles with one file for all platforms. You write a nice CMakeLists.txt and it will generate the Makefile for each platform (if you gave it the correct informations indeed) with all the little variations required.

So typically, I use the exactly same files on the three platforms and Cmake generate different Makefiles using the CMakeLists.txt (I use the same source folder from the same Hard-Drive and I sat up CMake so it generates the 3 makefile versions in build/Win build/OSX build/Linux)

At that point, all I need to do is to run "make" etc. on each platform to get it compile.

---

So using a "Source Control Management" and "Cmake", you should be able to work on the exactly same sources and to compile it without major headaches (well except those needed to set up the Cmake file ^^)

---

As you need more details about CMake and OSX here is the CMakeLists.txt of my project with lots of stuff removed (should almost double in size, but I removed all redundant stuffs).

This example is neither perfect (I am still not really fluent with Cmake commands) nor does it fits your needs (remember I use GCC under the 3 platforms so it's not configured to run with Xcode! it might work through as Xcode can use GCC but I'm not 100% sure.)

```
cmake_minimum_required(VERSION 2.6)

#------------------------------------------------------------------------------
#-------------------------------------------------------------- Init project --

set(CMAKE_PROJECT_NAME "OgreApp")
project(CMAKE_PROJECT_NAME)

if (CMAKE_BUILD_TYPE STREQUAL "")
  set(CMAKE_BUILD_TYPE "RelWithDebInfo" CACHE STRING "Choose the type of build, options are: None (CMAKE_CXX_FLAGS or CMAKE_C_FLAGS used) Debug Release RelWithDebInfo MinSizeRel." FORCE)
endif ()

set(CMAKE_DEBUG_POSTFIX "_d")

set(CMAKE_INSTALL_PREFIX "${CMAKE_CURRENT_BINARY_DIR}/dist")

if(${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
    set(OGRE_SDK "${PROJECT_SOURCE_DIR}/data/osx/SDK" )     # I placed the SDK into my project/data/osx/SDK, if you place it anywhere else, you need to change this
endif(${CMAKE_SYSTEM_NAME} MATCHES "Darwin")

#------------------------------------------------------------------------------
#---------------------------------------------------- Ogre, OIS & Boost Libs --

if(WIN32)
    set(CMAKE_MODULE_PATH "$ENV{OGRE_HOME}/CMake/;${CMAKE_MODULE_PATH}")
endif(WIN32)

if(${CMAKE_SYSTEM_NAME} MATCHES "Linux")
    set(CMAKE_MODULE_PATH "/usr/local/lib/OGRE/cmake/;${CMAKE_MODULE_PATH}")
endif(${CMAKE_SYSTEM_NAME} MATCHES "Linux")

if(${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
    set(CMAKE_MODULE_PATH
        "${OGRE_SDK}/CMake"
        "${OGRE_SDK}/CMake/Utils"
        "${OGRE_SDK}/CMake/Packages"
    )
endif(${CMAKE_SYSTEM_NAME} MATCHES "Darwin")

#------------------
#------ Ogre Lib --

if(WIN32 OR ${CMAKE_SYSTEM_NAME} MATCHES "Linux")

    find_package(OGRE REQUIRED)
    if (OGRE_Terrain_FOUND)
        set(OGRE_LIBRARIES ${OGRE_LIBRARIES} ${OGRE_Terrain_LIBRARIES})
        message(STATUS "Found OGRE_Terrain: ${OGRE_Terrain_LIBRARIES}")
    else (OGRE_Terrain_FOUND)
        message(SEND_ERROR "OgreTerrain Library not found.")
    endif(OGRE_Terrain_FOUND)

endif(WIN32 OR ${CMAKE_SYSTEM_NAME} MATCHES "Linux")

if(${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
    include_directories( ${OGRE_SDK}/lib/release/Ogre.framework/Headers/ )      # will search for OgreSDK/lib/release/Ogre.framework/Headers in OGRE_SDK (defined line 20)
endif(${CMAKE_SYSTEM_NAME} MATCHES "Darwin")

   MESSAGE(STATUS "This will use the following Ogre version: ${OGRE_VERSION_NAME}")

#-----------------
#------ OIS Lib --

find_package(OIS REQUIRED)

if(NOT OIS_FOUND)
    message(SEND_ERROR "Failed to find OIS.")
endif()

if(${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
    include_directories( ${OGRE_SDK}/include/OIS/ ) # will search for OgreSDK/include/OIS/
endif(${CMAKE_SYSTEM_NAME} MATCHES "Darwin")

#-------------------
#------ Boost Lib --

#if(${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
#   set(Boost_INCLUDE_DIR "${PROJECT_SOURCE_DIR}/data/osx/SDK/include")
#endif(${CMAKE_SYSTEM_NAME} MATCHES "Darwin")

if(WIN32) #-- Required by the Ogre Window 32 version (not Linux nor OSX atm)
    # Find Boost
    if (NOT OGRE_BUILD_PLATFORM_IPHONE)
        if (WIN32 OR APPLE)
            set(Boost_USE_STATIC_LIBS TRUE)
        else ()
            # Statically linking boost to a dynamic Ogre build doesn't work on Linux 64bit
            set(Boost_USE_STATIC_LIBS ${OGRE_STATIC})
        endif ()
        if (MINGW)
            # this is probably a bug in CMake: the boost find module tries to look for
            # boost libraries with name libboost_*, but CMake already prefixes library
            # search names with "lib". This is the workaround.
            set(CMAKE_FIND_LIBRARY_PREFIXES ${CMAKE_FIND_LIBRARY_PREFIXES} "")
        endif ()
        set(Boost_ADDITIONAL_VERSIONS "1.46" "1.46.0" "1.42" "1.42.0" "1.41.0" "1.41" "1.40.0" "1.40" "1.39.0" "1.39" "1.38.0" "1.38" "1.37.0" "1.37" )
        # Components that need linking (NB does not include header-only components like bind)
        set(OGRE_BOOST_COMPONENTS thread date_time)
        find_package(Boost COMPONENTS ${OGRE_BOOST_COMPONENTS} QUIET)
        if (NOT Boost_FOUND)
            # Try again with the other type of libs
            set(Boost_USE_STATIC_LIBS NOT ${Boost_USE_STATIC_LIBS})
            find_package(Boost COMPONENTS ${OGRE_BOOST_COMPONENTS} QUIET)
        endif()
        find_package(Boost QUIET)

        # Set up referencing of Boost
        include_directories(${Boost_INCLUDE_DIR})
        add_definitions(-DBOOST_ALL_NO_LIB)
        set(OGRE_LIBRARIES ${OGRE_LIBRARIES} ${Boost_LIBRARIES})
    endif()
endif()

#------------------------------------------------------------------------------
#---------------------------------------------------------------- Extra Libs --

if(${CMAKE_SYSTEM_NAME} MATCHES "Darwin")

    FIND_LIBRARY(IOKit_LIBRARY IOKit)
    FIND_LIBRARY(COCOA_LIBRARY Cocoa)
    FIND_LIBRARY(CARBON_LIBRARY Carbon)
    FIND_LIBRARY(OPENGL_LIBRARY OpenGL)
    #FIND_LIBRARY(GLUT_LIBRARY GLUT )

    SET(EXTRA_LIBS ${EXTRA_LIBS} ${IOKit_LIBRARY} ${COCOA_LIBRARY} ${CARBON_LIBRARY} ${OPENGL_LIBRARY})

endif(${CMAKE_SYSTEM_NAME} MATCHES "Darwin")

if(${CMAKE_SYSTEM_NAME} MATCHES "Linux")
    SET(EXTRA_LIBS ${EXTRA_LIBS} GL GLU )
endif(${CMAKE_SYSTEM_NAME} MATCHES "Linux")

if(WIN32)
    SET(EXTRA_LIBS ${EXTRA_LIBS} opengl32 glu32 ) #-lopengl32 -lglu32 -lglut32
endif(WIN32)

#------------------------------------------------------------------------------
#------------------------------------------ Prepare non library source files --

set(HDRS
    ./
)

set(SRCS
    ./main.cpp
)

include_directories(
    ${OIS_INCLUDE_DIRS}
    ${OGRE_INCLUDE_DIRS}
)

#------------------------------------------------------------------------------
#------------------------------------------------- Initialize Compiler flags --

#set(CMAKE_CXX_COMPILER "g++")                              #define the compiler to use
#set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x ")      #define the C++0X flag
set(CMAKE_VERBOSE_MAKEFILE ON)

if(${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /Volumes/Dev/OgreSDK/lib/release/Ogre.framework/Versions/1.7.3/Ogre ")      # not sure it's still required !
endif(${CMAKE_SYSTEM_NAME} MATCHES "Darwin")

#------------------------------------------------------------------------------
#----------------------------------------------------- Initialize Executable --

add_custom_command(TARGET ${CMAKE_PROJECT_NAME} PRE_BUILD COMMAND export LD_LIBRARY_PATH=${CMAKE_CURRENT_BINARY_DIR}/dist/bin:$LD_LIBRARY_PATH )

if(${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
    add_executable(${CMAKE_PROJECT_NAME} MACOSX_BUNDLE ${HDRS} ${SRCS})
    add_custom_command(TARGET ${CMAKE_PROJECT_NAME} POST_BUILD COMMAND install_name_tool -change /opt/local/lib/gcc46/libstdc++.6.dylib @executable_path/libs/libstdc++.6.dylib ${CMAKE_PROJECT_NAME} WORKING_DIRECTORY ${CMAKE_INSTALL_PREFIX}/bin/${CMAKE_PROJECT_NAME}.app/Contents/MacOS )
else ()
    add_executable(${CMAKE_PROJECT_NAME} WIN32 ${HDRS} ${SRCS})
endif(${CMAKE_SYSTEM_NAME} MATCHES "Darwin")

set_target_properties(${CMAKE_PROJECT_NAME} PROPERTIES DEBUG_POSTFIX _d)

#------------------------------------------------------------------------------
#----------------------------------------------- Initialize Static Libraries --

#------ GameBoard --

file(GLOB SRCS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} core/GameBoard.cpp core/GameBoard.h)
source_group("" FILES ${SRCS})
add_library(GameBoard STATIC ${SRCS})

#------ Player --

file(GLOB SRCS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} core/Player.cpp core/Player.h)
source_group("" FILES ${SRCS})
add_library(Player STATIC ${SRCS})

#------ DebugTools --

file(GLOB SRCS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} core/tools/*.cpp core/tools/*.h) #*/
source_group("" FILES ${SRCS})
add_library(DebugTools STATIC ${SRCS})

#------ etc. etc. etc.

## Tips for linking problems : If "A" depends on "B", then "A" must be BEFORE "B" in the following list. And remove "etc." indeed ;)
target_link_libraries(${CMAKE_PROJECT_NAME} GameBoard Player DebugTools etc. ${OGRE_LIBRARIES} ${OIS_LIBRARIES} ${EXTRA_LIBS} )

#------------------------------------------------------------------------------
#------------------------------------------------------------------- Install --

file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/dist/bin)

# post-build copy for win32
if(WIN32 AND NOT MINGW)
    add_custom_command( TARGET ${CMAKE_PROJECT_NAME} PRE_BUILD
        COMMAND if not exist .\\dist\\bin mkdir .\\dist\\bin )
    add_custom_command( TARGET ${CMAKE_PROJECT_NAME} POST_BUILD
        COMMAND copy \"$(TargetPath)\" .\\dist\\bin )
endif(WIN32 AND NOT MINGW)

if(MINGW OR ${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
    set(EXECUTABLE_OUTPUT_PATH ${PROJECT_BINARY_DIR}/dist/bin)
endif(MINGW OR ${CMAKE_SYSTEM_NAME} MATCHES "Darwin")

if(${CMAKE_SYSTEM_NAME} MATCHES "Linux")
    set(EXECUTABLE_OUTPUT_PATH ${PROJECT_BINARY_DIR}\\dist\\bin)
endif(${CMAKE_SYSTEM_NAME} MATCHES "Linux")

# Install required files into the OSX Bundle (once again I placed all the stuff required into my project folder/data/etc.)
if(${CMAKE_SYSTEM_NAME} MATCHES "Darwin")

    INSTALL(DIRECTORY ${PROJECT_SOURCE_DIR}/data/media DESTINATION bin/${CMAKE_PROJECT_NAME}.app/Contents/Resources)
    INSTALL(DIRECTORY ${PROJECT_SOURCE_DIR}/data/osx/Plugins DESTINATION bin/${CMAKE_PROJECT_NAME}.app/Contents)
    INSTALL(DIRECTORY ${PROJECT_SOURCE_DIR}/data/osx/Resources DESTINATION bin/${CMAKE_PROJECT_NAME}.app/Contents)
    INSTALL(DIRECTORY ${PROJECT_SOURCE_DIR}/data/osx/MacOS DESTINATION bin/${CMAKE_PROJECT_NAME}.app/Contents)
    INSTALL(DIRECTORY ${PROJECT_SOURCE_DIR}/data/osx/Frameworks DESTINATION bin/${CMAKE_PROJECT_NAME}.app/Contents)

endif(${CMAKE_SYSTEM_NAME} MATCHES "Darwin")

# Install required files for the Windows version
if(WIN32)

    install(TARGETS ${CMAKE_PROJECT_NAME}
        RUNTIME DESTINATION bin
        CONFIGURATIONS All)

    install(DIRECTORY ${CMAKE_SOURCE_DIR}/dist/Media
        DESTINATION ./
        CONFIGURATIONS Release RelWithDebInfo Debug
    )

    install(FILES ${CMAKE_SOURCE_DIR}/dist/bin/plugins.cfg
        ${CMAKE_SOURCE_DIR}/dist/bin/resources.cfg
        DESTINATION bin
        CONFIGURATIONS Release RelWithDebInfo
    )

    install(FILES ${CMAKE_SOURCE_DIR}/dist/bin/plugins_d.cfg
        ${CMAKE_SOURCE_DIR}/dist/bin/resources_d.cfg
        DESTINATION bin
        CONFIGURATIONS Debug
    )

    install(FILES ${OGRE_PLUGIN_DIR_REL}/OgreMain.dll
        ${OGRE_PLUGIN_DIR_REL}/RenderSystem_Direct3D9.dll
        ${OGRE_PLUGIN_DIR_REL}/RenderSystem_GL.dll
        ${OGRE_PLUGIN_DIR_REL}/OIS.dll
        DESTINATION bin
        CONFIGURATIONS Release RelWithDebInfo
    )

    install(FILES ${OGRE_PLUGIN_DIR_DBG}/OgreMain_d.dll
        ${OGRE_PLUGIN_DIR_DBG}/RenderSystem_Direct3D9_d.dll
        ${OGRE_PLUGIN_DIR_DBG}/RenderSystem_GL_d.dll
        ${OGRE_PLUGIN_DIR_DBG}/OIS_d.dll
        DESTINATION bin
        CONFIGURATIONS Debug
    )
endif(WIN32)

# similar install with Linux etc..

```
> 15 votes

---
Tags: c++, cross-platform, ogre
---


title: Rotating sprite to face cursor

text:
# Question
Title: Rotating sprite to face cursor
Given the sprites X and Y values, and the mouses X and Y values, how can I make the sprite face the mouse cursor?

I tried doing this in my move method which I found in another SO question:

```
    private function move(mousePosX:Number, mousePosY:Number) {
        if(key.isDown(Keyboard.A))
            this.vx -= this.speed;
        else
            this.vx *= this.friction;
        if(key.isDown(Keyboard.D))
            this.vx += this.speed;
        else
            this.vx *= this.friction;
        if(key.isDown(Keyboard.W))
            this.vy -= this.speed;
        else
            this.vy *= this.friction;
        if(key.isDown(Keyboard.S))
            this.vy += this.speed;
        else
            this.vy *= this.friction;

        this.x += vx;
        this.y += vy;

        // Make the player face the cursor
        this.rotation = Math.atan2(this.x - mousePosX, this.y - mousePosY);
    }

```

And rotation does happen, but it's of one or two pixels. `this.x` and `this.y` are the sprite X and Y values.

Cheers!

EDIT: Got it. here's the final calculation:

```
this.rotation = -(Math.atan2(this.x - mousePosX, this.y - mousePosY) * 180 / Math.PI);

```

# Answer
Trying to speed answer your question,

I guess you are halfway there, you probably are getting the rotation in radians from Math.atan2() call, and you're graphics library deals with degrees!

degree\_angle = rotation * 180 / 3.1415926 (PI);

Anyway, as a bonus, if you actually need movement in the mouse direction, the direction vector would be such as v(cos(rotation), sin(rotation)). Then multiply that for the desired movement "speed", and there it goes, following the mouse.

Please correct me if i'm wrong :)
> 0 votes

---
Tags: actionscript-3
---


title: Simplest format for video

text:
# Question
Title: Simplest format for video
I've been dwelling with a question lately,

I can generate screenshots with my library, but i found that i would like to be able to record video from a game.

Since video is just(well-simply enough, yeah) a collection of images, i guess i could easily write "screenshots" into a single file.

I know that makes sense, but the end result won't be understood by any video application around. That's where the question pumps in,

What is the simplest file format that i can write to, that a video editing application will be able to understand and convert to a format of choice later?

As a bonus: What if i want to add the sound too? What do you think?

Thanks for the help.

# Answer
> 2 votes
Google **"ffmpeg images to video"**, I believe that's what you're looking for. There's nothing wrong with using images to create the end video, like you said that's pretty much what a video is. I'd personally say **go with MPEG-4** for these reasons:

> MPEG-4 is the best option. The mpeg4 stream can be stored in either in the .avi or .mp4 (quicktime) container file: it can support high levels of lossy compression to keep file sizes small and also supports arbitrary frame rates. It is also translates much more easily to other platforms than wmv1 or wmv2.

Good reference here.

Hope it helps. I did the same type of project a little while ago, and it worked like a charm.

---
Tags: sound, video, file
---


# Question
Title: Where could I look online to learn about being a game designer?
I'm interested in being a video game designer but I know next to nothing about how to do what ever it is I will be doing as a game designer. Could you offer any advice of a good online area where I could learn about the basics of game designing and later on the more complicated information.

# Answer
> 4 votes
I happen to have a list of such links on my website: http://www.newarteest.com/game\_dev.html

The most helpful resource for someone in your position (ie. interested in but has no idea what video game designers do) is the first one on the list: http://www.sloperama.com/advice.html

# Answer
> -3 votes
http://www.gamedev.net/forum/31-for-beginners/

---
Tags: game-design
---


# Question
Title: How can I incrementally generate an graph?
I just started a new project in which I'd like the game world to consist of procedurally-generated locations connected by teleporters. After a bit of research, I've discovered this to be called either "graph theory" or "bloody complicated", depending on who is discussing it. Unfortunately, I've found very little information on *generating* graphs; most of the tools I've seen are directed toward examining existing graphs.

Assuming I have the terminology correctly sorted out, my requirements are that the graph be:

* simple — no location (vertex) should have a teleporter (edge) which connects back to itself, nor should two vertices have multiple edges connecting them
* connected — it should be possible to travel between any two vertices in the graph (though I don't foresee ever needing to *find* the path; simply knowing the player could find one if they chose to is sufficient)
* cyclic — there should be more than one path between any two vertices
* undirected — all edges can be traveled in either direction
* infinite — if the player so wishes, they should be able to travel indefinitely, with the graph continuing to generate incrementally as they approach its outermost unexplored vertices
* locally finite — a vertex's degree should never change after the player has visited it
* stably labelled — each vertex represents a location which will itself be procedurally generated from a seed; the same seed must be assigned to a vertex regardless of what path the player used to travel there or how large the graph is when they do

I've had some ideas (which I've not yet tried to implement) regarding using the local maxima of 2D perlin noise as vertices (the input *x* and *y* could then be used as its label), but that feels clunky and overcomplicated.

Is there a better way to generate a graph like this? I'm developing in Python 2.6 using Panda3D and numpy, and would of course be willing to look at including other libraries if they'll help with this problem!

**Edit**

I think I've done a poor job explaining some of my requirements, so it's illustration time! Hopefully, this will clear things up.

What I mean by having stable labels is that I want, for example, Player A to be able to do a bunch of exploring and find, among other things, a cyclic path back to their starting location and a mountain that looks like a cat. His game now looks something like the following (vertices are numbered with their seed and edges with the order in which the player traversed them). He started on vertex 8329 (green) and Happycat Mountain is in vertex 6745 (blue).

Player A's good friend Player B is a fan of cats, so he wants to show it to her. He gives her the root seed for his world and directions along the shorter route to the mountain of interest. Her game should now look like this:

The problem I'm currently having the most difficulty with is *"How do I generate the same seeds for Player B when her exploration hasn't followed the same path?"* That's what led me to the idea of using Perlin noise — as long as the same root seed is used, the maxima won't move, so their coordinates could be used as stable vertex seeds.

# Answer
> 6 votes
You can't make an infinite graph. Your memory is finite, thus the numbers of vertices and edges are also finite. What you can do is make a finite graph then add more to it. You seem to have realized this but I think it is important it be explicitly stated so you don't go down a dead end path.

You must be very careful when talking about "outermost vertices". A graph is a set of vertices, a set of edges, and a function that relates the two. There is no set geometric interpretation unless you apply one. For example: both of these pictures show the exact same graph. In the first image, vertex 2 could be considered an "outermost" vertex, yet in the second image vertex 2 would not be considered "outermost". If you considered three dimensions, you could say all vertices are "outermost".

This means you must have some other information for you to be able to know what an "outermost" vertex is. You could use (x,y) pairs as that would give you an easy to visualize geometric representation, however I don't think you need to go that far. From what you say, all you need to know is what vertices are in the graph already.

If you ran this every time you visited a vertex:

```
if(this.needsNeighbours)
{
    List<int> connections = genRandomNumbers(n);
    foreach (int connection in connections)
    {
        //Simple graph
        if(connection == this.seed || this.hasNeighbour(connection))
        {
            continue;
        }
        //Connections to already existing, unvisited vertices
        else if(nodeMap.containsKey(connection) &&
                nodeMap.getByKey(connection).needsNeighbours)
        {
            nodeMap.getByKey(connection).addNeighbour(this.seed);
            this.addNeighbour(connection);
        }
        //Grow graph with new vertices
        else
        {
            nodeMap.add(connection, new Node(connection));
            nodeMap.getByKey(connection).addNeighbour(this.seed);
            this.addNeighbour(connection);
        }
    }
    this.needsNeighbours = false;
}

```

your graph would satisfy all your requirements except for being cyclic. I don't know if you actually need a guarantee. If you do then you could specifically select an unvisited node and make a connection, that would guarantee a path between the current node and an already visited node as all unvisited nodes are connected to at least one visited node and since you had to have visited a visited node to get where you are there are now at least two paths.

It is simple because there is an explicit check for it, connected because all new nodes get at least one connection, locally finite because edges are only added before you visit or on your first visit, and only to unvisited nodes. Technically its not undirected, but functionally it is the same as you create a directional edge in both directions. You can label the node anything you want, I use the random number generated, but you could add other parameters to the constructor, one being your seed.

# Answer
> 1 votes
One method:

```
init:
  root = generateLocation using random seed
  store root's seed
  place player in root location

when the player enters a new location:
  release the memory used by locations that are further than 1 edge away, but keep their seeds
  generate some neighbors for the new location. for every neighbor n:
    gen.seed(getSeed(n))
    n = generateLocation using n's random seed
    numCyclicEdges = gen.randint(0, 1)
    create numCycleEdges edges to existing locations

getSeed(n):
  if(n already has a seed) return n's seed
  else return randomSeed()

```

There are lots of details I left out, but this should capture the general idea. You may want to keep neighbors in memory that are more edges away from the current location, depending on how much world-distance there is between portals, much available memory there is, etc.

---
Tags: procedural-generation, python, graph-theory
---


# Question
Title: What are some good methods of implementing RTS-style Box selection?
I'm scouting around for different methods of implementing a typical RTS box selection. This is for 3D game - so I'm looking for methods for finding units within selection box in 3D world. Here is a quick screenshot of what a box selection looks like in 2D Starcraft:

# Answer
> 5 votes
Your question was vague, but the answer to both interpretations could be simple.

Heres some pseudo code:

```
vec2 original_xy = get_mouse_position();
vec2 new_xy;

while (get_mouse_click_state() == MOUSE_DOWN) {
        new_xy = get_mouse_position();
        render_box(original_xy, new_xy);
        ...
        context_swap_buffers();
}

vec2 a = mouse_to_world(original_xy);
vec2 b = mouse_to_world(new_xy),

const float max_height = 100.f; // maximum search height
BoundingBox aabb(vec3(min(a.x, b.x), min(a.y, b.y), 0), vec3(max(a.x, b.x), max(a.y, b.y), max_height));
List<Object> objects_in_box;

for Object x in all_objects do {
    if (x.collides(aabb)) {
        list.add(x);
    }
}

```

---
Tags: camera, rts, selection
---


title: Movie clip in a button changes on hover

text:
# Question
Title: Movie clip in a button changes on hover
I have a button for my game which has a `MovieClip` in it. It consists of an image of a lock and an image of an item, representing the item being locked and unlocked. I make the button become slightly smaller when the mouse is over it to create the effect of a button slightly down.

For some reason, however, this makes the `MovieClip` in the button go to the next frame. I have no Actionscript code in the button or any frame except `stop()` on the first frame of the `MovieClip`, so I really don't understand why this would happen. It only goes to the next frame when I hover my mouse over the button and then quickly goes back to the first frame (since there's no `stop()` in the second frame).

After experimenting with `stop()` in both frames of the movie clip, it does indeed only happen when my mouse enters the button. Leaving the button doesn't do anything and the button left alone doesn't do anything. It just changes the frame when I hover my cursor over it. There's absolutely no script involved aside from `stop()` in the first frame of the movie clip in the button. What could be the cause of this problem?

# Answer
> 1 votes
I wonder why you put a MovieClip with two frames inside a Button? From my experience the Flash Button is really broken and scripts won't work inside the button. So if you have a "locked" (*frame 1*) and "unlocked" (*frame 2*) image in your MovieClip, you won't be able to access the "unlocked" image, because using a script to get to frame 2 won't work properly in the first place.

Better create two separate Button instances, or script the MovieClip so that it works as a button directly (eg. scale it on mouse-over/mouse-out and use `buttonMode` and `useHandCursor` properties to control mouse-pointer behavior).

# Answer
> 0 votes
I wouldn't use a Button object. "Button" is simply a shortcut for some common button functionality like mouseover and click states; you can set mouse event listeners on any MovieClip. You probably also want to set buttonMode=true so that the mouse cursor will turn into the hand to indicate the user can click:

```
movieClip.addEventListener(MouseEvent.CLICK, onClick);
movieClip.buttonMode = true;

```

# Answer
> -1 votes
Try putting gotoAndStop(1) in the second frame of the movie clip

---
Tags: flash, actionscript-3
---


# Question
Title: What kind of design or structure should I use to implement movement between an over-world map and a menu system?
I'm making a simple text-based RPG, where the player is the owner of five creatures that battle other teams for loot, experience and glory. I am using Python, and a curses emulator. I have a static ASCII over-world map. My character, represented by a glyph, can move about this static map. There are locations all over the map that the character can visit, that break down into two categories:

1. Towns, which are a series of menus that will allow the player to buy equipment for his team, hire new recruits or do other things.
2. Arenas, where the player's team will have a "battle" interface with actions he can perform, messages about the fight, etc. Later, I may include an ASCII representation of the fight; but for now, just screens of information, with action prompts, will be displayed.

What kind of design or structure should I use to implement movement between an over-world map and a menu system?

---

Right now, the game goes through a master loop that waits for keyboard input, and then moves the player about the screen. Upon keyboard input, the player coordinates are checked against a list of location objects, and if the player coordinates match a locations coordinates, then... I am not sure.

I'm not sure if I should call a separate function, to initiate either a menu or combat mode, or if I should create some kind of new `GameMode` object that contains a method for drawing the screen and printing the necessary info. If I go that way, I am not sure how to pass my players team data into this object.

My main concern is passing around the program flow into all of these objects. Should I be calling straight functions for different parts of my game, and objects to represent "things" within my game? I was reading about the MVC pattern, and how this kind of problem might benefit from decoupling the GUI from the game logic and user input, but I have no idea how this applies to my game.

# Answer
> 3 votes
You make a base class called GameState, or GameLevel. Store it as a reference or pointer. When game need to go into a battle (as in final fantasy style), you put your gamelevel type into a stack, and put the battle screen as the current gamelevel.

When you finish the battle, switch the references again. Of course, each type of level (town, over-world, battle) are (is a) sub-classes of GameLevel.

Also, remember to pause the stored GameLevels if necessary. With this system you could implement easily a system with a lot of submenus and exit from each one by pressing the escape key.

---
Tags: architecture, rpg
---


title: Slick2D and Clipping

text:
# Question
Title: Slick2D and Clipping
How would I go about using clipping in Slick2D? I want to have an infinitely large world, however I'm not very good with clipping and it's my only problem. I don't have anything drawn outside of the rectangle that the rectangle can move to, and it's bothersome.

# Answer
As Fault says, the question is a bit confusing. If you're looking for how to clip a large image like a background(which I'll assume is an Image), you could clip it using one of the draw functions.

```
//From the javadoc:
//Draw a section of this image at a particular location and scale on the screen
//clipx and clipy are the top left corner of the clipped image
//clipx2 and clipy2 are bottom left corner
background.draw(x, y, clipx, clipy, clipx2, clipy2);

```
> 0 votes

---
Tags: java, slick
---


title: Book about Entity System?

text:
# Question
Title: Book about Entity System?
I'm really interested about the capabilities of Entity System. I'm trying to search for a good book on this one, but failed.

I don't want to get lost on learning this paradigm so a book will be a big help. Can someone recommend a good book?

Also, is this language agnostic? Or are there languages that will have a hard time implementing this paradigm (eg. Objective-C)?

Thanks.

# Answer
> 12 votes
I learned about game entity systems through the book Game Engine Architecture by Jason Gregory. He discusses several implementations, ranging from class based to purely aggregate components, complete with examples. I highly recommend it, not just for that section, but for anybody who wants to know how to structure code for their game.

Edit: Just found this thread on Stack Overflow with tons of resources

# Answer
> 1 votes
You could try this: 3D Game Architecture Very well explained and with a full game engine as a "code snipped".

---
Tags: architecture, entity-system
---


title: LAN game in Actionscript 3

text:
# Question
Title: LAN game in Actionscript 3
I know this may be a somewhat dumb idea, but is there any "easy" resource that anyone can point me towards that shows how to set up a simple LAN connection in an Actionscript application? I only need to have two clients connected. Nothing extremely robust.

This is not an AIR application. It's for a game idea that I have that will need two players essentially. It will be local, so having each other's IP addresses will be an option. So no need to find or detect any IP addresses.

Thanks.

# Answer
> 4 votes
You can't establish a direct connection between two flash-applications. You could write a server (for example in JAVA) which both flash clients connect to by using XMLSocket.

You can also do all your coding in Actionscript, but for that at least one of your applications needs to be an AIR application. There you can use ServerSocket and use Socket to connect with a client to the server.

So the simplest approach would be to write your Game as an AIR Application. Then you start one as the "server" (establish a `ServerSocket`) and connect from the other application to the IP address of the server.

**Update:** Here's an article that will guide you through the basics of `ServerSocket` and `Socket`.

# Answer
> 2 votes
You can embed an socket server in your game or create a side application that you will use as server. It is fairly simple to do with AIR: http://www.adobe.com/devnet/air/flex/articles/creating\_socket\_server.html

another option is to use p2p connection with flash using cirrus: http://labs.adobe.com/technologies/cirrus/

---
Tags: networking, actionscript-3
---


title: Calculate path of laser beam?

text:
# Question
Title: Calculate path of laser beam?
Lets say we have a laser beam emitter that has a position and an angle (in a 2D world to simplify things). The laser emitted from that emitter will start at that position, and continue heading in the direction of the angle until it intersects with an object (some arbitrary polygon). If that object is reflective, the laser should bounce off the surface that it first intersects. This continues until the laser hits a non-reflective surface.

I guess the problem here can be divided into two problems: finding the first intersection and calculating the new angle from that intersection. I'm not exactly sure how to solve the first problem, but I figure the second one can be solved by finding the angle between the laser and the normal vector (i think that's what it's called) and calculating the new angle using that.

# Answer
I think this can be transfered to simple **ray casting** / **ray tracing**. You shoot ray, find hit, reflect, find other hit, etc.

The easiest way is brute force. You construct ray (position, direction) and calculate collision with all polygons (you should divide polygons on triangles) in scene. And find closest one. Of course you can't take collision behind rays origin, but only in front of it.

If you find closest intersection, look on material of polygon. If this is reflective, do whole procedure again. If it's not reflective, you are done.

If you have huge scene with lots of polygons and you need to shoot again and again, you can construct some kind of acceleration structure (kD-tree, BVH). But this is more complicated.

If you want more information, just google ray tracing or ray casting. You will find a lot of information.
> 2 votes

---
Tags: vector, geometry, angles
---


# Question
Title: Is it possible to use Windows Forms in an XNA project?
Is it possible to keep a Windows Form inside a XNA project? I tried it but without success.

Below I'm showing how my main file is.

```
using System;

namespace JogoSuecaOnline
{
#if WINDOWS || XBOX
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main(string[] args)
        {
            MainMenu menu = new MainMenu();
            menu.Show();
        }
    }
#endif
}

```

# Answer
Try this in your main file:

```
   static void Main(string[] args)
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new YourForm());
    }

```
> 2 votes

# Answer
There are two options. First of all you could embed an XNA view inside a WinForm. For information about how to do this: download, read through the documentation for, and play with the project files in:

---

The other thing you might want to do is to launch a WinForm from within an XNA game (so your game is running, and then the form is shown next to it). This is pretty easy: right click your game project -\> Add -\> Windows Form. This will set up the necessary references and create a template form for you.

To launch your form, simply create and show it. Here's an example to launch the form when your `Game` starts:

```
Form1 form;
protected override void Initialize()
{
    form = new Form1();
    form.Show();
    base.Initialize();
}

```
> 3 votes

# Answer
Alright this might be old as hell, but I was having trouble with this and I found an answer.

The example project provided by Microsoft (XNA WinForms Sample 1) includes three main classes that you need in order to MAKE a control.

* GraphicsDeviceControl.cs
* GraphicsDeviceService.cs
* ServiceContainer.cs

Starting with a fresh windows form project you will need to make references to Microsoft.Xna.Framework and Microsoft.Xna.Framework.Graphics. Now make a reference to your XNA project where your XNA game is located (or game library).

Copy over those three files and change the namespace on those three classes to your windows form namespace. Then you will want to make a NEW class which inherits from GraphicsDeviceControl.

Now modify the using statements to include the XNA libraries you need. Then add the overrides for Initialize, Dispose, Draw, and any other methods you will be needing to modify.

e.g.

```
#region Using Statements
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
#endregion

namespace WindowsFormsApplication1
{
    public class MapControl : GraphicsDeviceControl
    {
        protected override void Initialize()
        {
            //throw new System.NotImplementedException();
        }
        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);
        }
        protected override void Draw()
        {
            //throw new System.NotImplementedException();
        }
    }
}

```

Now compile the windows form project and your new control will appear in the toolbox.

This all came about because I couldn't figure out why I kept getting errors when trying to place the abstract base class GraphicsDeviceControl on the form, but it's taken me 2 years to actually figure out why.
> 1 votes

---
Tags: xna, software-engineering
---


title: Speed of bodies in Box2D and libgdx

text:
# Question
Title: Speed of bodies in Box2D and libgdx
I want to move my bodies at higher speeds, but they have a top speed.

I have an Ortoghraphic camera defined at 800x480. My world doesnt have gravity. I apply an impulse of 1000,and a force of 1000 too.

But the speed always is at the same value, it doesnt have more.

How do i add more speed to my body (its a dynamic body).

# Answer
Box2D has a hard-coded movement cap of 2 meters per tick. So if you are updating at 60Hz then you max speed is 120m/s or 432km/h.

You can either go into the source code and change this cap or you can adjust your pixel to meter ratio to allow for greater speeds. For example if 16pixels = 1meter and you are running at 60Hz then your max speed is slightly less than 2000pixels/second.

Because you are running into this problem I am assuming you are using 1pixel=1meter which will cause you further problems in the future.
> 5 votes

---
Tags: box2d, movement, libgdx
---


title: Concerns for Hosting a Facebook App

text:
# Question
Title: Concerns for Hosting a Facebook App
I am working solo on an AS3 Facebook App project of the Interactive Quiz type nature.

* What amount of bandwidth would it take for a simple Facebook app to run?
* What sort of traffic would be produced on a server as the result of hosting a Facebook app?
* How much traffic should we expect from running a Facebook app?
* What are the adverse effects of hosting a Facebook app on a server (even if they are minimal)?
* Is there a way to check if someone else's web host supports PHP?
* What sort of stress will be exerted upon a sever that hosts a Facebook app?

Any discussion that can shed light on these points would make me happy!

DISCLAIMER: I have little knowledge about servers and this will be my first Facebook App project. All I am looking for is an answer and not a down vote. Down votes are very costly when you only had 5 rep in the first place.

# Answer
Think of your "Facebook App" as simply a web page being embedded into a Facebook div. You still host it, just like any other page. So ask yourself these same questions, but replace "Facebook" with "Web page".

Like any webpage, your page on Facebook has the potential for very little traffic, or huge amounts of traffic -- it all depends on how well it is marketed, linked to, and deemed interesting by users.

So my advice would be to step back, imagine this whole thing as just a web page, and see if you can answer the questions from that perspective. Calculate how much load it takes to serve a single page or store data for a single user. Take those estimates, then estimate how many users/how much traffic you think you'll get, and go from there. If you've got those answers, then you probably answer the questions related to it being on Facebook.
> 2 votes

# Answer
Perhaps a solution would be to run a local host using MAMP and conducting "stress tests" on the local server. That could give you a quantitative idea of what amount of traffic to expect. I don't know too much about servers but maybe this idea will inspire you in the right direction
> 0 votes

---
Tags: server, facebook, php
---


# Question
Title: Browser game architecture considerations
I am currently working on a browser game. It's not my first one, but it is the most complex I have worked on to date.

In the past, I would code everything in PHP, and have functions checking whether certain maintenance operations were required or not, carrying them out when necessary (for instance, if players must receive 50 gold every day, I would have a function which checks when was the last time 50 gold were added to each player; if it's less than 24 hours, do nothing; if it's more than 24 hours, then add 50 gold * the number of times 24 hours have elapsed (in case no one has accessed the website in more than a day)).

This worked, but was rather inelegant and resulted in a quite large and complex codebase as the game's features grew.

For my current architecture, I am thinking of having a very elementary front end that just fetches the data from a database and renders it in the browser; when players perform actions from this front end, it adds the actions to an event queue.

Then I would have completely separate server code running 24/7 (written in C++ or Python or whatever) which would be continuously polling the event queue, updating the database accordingly, and also run a set of functions at various intervals (for example, add 50 gold everyday), a bit like cron would.

I think this architecture will be better, as it will allow me to better separate game logic and front end; it will scale better; and it will just make for better code overall.

Are there any considerations/drawbacks with such an architecture?

# Answer
The answer is yes.

Basically you are considering moving from server side scripted game to a dedicated running server, which runs all the time and the clients talk to (presumably through web services or something).

In your "do a bunch of checks in your php file" manner of doing things, it was relatively simple to update what the game did.... you'd dink the appropriate php file in your test/dev environment, see if it worked, and if it did, you uploaded it to the production web server, and the new rule simply worked.

If you have a dedicated server running and calculating all of these things all of the time, when you want to update it you have to STOP it from running, replace it, then start it up again. Naturally there will be a tendency to have a lot of state that the server works with, which will need to be saved off when shutting down and reloaded when it starts up.

Even if your dedicated server is relatively stateless, you still have down-time. In your "update a php and go" method, the game is only "down" for as long as it takes to upload the php files.

Which means that naturally you will want to be more deliberate, strategic, and careful about updates when you switch to a continuously running server.

Also, I don't see in your question anything to make me think that anything is happening "in real time" and if nothing is in real-time then a real-time always running server is sort of overkill.

It sounds more like you need to take a good look at your code and do a (probably painful) refactor of it in order to streamline how it works.

Good luck.
> 1 votes

---
Tags: architecture, browser-based-games
---


title: Articles about a plot in an open world

text:
# Question
Title: Articles about a plot in an open world
There are plenty of articles about open world game design and writing plots. But have you guys come across articles or blog entries about designing an engaging plot in an open world game? What i mean by this? In TES:Morrowind you're introduced to mechanics and are given the "main quest" within the first 5 minutes and then you're free to go, learn, kill, do whatever you want. I've spent hundreds of hours playing the game, but i have never got to doing the "main quest" and i'm sure alot of people are in the same situation, be it Morrowind, Oblivion or Skyrim. Maybe it's the power of TES games and a true testiment to how great RPGs they are, however for me, thinking as a designer, it seems like a massive design failure. Maybe it's the fact that there's no actual threat that needs to be dealt with, maybe it's that, amongs all the well designed and interesting quest within the game, the "main quest" just doesn't seem so interesting.

I've got a game idea in the back of my head, i want to create an action platformer, but the "level selection" would be open world style "dunegons" like you find in MMOs. This is a vague and undeveloped idea, so don't focus on it, i didn't give this design much thought, however an issue arose, i can't figure out, in general, how to make the player care about the open world aspect (f.e. dealing with roaming, pillaging parties, doing a gauntlet run to get some special armor, clearing a water source from enemies, etc.) while "forcing him" to finish the game, carrot-on-a-stick kind of way. There are "crazy" people who will go search everywhere between cutscenes in FF games, but i'm aiming at the general audience. I want to create a subtle system for guiding people throughout the game to a goal, while giving them an option of gaining power any way they want. This may aswell be impossible, but it doesn't hurt to ask.

I'm looking for articles or musings on this matter. Not solutions (since there's no design document, no direct solutions matter at this point), just thoughts from other people, probably with other games as a reference.

# Answer
> 6 votes
While not directly relevant to your question, a recent article on the Zelda franchise that Kotaku ran touches on a few facets of open world design (in the context of the original two games):

http://kotaku.com/5885595/zelda-just-keeps-getting-worse-but-it-isnt-beyond-saving?tag=zelda

In particular check out the sections:

**'Everything That Is The Case'**, where he talks about the impact a truly *open* world can have on a player;

**'Helicopter Parents'**, where he discusses the importance of difficulty in experiences that are left up to the player to create;

and probably of most interest to you,

**'Death Mountain Speaks For Itself'**, where he talks about the story that can develop in a world without an explicit plot.

---

Yeesh, that was really dry. Sorry. I hope it helps. Now for some of my own thoughts.

I'm right there with you on The Elder Scrolls games. I've put 90+ hours into both Oblivion and Skyrim, and haven't even touched the main quests. One of the things that drives me in a video game that has even a remote sense of place is exploration and subsequently, discovery. Much like ***mdkess*** was saying, I LOVE running around a game world, just *finding* things. I've found every location on the map in Skyrim at this point, and I haven't actually gone INTO the caves and dungeons and such. I've just discovered them, gotten excited, and then run off to find more things. Is that a mountain? *I'm going to climb that mountain*. Is that a lake? *I wonder what's at the bottom*.

To translate that into relevant game design speech: one way to make a player interested in exploring your world, is to make the world feel like it's worth exploring. Be it through interesting/beautiful visuals, unique area design, or tangible consumable content; you need to demonstrate to the player that they *should* want to go exploring because they is definitely awesome stuff to find.

So long as they know that their time spent will be adequately rewarded, and won't feel like grinding while they do it (this is where the visuals and unique area design comes in), then they will want to explore.

---

And lastly, about subtly guiding a player through an open world, I'd recommend you check out Dark Souls, for a number of reasons.

1 . Directing Through Difficulty:

After an introductory level to teach you the base mechanics of the game, you are dropped into the main world with three potential paths to take. And unless you are somehow already a badass at the game, you will very quickly realize that two of those paths are a touch out of your league for now. So you pick the easy path, and start fighting. And then a while down *that* road, you'll be given another branching path. And so on, and so forth.

And while in most cases it will be clear which way you probably should go (and thus cause yourself the least amount of heart-wrenching death), the only thing preventing you from traveling any of the harder paths is your own skill.

You may not be good enough now, but eventually you will be.

2 . Every Action Has A Reward

No matter which path you take, or which boss you kill, you are improving yourself and furthering the story. New weapons, armour, souls (which are both experience AND currency in this game), MORE paths to take; each 'level' of Dark Souls is designed to be unique, and to be immediately rewarding upon completion.

---

Alright, I'm just going to stop here, and apologize for how poorly organized confusing this whole response probably is. I know there's a better way to say all this, but, well. I'm tired?

I hope at least the article helps a bit.

# Answer
> 6 votes
The games that I thought worked best had emergent AI behaviours. STALKER, for example, had really cool a-life simulation, so you'd want to explore just to see what new stuff there was waiting. Skyrim had mini quests galore, so as you explored, you would always find things to do. You could walk into any cave in the world and there would be something of note there, it was incredible.

I think that players have a natural tendency to want to explore - if you show them a mountain, they'll try to climb it.

Here is an old article on player motivations within the context of MUDs, which you might find interesting: http://www.mud.co.uk/richard/hcds.htm

For me, I'm motivated by two main things in a game, outside of story. First is the promise of material reward within the game. If I think that I can get a cool new sword, I'll go exploring to find it. The other is just finding interesting things within the game. In Skyrim, I tried to climb to the top of every mountain, and spent way too much time swimming around trying to find underwater secrets (as an aside, I was pretty disappointed that there weren't any). There was generally no significant reward within the game for this, but just getting to see the world and really test its limits is a lot of fun. Importantly, the mechanics of the game encouraged this - there was fast travel so that you could always get back on track (so you weren't penalized for walking for an hour in a random direction), and there was no penalty for death - you could save whenever, so another chance was just a function key away.

Now, to counter that last point about painless exploration, one thing that I got a lot of thrill out of in games is hardcore mode, where it's you versus the world and if you die the show's over. I don't think that I would have liked Skyrim like that, but it is something that does motivate a lot of players. I think here it acts as a multiplier on the previous rewards that I talked about. Finding that awesome sword is so much more satisfying when I know that I barely made it there alive. Not done well though, it can feel random. When the player dies, the player should feel like they made a mistake, which can be a very hard thing to execute on as a game developer. With a softer death system, you don't have to be so careful, as random feeling deaths can be hilarious at best or just mildly annoying at worst.

I think that with exploration in a game, you don't so much have to directly encourage it as you should be very careful to not (even accidentally) discourage it.

---
Tags: game-design, open-world
---


# Question
Title: How could I implement my library/game to run in a browser plugin?
I usually code cross-platform, to build as native code for Mac Linux and Windows, but I clearly see the value in being able to display my game in a browser.

Could you guide me in doing such a task? How could i have something like Unity Web Player? Cross-browser is preferable, but Chrome would already be great :)

I use technologies such as SFML, libRocket, Box2D and more.. If that is pertinent to the question!

Thanks

# Answer
First of all, the standard interface for browser plugins is NPAPI (Netscape Plugin API). More recently, there's been a move towards Pepper. However, I would **strongly** discourage you from making a browser plugins. Users hate it and it's generally *really* suspicious since plugins let you do more or less anything with a user's computer.

If you're really set on using native code, your best bet is probably Google Native Client (NaCL). This lets you run native code at near native speeds within a sandboxed environment. It's already been used to port Bastion to the Chrome web store thingy. This also has the advantage over a normal plugin of being at least somewhat cross-platform. It requires a specialised compiler toolchain which (from memory) currently uses GCC/G++. Mono has also been ported to NaCL, so you can run C#, F#, Java (via IKVM), etc.

That said, it still requires your users to install a plugin if they aren't using a very recent version of Chrome, but at least they only need to trust Google as opposed to some random developer they've never heard of before.
> 5 votes

---
Tags: sfml, browser, plugin
---


# Question
Title: What's a good way to handle game screen management in WPF?
What would be the preferred way of handling game screens in WPF (conforming to MVVM)? I'm not asking about game states but the actual mechanics of presenting various screens.

Do I implement screens as user controls? Do I collapse and show controls or dynamically add and remove controls from main window? How do I handle transitions (MenuToOptions, OptionsToMenu, GameToOptions, et cetera)?

# Answer
You have several options, and it all comes down to what works for your specific use case. The easiest option is probably to use a `Page` for each of your screens, then use the Navigate() method to switch pages. This has the advantage that is functions much like a browser (and, in fact, there is UI with back/forward buttons just like a browser that you can optionally use). If your application is more akin to a web application this can be very easy to control and extend.

Another option is to simply add and remove elements from the window manually in code behind, however I do *not* recommend this except as a last resort. You're almost always using WPF incorrectly if you're manually manipulating controls using code instead of using WPF's features.

Another method would be to put all your custom control containers in the window from the beginning, but have them all have the `Visibility.Collapsed` state. You can then simply have any number of controls display based on your current application state (although make sure you're doing this with bindings rather than code behind, for the same reason mentioned above.)

Lastly the best option after the `Page` navigation is the best WPF way: use templates. Simply put your controls in data templates and then the proper controls will be displayed upon setting your data context! Here's an example (assuming `my:` is mapped to your application's namespace)

```
<Window.Resources>
  <DataTemplate DataType="{x:Type my:TitleInformationViewModel}">
    <my:TitleScreenPage/>
  </DataTemplate>
  <DataTemplate DataType="{x:Type my:GameLevelViewModel}">
    <my:GameRenderCanvas/>
  </DataTemplate>
</Window.Resources>
<DockPanel>
  <ContentControl Content="{Binding}"/>
</DockPanel>

```

Now, you simply set the `DataContext` of your window to a view model object depending on what state your game is in an what you want to display. Since a blank `{Binding}` binds directly to the `DataContext` object, WPF will then search for any templates to use to display that object whenever the `DataContext` changes. If the object you set the `DataContext` to is a `TitleInformationViewModel` object, `ContentControl` will use the first template listed there and display your `TitleScreenPage` control. If instead it's a `GameLevelViewModel` object, it will instead display the `GameRenderCanvas` control.

This is much closer to the WPF way than manually adding/removing controls and much cleaner than invisible controls (those controls will still be hooked up and listening to their bindings regardless if they're displayed, which is not really desirable.) This or `Page` navigation is your best bets. The Navigation service is handy because you can navigate to any arbitrary page, whereas using DataTemplates requires you to declare all your templates for a window before using any of them.
> 1 votes

# Answer
Honestly I hate the built-in page system in WPF. It is clearly designed for web-browsing.

I recommend just creating a grid and dynamically adding/removing (or changing visibility) your elements (CustomControls or UserControls) for your MainWindow. Because each of these are just WPF elements within the same grid you can blend their opacity for smooth transitions or transform them with animations set through styles with animations. This also makes it easier for you to handled shared resources (frame / page system children are sandboxed basically) as well as easier to handle cross page functionality because you can always RelativeSource your way back to the MainWindow and then Path your way down into a different child element.

For example (Animation just thrown together probably doesn't work)

```
<Grid>
    <MainGame Visbility="{Binding Path=Mode, Converter=EqualsParamToVisible, ConverterParam={x:Static GameModeEnum.MainGame}}"/>
    <StartScreen Visbility="{Binding Path=Mode, Converter=EqualsParamToVisible, ConverterParam={x:Static GameModeEnum.StartScreen}}"/>

    <!-- AFAIK WPF draws these in code order if no z order specified -->
    <Rectangle x:Name="GrayOutGameWhenPaused" Visibility="{Binding ElementName=PART_PauseMenu, Path=Visibility}" Fill="#7F000000"/>
    <PauseMenu Margin="40, 30" x:Name="PART_PauseMenu">
        <PauseMenu.Style>
           <Style TargetType="{x:Type PauseMenu}">
               <Style.Triggers>
                   <DataTrigger Binding="{Binding Path=Paused}" Value="True">
                       <DataTrigger.EnterActions>
                           <BeginStoryboard>
                                <Storyboard>
                                    <DoubleAnimation Storyboard.TargetName="PART_PauseMenu" Storyboard.TargetProperty="RenderTransform.RotateTransform.Angle" From="0" To="360"  Duration="0:0:0.5" RepeatBehavior="4x" />
                                </Storyboard>
                           </BeginStoryboard>
                       </DataTrigger.EnterActions/>
                   </DataTrigger>
               </Style.Triggers>
           </Style>
        <PauseMenu.Style/>
    </PauseMenu>
</Grid>

```

It kind of depends on what kind of interface and what game you are trying to build. A simple game with a static interface like Tetris would be super easy to build in WPF. A complex user interface with a high performance game underneath - say a first person shooter through a Direct3d surface - might be to much to do like this.
> 2 votes

# Answer
I don't have a big WPF experience, but as I'm working in a game using it, I've had some ideas that we're using:

There is a MainWindow, something to hold all the aplications. Then, for each screen of the game, I create a page that will hold the necessary information (both graphic and logical). That way, one only need's to access the MainWindow in order to perform page changes, create constructor with parameters to pages and etc.
> 0 votes

---
Tags: wpf, screen
---


title: Animation Systems

text:
# Question
Title: Animation Systems
As an animator specializing in Disney-style animation for videos and movies and whatnot, one of the things I've always wondered about is game animations. I'm especially wondering about it now, because I want to make a 2d game. Since, in 3d games, most animations are re-used, there are (I'm guessing) blending systems in place for automatically making simple transfers between animations, greatly lessening the workload for an animator who won't have to make a bunch of short transition animations.

However, I'm looking for a 2d engine that can do the same thing. I know that, since 2d animated objects aren't bone rigged, it would be difficult to produce the sort of technology I'm suggesting. My question nonetheless is, is there a 2d engine that can take animated 2d objects (be they .swf, or .gif, or a sequence of images) and automatically interpolate in between frames for animation frames? if so, is it easy to use?

# Answer
> 3 votes
Since you mentioned .swf, Flash has been able to do it for many years. It's called "shape tween". It allows you to specify content key-frames and it automatically fills any number of in-between frames with interpolated forms.

Sometimes it's ambiguous how the forms merge, so you can optionally add "shape hints". Each shape hint has a corresponding point in each key-frame, allowing you to specify the corresponding parts of the shape before and after transitions.

And because it's Flash, you can import practically any type of image, and exporting the final animation as swf or gif. It's a very manual job, but the process is extremely easy and the animations usually end up looking good.

# Answer
> 1 votes
Since CS4, Flash has had the ability to create bone rigs for animation, including support for IK. It's not nearly as fancy as anything in a 3D tool like Maya, but it does provide the basics. And Flash has support shape tweening since it's creation--the bone support just makes things a ton easier to control! Flash also supports animation curves and a few other features you should be used to from 3D animation tools.

The things that Flash does *not* do that 3D game engines do is handle whole animation networks for more complex animation handling than simply bones and tweening. (see Morpheme or EA's ANT or any number of other game animation network tools) Rather than the game engine simply playing a specific animation, then playing another, etc. the animation networks define the various animation states, and allow much more sophisticated animations through allowing animations to interrupt and blend into other animations, mutliple animations playing merging and playing at the same time, etc. I don't know of any 2D animation tools that do this.

Overall, the 2D animation support in Flash is top notch, and anything missing is easily scriptable with Actionscript. It's probably your best bet for creating game animations, especially if you use Flash as a platform for your game and not just as a content creation tool. If you don't use Flash for your final game, it can still export your animations in a variety of formats, and many professional games out their even use Flash .swf files directly for their UIs, animation and all! (Autodesk's Scaleform)

---
Tags: animation, art
---


# Question
Title: How do I find the intersection of two lines
I have a bounding box on my character, its position in the previous frame an the current frame. The bounding box is axis aligned.

My character is running around inside a cave, I have a list of points (lines) that represents the wall of the cave (not axis aligned)

I've got a coarse grained algorithm that tells me when some part of my character is likely to have collided with some part of the cave wall.

I do not have a fine grained algorithm to tell me specifically which line of the wall was collided with and at which point.

My current thought was that I could just create a line for each corner of the bounding box from its position in the previous frame, to its position in the current frame, then test each of these lines for intersections with any of the lines in the cave wall.

My google fu however hasn't shown me an easy formula for calculating intersections. Have I picked a bad way to do this, or am I just bad at search?

My game is written in scala, however I can read/translate most any c style language and many scripting languages, whatever you feel like answering in

# Answer
> -4 votes
googling " intersection test line segment line segment" produced this:

http://paulbourke.net/geometry/lineline2d/

# Answer
> 7 votes
You can do that with different approaches;

* segment vs segment using parametric lines plus some verifications (because lines are not segments).
* segment vs box
* segment vs circle (this one would be my favorite)

. But as you request for a segment vs segment intersection test, here is a pseudo C++ example extracted from the very interesting book "Real time collision detection":

```
float Signed2DTriArea(Point a, Point b, Point c)
{
    return (a.x - c.x) * (b.y - c.y) - (a.y - c.y) * (b.x - c.x);
}

int Test2DSegmentSegment(Point a, Point b, Point c, Point d, float &t, Point &p)
{
    // signs of areas correspond to which side of ab points c and d are
    float a1 = Signed2DTriArea(a,b,d); // Compute winding of abd (+ or -)
    float a2 = Signed2DTriArea(a,b,c); // To intersect, must have sign opposite of a1

    // If c and d are on different sides of ab, areas have different signs
    if( a1 * a2 < 0.0f ) // require unsigned x & y values.
    {
        float a3 = Signed2DTriArea(c,d,a); // Compute winding of cda (+ or -)
        float a4 = a3 + a2 - a1; // Since area is constant a1 - a2 = a3 - a4, or a4 = a3 + a2 - a1

        // Points a and b on different sides of cd if areas have different signs
        if( a3 * a4 < 0.0f )
        {
            // Segments intersect. Find intersection point along L(t) = a + t * (b - a).
            t = a3 / (a3 - a4);
            p = a + t * (b - a); // the point of intersection
            return 1;
        }
    }

    // Segments not intersecting or collinear
    return 0;
}

```

---

Software license agreement of the book ask to include the following credit to use the code examples:

*code example "from Real-Time Collision Detection by Christer Ericson, published by Morgan Kaufmaan Publishers, © 2005 Elvesier Inc"*

# Answer
> 4 votes
Although someone has already provided an answer deemed satisfactory, I'm unsure the method you described will yield an accurate time of impact (TOI). My first inclination is that to find an exact answer to the question, "how far can the player move before colliding with a part of the cave, if a collision occurs at all?" requires resorting to continuous collision detection techniques (CCD).

Specifically, there is a technique whereby you can effectively "shrink" your AABB into a single point, and at the same time "grow" the line segments of the cave by the same amount by using Minkowski Addition. Then, the problem can be seen as casting a ray against a convex object, or set of convex objects (since a point moving through time with constant velocity becomes a ray). The earliest distance along the ray that intersects with the "bloated" cave will represent the earliest time of impact (TOI).

Most commonly literature on how to accomplish this deals with three dimensions, but still applies to two dimensions, and ought to transfer easily. I don't have time at the moment to spell out all the details or provide psuedo code, but maybe someone else will be able to verify and expand upon what I'm referring to. For now, here are a couple of papers that explain the process, and some terms you might be interested in Googling.

# Answer
> 0 votes
In an attempt to help others who find this in their travels, here is a 2D line intersection test using the methods as found at https://stackoverflow.com/a/1968345/431528.

```
inline bool lines_intersect_2d(Vector2 const& p0, Vector2 const& p1, Vector2 const& p2, Vector2 const& p3, Vector2* i const = 0) {
    Vector2 const s1 = p1 - p0;
    Vector2 const s2 = p3 - p2;

    Vector2 const u = p0 - p2;

    float const ip = 1.f / (-s2.x * s1.y + s1.x * s2.y);

    float const s = (-s1.y * u.x + s1.x * u.y) * ip;
    float const t = ( s2.x * u.y - s2.y * u.x) * ip;

    if (s >= 0 && s <= 1 && t >= 0 && t <= 1) {
        if (i) *i = p0 + (s1 * t);
        return true;
    }

    return false;
}

```

---
Tags: 2d, collision-detection, linear-algebra
---


# Question
Title: Can a 3g network work for this project and is my understanding correct?
I want to make a game for the android phone using unity. As you can tell by my last post i wanted to use networking to make this happen. I decided unity would be a good choice and in no time i was able to have two android devices connect to a simple game using unity master server and i was able to see both of my cubes update in real time over both phones.

My end goal is to make a game where you are a sphere and your goal is to knock your friends off the the arena(A sumo game). The arena will slowly get smaller until only 1 sphere is remaining. My question revolves around how doable this would be with a 3g network over the phone. It does not appear that unity3d has bluetooth support for android and i could not find a plugin for it anywhere. This would be ideal to have bluetooth local networking and if i am incorrect, please tell me.

The way I understand cell phone data transmission is you have your cellphone and it sends the data to the cell tower. The closer you are to the tower the better. Does your relative position to one another(Two clients connecting ) matter if you are both in range of the same cell tower? While my cubes updated just fine I know that 3g can be spotty. Is 3g viable for this idea? Is bluetooth usable for android with unity3d if not?

Thank you

# Answer
> 1 votes
Player proximity to each other has absolutely no effect, they will always go through the tower. Player proximity to the tower can have an effect depending on how close together towers are and how large their range is. As for connection speeds, I'm not sure how fast your connection really needs to go. 3G will generally operate at speeds of OVER 200 kbit/s. (This is the minimum speed specified by the standard, if a network cannot consistently get above this it isn't really 3G)

You can try metering your internet connection using a program like this and running your game on your computer.

Hope this helps!

---
Tags: android, unity, bluetooth
---


# Question
Title: How to access SpriteBatch, Input, and ContentManager from all game screens?
I'm trying to make a Game State Manager and I'm using the Microsoft Game State Management Sample as guidance. However, I want a more simplistic design (no transitions, reflection, or support for 360/Phone). Now, I am diverging a bit in to my own design.

I figure every single game screen is going to need access to the `SpriteBatch`, `ContentManager`, and `Input`. Input is a class I defined to detect key and mouse presses/releases/etc.

Currently I'm just using regular old dependency injection and just passing those three references in to the constructor of all newly created screens, but the code repetition is bugging me slightly.

Since **all** screens in my game are going to need to detect input, load content, and draw to the screen, I'd prefer a solution where I wouldn't have to cumbersomely pass and include these three objects in all new game screens. However, I'm not sure how exactly to do this.

I suppose the `Game Screen Manager` could maintain a reference to all of these objects, but then each game screen would have to maintain a reference to the game screen manager, which just *sounds* wrong. Also, they would have to be public properties on the game screen manager and I'm not sure I want to expose that much information to potential clients. Ideally, each game screen would not have to know about the game screen manager and would somehow have access to these three essential objects without requiring them in all of their constructors.

Any ideas? Thanks.

# Answer
> 3 votes
Well, to begin with, passing required objects into a constructor is a fine solution.

One alternative would be to use the `Services` architecture, which allows you to simply pass that around. It has some nice properties, but also makes things more complex. Take a look at this discussion.

It is still passing stuff into a constructor - but at least there is less typing.

You could also consider making a custom "Game Screen Resources" class and pass that around. I think this is perhaps more appropriate than services, if you want to continue down this route.

But do not dismiss the idea of just making everything global. *It's a game*. It doesn't have to be an architectural delight.

Of particular note is `Input` \- where the source data is already global (see XNA's `Mouse`, `Keyboard`, etc). Unless you are *actually doing* automated unit testing and actually *need* the ability to swap out implementations *now*, just go ahead and make your `Input` class a static class.

By the same token, you could make your `SpriteBatch` instance public (`Content` already is) and make your game class instance statically available (ie: global).

This is very good from a DTTSTCPW perspective. It's extremely easy, and can easily be modified later (with no more additional effort than implementing something more complicated in the first place).

(My answer here similar to this one and probably also worth reading.)

# Answer
> 0 votes
I use a variant of what they use in Flat Red Ball in my own framework, Radiant Wrench. Basically:

* The `Game` class is like the controller, it has an instance of the current screen
* The `Screen` class has `Sprite`s, `Text`s, etc.

Each of the drawable classes (Sprite, etc.) have a `Draw` method, which takes a `SpriteBatch` as a parameter. The game class then passes the sprite batch to the screen, which passes it to the dra method.

This served me pretty well. The separation of concerns is pretty good (from my perspective -- I like to hide anything platform-specific, like XNA-specific, from the actual game logic and classes as much as possible). Not sure if it's exactly what you want, though.

# Answer
> 0 votes
My solution goes against every programming rule in the book. It is very simple though. :P

I made a static global.cs class. I added a public static variable of type Main (my main class) called mainClassInstance.

Then in the initialiser for Main I say global.mainClassInstance = this.

From there any other classes can access spriteBatch using global.mainClassInstance.spriteBatch or whatever. (spriteBatch needs to be public)

Loading assets is slightly more tricky. We can't just set Content to be public. So I created the following function in Main.cs:

```
public Texture2D loadTexture(string fileName)
{
    return this.Content.Load<Texture2D>(fileName);
}

```

It can then be called with Texture2D asset = global.mainScript.loadTexture("asset") Note that this only works for Texture2Ds, you'll need more functions for other assets.

Now I know that global variables are messy, but this seems to me less messy than passing three arguments to EVERY class.

---
Tags: xna, c#, architecture
---


# Question
Title: Why am I getting a "multiple definition of *" error when initializing OpenGL extensions?
I'm creating a game engine using OpenGL, and I'm initializing the extensions manually, i.e. this:

`// .h file
PFNGLACTIVETEXTUREPROC glActiveTexture;
/* .cpp file, initialization function */
glActiveTexture = (PFNGLACTIVETEXTUREPROC) wglGetProcAddress("glActiveTexture");`

However, when I compile, I get the following error every time I call an OpenGL extension function:

`multiple definition of 'gl[some function]'`

Why might this be? It reeks of an include loop problem, but I have include guards everywhere.

# Answer
> 2 votes
Your .h file declares the variable `glActiveTexture`. Even with header guards, this means that when this header is included a new definition of the variable is created. To solve this, define the variable as `extern` and then define it in a single .cpp file of your choice.

I.e.

```
// .h file
extern PFNGLACTIVETEXTUREPROC glActiveTexture;

// .cpp file of your choice
PFNGLACTIVETEXTUREPROC glActiveTexture;

```

This tells the compiler to not create a new definition whenever it reads the header code, but to resolve it when linking. One of your .cpp files then provide this definition explicitly and the linker is happy.

---
Tags: opengl, windows
---


# Question
Title: iPhone Game framework on top of cocos2d?
I am using cocos2d to develop iPhone game, however, it is just an 2D engine and developer is too flexible to use them - i.e. codes tends to be unmanageable.

Are there any more high level framework for game development, perfer using cocos2d?

# Answer
> 4 votes
There are alternatives like Unity3D, Corona or UDK, but nothing (I know of) that builds on top of Cocos2D.

**Update:** In the meantime Kobold2D was released. It's based on Cocos2D but adds more features like LUA integration or ARC (automatic reference counting) for easier memory-management. The features introduced by Kobold2D don't make it a much "higher-level" library though. It helps to setup new projects though and comes with lots of additional code and bundled third-party libraries.

# Answer
> 2 votes
Kobold2D v2.0.4 is out now as of October 2012.

# Answer
> 1 votes
Check out this resource, thorough article about the best iPhone game development frameworks:

http://www.tonylea.com/2011/best-iphone-game-frameworks/

# Answer
> 1 votes
There are a couple kits available for sale that provide starting points/frameworks that are built on cocos2d. Sites like http://learn-cocos2d.com and http://raywenderlich.com have great tutorials and point to these kits. Another good one which is being updated currently is the iphonegamekit.com which includes source and documentation for a rpg game or checkers game using cocos2d.

---
Tags: iphone, cocos2d-iphone
---


# Question
Title: Texture in model not rendered by BasicEffect
**UPDATE: It is apparently the BasicEffect that is the culprit here. I tried to use another effect (which I coded myself) and then it works!?!? )I kinda like the EnableDefaultLighting, though...)**

So this question is now rephrased to: "what in the model exported by Blender can cause BasicEffect to fail to render the texture?".

I have imported this model into Blender and exported it to an .fbx file and imported it into my XNA project. The problem is that the model is pitch black (just as it is in Blender when I look at it in object mode) when drawn in XNA. I have verified that the texture really is there (and that only one iteration is made):

```
       foreach (var mesh in _model.Meshes)
            foreach (var part in mesh.MeshParts)
                if (part.Effect is BasicEffect)
                {
                    var be = part.Effect as BasicEffect;
                    using ( var stream = File.Create(@"c:\test.jpg") )
                        be.Texture.SaveAsJpeg(stream,2048,2048);
                }

```

I have followed exactly the same procedure with other models and it has worked. Since the model looks good in Blender and the textures really makes it into XNA... what can be wrong here?

For what it's worth: one difference from what I'm used to is that these textures are not stored inside the .fbx but in a separate subfolder, but the XNA content importer finds them (I get an error if I try to remove them).

UPDATE: it may be important to mention that this model actually has three textures: diffuse, specular and normal maps. However, ONE of them should be projected by the BasicEffect, right?

UPDATE: a screen shot from Blender.

# Answer
I would guess that the problems is with the UV mapping.

Is your texture mapping in blender set to UV with the correct map?

When blender export FBX it uses the txt version of FBX (not the binary one). Try to open open the FBX file in a text editor to see if something looks wierd (if the UVs or Normals are all zeros)
> 1 votes

---
Tags: xna, blender, effect
---


# Question
Title: Software engineering theory for hobbyist developers
In playing around with my hobby projects in various object oriented languages, I have realized that creating good class structure and program architecture is both crucial and not straightforward to effectively develop a program, in particular a game.

I am a self-taught programmer with virtually no formal training, and I've only learned the things which seemed to be of immediate practical use, so I have never really looked into things such as design patterns, software architecture, code organization principles and the like. The resources I find are often limited in scope (most commonly it's a showcase of a single pattern) and/or quite technical (all the UML going over my head doesn't help).

Is there a good resource which explains the important concepts and basics of software engineering, where I can learn about things like when and how to use Components, what kind of class structures are appropriate to what tasks, how design patterns relate to each other and which are useful for what?

# Answer
> 3 votes
If you want to program game engines or simply learn about it, pick a good book. I really recommend you 3D Game Engine Architecture and this one Game Engine Architecture

These two explain all about how a game engine is divided and are plenty of nice ideas and code snippets oriented to game programming.

---
Tags: software-engineering, design-patterns
---


title: Bubble shooter search alghoritm

text:
# Question
Title: Bubble shooter search alghoritm
So I have a Matrix of NxM. At a given position (for ex. \[2\]\[5\]) I have a value which represents a color. If there is nothing at that point the value is -1. What I need to do is after I add a new point, to check all his neighbours with the same color value and if there are more than 2, set them all to -1.

If what I said doesn't make sense what I'm trying to do is an alghoritm which I use to destroy all the same color bubbles from my screen, where the bubbles are memorized in a matrix where -1 means no bubble and {0,1,2,...} represent that there is a bubble with a specific color.

This is what I tried and failed:

```
public class Testing {

    static private int[][] gameMatrix=
        {{3, 3, 4, 1, 1, 2, 2, 2, 0, 0},
        {1, 4, 1, 4, 2, 2, 1, 3, 0, 0},
        {2, 2, 4, 4, 3, 1, 2, 4, 0, 0},
        {0, 1, 2, 3, 4, 1, 0, 0, 0, 0},
        {0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
        {0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
        };

    static int Rows=6;
    static int Cols=10;
    static int count;
    static boolean[][] visited=new boolean[15][15];
    static int NOCOLOR = -1;
    static int color = 1;

    public static void dfs(int r, int c, int color, boolean set)
    {
        for(int dr = -1; dr <= 1; dr++)
            for(int dc = -1; dc <= 1; dc++)
                if(!(dr == 0 && dc == 0) && ok(r+dr, c+dc))
                {
                    int nr = r+dr;
                    int nc = c+dc;

                    // if it is the same color and we haven't visited this location before
                    if(gameMatrix[nr][nc] == color && !visited[nr][nc])
                    {
                        visited[nr][nc] = true;
                        count++;

                        dfs(nr, nc, color, set);

                        if(set)
                        {
                            gameMatrix[nr][nc] = NOCOLOR;
                        }
                    }
                }
    }

    static boolean ok(int r, int c)
    {
        return r >= 0 && r < Rows && c >= 0 && c < Cols;
    }

    static void showMatrix(){
        for(int i = 0; i < gameMatrix.length; i++) {
            System.out.print("[");
            for(int j = 0; j < gameMatrix[0].length; j++) {
                System.out.print(" " + gameMatrix[i][j]);
            }
            System.out.println(" ]");
        }
        System.out.println();

    }

    static void putValue(int value,int row,int col){
        gameMatrix[row][col]=value;
    }

    public static void main(String[] args){
        System.out.println("Initial Matrix:");
        putValue(1, 4, 1);
        putValue(1, 5, 1);
        showMatrix();

        for(int n = 0; n < 15; n++)
            for(int m = 0; m < 15; m++)
                visited[n][m] = false;

        //reset count
        count = 0;
        //dfs(bubbles.get(i).getRow(), bubbles.get(i).getCol(), color, false);

        // get the contiguous count
        dfs(5,1,color,false);
        //if there are more than 2 set the color to NOCOLOR
        for(int n = 0; n < 15; n++)
            for(int m = 0; m < 15; m++)
                visited[n][m] = false;
        if(count > 2)
        {
            //dfs(bubbles.get(i).getRow(), bubbles.get(i).getCol(), color, true);
            dfs(5,1,color,true);
        }

        System.out.println("Matrix after dfs:");
        showMatrix();
    }

}

```

# Answer
What you need here is a depth first search.

```
  int R, C;
  int[][] matrix;
  int count;
  boolean[][] visited;
  int NOCOLOR = -1;
  public int main()
  {
    int startR = 0;
    int startC = 0;
    int color = 1 // red
    int R = 10;
    int C = 20;

    matrix = new int[R][C];
    visited = new boolean[R][C];

    matrix = LoadLevel(); // get a starting matrix with colors

    //reset visited matrix to false.
    for(int i = 0; i < R; i++)
        for(int j = 0; j < C; j++)
            visited[i][j] = false;

    //reset count
    count = 0;
    dfs(startR, startC, color, false); // get the contiguous count

    //if there are more than 2 set the color to NOCOLOR
    if(count > 2)
    {
        dfs(startR, startC, color, true);
    }
  }

  public void dfs(int r, int c, int color, boolean set)
  {
    for(int dr = -1; dr <= 1; dr++)
        for(int dc = -1; dc <= 1; dc++)
            if((dr == 0 ^ dc == 0) && ok(r+dr, c+dc)) // 4 neighbors
            {
                int nr = r+dr;
                int nc = c+dc;

                // if it is the same color and we haven't visited this location before
                if(matrix[nr][nc] == color && !visited[nr][nc])
                {
                    visited[nr][nc] = true;
                    count++;

                    dfs(nr, nc, color, set);

                    if(set)
                    {
                        matrix[nr][nc] = NOCOLOR;
                    }
                }
            }
  }

    boolean ok(int r, int c)
    {
      return r >= 0 && r < R && c >= 0 && c < C;
    }

```
> 7 votes

# Answer
I think it would be easy to implement BFS or DFS to search same colors. You can just go to all of it's neighbours and then to their neighbours (if they are of the same color) etc.

So you will create graph, where every point is connected to its four- (or eight-) neighborhood.
> 1 votes

---
Tags: game-mechanics, search
---


# Question
Title: XNA Subtract blending function doesn't work
I wanted to subtract a white image with black circle background from a picture to get a lighting circle here is the white image So I wrote this code

```
spriteBatch.Begin(SpriteSortMode.Deferred, new BlendState
{
      ColorBlendFunction = BlendFunction.Subtract,
      AlphaBlendFunction = BlendFunction.Subtract
});
//Draw the white image with black circle
spriteBatch.Draw(test, new Vector2(), Color.White);
spriteBatch.End();

```

I was aiming to get difference between it and the background image rendered to get something like this

But the result that the first image is only drawn while second is below it

# Answer
> 1 votes
Reposing my answer from here.

Just set the below as the BlendState in SpriteBatch.Begin(). Also worth noting is that if the SortMode is SpriteSortMode.Immediate you can alter the all of the GraphicsDevice's properties without calling Spritebatch.Begin again.

```
        GraphicsDevice.BlendState = new BlendState {

            ColorSourceBlend = Blend.Zero,
            ColorDestinationBlend = Blend.InverseSourceColor,

            AlphaSourceBlend = Blend.Zero,
            AlphaDestinationBlend = Blend.InverseSourceColor

        };

```

# Answer
> 1 votes
Try inverting the image, in substraction what happens is that (for every channel (RGB) of every pixel) the following calculation is done: result = clip( source - filter, 0, 255 ).

With filter the white image you posted. Meaning that the white parts of the source becoming black, and the black parts staying the same.

---
Tags: xna-4.0, blending
---


# Question
Title: How do you calculate game map changes, over time, when the user is not online?
With a game like *"Farmville"*, there is both processing during gameplay, and when the user is offline (plants are always growing, for example). Many of the game maps elements depend on time.

Is there a trick to make this scale? How can you possibly calculate 1 million users maps being modified every couple of seconds? Some of these games alert you, when things have changed, so it is not like they calculate everything when you login to the system.

How do you calculate game map changes, over time, when the user is not online?

# Answer
Let's take plants growing as an example.

Suppose you have a tomato plant that grows in 4 hours. While the player is in the game you're probably calculating it like this:

```
tomato_grow_time = 4 * 60 * 60;  /* 4 hours */

function update(seconds_since_last_draw) {
    tomato_plant.age += seconds_since_last_draw / tomato_grow_time;
    if (tomato_plant.age >= 1) {
       /* plant is finished growing */
    }
}

```

and you're calling `update` every frame. What would happen if you instead called it only when the player next logged in, instead of every x seconds? It'd still work, except the `if` condition would occur too late.

Instead of thinking of it in imperative terms, think of it as a function:

```
 function tomato_plant_age(time) {
      age = (time - tomato_plant.start_time) / tomato_grow_time;
 }

```

Now you can calculate when the age exceeds 1 (e.g. the plant is finished growing), using simple algebra:

```
 age = (time - start_time) / grow_time
 solve for time when age = 1
 ...
 time = (age * grow_time) + start_time

```

You don't really have to update every x seconds. You go through each of the plants and compute the time when they're finished growing. *Take the min() of these* to figure out the first plant that will trigger a notification. That's the only notification the app has to send out (unless your app repeatedly notifies, in which case you take all of them instead of the min() of them).

On Facebook, Farmville doesn't even notify you, so it's even simpler. They just update the plant ages when you next log in, or if someone visits your farm. *If nobody looks at the farm, there's no update.*

This approach only works when the updates are simple. It's one of the reasons these types of games tend to be very simple — it makes it easy to scale.
> 19 votes

# Answer
Well they have many servers but also things have set times, so their progress is based on their creation time.
> 0 votes

# Answer
Are you talking about an online game that relies on a server to store the game state, or a game that runs on the users local machine?

**Server Based Game**

If you are talking about a server based job, then you would create something like a cron job that runs at some given time interval (e.g., every 5 minutes, 1 hour, or whatever your game design dictates). When the job runs, a piece of software iterates through all the active games, updating item states, sending messages as appropriate, etc.

**Local Machine Based Game**

If you are talking about a game running on the users local machine, you will not necessarily have the luxury of being able to have the game run in the background all the time.

If the local machine has some kind of alarm/calendar/alert ability (e.g., "Run this program at time X" or "Give player message at this time"), then you can calculate ahead of time when events (e.g. "pokes") should happen. For example, player plants a plant, plant will be ready in 8 hours. Program sets system alarm to message player 8 hours from now.

If the local machine doesn't have any kind of alarm/calendar/event system, then you will have to write your software to record when it was last run, and then whenever it is started, it can determine how much time has passed, and then can simulate the game world forward that amount of time before the player begins playing.
> 0 votes

---
Tags: architecture
---


title: Xna Xbox framedrops when GC kicks in

text:
# Question
Title: Xna Xbox framedrops when GC kicks in
I'm developing an app (XNA Game) for the XBOX, wich is a pretty simple app. The startpage contains tiles with moving gif images.

Those gif images are actually all png images, wich gets loaded once by every tile, and put in an array. Then, using a defined delay, these images are played (using a counter wich increases everytime a delay passes).

This all works well, however, I noticed some small lag every x seconds in the movement of the GIF images. I then started to add some benchmarking stuff: http://gyazo.com/f5fe0da3ff81bd45c0c52d963feb91d8

As you can see, the FPS is pretty low for such a simple program (This is in debug, when running the app from the Xbox itsself, I get an avg of 62fps). 2 important settings:

```
Graphics.SynchronizeWithVerticalRetrace = false;
IsFixedTimeStep = false;

```

Changing isFixedTimeStep to true increases the lag. The settings tile has wheels wich rotate, and you can see the wheels go back a little every x seconds. The same counts for SynchronizeWVR, also increases lag.

I noticed a connection between the lag and the moment the garbage collector kicks in, everytime it kicks in, there is a lag ...

Don't mind the MAX HMU(Heap memory usage), as this is takes the amount of the start, the avg is more realistic.

Here is another screen from the performance monitor, however I don't understand much from this tool, first time I'm using it...

Hope it helps: http://gyazo.com/f70a3d400657ac61e6e9f2caaaf17587

# Answer
After a little research I found the culprit.

I have custom components that all derive from GameComponent, and who get added to the Component list of the main Game class.

This was one (of a total of 2) major problem, causing to update everything that wasn't needing an update. (The draw method was the only one who kept the page state in mind, and only drew if needed). I fixed this by using different "screens" (or pages as I called them), wich are the only components who derive from GameComponent.

Then I only update the page wich is active, and the custom components on that page also get updated. Problem fixed.

The second big problem, is the following; I made a class which helps me on positioning stuff on the screen, relative that is, with percentages and stuff like that. Parent containers, aligns & v-aligns etc etc. That class had properties, for size & vectors, but instead of saving the calculated value in a backing field, I recalculated them everytime I accessed a property. But calculating complex stuff like that uses references (to parent & child containers for example) wich made it very hard for the CLR, because it had alot of work to do.

I now rebuilt the whole positioning class to a fully functional optimized class, with different flags for recalculating when necessairy, and instead of drops of 20fps, I now get an average of 170+fps!
> 1 votes

---
Tags: xna, xbox360
---


# Question
Title: Rendering issue: depth buffering + blending: how do they work together?
This image describes the problem I'm having:

What you are seeing consists of two images:

* Image A(with the alien-concept art thingy), depth value .98, the white parts on the image is where the alpha value is 0.0f
* Image B(with the play game button thingy), depth value .99, one solid image without any transparency value.

Now, when I first set this up, I expected Image A to let the colours of Image B through where Image A is fully transparent. But it doesn't

Question 1 : Why doesn't it?

Question 2 : What can I do to fix it? Are there multiple ways to fix it?

Question 3 : Is this problem different for partial transparency? If so, how do I make it work with partial transparency as well?

Thanks.

# Answer
Are you rendering the images in the correct order? For blending to work, they need to render back-to-front, so Image B should be drawn first and then Image A should composite over it.

In general, the depth buffer does not work well when combined with blending / transparency; using the two together usually produces undesired results. See this answer to a similar question for a more in-depth explanation and rundown of the different approaches to solving it.
> 1 votes

---
Tags: c++, rendering, directx10
---