Building your First Application with Papervision3D: Part 1

Exclusive offer: get 50% off this eBook here
Papervision3D Essentials

Papervision3D Essentials — Save 50%

Create interactive Papervision 3D applications with stunning effects and powerful animations

£16.99    £8.50
by Jeff Winder Paul Tondeur | September 2009 | Open Source

This article by Jeff Winder & Paul Tondeur will guide you through the steps that lead to building your first Papervision3D application. In this article, we will see a brief introduction on classes and object-oriented programming to help you on your way.

This article covers the following:

  • Introduction to classes and object-oriented programming
  • Working with the document class/main application file

Introduction to classes and object-oriented programming

In this article we will learn to write our own classes that can be used in Flash, along with Flex Builder and Flash Builder. If you're a developer using the Flash IDE, it might be the first time you'll write your own classes. Don't worry about the difficulty level if you are new to classes. Learning how to program  in an OOP way using Papervision3D is a good way to become more familiar with classes and it  might motivate you to learn more about this subject. You will not be the first who learned to program in an OOP way, as a side effect of learning an external library such as Papervision3D is.

So what are classes? In fact, they are nothing more than a set of functions (methods) and variables (properties) grouped together in a single file, which is known as the class definition. A class forms the blueprint for new objects that you create.

Sounds a bit vague? What if you were told that you've probably already used classes? Each object you create from the Flash API is based on classes. For example, Sprites, MovieClips, and TextFields are objects that you have probably used in your code before. In fact, these objects are classes. The blueprints for these objects and their classes are already incorporated in Flash. First, have a look at how you can use them to create a new Sprite object:

var mySprite:Sprite = new Sprite();

Looks familiar—right? By doing this, you create a new copy of the Sprite class as an object called mySprite. This is called instantiation of an object. There's no difference between instantiating built-in classes or instantiating custom written classes. Papervision3D is a set of custom classes.

var myObject3D:DisplayObject3D = new DisplayObject3D();

So, although you know how to use classes, creating your own classes might be new to you.

Creating a custom class

An ActionScript class is basically a text-based file with an .as extension stored somewhere on your computer, containing ActionScript code. This code works as the previously mentioned blueprint for an object. Let's see what that blueprint looks like:

package {
public class ExampleClass
{
public var myName:String = "Paul";
public function ExampleClass()
{
}
public function returnMyName():String
{
return "My name is" + myName;
}
}
}

On the first line, you'll find the package statement, followed by an opening curly bracket and ended with a closing curly bracket at the bottom of the class. Packages are a way to group classes together and represent the folder in which you saved the file. Imagine you have created a folder called myPackage inside the same folder where you've saved an FLA or inside a defined source folder. In order to have access to the folder and its classes, you will need to define the package using the folder's name as shown next:

package myPackage {
...
}

This works the same way for subfolders. Let's imagine a folder called subPackage has been added to the imaginary folder myPackage. The package definition for classes inside this subfolder should then look like this:

package myPackage.subPackage {
...
}

If you don't create a special folder to group your classes, you can use the so-called default package instead of defining a name. All the examples in this article will use default packages. However, for real projects it's good practice to set up a structure in order to organize your files.

After the package definition, you'll find the class definition, which looks as follows:

public class ExampleClass
{
...
}

The name of the class must be the same name as the class file. In this example, the file needs to be saved as ExampleClass.as.

Besides the fact that working packages is a good way to organize your files, they can also be used to uniquely identify each class in a project.

At the top of the class definition you'll see the word public, which is a keyword defining that the class is accessible to all other code in the project. This keyword is called, an access modifier.

The defined name of the class will be used to instantiate new copies of the class. Instantiating this class could be done like this:

var classExample:ExampleClass = new ExampleClass();

Inside the class, a string variable is defined in pretty much the same way as you would when working with timeline scripting.

public var myName:String = "Paul";

The definition of a variable inside a class is called as a class property. You can add as many properties to a class as you want. Each definition starts off with an access modifier. In this case the access modifier is set to public, meaning that it is both readable and writeable by code located outside the class:

