• No results found

GAME CODING COMPLETE

N/A
N/A
Protected

Academic year: 2021

Share "GAME CODING COMPLETE"

Copied!
15
0
0

Loading.... (view fulltext now)

Full text

(1)

GAME CODING

COMPLETE

THIRD EDITION

Mike "MrMike" McShaffry et al

Charles River Media

A part of Course Technology, Cengage Learning

? COURSE TECHNOLOGY

1 % CENGAGE

(2)

CONTENTS

INTRODUCTION

XXVII

PART I: GAME PROGRAMMING FUNDAMENTALS

CHAPTER 1 WHAT is GAME PROGRAMMING REALLY LIKE?

The Good The Job The People

The Tools—Software Development Kits (SDKs) The Hardware

The Platforms The Show The Bad

Game Programming Is Freaking Hard Bits and Pieces

That's Not a Bug—That's a Feature The Tools

The Ugly

Hitting a Moving Target Crunch Mode (and Crunch Meals) Bah Humbug

Operating System Hell Fluid Nature of Employment Ifs All Worth It, Right?

4

5

6

7

8

8

11

12

12

12

14

15

16

16

17

18

18

19

20

CHAPTER 2 WHAT'S IN A GAME?

Game Architecture

Applying the Game Architecture Application Layer

Reading Input

File Systems and Resource Caching Managing Memory

Initialization, the Main Loop, and Shutdown Other Application Layer Code

21

22

24

26

27

27

28

29

29

xiij

(3)

Game Logic 31 Game State and Data Structures 31

Physics and Collision 32

Events 33 Process Manager 33 Command Interpreter 34 Game View for the Human Player 35

Graphics Display 36 Audio 38 User Interface Presentation 38

Process Manager 39 Options 39 Multiplayer Games 39

Game Views for Al Agents 40 Networked Game Architecture 41

Remote Game View 41 Remote Game Logic 42 Do I Have to Use DirectX? 43

Design Philosophy of DirectX 43 Direct3D or OpenGL 44 DirectSoundorWhat? 45 Directlnput or Roll Your Own ' 45

Other Bits and Pieces 46 Further Reading 46

CHAPTER 3 CODING TIDBITS AND STYLE THAT WILL SAVE You 47

Smart Design Practices 48 Avoiding Hidden Code and Nontrivial Operations 49

Class Hierarchies: Keep Them Flat 50 Inheritance Versus Containment 51 Virtual Functions Gone Bad 52 Use Interface Classes 53 Consider Using Factories 54 Use Streams to Initialize Objects 55 Smart Pointers and Naked Pointers 56

Reference Counting 56 Boost C++'s shared_ptr 58

(4)

Contents x v

Using Memory Correctly 61 Understanding the Different Kinds of Memory 62

Optimizing Memory Access 65 Memory Alignment 67 Virtual Memory 68 Writing Your Own Memory Manager 69

Mike's Grab Bag of Useful Stuff 72 An Excellent Random Number Generator 72

Supporting Optional Variables with OptionakT> 74

Pseudo-Random Traversal of a Set 78 Developing the Style That's Right for You 80

Further Reading 81

CHAPTER 4 BUILDING YOUR GAME 83

A Little Motivation 84 Creating a Project 85

Build Configurations 85 Create a Bullet-Proof Directory Structure 86

Where to Put Your Game Engine and Tools 88 Setting Visual Studio Build Options 89

Multiplatform Projects 91 Source Code Repositories and Version Control 93

Visual SourceSafe from Microsoft 94 Subversion and TortoiseSVN 95 Perforce by Perforce Software 96 AlienBrain from Avid 97 Using Source Control Branches 98 Building the Game: A Black Art? 100

Automate Your Builds 101 The Build Machine 102 Automated Build Scripts 102 Creating Buiid Scripts 104

Normal Build 104 Milestone Build 105 Multiple Projects and Shared Code 108

(5)

PART II: GET YOUR GAME RUNNING

CHAPTER 5 GAME INITIALIZATION AND SHUTDOWN

Initialization 101

Some C + + Initialization Pitfalls Exception Handling The Game's Application Layer

The Application Layer: GameCodeApp Initlnstancef): Checking System Resources Checking for Multiple Instances of Your Game Checking Hard Drive Space

Checking Memory Calculating CPU Speed What About Estimating VRAM? Do You Have a Dirtbag on Your Hands? Initialize Your Resource Cache

