3D Game Development with Microsoft Silverlight 3: Beginner's Guide - Gaston C. Hillar - E-Book

3D Game Development with Microsoft Silverlight 3: Beginner's Guide E-Book

Gastón C. Hillar

0,0
39,59 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Microsoft Silverlight is a programmable web browser plug-in that enables the animation, vector graphics, and audio-video playback features that characterize Rich Internet Applications. Silverlight is a great (and growing) RIA platform and games are the next level to exploit in it. But it doesn't offer 3D capabilities out of the box and integrating a 3D engine can involve lot of complex mathematics and matrix algebra. This book will help C# developers to get their fingers on the pulse of 3D in Silverlight.
This book uses Balder, an open source 3D engine offering 3D capabilities for Silverlight 3. It leaves out boring matrix algebra and complex 3D mathematics. By the end of the book you will have explored the entire engine, and will be able to design and program your own 3D games with ease!
The book begins by introducing you to the fundamental concepts of 2D games and then drives you into the 3D world, using easy-to-follow, step-by-step examples. The book employs amazing graphics and impressive performance, and increasingly adds more features to a 3D game giving you a rich interactive experience.
By following the practical examples in this book, you will learn the important concepts, from the creation of the initial models, up to the addition of physics and artificial intelligence.
The book helps you to provide realistic behaviors for 3D characters by enveloping models with different textures, using lights to create effects, animating multiple 3D characters using a physics engine (Farseer Physics Engine), and simulating real-life physics. Videos, music, and sounds associated with specific events offer the final touches to the 3D game development learning experience.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB

Seitenzahl: 476

Veröffentlichungsjahr: 2009

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

