Saturday, February 19, 2011

How to create a FPS game?

I would like to know How to create a fps-game with SDL lib?

Are there any books that explain with examples?

From stackoverflow
  • Pretty much anything that says in the TItle the "Tricks of the Game Programming Gurus" is going to show you how to make a FPS game. LeMothe loves them.

    Edit : forgot those titles.

    rmeador : It'll show you how, but I don't consider them to be good. The one I read years ago was pushing all sorts of bad practices. Hardly "guru" quality.
    Dan Blair : I agreed with you statement.
  • I found this site a while back, when I was playing around with SDL, you'll find so sample programs you can download here

  • Download the quake 3 sources at fileshack and learn from them.

    David Frenkel : A good point. Learning from the masters is never harmful. (though realize it may be dated, and even masters *can* make mistakes or not build for scaling)
  • this wins for most open ended question. You could literally write a book. But lets settle for pointing in the right direction...

    Step one, you will need good debugging skills for a project like this. Pick up Code Complete by Steve McConnell. Read the whole thing. The time invested will pay for itself more than anything else you could read/experiment with.

    Get your hands on some source code of some game. ANY game. Make sure you see something simple before you see something big and complex, and keep in mind when you look at any game code that they may have had a combined team put WAY more time into it than you will ever have. The point in this is to see code structure.

    Get a reference for 3D math, doesn't have to be THAT in depth, but you will need to know stuff like dot products backwards and forwards, be able to figure out how to create the matrix for your camera in the world etc. (even if your writing 0% of the rendering code)

    (edit) Here's a great book on 3D mathMathematics for 3D Game Programming and Computer Graphics, Second Edition (Game Development Series) This isn't the kind you learn in college, it's more like a cross between trig and more advanced practical concepts: How to create a toolbox for yourself of simple physics, efficient collision detection, etc.

    You will need to know something about rendering, and pipelines. SDL gives you a leg up, but make sure you understand the concepts of what it's doing.

    Read up about practical system design. Your various systems will have to interlock. Think it out well. Your system can be just a good in C or in C++, it's the THOUGHT that is put into how your data/control will flow that will count, NOT how perfectly you emulate design patterns (though these are very useful as well of coarse)

    Fundamentals of AI, not "real" AI, but functional AI; there is a big difference. State machines are great to start with, and sufficient for a simple FPS.

    Learn a little about estimation and planning. You will not have time to do everything you would want to do to properly make an FPS. You will have to both triage AND learn how to triage; they are 2 separate things, the latter being mroe difficult. Experience is the best teacher here of coarse. (though the legendary McConnell has book on this as well)

    Have a system to insert your gameplay into your level. If it is JUST you as a programmer, then your best bet is to write a plug in for an already existing editing program such as 3DS Max. I would highly recommend Max over Maya for a programmer. Maya script is nice, but it is more geared toward clever non-programmers. I find 3DS Max to think more along the lines of how a programmer would about creating and editing your world.

    You can spend YEARS making tools to let you do this right, so you want to do things in such a way that you can edit fast and accurately If you making your own editor, incorporate it into your game world. If your world is not TRULY 3D and you want to make lots of level fast you can save your level data as something like this, which will save you a lot of time Where X is a wall, the other letters are game objects which a dirt simple parser can translate into game objects and world coordinates

     xxxxxxxxxxxxxxxxxxxxxxxx
     xx..........P..........x
     xxxxxxx...........I....x
     xR....xxx...........E..x
     xx.................0xxxx
     xxxxxxxxxxxxxxxxxxxxxxxx
    

    But it all depends on your game. My point is that you will need to resort to "ghetto coding" how you get your gameplay data into your world is very important and you need to think of something that is both fast for you to implement AND fast with you to work with.

    And what it comes down to is what is your goal here? If it's to learn to code something the absolute right way, expect to spend most of your time iterating on code that seemed decent a month ago, but now that you realize what your requirements are, it could really use another pass. Do not be afraid to rewrite, you learn a lot by doing that, but if you goal is functionality, you will probably need to figure out where to hack some things in (like embedding gameplay data nad coordinates into code files) It IS ok to hack as long as you KNOW where you have hacked, and have carefully kept it separate from your good code so you can go back and properly write the code when you get the chance.

    The bottom line is, you need to decide what your goal in this is, learning, or functionality and find the happy medium between.

    Dave Sherohman : "You could literally write a book." Indeed, several have been written.
  • While not SDL specific, the NeHe OpenGL tutorials are an excellent place to start for learning about how to do 3D.

    If this is your first game, you'll probably want to aim lower than an FPS. Writing a simple 2D Tetris game using SDL will teach you everything you'll need to know about that library.

  • Although the very long post is valueable in the long run, I feel it doesn't give the proper instant motivation of getting things on screen. Here's some facts, along with my opinion

    -SDL is a 2D graphics library, you can't write an FPS in 2D, therefore you have to go with a 3D library, either DirectX, or openGL

    -SDL has the ability to "sync" with openGL, using it for graphics, but there's not a whole lot of help online for that topic

    I suggest you go to Lazyfoo.net, which is an absolutly amazing beginner's resource for game programming with SDL, it shows you how to draw to the screen, but also teaches you how to apply this to programming games. After going through this, you'll be able to make a tetris clone, or most other 2D type games

    After this, you'll be ready for 3D(it's a lot more complex, requires a better grasp of math, and takes a lot more code to do simpler things) if you go with openGL, check out NeHe's Tutorials , they're currently working on a new set, using SDL with openGL, because the older tutorials, although valueable, are coded rather badly and use the windows(win32) API

    keep in mind, game development is one of the most demanding, and rewarding programming you'll come across, so good luck

    Skilldrick : I've just started having a look at lazyfoo.net - awesome!!