Your Script Manager and the Events System Initialize DirectX and Create Your Window Create Your Game Logic and Game View Create the DirectX D3D Device Load Your User Options and Save Game Stick the Landing: A Nice Clean Exit

How Do I Get Out of Here? Forcing Modal Dialog Boxes to Close Shutting Down the Game What About Consoles? Getting In and Getting Out

CHAPTER 6 CONTROLLING THE MAIN LOOP

Inside the Main Loop

Rendering and Presenting the Display

Your Callback Functions for Updating and Rendering Game Logic

A Simple Cooperative Multitasker

Examples of Classes that Inherit from CProcess More Uses of CProcess Derivatives

A Base Class for Game Actors and Game Logic Can I Make a Game Yet?

(6)

Contents xvii

CHAPTER 7 LOADING AND CACHING GAME DATA

Game Resources: Formats and Storage Requirements 3D Object Meshes and Environments Animation Data

Map/Level Data Texture Data Bitmap Color Depth

Video and Prerendered Cinematics Resource Files

Packaging Resources into a Single File Other Benefits of Packaging Resources Data Compression and Performance Zlib: Open Source Compression The Resource Cache

IResourceFile Interface

ResHandle: Tracking Loaded Resources ResCache: A Simple Resource Cache Caching Resources into DirectX, et al. World Design and Cache Prediction I'm Out of Cache

169

171 172 174 175 175 176 179 182 183 183 184 185 190 192 193 194 200 200 204

CHAPTER 8 PROGRAMMING INPUT DEVICES

Getting the Device State Using Directlnput A Few Safety Tips

Working with the Mouse (and Joystick) Capturing the Mouse

Making a Mouse Drag Work Working with a Game Controller

Dead Zones Normalizing Input

One Stick, Two Stick, Red Stick, Blue Stick Ramping Control Values

Working with the Keyboard Mike's Keyboard Snooper GetAsyncKeyStateO and Other Evils Handling the Alt Key Under Windows What, No Dance Pad?

205

206 209 211 214 214 217 220 220 223 225 226 226 227 231 232 232

(7)

CHAPTER 9 USER INTERFACE PROGRAMMING 233

The Human's Game View 234 A WASD Movement Controller 244

Screen Elements 247 A Custom MessageBox Dialog 249

Modal Dialog Boxes 254

Controls 259 Control Identification 260

Hit Testing and Focus Order 261

Control State 263 More Control Properties 264

Hot Keys 264 Tooltips 265 Context-Sensitive Help 265

Dragging 266 Sounds and Animation 266

Some Final User Interface Tips 266

PART III: CORE GAME TECHNOLOGIES

CHAPTER 10 GAME EVENT MANAGEMENT 271

Game Events 272 Events and Event Data 273

The Event Listener 279 The Event Manager 283 Further Work 301 What Game Events Are Important? 301

Distinguishing Events from Processes 303

Further Reading 303

CHAPTER 11 SCRIPTING WITH LUA 305

What Is Scripting? 306 Data-Driven Software Design 307

Data Definition Versus Runtime Game Control 307 Pros and Cons of Using a Scripting Language 308

Common Scripting Paradigms 309 Data Definition Only 309 Graphical 309 Interpreted Script Languages 309

(8)

Contents x i x

Introducing Lua 310 Lack of Strang Typing 311

Tables 312 Metatables 314 Garbage Collection 315 Virtual Machines 315 Getting Started with a Lua Wrapper—LuaPlus 315

Where to Get LuaPlus 315 Are We Actually Going to Write Some Code Now? 316

Mind the Gap! 318 What Lives in Code, and What Lives in Script? 318

From Code to Script and Back Again 319

Wanna Buy a Bridge? 320 I'm Totally Wired 321

Additions to the Event Data Class 323

Registering Events 323 Serializing Events for Code and Script 331

Do You Hear What I Hear? 333 Script-Side Listeners 334 Creating a ScriptEventListener 336 Triggering an Event from Script 338

Let's Get OOP-Able! 338 Script Actor Listeners 340 Debugging Script 343 Caveman Debugging 344 Console 344 Symbolic Debuggers 345 Integrated Debuggers 345 External Debuggers 345 Introducing Decoda 346 Famous Last Words: "An Exercise for the Reader" 347

Pitfalls 347 Further Study 348 Special Thanks 350 References 350 Online 350 Books 351

(9)

CHAPTER 12 GAME AUDIO 353

How Sound Works 354 Digital Recording and Reproduction 356

Sound Files 357 A Quick Word About Threads and Synchronization 358