3D Game Development with Microsoft Silverlight 3 Beginner's Guide
Credits
About the Author
Acknowledgement
About the Reviewer
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code for the book
Errata
Piracy
Questions
1. Lights, Camera, and Action!
UFOs in the sky!: Invaders
Time for action—preparing the development environment
What just happened?
Time for action—recognizing digital art assets
What just happened?
Time for action—creating the raster digital content
What just happened?
Digital Content Creation tools
Basic elements of a 2D and/or 3D real-time game
Programming responsibilities
Time for action—installing tools to manipulate scalable digital content
What just happened?
XAML works fine with Silverlight 3
Time for action—creating the scalable digital content in XAML
What just happened?
Previewing and scaling XAML vector graphics
Time for action—testing the scalable digital content using XamlPad
What just happened?
Editing vector illustrations using Expression Design
Have a go hero—preparing scalable digital content for a new remake
Preparing a gaming framework
Time for action—creating Silverlight applications
What just happened?
Time for action—building and running Silverlight applications
What just happened?
Programming event handlers in the main page
Time for action—creating XBAP WPF applications
What just happened?
Time for action—building and running the XBAP WPF applications
What just happened?
Have a go hero—creating a prototype for the remake
Pop quiz—preparing the digital content
Summary
2. Working with 2D Characters
Creating an accelerated graphics viewport
Time for action—enabling hardware acceleration
What just happened?
Time for action—transforming media using the GPU
What just happened?
Caching rendered content
Scaling and rotating a vector-based illustration
Time for action—shaking many illustrations at the same time
What just happened?
Running loops faster
Accelerating transforms and blends
Using 2D vectors
Time for action—detecting GPU-acceleration problems
What just happened?
Understanding GPU acceleration limitations
Creating encapsulated object-oriented characters
Time for action—creating User Control classes to hold images
What just happened?
Time for action—displaying images and sprites
What just happened?
Showing a sprite on the screen
Defining the behavior
Understanding dimensions
Managing resolutions
Screen resolutions
Have a go hero—completing the animation
Pop quiz—working with sprites and the GPU
Summary
3. Combining Sprites with Backgrounds
The first remake assignment
Time for action—creating sprites based on XAML vector-based graphics
What just happened?
Defining the relative center point
Time for action—creating a specialized sprite management class
What just happened?
Taking full advantage of object-oriented capabilities
Preparing the classes for inheritance
Wrapping a UserControl to manage it
Time for action—creating a superclass for some characters
What just happened?
Time for action—creating the subclasses for the characters
What just happened?
Time for action—creating methods for the game loop
What just happened?
Creating objects on the fly
Managing dynamic objects
Time for action—writing the game loop
What just happened?
Animating multiple sprites
Managing a complex game loop
Time for action—detecting collisions between 2D characters
What just happened?
Using colors to paint sprites
Have a go hero—using backgrounds
Have a go hero—preparing Invaders 3000
Pop quiz—simplifying game loops
Summary
4. Working with 3D Characters
The second remake assignment
Time for action—exporting a 3D model without considering textures
What just happened?
XAML 3D models
Time for action—from DCC tools to WPF
What just happened?
XBAP WPF applications with 3D content
Time for action—displaying a 3D model in a 2D screen with WPF
What just happened?
Understanding the 3D world
X, Y, and Z in practice
GPU 3D acceleration
Understanding meshes
Time for action—using other XAML exporter for DCC tools
What just happened?
Time for action—adding 3D elements and interacting with them using Expression Blend
What just happened?
Interacting with 3D elements using Expression Blend
Silverlight and the 3D world
Time for action—exporting a 3D model to ASE
What just happened?
Time for action—installing Balder 3D engine
What just happened?
Time for action—from DCC tools to Silverlight
What just happened?
Displaying a 3D model in a 2D screen with Silverlight
Using 3D vectors
Have a go hero—working with multiple 3D characters
Pop quiz—3D models and real-time rendering
Summary
5. Controlling the Cameras: Giving Life to Lights and Actions
Understanding 3D cameras
Time for action—when seeing is believing
What just happened?
Controlling the position, the direction, and the up vector
Time for action—performing transformations
What just happened?
Defining and applying transformations
Time for action—zooming in and out
What just happened?
Controlling the perspective field of view
Controlling the clipping planes
Time for action—understanding perspective and orthographic cameras
What just happened?
Have a go hero—rotating cameras around a 3D model
Silverlight and the cameras
Time for action—controlling cameras on the fly
What just happened?
Understanding cameras related to matrixes
Have a go hero—working with many cameras
Pop quiz—working with cameras in a 3D world
Summary
6. Controlling Input Devices to Provide Great Feedback
Giving life to the game!
Time for action—creating a keyboard manager class
What just happened?
Using the keyboard
Time for action—programming the input control in the game loop
What just happened?
Time for action—mapping a gamepad to the keyboard
What just happened?
Understanding the gamepad as an input device
Time for action—using the gamepad
What just happened?
Time for action—creating a mouse manager class
What just happened?
Using the mouse
Time for action—using the mouse manager in the game loop
What just happened?
Time for action—using the gamepad as a mouse
What just happened?
Time for action—rotating cameras using input devices
What just happened?
Have a go hero—taking full advantage of the gamepad
Bridging with DirectInput capabilities
Time for action—installing the necessary SDKs
What just happened?
Considering deployment's additional requirements
Time for action—understanding sticks and buttons
What just happened?
Understanding the steering wheel as an input device
Time for action—testing the input devices with a DirectInput wrapper
What just happened?
Understanding the analog axis for a steering wheel
Understanding the analog axis for a gamepad
Time for action—adapting a joystick manager class
What just happened?
Time for action—using the steering wheel in the game loop
What just happened?
Using the joystick manager
Working with many input devices
Using other input devices
Have a go hero—using the Wiimote
Have a go hero—working with time, analog and digital values
Pop quiz—working with gaming input devices
Summary
7. Using Effects and Textures to Amaze
Dressing characters using textures
Time for action—adding textures in DCC tools
What just happened?
Time for action—exporting 3D models from DCC tools to Silverlight
What just happened?
Displaying a 3D model using textures in a 2D screen with Silverlight
Time for action—enveloping 3D models
What just happened?
Understanding textures
Repeating textures as tiles
Time for action—replacing textures
What just happened?
Have a go hero—playing with textures
Displaying lights, shadows, materials, and textures
Time for action—working with lights and understanding shadows
What just happened?
Understanding different kinds of lights
Have a go hero—creating effects using lights
Pop quiz—working with textures, materials, and lights
Summary
8. Animating 3D Characters
Invaders 3D
Time for action—adding a UFO
What just happened?
Time for action—creating a new game superclass to generalize time management capabilities
What just happened?
Time for action—specializing a game superclass
What just happened?
Time for action—creating a subclass for a 3D character
What just happened?
Using an Actor to represent a 3D character
Time for action—adding an Actor to the game
What just happened?
Moving 3D characters as Actors
Time for action—rotating 3D characters
What just happened?
Using the World matrix in order to perform transformations to meshes
Performing compound transformations
Time for action—scaling 3D characters
What just happened?
Using the World matrix in order to scale meshes
Have a go hero—creating a specialized XAML 3D character wrapper class
Using bones and skeletons
Time for action—animating models with skeletons and bones
What just happened?
Using skeletons and bones
Time for action—adding an Actor with skeletons and bones to the game
What just happened?
Understanding complex 3D animation techniques
Have a go hero—aliens walking
Pop quiz—animating 3D characters in a scene
Summary
9. Adding Realistic Motions Using a Physics Engine
Using physical principles in games to beat invaders
Time for action—installing Farseer Physics Engine
What just happened?
Time for action—adding parallel physics bodies and geometries to 3D characters
What just happened?
Creating bodies
Creating geometries
Updating a 3D model according to the associated body's properties
Time for action—working with forces, impulses, acceleration and speed
What just happened?
Specifying the gravitational force
Applying forces
Applying impulses
Working with a 2D physics simulator in the game loop
Time for action—working with torques and rotations
What just happened?
Applying torques
Translating 2D physics to a 3D world
Working with Farseer Physics Engine in XBAP WPF applications
Have a go hero—circles are not rectangles
Have a go hero—applying particle systems
Pop quiz—working with bodies, geometries, and physics
Summary
10. Applying Artificial Intelligence
Detecting collisions between 3D characters
Time for action—adding a second UFO
What just happened?
Time for action—detecting collisions between 3D characters
What just happened?
Working with advanced responses to collisions
Controlling collision moments using events
Working with collision categories
Using engines to improve collision detection precision
Have a go hero—3D Moon Lander
Using artificial intelligence in games to control 3D characters
Time for action—using chasing algorithms
What just happened?
Working with states for the characters
Pursuing an enemy
Generating and controlling random situations
Time for action—using evasion algorithms
What just happened?
Evading an enemy
The advantages of using an AI engine
Have a go hero—adding complex AI algorithms
Pop quiz—working with collision detection and artificial intelligence
Summary
11. Applying Special Effects
Working with 3D characters in the background
Time for action—adding a transition to start the game
What just happened?
Time for action—creating a low polygon count meteor model
What just happened?
Time for action—from 3D Studio Max to Silverlight
What just happened?
Time for action—creating a subclass for a 3D meteor
What just happened?
Time for action—creating and controlling a meteor rain
What just happened?
Advantages of using multiple physics engines
Time for action—simulating fluids with movement
What just happened?
Simulating waves
Time for action—creating a subclass for a complex asteroid belt
What just happened?
Using an Actor to represent a wave in the background
Time for action—adding an asteroid belt background to the game
What just happened?
Working with encapsulated physics controllers
Have a go hero—adding dissolutions, fire, smoke, and explosions
Pop quiz—working with special effects
Summary
12. Controlling Statistics and Scoring
Showing gauges and scorecards
Time for action—using special fonts
What just happened?
Embedding fonts in the project
Time for action—creating a score gauge showing text
What just happened?
Using Expression Blend to create 2D gauges
Time for action—showing a score gauge
What just happened?
Calculating, saving, and showing statistics
Time for action—creating a bonus gauge showing text
What just happened?
Time for action—creating a fuel gauge
What just happened?
Time for action—creating a remaining lives gauge
What just happened?
Using a panel to show many aligned user controls
Time for action—showing and updating multiple gauges
What just happened?
Working with multiple gauges
Have a go hero—adding gauges for multiplayer games
Pop quiz—working with special fonts and gauges
Summary
13. Adding Environments and Scenarios
Working with levels and stages
Time for action—installing Windows Presentation Foundation Pixel Shader Effects Library
What just happened?
Time for action—adding screens to organize the game
What just happened?
Time for action—applying transition effects
What just happened?
Rendering a WriteableBitmap and using it as an ImageBrush
Creating a StoryBoard
Working with a StoryBoard to animate an effect
Time for action—changing the transition effect
What just happened?
Exploring transition effects
Working with multiple transition effects
Time for action—using skill levels
What just happened?
Time for action—changing and improving the environments according to the skill level
What just happened?
Retrieving values for parameters using LINQ to XML
Time for action—saving configurations
What just happened?
Have a go hero—displaying amazing menus with configuration options
Have a go hero—showing stages
Pop quiz—avoiding the GAME OVER screen
Summary
14. Adding Sound, Music, and Video
Hear the UFOs coming
Time for action—installing tools to manipulate videos
What just happened?
Time for action—preparing a video to use it in Silverlight
What just happened?
Video formats supported in Silverlight 3
Using free applications to convert video formats
Time for action—reproducing videos
What just happened?
Locating videos in a related web site
Stretching videos
Taking advantage of GPU acceleration to scale videos
Time for action—applying projections
What just happened?
Time for action—animating projections
What just happened?
Working with a StoryBoard in XAML to animate a projection
Time for action—solving navigation problems
What just happened?
Time for action—reproducing music
What just happened?
Time for action—preparing audio files to use them in Silverlight
What just happened?
Audio formats supported in Silverlight 3
Using free applications to convert audio formats
Time for action—creating a class to handle audio concurrency
What just happened?
Using a round robin algorithm to work with concurrent sounds
Time for action—generating sounds associated to game events
What just happened?
Have a go hero—animating the game over scene
Have a go hero—configuring sounds and music
Pop quiz—working with audio and video in Silverlight 3
Summary
A. Pop quiz—Answers
Index