Bash Shell Scripting: what simple logic am I missing

This may be too generic a question as is but... I am stumped by trying to move through the directories from within a shell script. I'm not a *nix power user, but I am comfortable working through the command line for most tasks. I'd like to call a script that can move 'me' to a directory instead of just the script process similar to the following:

prompt:> goto lit
where goto is an alias -> goto='./goscript'
and
goscript has some simple code in such as: cd /path to work dirs/lit/user dir
(assuming each user has a directory inside /lit)

I've avoided this issue myself by setting my personal alias' to move to the desired directory, run a script, then return to the original directory. This question was brought to me by a co-worker who uses a similar method, but wanted to make the process more generic so we don't need to create every single alias we need. I thought this would be an easy problem to solve, but I'm stumped as I don't really have a great deal of shell scripting experience ...as of yet.

From stackoverflow
  • You can't. The script has its own copy of the environment, and so it can't change the login shell's environment.

  • You can't use cd in a bash script. You could alias the cd and path though.

    alias goto='cd /path_to_work/usr/dir'
    

    UPDATE: you would put that line in your .bashrc file and then do

    source ~/.bashrc
    

    to create the alias.

  • You can accomplish some simple stuff like this using an alias. For example, I have some aliases that put me into a workspace environment and configure variables for our Makefile system. Here's a real alias I am using as an example. The '&&' will continue executing the commands until one of them fails--in simple scenarios like this, no clean-up is needed, since failure isn't likely.

    alias main1='cd ~/code/main1 && export TOP=`pwd` && export DEBUG=1'
    

    If you want to develop a shared library of aliases amongst your co-workers, you can share them over NFS and source the file to be included.

  • Each script has its own idea of the current working directory. "cd" is not a process but a shell build-in.

    The way to do what you want is to create an alias. In csh it will be something like:

    alias goto 'cd /path_to_work/\!*/user_dir'
    

    sh/bash have similar alias facilities

  • You can create a function that is called goto (or whatever) and make sure it is defined in your .bashrc (or you can "source" it from your current shell):

    function goto {
        #  the "$USER" part will expand to the current username
        # the "$1" will expand to the first argument to the function ("goto xyz" => $1 is "xyz")
        cd /some-path/lit/$USER/$1
    }
    

    Put this in ~/.bashrc or in a separate file and call "source the-file" from your prompt then you can call the function just like any other program:

    prompt> goto folder
     cd /some-path/lit/your-user/folder
    
  • To execute a script in the same environment of your prompt you have to invoke it with .

    Say you have the script named up:

    cd ..
    

    if you invoke it with . you get:

    $> pwd
    $> /home/users/rd/proj
    $> . up
    $> pwd
    $> /home/users/rd
    
    Rene Saarsoo : The dot is actually equivalent to "source" command. Although at least in my system I have to write ". ./up" instead of just ". up" - othwerwise I'll get error: "bash: ELF: command not found"
    Remo.D : You're right about source. The reason you gat the error is that you don't have . in the path. That's the default behaviour (whose reason I've nver quite understood) for many unix shell.
    Adam Liss : @Remo.D: the reason is security. It ensures you won't accidentally execute a command from the current directory instead of the "real" command. Imagine a shell script in your home directory called 'ls' whose contents were 'rm -rf /'
  • I tend to have a couple dozen aliases in my .rc that look like this:

    alias work='cd /home/foo/work'
    alias rails='cd /home/foo/rails'
    alias assets='cd /home/foo/rails/assets'
    

    etc.

    If that isn't going to work for you, you might be able to use the debug hooks in bash to replace the command line in-place before it is executed - if the 'goto' keyword is the first thing on the line. This will involve googling around for 'trap' in bash, but be forewarned, such incantations do not behave the same on all systems. I wrote up one such experience a few months ago, and you're welcome to the results.

  • Even better than using an alias as others have described, check out the CDPATH variable! It's basically equivalent of the PATH functionality, but applied to the cd command.

    For example, if I define my CDPATH=${HOME}/subdir, and ~/subdir contains another directory, subsubdir, then I can simply execute:

    cd subsubdir
    

    from any directory, and I can navigate the the path as expected.

    Here's some more specifics:

    http://www.caliban.org/bash/#bashtips

    To set the CDPATH variable, add a line to your .bashrc, such as

    export CDPATH=${HOME}/subdir
    
    Adam Liss : +1 for using the right tool for the job ... something I'm trying to teach my kids, who seem to think _everything_ is a hammer.
    Jonathan Leffler : Also, if you value your sanity, ensure that the first character in the value of CDPATH is ':' so that when you type 'cd bin' and there is a bin directory in the current directory, that's where you go to.
  • I wasn't a member when I asked this (ironically my anonymous login question has higher flair than my official login questions combined), so I can't close it now - But- The Remo D. et al. answer would be the one that led to the working solution we needed. If anyone with mod powers can close this & select that as the accepted answer, i'd apprediate it.

