CSCE 590E Spring 2007 Game Programming By Jijun Tang
Announcements We will meet in 2A21 on Wednesday Please bring laptops (with mouse) on Wednesday Please install 3D Canvas Pro Flash Game due this Wednesday Small game due Friday, March 9 th, 5:00pm
Game Design Presentation Two presentations, on March 5 th and March 7 th. March 5 th : group A, Cheeze Puffs!, Team Swampus March 7 th : Group D, Group E, Psychosoft Each has 20 minutes to present, 5 minutes to answer questions
Contents for the Presentation Description, specification, goals, game play System requirement, audience, rating Interface, input/output, interactions, cameras Premise/limitations/choices/resources Content designs, audio Level designs, flexibility Use case/UML (rough) Engines to use Version control/testing strategy Brief timeline (demo date is May 2 nd -9 th )
Logos-so-far
3D Canvas Pro Requires XP/2000, DirectX 9 Requires license code Installation package is available for download After installation, enter the code under the help menu
Programming Teams In the 1980s programmers developed the whole game (and did the art and sounds too!) Now programmers write code to support designers and artists (content creators)
Different Programs Game code Anything related directly to the game Game engine Any code that can be reused between different games Tools In house tools Plug-ins for off-the-shelf tools
Methodologies Code and Fix Waterfall Iterative Agile
Make Coding Easier Version control Coding standards Automated build Code review Unit testing and acceptance testing
Languages C/C++ Java Script: Flash, Python, LISP, etc. C# XNA for PC and Xbox
Programming Fundamentals
Data Structures: Array Elements are adjacent in memory (great cache consistency) Requires continuous memory space They never grow or get reallocated Use dynamic incremental array concept GCC has a remalloc function In C++ there's no check for going out of bounds Use vector if possible Keep in mind of checking boundaries Inserting and deleting elements in the middle is expensive
List Very cheap to add/remove elements. Available in the STL (std::list) Every element is allocated separately, not placed contiguously in memory Lots of little allocations Bad cache awareness, but can use arrays to hold pre-allocated items Single/Double linked list
Lists
Dictionaries Maps a set of keys to some data. std::map, std::hash, etc Very fast access to data Perfect for mapping IDs to pointers, or resource handles to objects May waste space, need to design comparison operators
Hash Table
Others Stacks First in, last out std::stack adaptor in STL Queues First in, first out std::deque Priority queue is useful in game to schedule events
Stack/Queue/Priority Queue
Bit packing Fold all necessary data into a smaller number of bits Bool in C++ may use up to 4 bytes, thus is very expensive Very useful for storing boolean flags: pack 32 in an integer Possible to apply to numerical values if we can give up range or accuracy Very low level trick Use shifts to handle the operation or use assembly Only use when absolutely necessary
Bits
OO Design and Patterns
Object Oriented Design Concepts Class Abstract specification of a data type Instance A region of memory with associated semantics to store all the data members of a class Object Another name for an instance of a class
Inheritance Models “is-a” relationship Extends behavior of existing classes by making minor changes Do not overuse, if possible, use component systerm UML diagram representing inheritance
Polymorphism The ability to refer to an object through a reference (or pointer) of the type of a parent class Key concept of object oriented design C++ implements it using virtual functions
Multiple Inheritance Allows a class to have more than one base class Derived class adopts characteristics of all parent classes Huge potential for problems (clashes, casting, dreaded diamond, etc) Multiple inheritance of abstract interfaces is much less error prone (virtual inheritance) Java has no multiple inheritance
The Dreaded Diamond
Limitations of inheritance Tight coupling Unclear flow of control Not flexible enough A person is an employee, and a father What if the person is also an employer Static hierarchy The inheritance hierarchy is fixed at instantiation The object's type does not change with time.
Component Systems Use aggregation (composition) instead of inheritance A game entity can “own” multiple components that determine its behaviour Each component can execute whenever the entity is updated Messages can be passed between components and to other entities
Component Systems Component system organization
Benefits of Component Systems Data-Driven Composition The structure of the game entities can be specified in data Components are created and loaded at runtime Very easy to change (which is very important in game development)
Analysis of Component System Very hard to debug Performance can be a bottleneck Keeping code and data synchronized can be a challenge Extremely flexible Great for experimentation and varied gameplay Not very useful if problem/game is very well known ahead of time
Design Patterns Design pattern is a general repeatable solution to a commonly occurring problem in software design Design patterns can speed up the development process by providing tested, proven development paradigms Algorithm (for computation problem) is not pattern (for design)
Object Factory Creates objects by name Pluggable factory allows for new object types to be registered at runtime Extremely useful in game development for passing messages, creating new objects, loading games, or instantiating new content after game ships
UML for Factory
Singleton Implements a single instance of a class with global point of creation and access For example, GUI Don't overuse it!!!
Observer Allows objects to be notified of specific events with minimal coupling to the source of the event Two parts subject and observer
UML for Observer
Composite Allow a group of objects to be treated as a single object Very useful for GUI elements, hierarchical objects, inventory systems, etc
UML for Composite
Debugging
The Five Step Debugging Process 1. Reproduce the problem consistently 2. Collect clues 3. Pinpoint the error 4. Repair the problem 5. Test the solution
Step 1: Reproduce the Problem Consistently Sample reproduce steps: 1. Start a single player game 2. Choose Skirmish on map Find the enemy camp 4. From a distance, use projectile weapons to attack the enemies at the camp 5. Result: 90 percent of the time the game crashes
Step 2: Collect Clues Each clue a chance to rule out a cause Each clue a chance to narrow down the list of suspects Realize that some clues can be misleading and should be ignored
Step 3: Pinpoint the Error Two main methods: 1. Propose a Hypothesis You have an idea what is causing the bug Design tests to prove or disprove your hypothesis 2. Divide and Conquer Narrow down what could be causing the bug Eliminate possibilities from the top down or Backtrack from the point of failure upward
Step 4: Repair the Problem Propose solution Consider implications at point in project Programmer who wrote the code should ideally fix the problem (or at least be consulted) Explore other ways the bug could occur Ensure underlying problem fixed and not just a symptom of the problem Bug trace database
Step 5: Test the Solution Verify the bug was fixed Check original repro steps Ideally have someone else independently verify the fix Make sure no new bugs were introduced At the very end of the project, have other programmers review the fix
Expert Debugging Tips Question assumptions Minimize interactions and interference Minimize randomness Break complex calculations into steps Check boundary conditions, use assertions Disrupt parallel computations Exploit tools in the debugger (VC is good) Check code that has recently changed Explain the bug to someone else Debug with a partner (A second pair of eyes) Take a break from the problem Get outside help (call people)
Tough Debugging Scenarios Bug exists in Release but not Debug Uninitialized data or optimization issue Bug exists on final hardware, not dev-kit Find out how they differ – usually memory size or disc emulation Bug disappears when changing something innocuous (e.g., add a print) Timing or memory overwrite problem Intermittent problems Record as much info when it does happen Unexplainable behavior Retry, Rebuild, Reboot, Reinstall Internal compiler errors Full rebuild, divide and conquer, try other machines Suspect it ’ s not your code Check for patches, updates, or reported bugs Contact console maker, library maker, or compiler maker
Understanding the Underlying System Knowing C or C++ not enough Know how the compiler implements code, and optimize code Know the details of your hardware Especially important for console development Know some assembly and be able to read it Read memories will help Helps with optimization bugs or compiler issues
Adding Infrastructure to Assist in Debugging Alter game variables during gameplay Visual AI diagnostics Logging capability Recording and playback capability Track memory allocation Print as much information as possible on a crash Educate your entire team testers, artists, designers, producers
Prevention of Bugs Set compiler to highest warning level Set compiler warnings to be errors Compiler on multiple compilers Write your own memory manager Use asserts to verify assumptions Initialize variables when they are declared Bracket loops and if statements Use cognitively different variable names Avoid identical code in multiple places Avoid magic (hardcoded) numbers Verify code coverage when testing
Game Architecture
Overall Architecture The code for modern games is highly complex With code bases exceeding a million lines of code, a well-defined architecture is essential
Overall Architecture Main structure Game-specific code Game-engine code Both types of code are often split into modules, which can be static libraries, DLLs, or just subdirectories Architecture types Ad-hoc (everything accesses everything) Modular DAG (directed acyclic graph) Layered
Overall Architecture Options for integrating tools into the architecture Separate code bases (if there's no need to share functionality) Partial use of game-engine functionality Full integration
Overview: Initialization/Shutdown The initialization step prepares everything that is necessary to start a part of the game The shutdown step undoes everything the initialization step did, but in reverse order
Overview: Initialization/Shutdown Resource Acquisition Is Initialization A useful rule to minimalize mismatch errors in the initialization and shutdown steps Means that creating an object acquires and initializes all the necessary resources, and destroying it destroys and shuts down all those resources Optimizations Fast shutdown Warm reboot
Overview: Main Game Loop Games are driven by a game loop that performs a series of tasks every frame Some games have separate loops for the front and and the game itself Other games have a unified main loop
Overview: Main Game Loop Tasks Handling time Gathering player input Networking Simulation Collision detection and response Object updates Rendering Other miscellaneous tasks
Overview: Main Game Loop Structure Hard-coded loops Multiple game loops For each major game state Consider steps as tasks to be iterated through
Overview: Main Game Loop Coupling Can decouple the rendering step from simulation and update steps Results in higher frame rate, smoother animation, and greater responsiveness Implementation is tricky and can be error- prone
Overview: Main Game Loop Execution order Most of the time it doesn't matter In some situations, execution order is important Can help keep player interaction seamless Can maximize parallelism Exact ordering depends on hardware
Game Entities What are game entities? Basically anything in a game world that can be interacted with More precisely, a self-contained piece of logical interactive content Only things we will interact with should become game entities Organization Simple list Multiple databases Logical tree Spatial database
Game Entities Updating Updating each entity once per frame can be too expensive Can use a tree structure to impose a hierarchy for updating Can use a priority queue to decide which entities to update every frame
Game Entities Object creation Basic object factories Extensible object factories Using automatic registration Using explicit registration
Game Entities Level instantiation Loading a level involves loading both assets and the game state It is necessary to create the game entities and set the correct state for them Using instance data vs. template data
Game Entities Identification Strings Pointers Unique IDs or handles
Game Entities Communication Simplest method is function calls Many games use a full messaging system Need to be careful about passing and allocating messages