3D Game Development with Microsoft Silverlight 3 Beginner's Guide

Gastón C. Hillar

3D Game Development with Microsoft Silverlight 3 Beginner's Guide

Copyright © 2009 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: September 2009

Production Reference: 1180909

Published by Packt Publishing Ltd.

32 Lincoln Road

Olton

Birmingham, B27 6PA, UK.

ISBN 978-1-847198-92-1

www.packtpub.com

Cover Image by Gastón Hillar and Adline Swetha Jesuthas

Cover image for illustrative purposes only.

Credits

Author

Gastón C. Hillar

Reviewers

Tarkan Karadayi

Richard Griffin

Acquisition Editor

James Lumsden

Development Editor

Darshana D. Shinde

Technical Editor

Arani Roy

Copy Editor

Sneha Kulkarni

Indexer

Hemangini Bari

Editorial Team Leader

Abhijeet Deobhakta

Project Team Leader

Priya Mukherji

Project Coordinator

Zainab Bagasrawala

Proofreader

Lesley Harrison

Graphics

Nilesh R. Mohite

Production Coordinators

Aparna Bhagat

Shantanu Zagade

Cover Work

Aparna Bhagat

About the Author

Gastón C. Hillar has been working with computers since he was eight. He began programming with the legendary Texas TI-99/4A and Commodore 64 home computers in the early 80's.

He has a Bachelor's degree in Computer Science in which he graduated with honors, and he also has an MBA (Master in Business Administration) in which graduated with an outstanding thesis. He has worked as a developer, an architect, and project manager for many companies in Buenos Aires, Argentina. Now, he is an independent IT consultant and a freelance author always looking for new adventures around the world. He also works with electronics (he is an electronics technician). He is always researching new technologies and writing about them. He owns an IT and electronics laboratory with many servers, monitors, and measuring instruments.

He has written another book for Packt, "C# 2008 and 2005 Threaded Programming: Beginner's Guide".

He contributes to Dr. Dobb’s Go Parallel programming portal http://www.ddj.com/go-parallel/ and he is a guest blogger at Intel Software Network http://software.intel.com

He is the author of more than 40 books in Spanish about computer science, modern hardware, programming, systems development, software architecture, business applications, balanced scorecard applications, IT project management, the Internet, and electronics.

He usually writes articles for the Spanish magazines "Mundo Linux", "Solo Programadores" and "Resistor".

He lives with his wife, Vanesa, and his son, Kevin. When not tinkering with computers, he enjoys developing and playing with wireless virtual reality devices and electronics toys with his father, his son, and his nephew Nico.

You can reach him at: <[email protected]>

You can follow him on Twitter at: http://twitter.com/gastonhillar

Gastón's blog is at: http://csharpmulticore.blogspot.com

Acknowledgement

While writing this book, I was fortunate enough to work with an excellent team at Packt Publishing Ltd, whose contributions vastly improved the presentation of this book. James Lumsden helped me to transform the idea in the final book and to take my first steps working with a new Beginner's Guide. Zainab Bagasrawala made everything easier with both her incredible time management and patience. Darshana Shinde helped me realize my vision for this book and provided many sensible suggestions regarding the text, the format and the flow. The reader will notice her great work. Arani Roy made the sentences, the paragraphs, and the code easier to read and to understand. He has added great value to the final drafts.