Game Sound System Architecture 359 Sound Resources and Handles 360 lAudioBuffer Interface and AudioBuffer Class 372

lAudio Interface and Audio Class 375 DirectSound Implementations 378

Sound Processes 391 Launching Sound Effects 396 Other Technical Hurdles 397

Sounds and Game Objects 397 Timing and Synchronization 397

Mixing Issues 399 Some Random Notes 401

Data-Driven Sound Settings 402 Background Ambient Sounds and Music 402

Speech 403 The Last Dance 406

CHAPTER 13 3D BASICS 407

3D Graphics Pipeline 408 3D Math 101 409

Coordinates and Coordinate Systems 410

Vector Mathematics 413 C + + Math Classes 419 Vector Classes 419 Matrix Mathematics 421 Quaternion Mathematics 431 View Transformation 436 Projection Transformation 437 Enough Math—Please Stop 439

Triangles 439 Lighting, Normals, and Color 441

Textured Vertices 444 Other Vertex Data 445

(10)

Contents xxi

Triangle Meshes 445 Indexed Triangle Meshes 448

Materials 452 Texturing 455 Subsampling 456 Mip-Mapping 458 3D Graphics—It's Just the Beginning 459

CHAPTER 14 3D SCENES 4 6 1

The Plane Class 462 The Frustum Class 463 Scene Graph Basks 468

ISceneNode Interface Class 468 SceneNodeProperties and RenderPass 471

SceneNode—It All Starts Here 473 The Scene Graph Manager Class 480 Special Scene Graph Nodes 488

Implementing Separate Render Passes 488

A Simple Camera 491 Building and Rendering Simple Geometry 494

Rendering the Sky 498 Using Meshes in Your Scene 503

What About Shaders? 508 The .FX File 509 The EffectManager Class 514

The ShaderMeshNode Class 516

What's Missing? 519 Still Hungry? 520 Further Reading 521

CHAPTER 15 COLLISION AND SIMPLE PHYSICS 5 2 3

Mathematics for Physics Refresher 525 Meters, Feet, Cubits, or Kellicams? 525 Distance, Velocity, and Acceleration 526 Mass, Acceleration, and Force 527 Rotational Inertia, Angular Velocity, and Torque 530

Distance Calculations and Intersections 531

Choosing a Physics SDK 532 Object Properties 534

(11)

Collision Hulls 535 Requirements of Good Collision Geometry 535

Visible Geometry Versus Collision Geometry 537 Collision Hulls for Human Characters 538 Special Objects: Stairs, Doorways, and Trees 540

Using a Collision System 541 Integrating a Physics SDK 543

Components of the Bullet SDK 547 Receiving Collision Events 560 A Final Word on Integrating Physics SDKs 562

But Wait, There's So Much More 563

CHAPTER 16 NETWORK PROGRAMMING PRIMER 565

How the Internet Works 566 Winsock or Berkeley? 567 Internet Addresses 568 The Domain Name System 570 Useful Programs and Files 572

Sockets API 572 Sockets Utility Functions 573

Domain Name Service (DNS) Functions 575 Sockets Initialization and Shutdown 576 Creating Sockets and Setting Socket Options 577

Server Functions 582 Socket Reading and Writing 585

Making a Multiplayer Game with Sockets 586

Packet Classes 587 Core Socket Classes 590 A Socket Class for Listening 599 A Socket Manager Class 601 Core Client-Side Classes 610 Core Server-Side Classes 611 Wiring Sockets into the Event System 612

(12)

Contents

xxiii

PART IV: ADVANCED TOPICS AND BRINGING IT ALL TOGETHER

CHAPTER 17 AN INTRODUCTION то GAME Al 623

Intro to Al concepts 624 Movement 625 Path Finding 627

A* (A-Star) 633 Making a Professional Game 640

Simple Decision Making 641 State Machines 642 Making a Professional Game 650

Advanced Decision Making 651 Fuzzy Logic 651 Goal-Oriented Agents 652 Types of Game Al 653

Simple Action Games and Platformers 653

Shooters 653 Strategy Games 653 Role-Playing Games 654 Further Reading 654

CHAPTER 18 INTRODUCTION TO MULTIPROGRAMMING 655

What Multiprogramming Does 656

Creating Threads 658 Process Synchronization 660

Test and Set, the Semaphore, and the Mutex 661

The Win32 Critical Section 662 Interesting Threading Problems 663

Thread Safety 665 Multithreading Classes 665

The RealtimeProcess Class 666 Sending Events from Real-Time Processes 669

