Difference between revisions of "Introduction to Graphics"

From GiderosMobile
(removed duplicate text)
(moved shape to its own page because it's quite long)
Line 174: Line 174:
 
*'''Fit width''': This mode fits the width of the stage, preserving the aspect ratio. It’s possible that there might be blank areas at the top and bottom of the screen, or these areas may be outside the visible area. If you have more than one screen in your application, and screen transition is from left to right (or vice versa), then this mode is a perfect fit for you.
 
*'''Fit width''': This mode fits the width of the stage, preserving the aspect ratio. It’s possible that there might be blank areas at the top and bottom of the screen, or these areas may be outside the visible area. If you have more than one screen in your application, and screen transition is from left to right (or vice versa), then this mode is a perfect fit for you.
 
*'''Fit height''': Similar to fit width, this time guaranteeing to fit the height. Very suitable for shoot'em-up type games.
 
*'''Fit height''': Similar to fit width, this time guaranteeing to fit the height. Very suitable for shoot'em-up type games.
 
== Shapes ==
 
Gideros provides a Shape class for drawing primitive shapes. It is similar to the drawing API found in Flash although at the moment it only has a subset of Flash’s capabilities. Since the Shape class inherits from Sprite (which itself inherits from EventListener), instances of the shape class can be rotated, scaled, positioned on the screen, listen for and dispatch events - basically anything that Sprites can do. See the chapter on Sprites for a full list of inherited capabilities.
 
 
The unique functions added by the Shape class are:
 
{| class="wikitable"
 
|-
 
! Function Name !! Description
 
|-
 
| Shape.new() || Creates a new Shape object
 
|-
 
| Shape:setFillStyle(type, …) || Sets the fill style for a shape
 
|-
 
| Shape:setLineStyle(width, color, alpha) || Sets the line style for a shape
 
|-
 
| Shape:beginPath(winding) || Begins a path
 
|-
 
| Shape:endPath() || Ends a path
 
|-
 
| Shape:moveTo(x,y) || Moves the pen to a new location
 
|-
 
| Shape:lineTo(x,y) || Draws a line from the current location to the specified point
 
|-
 
| Shape:closePath() || Draws a line from the current location to the first point in the path
 
|-
 
| Shape:clear() || Clears all paths from the shape and resets the line and fill style to default values
 
|}
 
 
One question that you might ask is: Why draw using this primitive API? Wouldn’t it be better to use some other authoring environment (e.g., Photoshop, Inkscape, Gimp) then import the image as a Texture? In most cases, an authoring tool is the right answer. However, there are cases where you don’t know which graphics you need in advance:
 
    • Drawing tool (e.g., drawing lines based on user input)
 
    • Graphs (e.g., stock prices, bar-charts)
 
    • Graphics equalizer in a music player
 
    • Skinning physics engine soft bodies
 
 
=== Gideros coordinate system ===
 
The standard cartesian coordinate system that everyone learns in school consists of an origin point (x=0, y=0) which is often drawn in the center of a page. The x values increase to the right horizontally and the y values increase upwards vertically (i.e., x values are negative to the left of the origin and positive to the right, y values are negative below the origin and positive above). 
 
 
The origin point in the Gideros coordinate system is in the upper left-hand corner of the screen with an inverted y-axis (i.e., y values are negative above the origin and positive below the origin).  The x-axis is the same as the standard cartesian coordinate system.
 
 
[[File:Coordinate system.png]]
 
 
=== Usage overview ===
 
Shapes consist of zero or more paths.  Each path consists of zero or more lines with the same line and fill style. A different line or fill style can be used for each path. Since a path can only have one line style and one fill style, multiple paths are required to use different line / fill styles within a shape.
 
 
A pen & paper analogy is often used to describe the drawing approach used by the Shape class.  The “moveTo” function can be thought of as lifting a pen off the paper and moving it to a different location without drawing anything. The “lineTo” function draws a straight line from the current pen location to the destination location.
 
 
The overall flow for drawing with the Shape class is:
 
    • Create a new shape
 
    • For each path that you want to draw;
 
    • Begin the path
 
    • Set the fill style (fill or line must be set for the shape to be visible)
 
    • Set the line style (fill or line must be set for the shape to be visible)
 
    • Move pen and draw lines
 
    • Close the path (optional)
 
    • End the path
 
 
=== Drawing your first line ===
 
Our first drawing will be a simple horizontal line from x=100,y=100 to x=200,y=100 as shown in the following figure.    We’ll use the moveTo function to move to the first point, then the lineTo function to actually draw the line.
 
 
[[File:First line.png]]
 
 
Here’s the code to draw the line:
 
<source lang="lua">
 
local shape = Shape.new() -- create the shape
 
shape:beginPath()        -- begin a path
 
shape:setLineStyle(1)    -- set the line width = 1
 
shape:moveTo(100,100)    -- move pen to start of line
 
shape:lineTo(200,100)    -- draw line
 
shape:endPath()          -- end the path
 
stage:addChild(shape)    -- add the shape to the stage
 
</source>
 
 
Some things to note about this code:
 
* without the call to setLineStyle, the line wouldn’t have been visible --  in this example, we used setLineStyle to set the line width to 1 (the default line color is black)
 
* we added the shape directly to the stage.  For this example that’s good enough.  For more complicated examples you’d probably use some other parent.  Most of the following Shape examples will use this same approach.
 
 
=== Drawing a Rectangle ===
 
Lines aren’t very interesting so let's expand our line into a filled rectangle. We’ll draw the rectangle with the upper left corner at 100,100 and the lower right corner at 200,200. We’ll also fill the rectangle with a boring gray color.
 
<source lang="lua">
 
local shape = Shape.new() -- create the shape
 
shape:beginPath()        -- begin a path
 
shape:setLineStyle(1)    -- set the line width = 1
 
shape:setFillStyle(Shape.SOLID, 0xcccccc) -- NEW: boring gray
 
shape:moveTo(100,100)    -- move pen to start of line
 
shape:lineTo(200,100)    -- draw top of rectangle
 
shape:lineTo(200,200)    -- NEW: draw right side of rectangle
 
shape:lineTo(100,200)    -- NEW: draw bottom of rectangle
 
shape:lineTo(100,100)    -- NEW: draw left side of triangle
 
shape:endPath()          -- end the path
 
stage:addChild(shape)    -- add the shape to the stage
 
</source>
 
 
This example is similar to our line drawing program plus 1 additional line to fill the rectangle and 3 additional new lines to draw the right, bottom, and left sides of the rectangle.
 
 
[[File:First rectangle.png]]
 
 
=== Drawing Arbitrary Polygons ===
 
There are a couple of simplifications that we can make to the rectangle code:
 
* The call to moveTo can be replaced with lineTo.  The first call to lineTo after a path is started behaves just like a moveTo.
 
* Although a rectangle has 4 points, we have to use a total of 5 moveTo/lineTo calls -- the first point has to be used twice (once for the initial moveTo command and once to close the rectangle with the final lineTo call).    The last lineTo command can be replaced with a call to closePath. The closePath function is equivalent to a lineTo command to the first point in a path.
 
 
The following code uses these two simplifications to draw a polygon from an arbitrary list of data points:
 
<source lang="lua">
 
local path = { {100,100}, {200,100}, {200,200}, {100,200} }
 
local shape = Shape.new()
 
shape:setLineStyle(1)
 
shape:setFillStyle(Shape.SOLID, 0xcccccc)
 
shape:beginPath()
 
for i,p in ipairs(path) do
 
shape:lineTo(p[1], p[2])  -- lineTo used for all points
 
end
 
shape:closePath()  -- connect last point to first point
 
shape:endPath()
 
</source>
 
 
We can change path to have as many points as we’d like and the above code will draw the closed polygon.
 
 
path = { {x1,y1}, {x2,y2}, … add as many points as you want … }
 
 
=== Shape Anchor Point ===
 
Shapes are “anchored” at the graph origin (0,0). The anchor point affects how the shape behaves when manipulated (e.g., rotated, scaled). If we were to rotate the rectangle we drew earlier by 90°, the rectangle would have rotated off the screen since it would have rotated about the (0,0) origin point. The anchor point also affects scaling -- scaling the rectangle would have moved it further away from (0,0) if it was enlarged and closer to (0,0) if we’d scaled it down.
 
<br/>
 
 
Let’s change our previous polygon example so that the rectangle will stay centered at its center point (150,150) if rotated or scaled. The code will need the following two changes:
 
    • Draw the rectangle centered at (0,0)
 
    • Use the inherited Sprite:setPosition function to position the shape
 
 
We can make these changes by modifying the first few lines of our previous example like so:
 
<source lang="lua">
 
local path = { {-50,-50}, {50,-50}, {50,50}, {-50,50} }
 
-- CHANGED: points are now centered around (0,0)
 
local shape = Shape.new()
 
shape:setPosition(150,150) -- NEW
 
-- ... the rest of the original example would go here …
 
</source>
 
 
=== Line and Fill Styles ===
 
We’ve used setLineStyle and setFillStyle in our examples, but the lines and rectangles that we’ve drawn so far are pretty boring.  This section provides more details on these two functions.
 
 
The setLineStyle function has one required parameter (width) and two optional parameters (color, alpha):
 
'''width''': width of the line (integer number > 0)
 
'''color''': color value of the line (optional hexadecimal number, default = 0x000000)
 
(red is 0xFF0000, blue=0x0000FF, green=0x00FF00, white=0xFFFFFF, etc.)
 
'''alpha''': alpha value for the line (optional floating point value between 0 & 1, default=1) (0 = invisible, 0.5 = 50% transparency, 1 = no transparency)
 
 
The following figure shows some example line styles.
 
 
[[File:Linestyles.png]]
 
 
Shapes can be unfilled, filled with a color, or filled with a texture. The first argument to setFillStyle determines the fill type:
 
* Shape.NONE: Clears the fill style (i.e., the shape will not be filled)
 
* Shape.SOLID: Sets the fill style as a solid color. In this mode,  an additional color parameter is required (hexadecimal number).  An optional alpha value (floating point number between 0 and 1) can also be specified.
 
* Shape.TEXTURE: Fills the shape with a tiled texture. In this mode, and additional texture argument is required.  An optional transformation matrix can also be specified.
 
 
The following illustrates how to use the three different types of fill styles:
 
<source lang="lua">
 
setFillStyle(Shape.NONE) -- unfilled
 
setFillStyle(Shape.SOLID, 0xff0000) -- fill solid red color
 
setFillStyle(Shape.SOLID, 0xff0000, 0.5) -- fill with red, 50% transparency
 
local texture = Texture.new("image.png")
 
setFillStyle(Shape.TEXTURE, texture) -- fill with texture
 
local matrix = Matrix.new(0.5, 0, 0, 0.5, 0, 0)
 
setFillStyle(Shape.TEXTURE,texture,matrix) -- fill with texture scale x/y by 0.5
 
</source>
 
 
There are two important things to note when using texture fills:
 
* If the shape of the texture is smaller than the area to be filled, Gideros will tile the textures in both the x and y dimensions. The tiles will be aligned so that the upper left-hand corner of the texture will be at x=0, y=0 (unless this is modified by a transformation matrix).
 
* If the width and/or height of the texture is not a power of 2, Gideros will increase the width/height to be a power of 2 with the expanded area left unfilled or transparent. For example, a 33 (width) x 123 (height) texture will be re-sized to 64 x 128 then tiled as necessary.
 
 
As stated previously, all lines and drawn shapes within a path share the same line and fill style. Gideros applies the most recently specified line and fill style when each path is ended (i.e., with endPath). The following code draws a shape with 2 paths. Everything drawn between a beginPath/endPath pair will have the same line and fill style. In other words, even though setLineStyle is called 5 different times, only 2 of them have an effect because there are only 2 paths.
 
<source lang="lua">
 
local s = Shape.new()
 
s:setLineStyle(1)
 
s:beginPath()
 
s:moveTo(10,10); s:lineTo(20,10) -- line width will be 1
 
s:endPath()
 
-- All lines in the following path will have a width of 3.
 
-- Only the setLineStyle call right before endPath has an effect
 
s:beginPath()
 
s:setLineStyle(1)
 
s:moveTo(10,10); s:lineTo(20,10) -- line width will be 3
 
s:setLineStyle(2)
 
s:moveTo(10,10); s:lineTo(20,10) -- line width will be 3
 
s:setLineStyle(3)
 
s:endPath()
 
s:setLineStyle(4)
 
</source>
 
 
=== Winding Rules ===
 
Simple paths such as circles, triangles, rectangles have a well-defined and obvious “fill area.”. For complex paths (e.g., concentric circles,  shapes with intersecting lines), multiple choices can be made as to whether fill an area. The Shape:beginPath function takes an optional winding argument that determines how the path will be filled (the default value for the argument is Shape.EVEN_ODD). To determine whether an area should be filled, the following two rules are available within Gideros:
 
* Even-odd rule (Shape.EVEN_ODD)
 
# Draw a line with a start point in the area to be filled extending to infinity in any direction
 
# If the line crosses an even number of lines, the area should NOT be filled
 
# If the line crosses an odd number of lines, the area should be filled
 
* Non-zero rule (Shape.NON_ZERO) - this rule depends on the drawing direction (or winding) of the edges of the path. When paths of opposite drawing direction intersect, the area will be unfilled.
 
# Draw a line with a start point in the area to be filled extending to infinity in any direction
 
# Start with a count of 0
 
# Every time the line crosses a line of the polygon drawn in one direction add one to the count. Subtract one from the count for every edge drawn in the opposite dimension.
 
# If the ending count is zero, the area should NOT be filled. If the ending count is zero, the area should be filled.
 
 
For example, consider a simple path such as a rectangle: a line started from “outside” the rectangle will either cross 0 edges or 2 edges. Since the line crosses an even number of lines, the area should not be filled using the even-odd rule. The area wouldn’t be filled with the non-zero rule either: the line would either cross 0 edges (count would be 0) or two edges -- one edge drawn in one direction, the other edge drawn in the opposite direction (the count would be 0). If a line is started inside the rectangle, the line will intersect one edge (an odd count for the even-odd rule, and a count of either -1 or 1 for the non zero rule).
 
 
In can be confusing to decide whether an area should be filled but thankfully examples of different winding rules are easy to find since these two winding rules are used in flash, SVG, postscript, and many other drawing technologies.
 
  
 
== Using tilemaps ==
 
== Using tilemaps ==

Revision as of 01:25, 13 July 2020

The Ultimate Guide to Gideros Studio

Graphics and animation

Introduction to graphics

In Gideros Studio, all graphical content is constructed by creating graphical instances and adding them to the scene tree. For example, the Bitmap class is used to display bitmap graphics, and TextField is used to display text object. Sprite class is used to group and transform these instances.

Sprite is the base class of all display classes and has no visual representation. It’s the main construction element and used to create display hierarchies. Sprites can have other sprites as their children and these children inherit properties such as position, scaling, and transparency from their parent sprite. Hierarchy is an important feature in graphics - when you move your parent sprite, all the child (and grandchild) sprites also move simultaneously. Here are some examples:

- Create a new Sprite instance:
local childSprite = Sprite.new()
- Add the new Sprite as a child:
mySprite:addChild(childSprite)
- Set the position:
mySprite:setPosition(10, 20)
- Set the scaling:
mySprite:setScale(0.5, 1)
- Set the rotation angle:
mySprite:setRotation(90)
- Set the alpha transparency:
mySprite:setAlpha(0.7)
- Get the first child:
mySprite:getChildAt(1)
- Remove the child:
mySprite:removeChild(childSprite)

Sprites can have only one parent. Therefore if you add a child object that already has a different sprite as a parent, the sprite is removed from the child list of the other sprite and then added to this sprite.

Stage

The scene tree is the hierarchy of all graphical objects currently displayed and this hierarchy needs a root. The root of the scene tree is an instance of the Stage class which is automatically created and set as a global variable when Gideros starts. You can access this global variable with the name stage.

When Gideros starts, the display list hierarchy contains one item (the global Stage instance) only and we can add more:

- Create a Sprite object
local mySprite = Sprite.new()
- Add this sprite to the stage:
stage:addChild(mySprite)

Textures and Bitmaps

Texture class is used to load an image file and holds the data stored in the image file. The Bitmap class inherits from Sprite and wraps a Texture object for on-screen display. By separating image display (Bitmap) from data (Texture), it’s possible to create many Bitmap objects simultaneously display the same Texture object each with its own display characteristics.

- Load a texture:
local texture = Texture.new("image.png")
- Load a texture with filtering:
local texture = Texture.new("image.png", true)
- Create a Bitmap object to display the texture
local bitmap = Bitmap.new(texture)
- Add the Bitmap object to the stage
stage:addChild(bitmap)

Anchor Point

Each Bitmap object has an anchor point that affects the positioning of the texture displayed. By modifying the anchor point, you change the origin of the texture. For example, setting the anchor point to (0.5, 0.5) moves the center of the texture to the origin. If you set the anchor point to (1, 1) instead, the bottom-right corner of the texture will be the origin. The default value of anchor point is (0, 0) which means top-left of the texture is the origin by default.

Anchorpoint.png

setAnchorPoint(0,0), setAnchorPoint(0.5, 0.5), setAnchorPoint(1,1)

In this example, we set the anchor point to (0.5, 0.5):

local bitmap = Bitmap.new(Texture.new("image.png"))
bitmap:setAnchorPoint(0.5, 0.5)

Texture Atlas

A Texture Atlas is a single large image which contains many smaller sub-images. Each sub-image contained in the texture atlas is defined with a rectangular area.

There are two main reasons for using a texture atlas instead of many independent textures:

1. Texture atlases usually consume less memory.

To use an image as a texture, its width and height always have to be a power of two. Gideros automatically increase the texture size to conform to this rule. For example, an image with dimensions of 100x200 becomes a texture with dimensions of 128x256 in memory. That’s where the texture atlas becomes handy. Texture atlases usually have power-of-two dimensions and therefore don’t need to be enlarged.

2. Rendering from a texture atlas is usually faster.

Each texture is bound to OpenGL just before rendering it and binding is a costly operation. Using texture atlases instead of individual textures helps in reducing bind operations.

TextureRegion

The TextureRegion class specifies a texture and a rectangular region in it. It is used to define independent texture regions within a texture atlas. Displaying texture regions is the same as displaying textures: create a Bitmap object that wraps the TextureRegion object:

-- Load a texture
local texture = Texture.new("image.png")
-- Create a texture region as top left point is (30, 40) with dimensions (100, 50)
local textureRegion = TextureRegion.new(texture, 30, 40, 100, 50)
-- Create a Bitmap object to display the texture region
local bitmap = Bitmap.new(textureRegion)

TexturePack

The TexturePack class is used to create and load texture atlases. You can either create your texture atlas dynamically in your game or use a pre-packed texture atlas. After creating your texture pack, you can get a region of it as a TextureRegion object by using the getTextureRegion function. These features are described below in more details.

Dynamic Creation of Texture Packs

To create a texture pack dynamically (at run-time), create a TexturePack object with an array of file names of textures:

local texturePack = TexturePack.new({"1.png", "2.png", "3.png", "4.png"})

Gideros loads and packs these images fast and gives you a ready to use texture pack. After creating your texture pack, you can display it easily since it's also a texture in itself:

local bitmap = Bitmap.new(texturePack)
stage:addChild(bitmap)

Note: Gideros uses an algorithm called MaxRects to pack the textures. This algorithm is considered as one of the best packing algorithms in terms of speed and efficiency. If you are interested, you can find the details of MaxRects algorithm at http://clb.demon.fi/projects/even-more-rectangle-bin-packing

Pre-packed Texture Packs

Another option to create texture packs is to use an external texture packer tool. Gideros Texture Packer, which comes with the installation package can be used to create texture packs.

Getting Texture Regions from Texture Packs

To get the texture region from the texture pack, you need to call the name of the image:

local texturePack = TexturePack.new({"1.png", "2.png", "3.png", "4.png"})
local textureRegion = texturePack:getTextureRegion(1.png)

Automatic image resolution

There are multiple resolutions that game developers should consider. To efficiently use texture memory and processing power of GPUs, applications should use low-resolution images on devices with low-resolution screens and high-resolution images on devices with high-resolution screens. With the help of automatic image resolution, you can bundle both low and high-resolution images together with your application and Gideros automatically selects the best resolution according to your scaling.

Automatic image resolution is directly related to automatic screen scaling. For example, if your screen is automatically scaled by 2, then using the double-sized image is the best choice in terms of quality and efficiency.

Open the project “Hardware/Automatic Image Resolution” to see automatic image resolution in action. Run this example multiple times by selecting different resolutions on Gideros Player such as 320x480, 640x960, and 480x800. As you can see, for the different resolutions, the original 200x200 image or high-resolution variants (300x300 and 400x400) are selected and displayed automatically.

Now right click on the project name and select “Properties…” to understand how we configure automatic image resolution parameters:

Project properties.png

In this example, our logical dimensions are 320x480 and scale mode is Letterbox. So the scaling factor for a device with screen resolution 320x480 (older iPhones) is 1, scaling factor for 480x960 (iPhone 4) is 2 and scaling factor for 480x800 (Samsung Galaxy S) is around 1.5.

We have configured image scales as:

Image scales.png

So if you have a base image with a resolution of 200x200 and a name “image.png”, you provide these 3 images:

   • image.png (200x200)
   • image@1.5x.png (300x300)
   • image@2x.png (400x400)

and let Gideros pick the appropriate one.

Providing the alternative images (image@1.5x.png and image@2x.png) is optional but you should always provide the base image (image.png). When Gideros cannot find the alternative image to load, it loads the base image. Also, size calculations are done according to the size of the base image.

Design for High-Resolution Devices

In our example, we set the logical dimensions as 320x480 and provided higher-resolution alternative images.

On the other hand, it is possible to set the logical dimensions as 480x960 or 768x1024 and provide lower-resolution images. In this case, we can configure the image scales like:

Image scales 2.png

and provide alternative images with suffix “@half” as half-resolution of the original ones.

Automatic screen scaling

To handle a wide variety of resolutions, Gideros provides a functionality called Automatic Screen Scaling.

Before starting your project, you determine your logical resolution and position all your sprites according to this.

For example, if you determine your logical resolution as 320x480, your upper left corner will be (0, 0), your lower right corner will be (319, 479) and the center coordinate of your screen will be (160, 240). Then according to your scale mode, Gideros automaticaly scales your screen according to the real resolution of your hardware.

There are 8 types of scaling modes:

  • No scale: No scaling simply tells your application not to scale at all. In this mode, there’s no scaling at all, and your stage sits on the upper left corner of the device screen.
  • No scale, center: This mode is similar to “no scale”, except one minor difference: Stage is centered on the device screen.
  • Pixel perfect: This mode is similar to “No scale, center”, with a minor difference: Scale value is rounded to values like 1/3, ½, 1, 2 or 3. This mode can be used in games which benefit from pixel art games - it guarantees a crisp look and feel for screen sprites.
  • Letterbox: Preserving the aspect ratio, it scales the stage so it fits the content on the device screen. There’s a possibility that blank areas may occur on the device. Mostly, developer keeps the background a bit “bigger” in order to eliminate these blank areas and fill it with background.
  • Crop: This mode again does preserve the aspect ratio, and ensures that no blank areas are left on the screen. Hence, some part of the background may be outside the visible area.
  • Stretch: The whole stage sits on the screen. Since x/y is not preserved, there’s a possibility that aspect ratio might change.
  • Fit width: This mode fits the width of the stage, preserving the aspect ratio. It’s possible that there might be blank areas at the top and bottom of the screen, or these areas may be outside the visible area. If you have more than one screen in your application, and screen transition is from left to right (or vice versa), then this mode is a perfect fit for you.
  • Fit height: Similar to fit width, this time guaranteeing to fit the height. Very suitable for shoot'em-up type games.

Using tilemaps

Optimization and memory management

Timelined animations with Movieclip

Note: Currently there’s no way to set the animation speed, however you can prepare different animations for different speeds like:

local eliAnim = MovieClip.new{
{1, 7, self.anim[1]},
{8, 15, self.anim[2]},
{16, 18, self.anim[1]},
{19, 21, self.anim[2]},
}
eliAnim:setGotoAction(15, 1) --> frames 1-15: slow animation
eliAnim:setGotoAction(21, 16) --> frames 16-21: fast animation
eliAnim:gotoAndPlay(1) --> play slow animation
eliAnim:gotoAndPlay(16) --> play fast animation

This way, you can position your MovieClip wherever you want (e.g. running player, walking player, flying helicopter, etc).


PREV.: Classes in Gideros
NEXT: Introduction to Fonts