WPF: Problem with binding values to ComboBox inside GridViewColumn

My Views dataContext is bounded to a presentationModel with two observableCollections Members. In the View I have one listView which ItemSource is bound to is the first observableCollection. In one of the LilstViews column I want to present values from the second obeservable Colletion in my presentationModel. I cant figure out how to get the values from the observableCollection into my combobox. Does anyone have an idea how to solve this problem?

From stackoverflow
  • First thing you need to do is create a data template containing your ComboBox, in this case I have bound the ItemsSource to a DependencyProperty on the host Window. This contains the presentation model, which has a property called ComboSource. SelectedValue has been bound, via the ListViewItem's DataContext, to a property which holds the selected value.

    <ListView.Resources>
        <DataTemplate x:Key="comboBoxTemplate">
            <ComboBox
                ItemsSource="{Binding 
                                Path=ModelData.ComboSource, 
                                RelativeSource={RelativeSource AncestorType=Window}}"
                SelectedValue="{Binding 
                                Path=DataContext.Selection, 
                                RelativeSource={RelativeSource AncestorType=ListViewItem}}"
                DisplayMemberPath="Item"
                SelectedValuePath="Id"
                />
        </DataTemplate>
    </ListView.Resources>
    

    Then you will need to reference this from the CellTemplate on the GridViewColumn

    <GridViewColumn
        Header="Selection"
        Width="160"
        CellTemplate="{StaticResource comboBoxTemplate}"
        />
    
    KaJo : Tanks!!! This was very helpful
  • I can't get this sample to work. It would be a great help if you could post sample code for download or tell me where to get something similar.

    Thanks, Dan

Making an iframe take vertical space

I would like to have an iframe take as much vertical space as it needs to display its content and not display a scrollbar. Is it at all possible ?

Are there any workarounds?