var classExample:ExampleClass = new ExampleClass();
classExample.myName = "Jeff";

As you can see, this creates an instance of ExampleClass. We also changed the myName property from Paul to Jeff. When a property is defined as public, this is allowed to happen. In case you want access to this property inside the class itself, you can mark the property as private:

private var myName:String = "Paul";

Executing the previous code to change myName from Paul to Jeff will result in a compile-time error. In the next lines we see the creation of a new function called ExampleClass in the class. Functions that have the same name as the name of the class are known as constructors.

public function ExampleClass()
{
}

Constructors always have a public access modifier and are called automatically each time the class is instantiated. This means that the code inside this function will be executed automatically.

All other function definitions inside the class are called methods.

public function returnMyName():String
{
return "My name is" + myName;
}

At the end of this method definition, you'll notice a colon followed by a data type. This defines the type of object the method returns. When you work with functions on the timeline in Flash, you can define this as well, but it's not required to do so. The method returnMyName() is defined to return a string. In case you do not want to return any data type, you can define this by using a void as the return type:

public function returnNothing():void
{
//Do not return something
}

We need to define return type only for methods and not for constructors.

Classes, as well as properties and methods, have access modifiers that define from where each of these objects can be accessed. So far we've seen that a public keyword allows code outside the class to access a property, or call a method inside the class. When you allow access from other code, you need to be aware that this code can mess up your class. You can prevent this by using the private keyword, which makes the property or method only accessible inside your class. Two other access modifiers that are often used are internal and protected. Classes inside the same package can access internal methods or properties and protected methods can only be used inside a related subclass. Subclasses are a part of inheritance, which will be explained in a bit.

As long as you have not planned to give access to scripts outside your class, it's a good practice to mark all properties and methods of a class as private by default. When defining a property or method, you should always ask yourself whether you want them to be accessed from outside your class.

Papervision3D Essentials Create interactive Papervision 3D applications with stunning effects and powerful animations
Published: September 2009
eBook Price: £16.99
Book Price: £27.99
See more
Select your format and quantity:

Inheritance

Sometimes you want to create a new class that looks a lot like an existing one, except that you want to add a new functionality. You could copy the existing class, paste it into your new class, and add the functionality. However, that is not very efficient. This is where inheritance comes into play. Inheritance is the technique of extending an existing class, called the super class or base class, with another class, called the sub class, which adopts the entire class definition from the super class. The new class has access to all non-private properties and methods that are defined inside the super class.

Imagine you are about to create a car and a motorbike by code. You could make two classes—one for the car and the other for the motorbike. However, you will soon notice that functionalities and properties of both classes will overlap. For example, they can both drive and steer, and have properties such as the amount of wheels and speed. In an abstract manner, these properties and functionalities overlap because the car and the motorbike are both vehicles. Creating a vehicle super class that is subclassed by a car class and a motorbike class prevents this overlap.
When needed, the subclass class can define how it differs or behaves differently from its parent class. For example, a car has four wheels and can drive in a reverse direction. A motorbike has two wheels and cannot drive in a reverse direction.

Take a look at how this can be achieved by two simple classes:

package {
public class BasicClass
{
public function doSomething():void
{
trace("I'm doing something");
}
}
}
package {
public class SubClass extends BasicClass
{
public function saySomething():void
{
trace("I'm saying something");
}
}
}

The first class will be the super class once it's extended and has only one method. Instantiating a BasicClass and calling a method is pretty straightforward.

var basicClass:BasicClass = new BasicClass();
basicClass.doSomething();

Nothing special so far. According to the class definition of SubClass we see that it extends BasicClass. By doing so, it is possible to use properties and methods from the BasicClass. Let's see what this looks like:

var subClass:SubClass = new SubClass();
subClass.doSomething();
subClass.saySomething();

This example calls the doSomething method on SubClass, which inherits this method from BasicClass. Extending classes can be done not only with custom classes, but is also possible with built-in classes. Have a look at how you create an extended sprite:

package {
import flash.display.Sprite;
public class extendedSprite extends Sprite
{
}
}

Notice there's a new line right after the package definition:

import flash.display.Sprite;