The RealtimeEventListener Class 672 Background Decompression of a ZIP File 673

Further Work 676 About the Hardware 677 About the Future 678

(13)

CHAPTER 19 A GAME OF TEAPOT WARS! 679

Game Actors 681 The ActorParams Class 683

TeapotParams and TeapotMeshNode Classes 690 How About GridParams and SphereParams? 696

Game Events 696 The Application Layer 701 The Game Logic 703

The TeapotWarsGame Class 706 The TeapotWarsEventListener Class 715 The Game View for a Human Player 722

The ScreenElementScene Class 723 The TeapotWarsGameView Class 723 The TeapotWarsGameViewListener Class 731

The Teapot Controller 734 The Al View and Listener 736 More Teapot Wars, if You Are Willing 739

CHAPTER 20 A SIMPLE GAME EDITOR IN C# 741

What Should a Level Editor Do? 742

WhyC#? 742 How the Editor Is Put Together 742

The Editor Architecture 743 The Application Layer 743 The Editor's Logic Class 744 The Editor View 748 Wrapping Up the Editor Architecture 751

Differences Between Managed-Code Land and Unmanaged-Code Land 752

Functions to Access the Editor Game Engine 752

Creating the DLL 755 The C# Editor Application 756

C# Basic Editor App 757 C# NativeMethods Class 758 The EngineDisplayForm Class 759 The C# MessageHandler Class 762 The C# Program Class 765

(14)

Contents x x v

Getting Information About Actors in the Level 766 Adding Accessor Functions to the Editor Game Engine 767

Adding Functions to the Editor DLL 771 Displaying Actor Properties in the Editor 772 Creating, Changing, and Removing Actors 778

The ActorCreationForm Class 781 Adding Actor Update Methods to ActorPropertiesForm 786

Saving and Loading Levels 787

Future Work 795 Special Thanks 795 Further Reading 796

Online 796

CHAPTER 21 DEBUGGING YOUR GAME 797

The Art of Handling Failure 799 Debugging Basics 801

Using the Debugger 803 Installing Windows Symbol Files 806

Debugging Full-Screen Games 808 Remote Debugging 809 Debugging Minidumps 811 Debugging Techniques 817

Debugging Is an Experiment 818 Reproducing the Bug 821 Eliminating Complexity 822 Setting the Next Statement 823 Assembly Level Debugging 824 Peppering the Code 827 Draw Debug Information 828 Lint and Other Code Analyzers 829 Nu-Mega's BoundsChecker and Runtime Analyzers 829

Disappearing Bugs 829 Tweaking Values 830 Caveman Debugging 830 When All Else Fails 832 Different Kinds of Bugs 832

Memory Leaks and Heap Corruption 833

(15)

Stack Corruption 839 Cut and Paste Bugs 839 Running Out of Space 840 Release Mode Only Bugs 841 Multithreading Gone Bad 841

Weird Ones 842 Parting Thoughts 844 Further Reading 844

CHAPTER 22 DRIVING TO THE FINISH 845

Finishing Issues 847 Quality 847 Code 850 Content 854 Dealing with Big Trouble 855

Projects Seriously Behind Schedule 856 Personnel-Related Problems 863 Your Competition Beats You to the Punch 865

There's No Way Out—or Is There? 866 One Last Word—Don't Panic 866 The Light—It's Not a Train After All 867

Test the Archive 868 The Patch Build or the Product Demo 868

The Post-Mortem 869 What to Do with Your Time 870

References

Related documents

The Main Toolbar (at the top of the screen) has buttons that invoke a variety of commands and options, including create a new problem, open an input file, save an input file,

The editor allows developers to create adventure games without the assistance of specialists using built-in assets and game logic.. The production of the editor is still in

Now that you have defined the objects with their behavior in the form of events and actions, it is time to create the rooms or levels in which the game takes place. Any game will

Projects must be saved as a game maker project file (FILE  SAVE) and as a executable file (FILE  CREATE EXECUTABLE).. Both versions of the project must be emailed to

If you need to perform maintenance on a device, you can set a maintenance window in which Toolset Network Performance Monitor stops polling the device, does not create events about

You can also save your game progress at any time while playing by first pressing the START button, and then selecting Save from the Pause Menu (see Pause Menu on page 10).. You can

Fixed a rare issue where the laundry room would not load and you would fall through the floor Fixed the in game menu options for resolution and texture detail options, so they now

streaming events to bring friends, family and coaches the live game experience in high definition from any device, anywhere in the world.. Come be a part of our growing