From stackoverflow
  • This CSS snippet should remove the vertical scrollbar:

    body {
    overflow-x: hidden;
    overflow-y: hidden;
    }
    

    I'm not sure yet about having it take up as much vertical space as it needs, but I'll see if I can't figure it out.

  • This should set the IFRAME height to its content's height:

    <script type="text/javascript">
    the_height = document.getElementById('the_iframe').contentWindow.document.body.scrollHeight;
    document.getElementById('the_iframe').height = the_height;
    </script>
    

    You may want to add scrolling="no" to your IFRAME to turn off the scrollbars.

    edit: Oops, forgot to declare the_height.

    ConroyP : Very handy, cheers. Might be worth mentioning that this won't work so well if the iframe is on a different domain due to the same origin policy
  • @Daniel

    I don't mind the body scrollbar, I would actually rather have that one than have the iframe generate a second set of toolbars that take only part of the page.

    @Teifion

    This would not work, you can set a height in pixel for the iframe though, but I find that a rather ugly solution (setting the iframe height to some random large value)

  • Adding a DOCTYPE declaration to the IFRAME source document will help to calculate the correct value from the line

    document.getElementById('the_iframe').contentWindow.document.body.scrollHeight
    

    see W3C DOCTYPE for examples

    I was having problems with both IE and FF as it was rendering the iframe document in 'quirks' mode, until I added the DOCTYPE.

    FF/IE/Chrome support: The .scrollHeight doesnt work with Chrome so I have come up with a javascript example using jQuery to set all IFRAME heights on a page based on the iframes content. NOTE: This is for reference pages within the your current domain.

    <script type="text/javascript">
        $(document).ready(function(){
            $('iframe').each(function(){
                var context = $(this);
                context.load(function(event){ // attach the onload event to the iframe  
                    var body = $(this.contentWindow.document).find('body');
                    if (body.length > 0 && $(body).find('*').length > 0) { // check if iframe has contents
                        context.height($(body.get(0)).height() + 20);
                    } else {
                        context.hide(); // hide iframes with no contents
                    }
                });
            });
        });
    </script>
    
  • The workaround is not to use <iframe> and preprocess code on server-side.

  • Also check out this thread: http://stackoverflow.com/questions/754519/how-does-the-diggbar-dynamically-resize-its-iframes-height-based-on-content-not.

    It addresses the same question.

Lambda expression exercise

I have been trying to learn more about lambda expressions lately, and thought of a interesting exercise...

is there a way to simplify a c++ integration function like this:

// Integral Function
double integrate(double a, double b, double (*f)(double))
{
    double sum = 0.0;

    // Evaluate integral{a,b} f(x) dx
    for(int n = 0 ; n <= 100; ++n)
    {
        double x = a + n*(b-a)/100.0;
        sum += (*f)(x) * (b-a)/101.0;
    }
    return sum;
}

by using c# and lambda expressions?