To extend as well as instantiate classes that are not part of the current package, you need to define an import. Imports relate to packages and classes. In this case, the class Sprite was imported from package flash.display.

Extending is a good way to create new classes, based on other existing classes—isn't it? It keeps your code very clean and abstract. But what if you want to change an existing method in your super class? Changing the super class directly isn't always possible and is definitely not a good idea, as you want to leave the existing code intact to prevent breaking the class. When you're using a third-party library such as Papervision3D, it's not unthinkable that you'll update the classes in the future. When you apply changes directly to some of these classes, your code will break as soon as you update to a new version.

Luckily, object-oriented programming offers a solution. Have a look at how we can change the method doSomething() inside BasicClass, by overriding it in the SubClass:

package {
public class SubClass extends BasicClass
{
override public function doSomething():void
{
trace("Hi, you need to do something ");
}
public function saySomething():void
{
trace("I'm saying something");
}
}
}

We've added the method doSomething() to the subclass. However you can't do this without explicitly saying that you want to override the doSomething() method from the super class. When you override a method, it will replace the original method. You can still call the overridden method in the super class from the overriding method in the sub class.

override public function doSomething():void
{
trace("Hi, you need to do something ");
super.doSomething();
}

When you now call the doSomething() method in the SubClass, it will trace:

Hi, you need to do something
I'm doing something

This is where the brief introduction to OOP ends. If you want to know more, there are numerous books and online tutorials on the subject of OOP.

Working with the Document Class/Main Application File

The Document Class in the Flash IDE, or Main Application File in Flex Builder and Flash Builder, is a special class that contains a constructor, which will be called by the SWF file once it's loaded. You could say that the constructor inside your document class will be the entry point of your application. The document class requires that it is an extended Sprite or MovieClip, or any other class type that inherits from either of these objects.

For the sake of simplicity, this article refers to the document class and not to the main application file. Although their names differ, their usage is exactly the same. Also note that a synonym for main application file is Application Class.

Flex Builder and Flash Builder have the same workflow to get the document class up and running. However, the Flash IDE takes another approach. Let's start by explaining how it is done in the Flash IDE.

Setting up the document class for Flash

In Flash, you can choose to define a document class as the entry point of your application. This class can extend the MovieClip that represents the timeline in Flash, and replaces the stage as the entry point of your application. Although you can use a combination of your stage and a document class as the entry point, it's not a very common thing to do.

Defining the document class is quite easy. Start Flash and follow the instructions

  1. Create a new ActionScript file and save it somewhere on your hard drive under the name DocumentClassExample.as.
  2. Create a new Flash AS3 file and save it as DocumentClassExample.fla in the same location where you saved your DocumentClassExample.as file.
  3. Open the Properties panel of your FLA file. At the bottom right you'll find an input field labeled as Document class. Just enter the class name that you want to use as our document class—DocumentClassExample in this case, just like in the following screenshot:

Papervision3D Essentials

That's all you need to do to use a class as the entry point of your application. Easy, isn't it? Okay, it doesn't even look like 3D, but it's important basic information when you're new to working with classes in Flash.

Let's publish our movie now and see what happens. If you've followed the steps correctly, Flash will throw compiler error 5007.

5007: An ActionScript file must have at least one externally visible definition.

This is an expected error. We've defined the document class in the Properties panel, but we haven't written any class yet. We've only created an empty file that does not yet contain a class definition. For now, this file isn't understandable by Flash and that's why it threw this error. It's pretty reasonable that it warns us of this error. Let's write our first lines of code and define the class correctly. Open DocumentClassExample.as in Flash, add the following code, and save it:

package {
import flash.display.Sprite;
public class DocumentClassExample extends Sprite
{
public function DocumentClassExample()
{
trace("Hello world!");
}
}
}

Now you can publish your Flash file without getting any compiler errors. On line 3, you see that the class extends the sprite class, which is required as said at the beginning of this section. The constructor in this class contains only a trace and publishing this file should show the string in your output window.

Setting up the document class for Flex Builder and Flash Builder