Special thanks go to Einar Ingebrigtsen (http://www.ingebrigtsen.info), Balder's lead developer. Einar's work inspired this book. He made it possible to have a game engine for Silverlight 3. This book was possible because Einar helped me with each new feature added to Balder. His outstanding knowledge on game development made it possible to work with an excellent engine. I also have to thank Petri Wilhelmsen, another Balder's developer who also helped to improve the engine. I would like to thank my technical reviewers and proofreaders, for their thorough reviews and insightful comments. I was able to incorporate some of the knowledge and wisdom they have gained in their many years in the software development industry. The examples, the pictures and the code include the great feedback provided by Tarkan Karadayi. Tarkan helped me a lot to include better and shorter code to simplify the learning process. I would like to thank Mark Dawson, Kit3D's developer. Mark's work also inspired the development of many simple 3D applications using previous Silverlight versions and his simple yet powerful engine. I wish to acknowledge Bill Reiss, as he worked to show the world that Silverlight games were possible. He was another great source of inspiration for my work on this book. I would like to thank Doug Holland, as his blog posts at Intel Software Network always helped me to stay tuned with tips related to many products used in this book.

I must acknowledge David Barnes, Beginner's Guide Series Editor at Packt. His help in my previous book and his wisdom is also part of this new one. I must also thank Shilpa Dube, Rakesh Shejwal and Rajashree Hamine. They helped me in my previous book written for Packt and this new one was much easier bearing in mind their excellent tips.

I wish to acknowledge Hector A. Algarra, who always helped me to improve my writing.

Special thanks go to my wife, Vanesa S. Olsen, my son Kevin, my nephew, Nicolas, my father, Jose Carlos, who acted as a great sounding board and participated in many hours of technical discussions, my sister, Silvina, who helped me when my grammar was confusing and my mother Susana. They were always supporting me during the production of this book.

About the Reviewer

Tarkan Karadayi has been writing code since age 14. He has a Masters in Computer Science and is currently working as a Lead Developer.

I would like to thank my wife Anna, my parents and my three sons Taran, Kyle, and Ryan for their love and support.

I would like to dedicate this book to my son Kevin and my wife Vanesa

Preface

Most online interactive content uses 2D graphics. To represent real-life situations, Rich Internet Applications (RIAs) need to show real-time 3D scenes. This book will let you add a new dimension to your Silverlight applications using C# and XAML. The book covers the various tools and libraries needed for giving life to 3D models in a Silverlight viewport—right from editing, exporting, loading, and controlling 3D models up to specific 3D algorithms. It will help you learn to develop 3D games and interactive 3D scenes for a web site with animated models, with numerous examples and clear explanations packed with screenshots to aid your understanding of every process. After all of the code is written and the additional art assets edited, they are all compressed into .zip files for easy availability and use.

What this book covers

Chapter 1: Lights, Camera, and Action!: In this chapter, we will cover many topics that will help us to understand the new tools and techniques involved in preparing 2D graphics to be used in Silverlight games. This chapter is all about tools and graphics.

Chapter 2: Working with 2D Characters: In this chapter, we will begin creating 2D characters that move on the screen and we will learn to control their behavior in the 2D space. We will learn about GPU hardware acceleration, 2D vectors, resolutions, sprites, and animation.

Chapter 3: Combining Sprites with Backgrounds: In this chapter, we will control multiple sprites created on demand. We will animate several independent sprites at the same time, while responding to the keys pressed by the player to control characters and some game logic.

Chapter 4: Working with 3D Characters: In this chapter, we will take 3D elements from popular and professional 3D DCC tools and we will show them rendered in real-time on the screen. We will learn a lot about 3D models, meshes, and 3D engines.

Chapter 5: Controlling the Cameras: Giving Life to Lights and Actions: In this chapter, we will learn everything we need to know about 3D cameras to be able to render our models in real-time on a 2D screen from different angles. We will change the values for their most important properties and we will be able to watch their effects in a rendered 3D view.

Chapter 6: Controlling Input Devices to Provide Great Feedback: In this chapter, we will learn everything we need to know about the most widely used gaming input devices. We will be able to read values from them in order to control many aspects of our games.

Chapter 7: Using Effects and Textures to Amaze: In this chapter, we will learn everything we need to know about the process of enveloping a 3D model using textures. We will be able to take 3D elements from popular and professional 3D DCC tools and we will show them rendered in real-time on the screen with different textures and enlightened by many lights.

Chapter 8: Animating 3D Characters: In this chapter, we will learn how to move, rotate, and scale the 3D models in the 3D scenes. We will use object-oriented capabilities to define independent behaviors for simple and complex 3D characters.

Chapter 9: Adding Realistic Motions Using a Physics Engine: In this chapter, we will simulate some laws of 2D and 3D physics. We will learn to define gravity force, mass, drag coefficients, and moment of inertia to represent the physical properties of the bodies that define a model.

Chapter 10: Applying Artificial Intelligence: In this chapter, we will detect collisions between 3D characters and we will define specific behaviors using artificial intelligence, persecution, and evasion algorithms

Chapter 11: Applying Special Effects: In this chapter, we will use advanced physics and special effects. We will generate gravity effects, we will add fluids with movements, and we will use transitions to determine different states in a game.

Chapter 12: Controlling Statistics and Scoring: In this chapter, we will create gadgets to display different kinds of information to the player on the screen. We will also calculate different kinds of information in order to update the gauges. Also, we will measure and improve the game’s overall performance.

Chapter 13: Adding Environments and Scenarios: In this chapter, we will create menus and attractive transitions. We will add configuration options and we will save them using an isolated storage.

Chapter 14: Adding Sound, Music, and Video: In this chapter, we will generate sounds associated to game events. We will also add presentation videos and background music.

Appendix: Pop Quiz Answers: This appendix will include answers to all the pop quiz questions chapter-wise.

What you need for this book

You will need Visual C# 2008 (.NET Framework 3.5) with Service Pack 1, or greater—Visual C# 2010—installed.

You can use the free Visual Web Developer 2008 Express Edition or greater (http://www.microsoft.com/express/vwd/). However, you have to read the documentation to consider its limitations carefully.

Who this book is for

This book is designed primarily for C# developers with a basic knowledge of Visual Studio IDE who want to develop online 3D games using Silverlight, or create interactive 3D scenes for a web site with animated models. No prior experience in 3D programming, 3D animation, and Silverlight is required.

The book is also aimed at 3D developers who want to improve their online content by offering innovative 3D models in action.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.

To send us general feedback, simply send an email to <[email protected]>, and mention the book title via the subject of your message.

If there is a book that you need and would like to see us publish, please send us a note in the SUGGEST A TITLE form on www.packtpub.com or email <[email protected]>.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book on, see our author guide on www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code for the book

Visit http://www.packtpub.com/files/code/8921_Code.zip to directly download the example code.

The downloadable files contain instructions on how to use them.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration, and help us to improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/support, selecting your book, clicking on the let us know link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata added to any list of existing errata. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.

Piracy

Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works, in any form, on the Internet, please provide us with the location address or web site name immediately so that we can pursue a remedy.

Please contact us at <[email protected]> with a link to the suspected pirated material.

We appreciate your help in protecting our authors, and our ability to bring you valuable content.

Questions

You can contact us at <[email protected]> if you are having a problem with any aspect of the book, and we will do our best to address it.

Chapter 1. Lights, Camera, and Action!

We want to develop 3D games using Silverlight 3. We will need to work hard in order to achieve this exciting goal. First, we must understand some fundamentals related to various tools and 2D graphics, and their relevance to Silverlight 3. In this chapter, we will cover many topics that will help us understand the new tools and techniques involved in preparing 2D graphics to be used in Silverlight games. This chapter is all about graphics.

In this chapter, we will:

Prepare a development environment to develop games using Silverlight 3Recognize the digital art assets from an existing gameCreate and prepare the digital content for a new 2D gameUnderstand the tools involved in a 2D game development processLearn to manipulate, preview, and scale the digital contentBuild and run our first graphics application using the digital content

UFOs in the sky!: Invaders

You love 3D games. You have always wanted to develop a 3D game with amazing characters, dazzling scenarios, outstanding effects, and many skill levels. And now you have the opportunity. A legendary game developer drives a new game contest. He challenges Silverlight developers to show him some ideas for a modern 2D Invaders game. If he likes a developer's idea, he will contract him to develop 3D games for his well-known gaming web site using Silverlight 3. This web site pays high wages to developers. It is an incredible opportunity and you cannot miss this train. Tickets, please!

Developing 3D games is an exciting process, but it is also difficult. However, working with a 2D game before moving into the 3D world is a nice starting point. That is exactly what we are going to do.

During our journey, we will need to exploit our creativity as much as possible. Game development requires many heterogeneous skills. However, the most important ingredient is creativity.

We already know how to develop some applications using the C# programming language. However, RIAs (Rich Internet Applications) offer an exciting way ahead for game development because they provide a rich experience for users without the need to install software on their computers. Users expect RIAs to be like conventional downloadable games that offer amazing graphics, impressive performance, and a very interactive experience. Silverlight is a great (and growing) RIA platform, and games are the next level to exploit in Silverlight. 3D games represent our challenge in this book and we shall take full advantage of our C# knowledge here.

So, let's take our C#, XAML, and Silverlight development skills to the next level. We want to take full advantage of modern technologies. First of all, we must install the latest tools and begin working on some 2D games' basics. Later, we will use that knowledge in developing 3D games using Silverlight 3, the newest kid on the block from Microsoft.

The only requirements needed to develop 3D games using Silverlight are to understand the basics of the C# programming language, XAML code, and the Visual Studio IDE. We will cover the rest of the requirements in our journey through the 3D game development world!

Time for action—preparing the development environment

First, we must download and install various Silverlight development tools.

We need to install Visual C# 2008 (.NET Framework 3.5) with Service Pack 1 or greater (Visual C# 2010) in order to successfully complete the installations provided here. Installing Silverlight 3 Tools will uninstall the previous Silverlight versions. We will not be able to create Silverlight 2 applications using Visual C# 2008 with Silverlight 3 Tools installed in our system. Visual C# 2010 does not have this restriction because it allows us to choose the desired Silverlight version target.

Tip

You can use the free Visual Web Developer 2008 Express Edition or greater (http://www.microsoft.com/express/vwd/). However, you have to read the documentation and consider its limitations carefully.

The following are steps for preparing the development environment:

Download the following files:

Application name

Download link

File name

Description

Expression Design

http://www.microsoft.com/expression/products/Overview.aspx?key=design

Design_Trial_en.exe

It is a commercial tool, but the trial offers a free fully functional version for 30 days. This tool will enable us to transform vector assets to the appropriate format for use in Silverlight 3.

Inkscape

http://inkscape.org/download/?lang=en

Inkscape-0.46.win32.exe

It is a very complete free, open source, vector drawing program. This tool will enable us to import many vector assets in different, popular file formats and export them to a format recognized by Expression Design.

Silverlight 3 Tools for Visual Studio

http://www.microsoft.com/downloads/details.aspx?familyid=9442b0f2-7465-417a-88f3-5e7b5409e9dd&displaylang=en

Silverlight3_Tools.exe

We must install it to create Silverlight 3 applications in Visual Studio IDE using XAML and C#. This will uninstall previous Silverlight SDKs (Software Development Kits).

Silverlight 3 Offline Documentation (in a CHM format)

http://www.microsoft.com/downloads/details.aspx?familyid=0A9773A7-C854-41FA-B73D-535ABFB73BAF&displaylang=en

Silverlight_3_Docs.zip

We must download and decompress this file, as we will be needing access to the Silverlight 3 official documentation.

Expression Blend 3 + SketchFlow

http://www.microsoft.com/expression/try-it/Default.aspx#PageTop

Blend_Trial_en.exe

This tool will enable us to create content and prototypes that target Silverlight 3. It will be really helpful to use Expression Blend 3 to create rapid prototypes for some game scenes.

.NET RIA Services

http://www.microsoft.com/downloads/details.aspx?FamilyID=76bb3a07-3846-4564-b0c3-27972bcaabce&displaylang=en

RiaServices.msi

This framework allows the creation of business applications that are capable of talking to our games. In the same link, there is a PDF file available for download with interesting documentation about this framework.

Silverlight Toolkit (updated for Silverlight 3 compatibility)

http://codeplex.com/Silverlight

Silverlight 3 Toolkit July 2009.msi

It is convenient to download the latest stable release. This toolkit provides a nice collection of Silverlight controls, components, and utilities made available outside the normal Silverlight release cycle. It will be really helpful to use these controls to provide many game statistics. Besides, it includes more Silverlight themes.

Run the installers in the same order in which they appear in the previous list, and follow the steps to complete the installation wizards. Take into account that to install Silverlight 3 Tools for Visual Studio, you will need an Internet connection for a small download when the wizard begins. One of the items enumerated under the Products affected by the software update: list is Download Preparation, as shown in the following screenshot:Once the installations have successfully finished, run Visual Studio 2008 or Visual Web Developer 2008 (or later). You will see the Microsoft Silverlight Projects label displayed on the splash screen, as shown in the following picture:If the splash screen disappears too quickly, you will not be able to check Silverlight's availability. However, you can check it once Visual Studio 2008 or Visual Web Developer 2008 (or later) is running. Select Help | About Microsoft Visual Studio. A dialog box will appear and you will see Microsoft Silverlight Projects 2008 displayed under the Installed products list. Select this item and check whether Product details shows number 3 after the second dot (.). For example, 9.0.30730.126 indicates that Silverlight 3 is installed, as shown in the following picture:

What just happened?

We installed Silverlight 3 Tools for Visual Studio, Expression Blend 3 for Silverlight 3, .NET RIA Services, and Silverlight Toolkit.

Now, we have everything we need to begin creating and testing amazing 2D games using Silverlight 3 and C#.

Time for action—recognizing digital art assets

One of the best ways of explaining a new game idea is showing it in a very nice picture. This is exactly what you want to do. However, it is very difficult to find a new game idea from scratch. Therefore, in working out how to impress the legendary game developer, you ask for some help in an 8-bit retro gaming community. You meet a legendary space shooter games' expert and he shows you many remakes of the classic 8-bit Invader game—also known as Space Invaders. The remakes are too simple and they do not exploit modern widescreen displays, as they run in very low resolutions inside the web browsers. A dazzling remake of an Invaders game sounds like a very nice idea!

We are going to take a snapshot of the first scene of one of the most exciting 8-bit implementations of the Invaders game—the legendary TI Invaders—as shown in the following picture:

What just happened?

Looking at the TI Invaders scene picture, we can recognize the following digital art assets:

Green aliensBlue aliensRed aliensTents to protect our ship against the aliens' attackA ship

These assets are organized as shown in the following picture:

The aliens are organized in five rows and eleven columns. There are four tents and just one ship to challenge all these aggressive invaders.

Time for action—creating the raster digital content

This prehistoric game used a 256X192 pixels screen (49,152 pixels). We are going to prepare raster digital assets for the game optimized for a 1680X1050 pixels screen (1,764,000 pixels). The game should look nice when compared to the older version.

The old version used 8X8 pixels raster digital assets. In this new version, we can use 50X50 pixels raster digital assets.

Tip

The creation of raster digital assets for a 2D game is very complex and requires professional skills. Digital artists and graphic designers are very important members of a professional game development team. They provide great quality digital assets to the programming team.

As you do not have access to professional digital artists yet, you must download some freeware icons and then prepare them to be a part of a game demonstration. Luckily, you will find some nice space and zoom-eyed creatures in PNG (Portable Network Graphics) format that are free to download from Turbomilk (a professional visual interface design company, http://turbomilk.com). They are ideal to use in the game.

Tip

PNG is an open, extensible image format with lossless compression. Silverlight 3 works great with PNG images. I recommend not using the JPEG (Joint Photographic Experts Group) format for foreground digital assets or iconic graphics because it uses a lossy compression method that removes some information from the image.

First, we are going to download, manipulate, resize, and finally save the new versions of the new raster digital content for the game:

Download the PNG images for the green, blue, and red aliens, the tents, and the ship. You can take some nice images from http://turbomilk.com/downloads/.Save all the original PNG images in a new folder (C:\Silverlight3D\Invaders\GAME_PNGS), as shown in the following picture:Open the images for the aliens, ship, and tents using an image-manipulation tool. You can use a free and open source software such as GIMP (the GNU Image Manipulation Program) that is available at http://www.gimp.org, or a commercial software such as Adobe Photoshop available at http://www.adobe.com, or free software such as Picasa available at http://picasa.google.com.Remove the shadows from the images because we are not going to use them as icons. You can select the shadows and delete them using the magic wand tool (fuzzy select tool). It requires high precision in the selection to avoid deleting the original drawing. Shadows have to be removed because we want to use them as raster content for the game, as shown in the following picture:Remove the transparent pixels from the images (that is, erase the selection).Resize the images for the aliens and the ship to 50X50 pixels square, while keeping proportions. Save them in a PNG format using the following names:
ALIEN_01_01.png—the blue alien, the octopusALIEN_02_01.png—the red alien, the gothic cherryALIEN_03_01.png—the green alien, the eyeSHIP_01_01.png—the ship
Resize the image for the tents to 100X100 pixels square, while keeping proportions. Save it in a PNG format using the name TENT_01_01.png.Now, copy the newly manipulated and resized images in a new folder (C:\Silverlight3D\Invaders\GAME_PNGS_RESIZED), as shown in the following picture:

What just happened?

We created raster digital content for the game optimized for a 1680X1050 pixels screen. We downloaded some images, and manipulated them to remove the shadows and prepare them for the game's main scene. We used a naming convention for the images as we want to keep everything well organized for the game.

The game will look nice using these modern raster digital art assets.

Digital Content Creation tools

The Digital Content Creation tools (DCC) are very important partners for game designers and developers. They allow digital artists and graphic designers to concentrate on the creation of different kinds of digital art assets, which are then used in the applications.

Tip

We can also use everything we are learning in developing the applications that have intensive graphical resources. However, we will call them games in the rest of the book.

It is very easy to understand their purpose using an example. If you want to show a sky with stars as an application's background, the easiest way to do it is by loading a bitmap (PNG, BMP, JPG, and so on) using the procedures or controls provided by the programming language.

A digital artist will create and manipulate the sky bitmap using an image manipulation tool such as GIMP, Photoshop, or Picasa.

Developing games requires the usage of a great number of resources; it is not just programming tasks. We are going to use many popular DCC tools during our journey to create Silverlight 3D games. As many of these tools are very expensive, we will use some open source and free alternatives to carry out the most important tasks.

A good practice before beginning 2D and 3D game development is to research the tools used to create the 2D and 3D digital content. This way, we will have a better idea of how to create the different scenes and the most common techniques. Later, we will learn the programming techniques used to give life to these graphics-related operations. We will be able to provide great real-time interaction to all these digital content assets, as shown in the following diagram:

Basic elements of a 2D and/or 3D real-time game

A modern 2D and/or 3D real-time game uses the basic elements shown in the previous diagram. Let's go through them in the following list:

images: These can be raster bitmaps as used in our previous example, or vector graphics—also known as vector-based illustrations. In some cases, they are useful as a background made of a starry sky, or a cloudy sky. In other cases, they are used as textures to envelope different 3D objects. For example, a 2D brick's image is used as a texture to envelope a 3D object representing a wall.models: These contain information about the representations of primitive elements (point, lines, triangles, and polygons) to create great meshes, similar to a wire mesh that describes a 3D model. Their different parts can be enveloped by textures. Then everything renders in a representation in the 2D space shown by the players' screens.Effects definitions: These can be applied to 3D models to offer more realism in the production of many scenes. To simplify the development process, there are many specific programming languages used to define the behavior of effects.Maps: It is easier to create real-time digital content using different kinds of maps and diverse proprietary formats. Maps can specify the location of the different kinds of houses and trees in a game that involves driving a car in a city. It is possible to create many levels based on the same logic and behavior programmed for a game, but by using many different maps.

Many specialized DCC tools help in creating the basic elements explained in the aforementioned list. For example, using GIMP you can see the alpha channel for the ship's PNG image, as shown in the following picture:

Programming responsibilities

We do not have to write lines of code dedicated to creating an image. Instead, modern game programming focuses on the following tasks:

Loading: We must load 2D images, 3D models, textures, effects definitions, and maps using different kinds of content loaders, parsers, import techniques, and translators. They are going to help us in transforming the original file formats to the ones supported by the programming language and the framework used to develop the game.Drawing: A game's main goal is to show real-time graphics content in a screen. One of the main problems is that 3D scenes have to be shown in a screen capable of showing just two of these three dimensions.Logic and control: While the content is being loaded and shown, it is necessary to apply some AI (Artificial Intelligence) to logic operations, and to provide feedback according to the controls offered to the user for certain game actors and aspects. In order to achieve this goal, it is necessary to develop accurate time-management techniques coordinated with the information obtained from the hardware applied to control the game—the keyboard, mouse, racing wheel, gamepad, or the Wiimote (Wii Remote), among others. All of these tasks must be done while managing many heterogeneous pieces and showing a very complex audiovisual production. Thus, we must take into account everything related to the execution speed and issues of performance.

Programming games requires more knowledge about the underlying hardware on which the game will be run. We must establish performance baselines and minimum requisites to achieve a desirable performance for the game. Besides, we must specify the recommended input devices to take full advantage of the game. These tasks could seem pretty trivial, but they are very important because some games are very complex and demand many difficult optimizations to be able to run on the mainstream hardware available.

This is a simple summary of a game's programming responsibilities. We will work through them all throughout this book.

Time for action—installing tools to manipulate scalable digital content

Your cell phone rings. An old friend sees your name in the participants' list and calls you because he has some interesting information. He tells you the game has to scale to huge resolutions such as the ones found in exclusive XHD (eXtreme High Definition) displays. These displays can support resolutions as high as 2560X1600 pixels.

Scaling the raster digital assets is a big problem because pixelation becomes easily visible. If you scale the final alien for using it in a higher resolution, it will look really pixelated as shown in the following picture:

You want the game to use the entire screen space, even in the XHD displays. To make this possible, you could prepare another set of raster digital assets for the game optimized for a 2560X1600 pixels screen (4,096,000 pixels). However, the game can also be run using a 1920X1080 pixels screen (2,073,600 pixels). There is another alternative of creating a new set of scalable vector graphics (vector-based illustrations), which are ready to scale to any screen resolution without generating pixelation problems.

This way, you can provide two versions of the same game—one using raster digital assets optimized for a 1680X1050 pixels screen and the other using scalable vector graphics. There is no restriction in the number of games per participant. Therefore, you can submit both versions.

Tip

The creation of scalable vector graphics assets for a 2D game is very complex and involves professional skills. We are going to simplify this process by using the existing clipart.

First, we must download and install some additional tools that will help us in converting the existing scalable vector graphics to the most appropriate file formats to use in Silverlight 3:

Tip

The necessary tools will depend on the applications the digital artists use to create the scalable vector graphics. However, we will be using some tools that will work fine with our examples.

Download the following files:

Application name

Download link

File name

Description

Expression Design

http://www.microsoft.com/expression/products/Overview.aspx?key=design

Design_Trial_en.exe

It is a commercial tool, but the trial offers a free fully functional version for 30 days. This tool will enable us to transform vector assets to the appropriate format for use in Silverlight 3.

Inkscape

http://inkscape.org/download/?lang=en

Inkscape-0.46.win32.exe

It is a very complete free, open source, vector drawing program. This tool will enable us to import many vector assets in different, popular file formats and export them to a format recognized by Expression Design.

Run the installers and follow the steps to complete the installation wizards.Once Inkscape's installation is finished, you will be able to load and edit many vector assets in different file formats as shown in the following picture:

What just happened?

We installed Expression Design and Inkscape. Now we have the necessary tools to convert the existing vector clipart to the most appropriate formats to use in Silverlight 3.

XAML works fine with Silverlight 3

Why do we need to install so many tools to create a simple vector asset to use in Silverlight 3? It's because Silverlight 3 uses XAML (eXtensible Application Markup Language), and the best way to add scalable vector content is using objects defined in XAML. However, many tools that offer functions to export to XAML do not work as expected and are not compatible with Silverlight 3. Besides, many converters are still in alpha versions and have problems when we need to convert complex vector art.

The game must be finished on or before the due date. Therefore, to avoid problems related to XAML vector assets, we are going to perform additional steps. But we will be sure that the resulting XAML will work fine with Silverlight 3.

Time for action—creating the scalable digital content in XAML

As you do not have access to professional digital artists yet, you must download some free clipart and then prepare it to be a part of a scalable game demonstration. This time, you want to offer a different version of the game by mixing some Halloween monsters (the new invaders) with the ship. This will be the vector-graphics based game. Luckily, you find some nice, free-to-use clipart in WMF (Windows Meta-File) scalable vector format from Microsoft Office Clipart. They are great to use for offering a different scalable version of the game.

Tip

WMF is an old, scalable vector format. Silverlight 3 does not offer direct support for WMF graphics. Therefore, we must convert WMF graphics to XAML. Following the next steps, we can also convert from any vector formats supported by Inkscape such as SVG (Scalable Vector Graphics), AI (Adobe Illustrator), PDF (Adobe PDF), and EMF (Enhanced Meta-File) among others.

First, we are going to download, organize, and convert some scalable vector graphics to XAML which is compatible with Silverlight 3:

Download or copy the vector graphics for the green, blue, and red aliens, the tents, and the ship. Remember that this version is themed on Halloween monsters. You can take some nice graphics from the Microsoft Office Clipart Collection.Save all of the original WMF images in a new folder (C:\Silverlight3D\Invaders\GAME_WMFS), as shown in the following picture:Repeat the following steps (4 to 13) for each vector graphic (WMF file).Open the vector graphic file in Inkscape.Select File | Save a copy.... A dialog box showing many export options will appear.Remove the extension from the filename. For example, if the filename shown is ALIEN_01_01.wmf, the new name will be ALIEN_01_01.Choose the PDF via Cairo (*.PDF) option in the combo box that lists the available file formats to export. Click on Save and then on OK. Now, you will have the vector graphic as a PDF file. You will be able to open the file using any PDF reader such as Adobe Acrobat Reader or Foxit Reader.Rename the new PDF file and change its PDF extension to AI. For example, if the file name generated by Inkscape is ALIEN_01_01.pdf, the new name will be ALIEN_01_01.ai.Now, open the file with the .ai extension in Microsoft Expression Design.Select File | Export.... A dialog box with many export options will appear.Choose XAML Silverlight Canvas in the Format combo box under Export properties. Now, you will be able to see a nice image preview as shown in the following picture:Click on Browse... and choose the destination folder for the new XAML file (C:\Silverlight3D\Invaders\GAME_XAML).Click on Export All and Expression Design will create the XAML file. You can preview the XAML file in Internet Explorer, as shown in the following picture:

What just happened?

We created scalable vector graphics and converted them to an XAML format, which is compatible with Silverlight 3. We downloaded some images and used a process to convert them to a format that Microsoft Expression Design can read. As this tool does not work with WMF files, we needed to provide an AI-compatible format.

We converted the files to a PDF format, which is compatible with the newest AI formats. Expression Design can read this format, but it requires the files to have the .ai extension. That is why we needed to rename the files exported from Inkscape as PDF.

We used Inkscape because it is free, open source, and compatible with the most popular scalable vector graphics formats. However, we did not export to XAML from Inkscape because there are some incompatibilities in that conversion. The most secure way to export to XAML these days is using Expression Design.

This scalable vector content for the game could be optimized for any resolution. We used the same naming convention previously employed by the raster graphics, as we want to keep everything well organized for the two versions of the game. One will show raster aliens and the other, scalable Halloween monsters.

The game will look nice on XHD monitors using these scalable vector art assets.

Previewing and scaling XAML vector graphics

The XAML vector graphics can scale while keeping their quality intact when they are used in Silverlight 3 applications. This is not new; this happened with all the vector graphics formats. Scaling the vector graphics is not a problem because they do not have pixelation problems. However, they require more processing time than raster graphics to be shown on a screen.

If you scale one of the Halloween monsters to use it in a higher resolution, it will look really great as shown in the following picture:

A very interesting hidden tool that can help us when working with XAML and XAML vector graphics is XamlPad.

XamlPad is a part of the WPF (Windows Presentation Foundation) SDK. Once Visual Studio is installed, it is available in the following folder: Program Files\Microsoft SDKs\Windows\v6.0A\bin. You must create a manual shortcut to XamlPad.exe in that folder because it is not available in a menu shortcut.

Time for action—testing the scalable digital content using XamlPad

Now, we are going to test how an XAML vector graphic scales using XamlPad:

Open one of the XAML vector graphics exported by Expression Design using Windows Notepad.Select all of the text and copy it to the clipboard.Run XamlPad.Paste the clipboard's content (the XAML definition) in the XAML area. You will see the illustration appearing in the top panel, as shown in the following picture:Change the zoom many times, taking into account that you can enter manual values. You will see the illustration appearing with different sizes without pixelation problems.Click on Show/Hide the visual tree. The Visual Tree Explorer and Property Tree Explorer will allow you to navigate through the different components of this scalable XAML vector illustration, as shown in the following picture:

What just happened?

We used a very simple yet handy tool called XamlPad to preview XAML-scalable vector illustrations. Now, we are sure that the scalable clipart for the game is going to work fine in different resolutions. We can include these vector illustrations in Silverlight 3 applications.

Editing vector illustrations using Expression Design