From stackoverflow
  • What about this:

    public double Integrate(double a,double b, Func<double, double> f)
    {
        double sum = 0.0;
    
        for (int n = 0; n <= 100; ++n)
        {
            double x = a + n * (b - a) / 100.0;
            sum += f(x) * (b - a) / 101.0;
        }
        return sum;
    }
    

    Test:

        Func<double, double> fun = x => Math.Pow(x,2);        
        double result = Integrate(0, 10, fun);
    
    Marc Gravell : hehe - within seconds of each other ;-p
  • The real power comes, as stated, when calling it. For example, in C#

        static double Integrate(double a, double b, Func<double, double> func)
        {
            double sum = 0.0;
    
            // Evaluate integral{a,b} f(x) dx
            for(int n = 0 ; n <= 100; ++n)
            {
                double x = a + n*(b-a)/100.0;
                sum += func(x) * (b - a) / 101.0;
            }
            return sum;
        }
    

    Then:

        double value = Integrate(1,2,x=>x*x); // yields 2.335
        // expect C+(x^3)/3, i.e. 8/3-1/3=7/3=2.33...
    
  • Lambda Powa! Not sure whether this is right (No C# programmer! Just liking its lambda stuff)

    (a, b, c) => {
        double sum = 0.0;
        Func<double, double> dox = (x) => a + x*(b-a)/100.0;
    
        // Evaluate integral{a,b} f(x) dx
        for(int n = 0 ; n <= 100; ++n)
            sum += c(dox(n)) * (b-a)/101.0;
    
        return sum;
    }
    

    Ok, so i think while the code is C++, why not keep it C++ and get lambda in? Here it is how it looks for c++0x, being hopefully released as a Standard very soon :

    static double Integrate(double a, double b, function<double(double)> f)
    {
        double sum = 0.0;
    
        // Evaluate integral{a,b} f(x) dx
        for(int n = 0; n < 100; ++n) {
            double x = a + n * (b - a) / 100.0;
            sum += f(x) * (b - a) / 101.0;
        }
        return sum;
    }  
    
    int main() {
        Integrate(0, 1, [](double a) { return a * a; });
    }
    

How do I log cross-domain intranet traffic (including username) using a HTTPHandler?

I am attempting to log user activity for a couple internal websites as well as our SharePoint sites. I use JavaScript to make a call (GET) to an ashx page (HTTPHandler) that returns a 1x1 invisible GIF. The HTTPHandler grabs the referring URL, browser info, ip address, the action (sent as a QueryString), and (the part I'm strugging with) the username. The username is gathered using context.User.Identity in the HTTPHandler and 'Integrated Windows Authentication' is enabled in IIS 6. Here is the logging portion of the js:

    logAction: function(action) {
    try {
        var i = new Image(1, 1);
        i.src = "http://intranet/tracker/urchin.ashx?action=" + action;
    } catch (e) {
        //alert(e);
    }

Using jQuery, I added handlers to button clicks, link clicks, and 'unload' that call the ashx file and pass the action performed. (It is also called on page load).

All of this was working perfectly, or so I thought... It turned out that I was missing the initial page load event the first time the user opened one of the pages if it was not on the same domain as the HTTPHandler. Using Fiddler I could see the NTLM cycle for the page (401.2, 401.1, 200) but only a 401.2 for the ashx. It appears that the browser will not send the user credentials when the call to the HTTPHandler is cross-domain. The next page the user visits gets logged correctly, but that first page is not logged.

Here are our domains:

Is there something wrong with my design, or is this simply web browser security? Thanks!

From stackoverflow
  • Hi,

    You might want to see this: http://developer.yahoo.com/javascript/howto-proxy.html

    It may not be spot on about the problem you have (which I can't give you a precise technical answer to right now), but the above link will warn you of the problems/design decisions/security considerations that you must be aware of with what you are trying to achieve. You are right, there is a browser security issue, that much I do know.

    Also do a google search for cross domain ajax proxy. Some good reading for you there!

    Good luck!

YUI in IE6 & IE7

I'm using Bugzilla 3.2 RC2 (released 11/06/2008)

There is some conditional logic deep in there that shows a 2nd dropdown when the 1st has a value of "Resolved". Works great in IE8, Firefox, and Chrome.

It doesn't work at all in IE6 or IE7. No Javascript error and nothing happens.

I'm wondering if anybody else has run into this issue before in IE6/7 with the Y-UI javascript (at least that is where I think the problem is occurring.

var close_status_array = new Array("[% closed_status_array.join('", "') FILTER replace(',$', '')
                                                                FILTER none %]");
  YAHOO.util.Dom.setStyle('dup_id_discoverable', 'display', 'block');
  hideEditableField( "dup_id_container", "dup_id", 'dup_id_edit_action',
                     'dup_id', '[% bug.dup_id FILTER js %]' )
  showHideStatusItems( "",  ['[% "is_duplicate" IF bug.dup_id %]',
                             '[% bug.bug_status FILTER js %]']);
  YAHOO.util.Event.addListener( 'bug_status', "change", showHideStatusItems,
                                ['[% "is_duplicate" IF bug.dup_id %]',
                                 '[% bug.bug_status FILTER js %]']);
  YAHOO.util.Event.addListener( 'resolution', "change", showDuplicateItem);
  YAHOO.util.Event.addListener( 'dup_id_discoverable_action',
                                'click',
                                setResolutionToDuplicate,
                                '[% Param('duplicate_or_move_bug_status')
                                                                FILTER js %]');
  YAHOO.util.Event.addListener( window, 'load',  showHideStatusItems,
                              ['[% "is_duplicate" IF bug.dup_id %]',
                               '[% bug.bug_status FILTER js %]'] );

Ultimately, it renders:

var close_status_array = new Array("RESOLVED");  
YAHOO.util.Dom.setStyle('dup_id_discoverable', 'display', 'block');  
hideEditableField( "dup_id_container", "dup_id", 'dup_id_edit_action', 'dup_id', '' )  
showHideStatusItems( "",  ['', 'NEW']);  
YAHOO.util.Event.addListener( 'bug_status', "change", showHideStatusItems, ['', 'NEW']);  
YAHOO.util.Event.addListener( 'resolution', "change", showDuplicateItem);  
YAHOO.util.Event.addListener( 'dup_id_discoverable_action', 'click', setResolutionToDuplicate, 'RESOLVED');  
YAHOO.util.Event.addListener( window, 'load',  showHideStatusItems, ['', 'NEW'] );
From stackoverflow
  • I have the same problem :-(