Although it is possible, in this article we will not use Flex Builder or Flash Builder to create Papervision3D applications with the Flex Framework. Both authoring tools will be used only to manage our ActionScript projects.

Creating a document class in Flex Builder and Flash Builder is completely integrated in the way both programs works. If you don't know what a document class or main application file is, and if you've used Flex Builder or Flash Builder before, you've already created one without even knowing it. Let's see how we create a document class:

  1. Start the wizard for creating a new ActionScript project.
  2. Enter DocumentClassExample as your project name.
  3. Click Next and look at the field called Main application file. By default, this value is the name of the project with the extension .as added to it. In our case that's DocumentClassExample.as. The following screenshot shows the second window from a New ActionScript Project wizard in Flex Builder. The name of the document class is automatically defined in the Main application file field.
  4. Papervision3D Essentials

  5. Click Finish and you've successfully set up your own document class. When you are working with multiple classes, you can always recognize your document class in the Flex Navigator (Flex Builder) or Package Explorer (Flash Builder) with the help of the Papervision3D Essentialsp icon.
  6. Let's finish this class and trace "Hello World" in the constructor.

There is no need to do more than this, as Flex Builder and Flash Builder always need to have a document class to be defined in order to run your code. Debug, run this code, and you'll see the trace.

Summary

The article started off with a short introduction to OOP and classes for those who are new to programming in an object-oriented way. We now know what classes are and how we can:

  • Create a new class
  • Set imports
  • Define properties and methods
  • Tell what access modifiers are
  • Extend an existing class by using inheritance
  • Override methods from a super class
  • Create a new project with a document class/main application file

In the second part of this article, we will cover the basics of a 3D composition in Papervision3D and build our first Papervision3D application.

Papervision3D Essentials Create interactive Papervision 3D applications with stunning effects and powerful animations
Published: September 2009
eBook Price: £16.99
Book Price: £27.99
See more
Select your format and quantity:

About the Author :


Jeff Winder

Jeff Winder is an independent Flash developer living and working in Amsterdam, the Netherlands. He discovered Flash and ActionScript in 2003, mainly creating timeline animation, but was soon gripped by non-timeline coding. He has a special interest in new technologies that are related to Flash, especially open-source projects such as WiiFlash, FLARToolKit, and Papervision3D. Jeff acquired an MSc in Social Psychology at the University of Amsterdam. He is also a passionate musician, playing guitar and drums. Since 2006 Jeff has been self-employed and working for leading agencies. URL: http://www.jeffwinder.nl

Paul Tondeur

Paul Tondeur is as an internet entrepreneur who lives and works in Amsterdam, the Netherlands.

He started as a freelance PHP and Flash developer during his study multimedia technology in 2003. After successfully completing his study he was asked to become the CTO of a Dutch online marketing agency in 2004. At this company he developed a strong interest for 3D and got the chance to get professionally involved as the technical lead for serious Second Life projects. Second Life was too limited to fulfill his needs to create accessible interactive multiplayer 3D on the web and this is when he found out about Papervision3D during the early days. Because of his passion for the Flash platform this was love at first sight.

At the beginning of 2009, Paul decided he had to take more advantage of his technical skills as an internet entrepreneur. Currently he helps other companies as a Unity, Papervision3D, Red5 and mobile streaming consultant. Together with a team of people around him, he is also involved in creating a browser based MMO, incorporating the usage of Red5, Unity, Flash and Papervision3D.

URL: www.paultondeur.com

Books From Packt

Flash with Drupal
Blender 3D Architecture, Buildings, and Scenery

ImageMagick Tricks
ImageMagick Tricks

Joomla! 1.5 SEO
Joomla! 1.5 SEO

Drupal 6 Search Engine Optimization
Drupal 6 Search Engine Optimization

Mastering phpMyAdmin 3.1 for Effective MySQL Management
Mastering phpMyAdmin 3.1 for Effective MySQL Management

Drupal Multimedia
Drupal Multimedia

jQuery UI 1.6: The User Interface Library for jQuery
jQuery UI 1.6: The User Interface Library for jQuery

Ext JS 3.0 Cookbook
Ext JS 3.0 Cookbook

Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software