Packageflash.display3D
Classpublic final class Context3D
InheritanceContext3D Inheritance EventDispatcher Inheritance Object

Language version: ActionScript 3.0
Runtime version: AIR 3

The Context3D class provides a context for rendering geometrically defined graphics.

A rendering context includes a drawing surface and its associated resources and state. When possible, the rendering context uses the hardware graphics processing unit (GPU). Otherwise, the rendering context uses software. (If rendering through Context3D is not supported on a platform, the stage3Ds property of the Stage object contains an empty list.)

The Context3D rendering context is a programmable pipeline that is very similar to OpenGL ES 2, but is abstracted so that it is compatible with a range of hardware and GPU interfaces. Although designed for 3D graphics, the rendering pipeline does not mandate that the rendering is three dimensional. Thus, you can create a 2D renderer by supplying the appropriate vertex and pixel fragment programs. In both the 3D and 2D cases, the only geometric primitive supported is the triangle.

Get an instance of the Context3D class by calling the requestContext3D() method of a Stage3D object. A limited number of Context3D objects can exist per stage; one for each Stage3D in the Stage.stage3Ds list. When the context is created, the Stage3D object dispatches a context3DCreate event. A rendering context can be destroyed and recreated at any time, such as when another application that uses the GPU gains focus. Your code should anticipate receiving multiple context3DCreate events. Position the rendering area on the stage using the x and y properties of the associated Stage3D instance.

When the rendering context is attached to the stage of an HTML window, the default background of the HTMLLoader object obscures the 3D viewport. To turn off the default background, set the paintsDefaultBackground property to false:

window.htmlLoader.paintsDefaultBackground = false;

To render and display a scene (after getting a Context3D object), the following steps are typical:

  1. Configure the main display buffer attributes by calling configureBackBuffer().
  2. Create and initialize your rendering resources, including:
    • Vertex and index buffers defining the scene geometry
    • Vertex and pixel programs (shaders) for rendering the scene
    • Textures
  3. Render a frame:
    • Set the render state as appropriate for an object or collection of objects in the scene.
    • Call the drawTriangles() method to render a set of triangles.
    • Change the rendering state for the next group of objects.
    • Call drawTriangles() to draw the triangles defining the objects.
    • Repeat until the scene is entirely rendered.
    • Call the present() method to display the rendered scene on the stage.

The following limits apply to rendering:

Resource limits:

Resource Number allowed Total memory
Vertex buffers 4096 256 MB
Index buffers 4096 128 MB
Programs 4096 16 MB
Textures 4096 128 MB
Cube textures 4096 256 MB

AGAL limits: 200 opcodes per program.

Draw call limits: 32,768 drawTriangles() calls for each present() call.

The following limits apply to textures:

Texture limits for AIR 32 bit:

Texture Maximum size Total GPU memory
Normal Texture (below Baseline extended) 2048x2048 512 MB
Normal Texture (Baseline extended and above) 4096x4096 512 MB
Rectangular Texture (below Baseline extended) 2048x2048 512 MB
Rectangular Texture (Baseline extended and above) 4096x4096 512 MB
Cube Texture 1024x1024 256 MB

Texture limits for AIR 64 bit (Desktop):

Texture Maximum size Total GPU memory
Normal Texture (below Baseline extended) 2048x2048 512 MB
Normal Texture (Baseline extended to Standard) 4096x4096 512 MB
Normal Texture (Standard extended and above) 4096x4096 2048 MB
Rectangular Texture (below Baseline extended) 2048x2048 512 MB
Rectangular Texture (Baseline extended to Standard) 4096x4096 512 MB
Rectangular Texture (Standard extended and above) 4096x4096 2048 MB
Cube Texture 1024x1024 256 MB

512 MB is the absolute limit for textures, including the texture memory required for mipmaps. However, for Cube Textures, the memory limit is 256 MB.

You cannot create Context3D objects with the Context3D constructor. It is constructed and available as a property of a Stage3D instance. The Context3D class can be used on both desktop and mobile platforms, both when running in Flash Player and AIR.

View the examples.

See also

Context3DBlendFactor
Context3DClearMask
Context3DCompareMode
Context3DProgramType
Context3DRenderMode
Context3DStencilAction
Context3DTextureFormat
Context3DTriangleFace
Context3DVertexBufferFormat
flash.display3D.textures.Texture
flash.display3D.textures.CubeTexture
IndexBuffer3D
flash.geom.Matrix3D
Program3D
flash.display.Stage3D
VertexBuffer3D


Public Properties
 PropertyDefined by
  backBufferHeight : int
[read-only] Specifies the height of the back buffer, which can be changed by a successful call to the configureBackBuffer() method.
Context3D
  backBufferWidth : int
[read-only] Specifies the width of the back buffer, which can be changed by a successful call to the configureBackBuffer() method.
Context3D
 Inheritedconstructor : Object
A reference to the class object or constructor function for a given object instance.
Object
  driverInfo : String
[read-only] The type of graphics library driver used by this rendering context.
Context3D
  enableErrorChecking : Boolean
Specifies whether errors encountered by the renderer are reported to the application.
Context3D
  ignoreResourceLimits : Boolean
Specifies whether to ignore all 'soft' resource limits associated with a profile.
Context3D
  maxBackBufferHeight : int
Specifies the maximum height of the back buffer.
Context3D
  maxBackBufferWidth : int
Specifies the maximum width of the back buffer.
Context3D
  profile : String
[read-only] The feature-support profile in use by this Context3D object.
Context3D
 Inheritedprototype : Object
[static] A reference to the prototype object of a class or function object.
Object
  supportsVideoTexture : Boolean
[static][read-only] Indicates if Context3D supports video texture.
Context3D
  totalGPUMemory : Number
[read-only] Returns the total GPU memory allocated by Stage3D data structures of an application.
Context3D
Public Methods
 MethodDefined by
 Inherited
addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void
Registers an event listener object with an EventDispatcher object so that the listener receives notification of an event.
EventDispatcher
  
clear(red:Number = 0.0, green:Number = 0.0, blue:Number = 0.0, alpha:Number = 1.0, depth:Number = 1.0, stencil:uint = 0, mask:uint = 0xffffffff):void
Clears the color, depth, and stencil buffers associated with this Context3D object and fills them with the specified values.
Context3D
  
configureBackBuffer(width:int, height:int, antiAlias:int, enableDepthAndStencil:Boolean = true, wantsBestResolution:Boolean = false, wantsBestResolutionOnBrowserZoom:Boolean = false):void
Sets the viewport dimensions and other attributes of the rendering buffer.
Context3D
  
createCubeTexture(size:int, format:String, optimizeForRenderToTexture:Boolean, streamingLevels:int = 0):CubeTexture
Creates a CubeTexture object.
Context3D
  
createIndexBuffer(numIndices:int, bufferUsage:String = "staticDraw"):IndexBuffer3D
Creates an IndexBuffer3D object.
Context3D
  
Creates a Program3D object.
Context3D
  
createRectangleTexture(width:int, height:int, format:String, optimizeForRenderToTexture:Boolean):RectangleTexture
Creates a Rectangle Texture object.
Context3D
  
createTexture(width:int, height:int, format:String, optimizeForRenderToTexture:Boolean, streamingLevels:int = 0):Texture
Creates a Texture object.
Context3D
  
createVertexBuffer(numVertices:int, data32PerVertex:int, bufferUsage:String = "staticDraw"):VertexBuffer3D
Creates a VertexBuffer3D object.
Context3D
  
createVertexBufferForInstances(numVertices:int, data32PerVertex:int, instancesPerElement:int, bufferUsage:String = "staticDraw"):VertexBuffer3D
Creates a VertexBuffer3D object for instances data.
Context3D
  
Creates a VideoTexture object.
Context3D
 Inherited
Dispatches an event into the event flow.
EventDispatcher
  
dispose(recreate:Boolean = true):void
Frees all resources and internal storage associated with this Context3D.
Context3D
  
drawToBitmapData(destination:BitmapData, srcRect:Rectangle = null, destPoint:Point = null):void
Draws the current render buffer to a bitmap.
Context3D
  
drawTriangles(indexBuffer:IndexBuffer3D, firstIndex:int = 0, numTriangles:int = -1):void
Render the specified triangles using the current buffers and state of this Context3D object.
Context3D
  
drawTrianglesInstanced(indexBuffer:IndexBuffer3D, numInstances:int, firstIndex:int = 0, numTriangles:int = -1):void
Render the specified instanced triangles using the current buffers and state of this Context3D object.
Context3D
 Inherited
Checks whether the EventDispatcher object has any listeners registered for a specific type of event.
EventDispatcher
 Inherited
Indicates whether an object has a specified property defined.
Object
 Inherited
Indicates whether an instance of the Object class is in the prototype chain of the object specified as the parameter.
Object
  
Displays the back rendering buffer.
Context3D
 Inherited
Indicates whether the specified property exists and is enumerable.
Object
 Inherited
removeEventListener(type:String, listener:Function, useCapture:Boolean = false):void
Removes a listener from the EventDispatcher object.
EventDispatcher
  
setBlendFactors(sourceFactor:String, destinationFactor:String):void
Specifies the factors used to blend the output color of a drawing operation with the existing color.
Context3D
  
setColorMask(red:Boolean, green:Boolean, blue:Boolean, alpha:Boolean):void
Sets the mask used when writing colors to the render buffer.
Context3D
  
setCulling(triangleFaceToCull:String):void
Sets triangle culling mode.
Context3D
  
setDepthTest(depthMask:Boolean, passCompareMode:String):void
Sets type of comparison used for depth testing.
Context3D
  
setFillMode(fillMode:String):void
Set fill mode used for render.
Context3D
  
Sets vertex and fragment shader programs to use for subsequent rendering.
Context3D
  
setProgramConstantsFromByteArray(programType:String, firstRegister:int, numRegisters:int, data:ByteArray, byteArrayOffset:uint):void
Set constants for use by shader programs using values stored in a ByteArray.
Context3D
  
setProgramConstantsFromFloatVector(programType:String, firstRegister:int, data:Vector.<float>, numRegisters:int = -1):void
Sets the constant inputs for the shader programs.
Context3D
  
setProgramConstantsFromMatrix(programType:String, firstRegister:int, matrix:Matrix3D, transposedMatrix:Boolean = false):void
Sets constants for use by shader programs using values stored in a Matrix3D.
Context3D
  
setProgramConstantsFromVector(programType:String, firstRegister:int, data:Vector.<Number>, numRegisters:int = -1):void
Sets the constant inputs for the shader programs.
Context3D
 Inherited
Sets the availability of a dynamic property for loop operations.
Object
  
Sets the back rendering buffer as the render target.
Context3D
  
setRenderToTexture(texture:TextureBase, enableDepthAndStencil:Boolean = false, antiAlias:int = 0, surfaceSelector:int = 0, colorOutputIndex:int = 0):void
Sets the specified texture as the rendering target.
Context3D
  
setSamplerStateAt(sampler:int, wrap:String, filter:String, mipfilter:String):void
Manually override texture sampler state.
Context3D
  
Sets a scissor rectangle, which is type of drawing mask.
Context3D
  
setStencilActions(triangleFace:String = "frontAndBack", compareMode:String = "always", actionOnBothPass:String = "keep", actionOnDepthFail:String = "keep", actionOnDepthPassStencilFail:String = "keep"):void
Sets stencil mode and operation.
Context3D
  
setStencilReferenceValue(referenceValue:uint, readMask:uint = 255, writeMask:uint = 255):void
Sets the stencil comparison value used for stencil tests.
Context3D
  
setTextureAt(sampler:int, texture:TextureBase):void
Specifies the texture to use for a texture input register of a fragment program.
Context3D
  
setVertexBufferAt(index:int, buffer:VertexBuffer3D, bufferOffset:int = 0, format:String = "float4"):void
Specifies which vertex data components correspond to a single vertex shader program input.
Context3D
 Inherited
Returns the string representation of this object, formatted according to locale-specific conventions.
Object
 Inherited
Returns the string representation of the specified object.
Object
 Inherited
Returns the primitive value of the specified object.
Object
 Inherited
Checks whether an event listener is registered with this EventDispatcher object or any of its ancestors for the specified event type.
EventDispatcher
Events
 EventSummaryDefined by
 Inherited [broadcast event] Dispatched when the Flash Player or AIR application gains operating system focus and becomes active.EventDispatcher
 Inherited [broadcast event] Dispatched when the Flash Player or AIR application operating loses system focus and is becoming inactive.EventDispatcher
Property detail
backBufferHeightproperty
backBufferHeight:int  [read-only]

Language version: ActionScript 3.0
Runtime version: AIR 15

Specifies the height of the back buffer, which can be changed by a successful call to the configureBackBuffer() method. The height may be modified when the browser zoom factor changes if the wantsBestResolutionOnBrowserZoom is set to true in the last successful call to the configureBackBuffer() method. The change in height can be detected by registering an event listener for the browser zoom change event.

Implementation
    public function get backBufferHeight():int

See also

backBufferWidthproperty 
backBufferWidth:int  [read-only]

Language version: ActionScript 3.0
Runtime version: AIR 15

Specifies the width of the back buffer, which can be changed by a successful call to the configureBackBuffer() method. The width may be modified when the browser zoom factor changes if the wantsBestResolutionOnBrowserZoom is set to true in the last successful call to the configureBackBuffer() method. The change in width can be detected by registering an event listener for the browser zoom change event.

Implementation
    public function get backBufferWidth():int

See also

driverInfoproperty 
driverInfo:String  [read-only]

Language version: ActionScript 3.0
Runtime version: AIR 3

The type of graphics library driver used by this rendering context. Indicates whether the rendering is using software, a DirectX driver, or an OpenGL driver. Also indicates whether hardware rendering failed. If hardware rendering fails, Flash Player uses software rendering for Stage3D and driverInfo contains one of the following values:

Implementation
    public function get driverInfo():String
enableErrorCheckingproperty 
enableErrorChecking:Boolean  [read-write]

Language version: ActionScript 3.0
Runtime version: AIR 3

Specifies whether errors encountered by the renderer are reported to the application.

When enableErrorChecking is true, the clear(), and drawTriangles() methods are synchronous and can throw errors. When enableErrorChecking is false, the default, the clear(), and drawTriangles() methods are asynchronous and errors are not reported. Enabling error checking reduces rendering performance. You should only enable error checking when debugging.

Implementation
    public function get enableErrorChecking():Boolean
    public function set enableErrorChecking(value:Boolean):void

See also

ignoreResourceLimitsproperty 
ignoreResourceLimits:Boolean  [read-write]

Language version: ActionScript 3.0
Runtime version: AIR 50.0

Specifies whether to ignore all 'soft' resource limits associated with a profile.

This property should be used with caution. By default this is set to false and the GPU resources (number of and memory used by elements such as vertex and index buffers, programs and textures) are limited per the resource limits described in the Context3D documentation.

If this property is set to true, these limits are no longer applied and the program can continue to allocate GPU memory for new elements. Note that any subsequent error handling will be down to the application developers, but it may not be immediately obvious when resource failures occur due to the asynchronous nature of the Stage3D implementation within AIR.

Implementation
    public function get ignoreResourceLimits():Boolean
    public function set ignoreResourceLimits(value:Boolean):void
maxBackBufferHeightproperty 
maxBackBufferHeight:int  [read-write]

Language version: ActionScript 3.0
Runtime version: AIR 15

Specifies the maximum height of the back buffer. The inital value is the system limit in the platform. The property can be set to a value smaller than or equal to, but not greater than, the system limit. The property can be set to a value greater than or equal to, but not smaller than, the minimum limit. The minimum limit is a constant value, 32, when the back buffer is not configured. The minimum limit will be the value of the height parameter in the last successful call to the configureBackBuffer() method after the back buffer is configured.

Implementation
    public function get maxBackBufferHeight():int
    public function set maxBackBufferHeight(value:int):void
maxBackBufferWidthproperty 
maxBackBufferWidth:int  [read-write]

Language version: ActionScript 3.0
Runtime version: AIR 15

Specifies the maximum width of the back buffer. The inital value is the system limit in the platform. The property can be set to a value smaller than or equal to, but not greater than, the system limit. The property can be set to a value greater than or equal to, but not smaller than, the minimum limit. The minimum limit is a constant value, 32, when the back buffer is not configured. The minimum limit will be the value of the width parameter in the last successful call to the configureBackBuffer() method after the back buffer is configured.

Implementation
    public function get maxBackBufferWidth():int
    public function set maxBackBufferWidth(value:int):void
profileproperty 
profile:String  [read-only]

Language version: ActionScript 3.0
Runtime version: AIR 4

The feature-support profile in use by this Context3D object.

Implementation
    public function get profile():String

See also

supportsVideoTextureproperty 
supportsVideoTexture:Boolean  [read-only]

Language version: ActionScript 3.0
Runtime version: AIR 17.0

Indicates if Context3D supports video texture.

Implementation
    public static function get supportsVideoTexture():Boolean
totalGPUMemoryproperty 
totalGPUMemory:Number  [read-only]

Language version: ActionScript 3.0
Runtime version: AIR 21

Returns the total GPU memory allocated by Stage3D data structures of an application.

Whenever a GPU resource object is created, memory utilized is stored in Context3D. This memory includes index buffers, vertex buffers, textures(excluding video texture), and programs that were created through this Context3D.

API totalGPUMemory returns the total memory consumed by the above resources to the user. Default value returned is 0.The total GPU memory returned is in bytes. The information is only provided in Direct mode on mobile, and in Direct and GPU modes on desktop. (On desktop, using <renderMode>gpu</renderMode> will fall back to <renderMode>direct</renderMode>)

This API can be used when the SWF version is 32 or later. Implementation
    public function get totalGPUMemory():Number
Method detail
clear()method
public function clear(red:Number = 0.0, green:Number = 0.0, blue:Number = 0.0, alpha:Number = 1.0, depth:Number = 1.0, stencil:uint = 0, mask:uint = 0xffffffff):void

Language version: ActionScript 3.0
Runtime version: AIR 3

Clears the color, depth, and stencil buffers associated with this Context3D object and fills them with the specified values.

Set the mask parameter to specify which buffers to clear. Use the constants defined in the Context3DClearMask class to set the mask parameter. Use the bitwise OR operator, "|", to add multiple buffers to the mask (or use Context3DClearMask.ALL). When rendering to the back buffer, the configureBackBuffer() method must be called before any clear() calls.

Note: If you specify a parameter value outside the allowed range, Numeric parameter values are silently clamped to the range zero to one. Likewise, if stencil is greater than 0xff it is set to 0xff.

Parameters
red:Number (default = 0.0) — the red component of the color with which to clear the color buffer, in the range zero to one.
 
green:Number (default = 0.0) — the green component of the color with which to clear the color buffer, in the range zero to one.
 
blue:Number (default = 0.0) — the blue component of the color with which to clear the color buffer, in the range zero to one.
 
alpha:Number (default = 1.0) — the alpha component of the color with which to clear the color buffer, in the range zero to one. The alpha component is not used for blending. It is written to the buffer alpha directly.
 
depth:Number (default = 1.0) — the value with which to clear the depth buffer, in the range zero to one.
 
stencil:uint (default = 0) — the 8-bit value with which to clear the stencil buffer, in a range of 0x00 to 0xff.
 
mask:uint (default = 0xffffffff) — specifies which buffers to clear.

Throws
Error — Object Disposed: if this Context3D object has been disposed by a calling dispose() or because the underlying rendering hardware has been lost.
 
Error — 3768: The Stage3D API may not be used during background execution.

See also

configureBackBuffer()method 
public function configureBackBuffer(width:int, height:int, antiAlias:int, enableDepthAndStencil:Boolean = true, wantsBestResolution:Boolean = false, wantsBestResolutionOnBrowserZoom:Boolean = false):void

Language version: ActionScript 3.0
Runtime version: AIR 3

Sets the viewport dimensions and other attributes of the rendering buffer.

Rendering is double-buffered. The back buffer is swapped with the visible, front buffer when the present() method is called. The minimum size of the buffer is 32x32 pixels. The maximum size of the back buffer is limited by the device capabilities and can also be set by the user through the properties maxBackBufferWidth and maxBackBufferHeight. Configuring the buffer is a slow operation. Avoid changing the buffer size or attributes during normal rendering operations.

Parameters
width:int — width in pixels of the buffer.
 
height:int — height in pixels of the buffer.
 
antiAlias:int — an integer value specifying the requested antialiasing quality. The value correlates to the number of subsamples used when antialiasing. Using more subsamples requires more calculations to be performed, although the relative performance impact depends on the specific rendering hardware. The type of antialiasing and whether antialiasing is performed at all is dependent on the device and rendering mode. Antialiasing is not supported at all by the software rendering context.
0No antialiasing
2Minimal antialiasing.
4High-quality antialiasing.
16Very high-quality antialiasing.
 
enableDepthAndStencil:Boolean (default = true)false indicates no depth or stencil buffer is created, true creates a depth and a stencil buffer. For an AIR 3.2 or later application compiled with SWF version 15 or higher, if the renderMode element in the application descriptor file is direct, then the depthAndStencil element in the application descriptor file must have the same value as this argument. By default, the value of the depthAndStencil element is false.
 
wantsBestResolution:Boolean (default = false)true indicates that if the device supports HiDPI screens it will attempt to allocate a larger back buffer than indicated with the width and height parameters. Since this add more pixels and potentially changes the result of shader operations this is turned off by default. Use Stage.contentsScaleFactor to determine by how much the native back buffer was scaled up.
 
wantsBestResolutionOnBrowserZoom:Boolean (default = false)true indicates that the size of the back buffer should increase in proportion to the increase in the browser zoom factor. The setting of this value is persistent across multiple browser zooms. The default value of the parameter is false. Set maxBackBufferWidth and maxBackBufferHeight properties to limit the back buffer size increase. Use backBufferWidth and backBufferHeight to determine the current size of the back buffer.

Throws
Error — Object Disposed: if this Context3D object has been disposed by a calling dispose() or because the underlying rendering hardware has been lost.
 
Error — Bad Input Size: The width or height parameter is either less than the minimum back buffer allowed size or greater than the maximum back buffer size allowed.
 
Error — 3709: The depthAndStencil flag in the application descriptor must match the enableDepthAndStencil Boolean passed to configureBackBuffer() on the Context3D object.
createCubeTexture()method 
public function createCubeTexture(size:int, format:String, optimizeForRenderToTexture:Boolean, streamingLevels:int = 0):CubeTexture

Language version: ActionScript 3.0
Runtime version: AIR 3

Creates a CubeTexture object.

Use a CubeTexture object to upload cube texture bitmaps to the rendering context and to reference a cube texture during rendering. A cube texture consists of six equal-sized, square textures arranged in a cubic topology and are useful for describing environment maps.

You cannot create CubeTexture objects with a CubeTexture constructor; use this method instead. After creating a CubeTexture object, upload the texture bitmap data using the CubeTexture uploadFromBitmapData(), uploadFromByteArray(), or uploadCompressedTextureFromByteArray() methods..

Parameters
size:int — The texture edge length in texels.
 
format:String — The texel format, of the Context3DTextureFormat enumerated list.

Texture compression lets you store texture images in compressed format directly on the GPU, which saves GPU memory and memory bandwidth. Typically, compressed textures are compressed offline and uploaded to the GPU in compressed form using the Texture.uploadCompressedTextureFromByteArray method. Flash Player 11.4 and AIR 3.4 on desktop platforms added support for runtime texture compression, which may be useful in certain situations, such as when rendering dynamic textures from vector art. Note that this feature is not currently available on mobile platforms and an ArgumentError (Texture Format Mismatch) will be thrown instead. To use runtime texture compression, perform the following steps: 1. Create the texture object by calling the Context3D.createCubeTexture() method, passing either flash.display3D.Context3DTextureFormat.COMPRESSED or flash.display3D.Context3DTextureFormat.COMPRESSED_ALPHA as the format parameter. 2. Using the flash.display3D.textures.Texture instance returned by createCubeTexture(), call either flash.display3D.textures.CubeTexture.uploadFromBitmapData() or flash.display3D.textures.CubeTexture.uploadFromByteArray() to upload and compress the texture in one step.

 
optimizeForRenderToTexture:Boolean — Set to true if the texture is likely to be used as a render target.
 
streamingLevels:int (default = 0) — The MIP map level that must be loaded before the image is rendered. Texture streaming offers the ability to load and display the smallest mip levels first, progressively displaying higher quality images as the textures are loaded. End users can view lower-quality images in an application while the higher quality images load.

By default, streamingLevels is 0, meaning that the highest quality image in the MIP map must be loaded before the image is rendered. This parameter was added in Flash Player 11.3 and AIR 3.3. Using the default value maintains the behavior of the previous versions of Flash Player and AIR.

Set streamingLevels to a value between 1 and the number of images in the MIP map to enable texture streaming. For example, you have a MIP map that includes at the highest quality a main image at 64x64 pixels. Lower quality images in the MIP map are 32x32, 16x16, 8x8, 4x4, 2x2, and 1x1 pixels, for 7 images in total, or 7 levels. Level 0 is the highest quality image. The maximum value of this property is log2(min(width,height)). Therefore, for a main image that is 64x64 pixels, the maximum value of streamingLevels is 7. Set this property to 3 to render the image after the 8x8 pixel image loads.

Note: Setting this property to a value > 0 can impact memory usage and performance.

Returns
CubeTexture

Throws
Error — Object Disposed: if this Context3D object has been disposed by a calling dispose() or because the underlying rendering hardware has been lost.
 
Error — Resource Limit Exceeded: if too many Texture objects are created or the amount of memory allocated to textures is exceeded.
 
ArgumentError — Depth Texture Not Implemented: if you attempt to create a depth texture.
 
ArgumentError — Texture Size Is Zero: if the size parameter is not greater than zero.
 
ArgumentError — Texture Not Power Of Two: if the size parameter is not a power of two.
 
ArgumentError — Texture Too Big: if the size parameter is greater than 1024.
 
Error — Texture Creation Failed: if the CubeTexture object could not be created by the rendering context (but information about the reason is not available).
 
ArgumentError — Invalid streaming level: if streamingLevels is greater or equal to log2(size).

See also

createIndexBuffer()method 
public function createIndexBuffer(numIndices:int, bufferUsage:String = "staticDraw"):IndexBuffer3D

Language version: ActionScript 3.0
Runtime version: AIR 3

Creates an IndexBuffer3D object.

Use an IndexBuffer3D object to upload a set of triangle indices to the rendering context and to reference that set of indices for rendering. Each index in the index buffer references a corresponding vertex in a vertex buffer. Each set of three indices identifies a triangle. Pass the IndexBuffer3D object to the drawTriangles() method to render one or more triangles defined in the index buffer.

You cannot create IndexBuffer3D objects with the IndexBuffer3D class constructor; use this method instead. After creating a IndexBuffer3D object, upload the indices using the IndexBuffer3D uploadFromVector() or uploadFromByteArray() methods.

Parameters
numIndices:int — the number of vertices to be stored in the buffer.
 
bufferUsage:String (default = "staticDraw") — the expected buffer usage. Use one of the constants defined in Context3DBufferUsage. The hardware driver can do appropriate optimization when you set it correctly. This parameter is only available after Flash 12/AIR 4.

Returns
IndexBuffer3D

Throws
Error — Object Disposed: if this Context3D object has been disposed by a calling dispose() or because the underlying rendering hardware has been lost.
 
Error — Resource Limit Exceeded: if too many index buffers are created or the amount of memory allocated to index buffers is exceeded.
 
Error — 3768: The Stage3D API may not be used during background execution.
 
ArgumentError — Buffer Too Big: when numIndices is greater than or equal to 0xf0000.

See also

createProgram()method 
public function createProgram():Program3D

Language version: ActionScript 3.0
Runtime version: AIR 3

Creates a Program3D object.

Use a Program3D object to upload shader programs to the rendering context and to reference uploaded programs during rendering. A Program3D object stores two programs, a vertex program and a fragment program (also known as a pixel program). The programs are written in a binary shader assembly language.

You cannot create Program3D objects with a Program3D constructor; use this method instead. After creating a Program3D object, upload the programs using the Program3D upload() method.

Returns
Program3D

Throws
Error — Object Disposed: if this Context3D object has been disposed by a calling dispose() or because the underlying rendering hardware has been lost.
 
Error — The number of programs exceeds 4096 or the total memory size exceeds 16MB (use dispose to free Program3D resources).

See also


Example
This example illustrates how to create, upload, and activate a pair of vertex and pixel programs to a rendering context. Note that the object, renderContext, is an instance of the Context3D class. The programs in the example are written in Adobe Graphics Assembly Language (AGAL).
//A simple vertex program in AGAL
const VERTEX_SHADER:String =
    "m44 op, va0, vc0 \n" +	
	"mov v0, va1"; 

//A simple fragment (or pixel) program in AGAL		
const FRAGMENT_SHADER:String = "mov oc, v0";  

var vertexAssembly:AGALMiniAssembler = new AGALMiniAssembler();
var fragmentAssembly:AGALMiniAssembler = new AGALMiniAssembler();
var programPair:Program3D;

//Compile shaders
vertexAssembly.assemble( Context3DProgramType.VERTEX, VERTEX_SHADER, false );
fragmentAssembly.assemble( Context3DProgramType.FRAGMENT, FRAGMENT_SHADER, false );			

//Upload programs to render context
programPair = renderContext.createProgram();
programPair.upload( vertexAssembly.agalcode, fragmentAssembly.agalcode );
renderContext.setProgram( programPair );

createRectangleTexture()method 
public function createRectangleTexture(width:int, height:int, format:String, optimizeForRenderToTexture:Boolean):RectangleTexture

Language version: ActionScript 3.0
Runtime version: AIR 3.8

Creates a Rectangle Texture object.

Use a RectangleTexture object to upload texture bitmaps to the rendering context and to reference a texture during rendering.

You cannot create RectangleTexture objects with a RectangleTexture constructor; use this method instead. After creating a RectangleTexture object, upload the texture bitmaps using the Texture uploadFromBitmapData() or uploadFromByteArray() methods.

Note that 32-bit integer textures are stored in a packed BGRA format to match the Flash BitmapData format. Floating point textures use a conventional RGBA format.

Rectangle textures are different from regular 2D textures in that their width and height do not have to be powers of two. Also, they do not contain mip maps. They are most useful for use in render to texture cases. If a rectangle texture is used with a sampler that uses mip map filtering or repeat wrapping the drawTriangles call will fail. Rectangle texture also do not allow streaming. The only texture formats supported by Rectangle textures are BGRA, BGR_PACKED, BGRA_PACKED. The compressed texture formats are not supported by Rectangle Textures.

Parameters
width:int — The texture width in texels.
 
height:int — The texture height in texels.
 
format:String — The texel format, of the Context3DTextureFormat enumerated list.
 
optimizeForRenderToTexture:Boolean — Set to true if the texture is likely to be used as a render target.

Returns
RectangleTexture

Throws
Error — Object Disposed: if this Context3D object has been disposed by a calling dispose() or because the underlying rendering hardware has been lost.
 
Error — Resource Limit Exceeded: if too many Texture objects are created or the amount of memory allocated to textures is exceeded.
 
ArgumentError — Texture Size Is Zero: if both the width or height parameters are not greater than zero.
 
ArgumentError — Texture Too Big: if either the width or the height parameter is greater than 2048.
 
Error — Texture Creation Failed: if the Texture object could not be created by the rendering context (but information about the reason is not available).
 
Error — Requires Baseline Profile Or Above: if rectangular texture is created with baseline constrained profile.

See also

createTexture()method 
public function createTexture(width:int, height:int, format:String, optimizeForRenderToTexture:Boolean, streamingLevels:int = 0):Texture

Language version: ActionScript 3.0
Runtime version: AIR 3

Creates a Texture object.

Use a Texture object to upload texture bitmaps to the rendering context and to reference a texture during rendering.

You cannot create Texture objects with a Texture constructor; use this method instead. After creating a Texture object, upload the texture bitmaps using the Texture uploadFromBitmapData(), uploadFromByteArray(), or uploadCompressedTextureFromByteArray() methods.

Note that 32-bit integer textures are stored in a packed BGRA format to match the Flash BitmapData format. Floating point textures use a conventional RGBA format.

Parameters
width:int — The texture width in texels.
 
height:int — The texture height in texels.
 
format:String — The texel format, of the Context3DTextureFormat enumerated list.

Texture compression lets you store texture images in compressed format directly on the GPU, which saves GPU memory and memory bandwidth. Typically, compressed textures are compressed offline and uploaded to the GPU in compressed form using the Texture.uploadCompressedTextureFromByteArray method. Flash Player 11.4 and AIR 3.4 on desktop platforms added support for runtime texture compression, which may be useful in certain situations, such as when rendering dynamic textures from vector art. Note that this feature is not currently available on mobile platforms and an ArgumentError (Texture Format Mismatch) will be thrown instead. To use runtime texture compression, perform the following steps: 1. Create the texture object by calling the Context3D.createTexture() method, passing either flash.display3D.Context3DTextureFormat.COMPRESSED or flash.display3D.Context3DTextureFormat.COMPRESSED_ALPHA as the format parameter. 2. Using the flash.display3D.textures.Texture instance returned by createTexture(), call either flash.display3D.textures.Texture.uploadFromBitmapData() or flash.display3D.textures.Texture.uploadFromByteArray() to upload and compress the texture in one step.

 
optimizeForRenderToTexture:Boolean — Set to true if the texture is likely to be used as a render target.
 
streamingLevels:int (default = 0) — The MIP map level that must be loaded before the image is rendered. Texture streaming offers the ability to load and display the smallest mip levels first, progressively displaying higher quality images as the textures are loaded. End users can view lower-quality images in an application while the higher quality images load.

By default, streamingLevels is 0, meaning that the highest quality image in the MIP map must be loaded before the image is rendered. This parameter was added in Flash Player 11.3 and AIR 3.3. Using the default value maintains the behavior of the previous versions of Flash Player and AIR.

Set streamingLevels to a value between 1 and the number of images in the MIP map to enable texture streaming. For example, you have a MIP map that includes at the highest quality a main image at 64x64 pixels. Lower quality images in the MIP map are 32x32, 16x16, 8x8, 4x4, 2x2, and 1x1 pixels, for 7 images in total, or 7 levels. Level 0 is the highest quality image. The maximum value of this property is log2(min(width,height)). Therefore, for a main image that is 64x64 pixels, the maximum value of streamingLevels is 7. Set this property to 3 to render the image after the 8x8 pixel image loads.

Note: Setting this property to a value > 0 can impact memory usage and performance.

Returns
Texture

Throws
Error — Object Disposed: if this Context3D object has been disposed by a calling dispose() or because the underlying rendering hardware has been lost.
 
Error — Resource Limit Exceeded: if too many Texture objects are created or the amount of memory allocated to textures is exceeded.
 
ArgumentError — Depth Texture Not Implemented: if you attempt to create a depth texture.
 
ArgumentError — Texture Size Is Zero: if both the width or height parameters are not greater than zero.
 
ArgumentError — Texture Not Power Of Two: if both the width and height parameters are not a power of two.
 
ArgumentError — Texture Too Big: if either the width or the height parameter is greater than 2048 for baseline and baseline constrained profile or if either the width or the height parameter is greater than 4096 for profile baseline extended and above.
 
Error — Texture Creation Failed: if the Texture object could not be created by the rendering context (but information about the reason is not available).
 
ArgumentError — Invalid streaming level: if streamingLevels is greater or equal to log2(min(width,height)).

See also

createVertexBuffer()method 
public function createVertexBuffer(numVertices:int, data32PerVertex:int, bufferUsage:String = "staticDraw"):VertexBuffer3D

Language version: ActionScript 3.0
Runtime version: AIR 3

Creates a VertexBuffer3D object.

Use a VertexBuffer3D object to upload a set of vertex data to the rendering context. A vertex buffer contains the data needed to render each point in the scene geometry. The data attributes associated with each vertex typically includes position, color, and texture coordinates and serve as the input to the vertex shader program. Identify the data values that correspond to one of the inputs of the vertex program using the setVertexBufferAt() method. You can specify up to sixty-four 32-bit values for each vertex.

You cannot create VertexBuffer3D objects with a VertexBuffer3D constructor; use this method instead. After creating a VertexBuffer3D object, upload the vertex data using the VertexBuffer3D uploadFromVector() or uploadFromByteArray() methods.

Parameters
numVertices:int — the number of vertices to be stored in the buffer. The maximum number of vertices in a single buffer is 65535.
 
data32PerVertex:int — the number of 32-bit(4-byte) data values associated with each vertex. The maximum number of 32-bit data elements per vertex is 64 (or 256 bytes). Note that only eight attribute registers are accessible by a vertex shader program at any given time. Use SetVertextBufferAt() to select attributes from within a vertex buffer.
 
bufferUsage:String (default = "staticDraw") — the expected buffer usage. Use one of the constants defined in Context3DBufferUsage. The hardware driver can do appropriate optimization when you set it correctly. This parameter is only available after Flash 12/AIR 4

Returns
VertexBuffer3D

Throws
Error — Object Disposed: if this Context3D object has been disposed by a calling dispose() or because the underlying rendering hardware has been lost.
 
Error — Resource Limit Exceeded: if too many vertex buffer objects are created or the amount of memory alloted to vertex buffers is exceeded.
 
ArgumentError — Buffer Too Big: when numVertices is greater than 0x10000 or data32PerVertex is greater than 64.
 
ArgumentError — Buffer Has Zero Size: when numVertices is zero or data32PerVertex is zero.
 
ArgumentError — Buffer Creation Failed: if the VertexBuffer3D object could not be created by the rendering context (but additional information about the reason is not available).
 
Error — 3768: The Stage3D API may not be used during background execution.

See also


Example
The following example illustrates how to create and load a vertex data buffer. The buffer in the example contains two types of data for each vertex: the position, as x, y, z coordinates; and the color, as rgb components. After the vertex buffer is created, the example calls the setVertexBufferAt() method to specify that the first three data points are passed to the vertex program as 3 Floating point values in va0 and that the second three data points are passed as va1. A vertex program can have up to 8 inputs, also known as vertex attribute registers, defined in this way.
const dataPerVertex:int = 6;
var vertexData:Vector.<Number> = Vector.<Number>(
    [
	  // x, y, z    r, g, b format
	     0, 0, 0,   1, 1, 1,
	    -1, 1, 0,   0, 0,.5,
	     1, 1, 0,   0, 0, 1,
	     1,-1, 0,  .5, 0, 0,
	    -1,-1, 0,   1, 0, 0
	]
);
var vertexes:VertexBuffer3D = renderContext.createVertexBuffer( vertexData.length/dataPerVertex, dataPerVertex );
vertexes.uploadFromVector( vertexData, 0, vertexData.length/dataPerVertex );
			
//Identify vertex data inputs for vertex program
renderContext.setVertexBufferAt( 0, vertexes, 0, Context3DVertexBufferFormat.FLOAT_3 ); //Defines shader input va0 as the position data
renderContext.setVertexBufferAt( 1, vertexes, 3, Context3DVertexBufferFormat.FLOAT_3 ); //Defines shader input va1 as the color data

createVertexBufferForInstances()method 
public function createVertexBufferForInstances(numVertices:int, data32PerVertex:int, instancesPerElement:int, bufferUsage:String = "staticDraw"):VertexBuffer3D

Language version: ActionScript 3.0
Runtime version: AIR 20.0

Creates a VertexBuffer3D object for instances data.

Use a VertexBuffer3D object to upload a set of instance data to the rendering context. The vertex buffer contains the data needed to render each instance in the scene geometry. Vertex Buffers with instance data provide attributes that are common to all the vertices of an instance. and serve as the input to the vertex shader program. Identify the data values that correspond to one of the inputs of the vertex program using the setVertexBufferAt() method. You can specify up to sixty-four 32-bit values for each element of vertex buffer.

You cannot create VertexBuffer3D objects with a VertexBuffer3D constructor; use this method instead. After creating a VertexBuffer3D object, upload the vertex data using the VertexBuffer3D uploadFromVector() or uploadFromByteArray() methods.

Parameters
numVertices:int — the number of elements to be stored in the buffer. The maximum number of elements in a single buffer is 65535.
 
data32PerVertex:int — the number of 32-bit(4-byte) data values associated with each element. The maximum number of 32-bit data elements per vertex is 64 (or 256 bytes).
 
instancesPerElement:int — the number of instances which will use one element of the vertex buffer.
 
bufferUsage:String (default = "staticDraw") — the expected buffer usage. Use one of the constants defined in Context3DBufferUsage. The hardware driver can do appropriate optimization when you set it correctly. This parameter is only available after Flash 12/AIR 4

Returns
VertexBuffer3D

Throws
Error — Object Disposed: if this Context3D object has been disposed by a calling dispose() or because the underlying rendering hardware has been lost.
 
Error — Resource Limit Exceeded: if too many vertex buffer objects are created or the amount of memory alloted to vertex buffers is exceeded.
 
ArgumentError — Buffer Too Big: when numVertices is greater than 0x10000 or data32PerVertex is greater than 64.
 
ArgumentError — Buffer Has Zero Size: when numVertices is zero or data32PerVertex is zero.
 
ArgumentError — Buffer Creation Failed: if the VertexBuffer3D object could not be created by the rendering context (but additional information about the reason is not available).
 
Error — 3768: The Stage3D API may not be used during background execution.
 
Error — Requires Standard Extended Profile Or Above: if this method is called when the requested profile is less than standard extended profile.
 
Error — Invalid Instances Per Element: if the instancesPerElement is not greater than zero.

See also

createVideoTexture()method 
public function createVideoTexture():VideoTexture

Language version: ActionScript 3.0
Runtime version: AIR 17.0

Creates a VideoTexture object.

Use a VideoTexture object to obtain video frames as texture from NetStream object or Camera object and to upload the video frames to the rendering context.

The VideoTexture object cannot be created with the VideoTexture constructor; use this method instead. After creating a VideoTexture object, attach NetStream object or Camera Object to get the video frames with the VideoTexture attachNetStream() or attachCamera() methods.

Note that this method returns null if the system doesn't support this feature.

VideoTexture does not contain mipmaps. If VideoTexture is used with a sampler that uses mip map filtering or repeat wrapping, the drawTriangles call will fail. VideoTexture can be treated as BGRA texture by the shaders. The attempt to instantiate the VideoTexture Object will fail if the Context3D was requested with sotfware rendering mode.

A maximum of 4 VideoTexture objects are available per Context3D instance. On mobile the actual number of supported VideoTexture objects may be less than 4 due to platform limitations.

Returns
VideoTexture

Throws
Error — Object Disposed: if this Context3D object has been disposed by a calling dispose() or because the underlying rendering hardware has been lost.
 
Error — Resource Limit Exceeded: if too many Texture objects are created or the amount of memory allocated to textures is exceeded.
 
Error — Texture Creation Failed: if the Texture object could not be created by the rendering context (but information about the reason is not available).
dispose()method 
public function dispose(recreate:Boolean = true):void

Language version: ActionScript 3.0
Runtime version: AIR 3

Frees all resources and internal storage associated with this Context3D.

All index buffers, vertex buffers, textures, and programs that were created through this Context3D are disposed just as if calling dispose() on each of them individually. In addition, the Context3D itself is disposed freeing all temporary buffers and the back buffer. If you call configureBackBuffer(), clear(), drawTriangles(), createCubeTexture(), createTexture(), createProgram(), createIndexBuffer(), createVertexBuffer(), or drawToBitmapData() after calling dispose(), the runtime throws an exception.

Warning: calling dispose() on a Context3D while there is still a event listener for Events.CONTEXT3D_CREATE set on the asociated Stage3D object the dispose() call will simulate a device loss. It will create a new Context3D on the Stage3D and issue the Events.CONTEXT3D_CREATE event again. If this is not desired remove the event listener from the Stage3D object before calling dispose() or set the recreate parameter to false.

Parameters
recreate:Boolean (default = true)

See also

drawToBitmapData()method 
public function drawToBitmapData(destination:BitmapData, srcRect:Rectangle = null, destPoint:Point = null):void

Language version: ActionScript 3.0
Runtime version: AIR 3

Draws the current render buffer to a bitmap.

The current contents of the back render buffer are copied to a BitmapData object. This is potentially a very slow operation that can take up to a second. Use with care. Note that this function does not copy the front render buffer (the one shown on stage), but the buffer being drawn to. To capture the rendered image as it appears on the stage, call drawToBitmapData() immediately before you calling present().

Beginning with AIR 25, two new parameters have been introduced in the API drawToBitmapData(). This API now takes three parameters. The first one is the existing parameter destination:BitmapData. The second parameter is srcRect:Rectangle, which is target rectangle on stage3D. The third parameter is destPoint:Point, which is the coordinate on the destination bitmap. The parameters srcRect and destPoint are optional and default to (0,0,bitmapWidth,bitmapHeight) and (0,0), respectively.

When the image is drawn, it is not scaled to fit the bitmap. Instead, the contents are clipped to the size of the destination bitmap.

Flash BitmapData objects store colors already multiplied by the alpha component. For example, if the "pure" rgb color components of a pixel are (0x0A, 0x12, 0xBB) and the alpha component is 0x7F (.5), then the pixel is stored in the BitmapData object with the rgba values: (0x05, 0x09, 0x5D, 0x7F). You can set the blend factors so that the colors rendered to the buffer are multiplied by alpha or perform the operation in the fragment shader. The rendering context does not validate that the colors are stored in premultiplied format.

Parameters
destination:BitmapData
 
srcRect:Rectangle (default = null)
 
destPoint:Point (default = null)

Throws
Error — Object Disposed: if this Context3D object has been disposed by a calling dispose() or because the underlying rendering hardware has been lost.
 
Error — 3768: The Stage3D API may not be used during background execution.
 
Error — 3802: If either one of the parameters destPoint:Point or srcRect:Rectangle is outside the bitmap/stage3D coordinate bound, or if non-Numeric(NaN) values are passed as input.

Example
The following example renders two triangles to both the normal render buffer and a BitmapData object. The BitmapData object is displayed using a Bitmap object added to the normal display list. A drop shadow filter is applied to the bitmap rendering.
package
{
    import com.adobe.utils.AGALMiniAssembler;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Sprite;
	import flash.display.Stage3D;
	import flash.display3D.Context3D;
	import flash.display3D.Context3DProgramType;
	import flash.display3D.Context3DRenderMode;
	import flash.display3D.Context3DVertexBufferFormat;
	import flash.display3D.IndexBuffer3D;
	import flash.display3D.Program3D;
	import flash.display3D.VertexBuffer3D;
	import flash.events.Event;
	import flash.filters.DropShadowFilter;
	
	public class Context3D_drawToBitmapData extends Sprite
	{
		public const viewWidth:Number = 320;
		public const viewHeight:Number = 200;
		
		private var bitmap:Bitmap;
		private var stage3D:Stage3D;
		private var renderContext:Context3D;
		private var indexList:IndexBuffer3D;
		private var vertexes:VertexBuffer3D;
		
		private const VERTEX_SHADER:String =
			"mov op, va0	\n" +	//copy position to output 
			"mov v0, va1"; //copy color to varying variable v0
		
		private const FRAGMENT_SHADER:String = 
			"mov oc, v0"; //Set the output color to the value interpolated from the three triangle vertices 

		private var vertexAssembly:AGALMiniAssembler = new AGALMiniAssembler();
		private var fragmentAssembly:AGALMiniAssembler = new AGALMiniAssembler();
		private var programPair:Program3D;
		
		public function Context3D_drawToBitmapData()
		{
			stage3D = this.stage.stage3Ds[0];
			stage3D.x = 0;
			stage3D.y = 0;

			//Add event listener before requesting the context
			stage3D.addEventListener( Event.CONTEXT3D_CREATE, contextCreated );			
			stage3D.requestContext3D( Context3DRenderMode.AUTO );
			
			//Compile shaders
			vertexAssembly.assemble( Context3DProgramType.VERTEX, VERTEX_SHADER, false );
			fragmentAssembly.assemble( Context3DProgramType.FRAGMENT, FRAGMENT_SHADER, false );			
		}
		
		//Note, context3DCreate event can happen at any time, such as when the hardware resources are taken by another process
		private function contextCreated( event:Event ):void
		{
			renderContext = Stage3D( event.target ).context3D;
			trace( "3D driver: " + renderContext.driverInfo );

			renderContext.enableErrorChecking = true; //Can slow rendering - only turn on when developing/testing
			renderContext.configureBackBuffer( viewWidth, viewHeight, 2, false );
			
			//Create vertex index list for the triangles
			var triangles:Vector.<uint> = Vector.<uint>( [ 0, 1, 2, 0, 3, 4 ] );
			indexList = renderContext.createIndexBuffer( triangles.length );
			indexList.uploadFromVector( triangles, 0, triangles.length );
			
			//Create vertexes
			const dataPerVertex:int = 6;
			var vertexData:Vector.<Number> = Vector.<Number>(
				[
				  // x, y, z    r, g, b format
					 0, 0, 0,   1, 1, 1,
					-1, 1, 0,   0, 0,.5,
					 1, 1, 0,   0, 0, 1,
					 1,-1, 0,  .5, 0, 0,
					-1,-1, 0,   1, 0, 0
				]
			);
			vertexes = renderContext.createVertexBuffer( vertexData.length/dataPerVertex, dataPerVertex );
			vertexes.uploadFromVector( vertexData, 0, vertexData.length/dataPerVertex );
			
			//Identify vertex data inputs for vertex program
			renderContext.setVertexBufferAt( 0, vertexes, 0, Context3DVertexBufferFormat.FLOAT_3 ); //va0 is position
			renderContext.setVertexBufferAt( 1, vertexes, 3, Context3DVertexBufferFormat.FLOAT_3 ); //va1 is color
			
			//Upload programs to render context
			programPair = renderContext.createProgram();
			programPair.upload( vertexAssembly.agalcode, fragmentAssembly.agalcode );
			renderContext.setProgram( programPair );
			
			//Clear required before first drawTriangles() call
			renderContext.clear( .3,.3,.3 );
			
			
			//Draw the 2 triangles
			renderContext.drawTriangles( indexList, 0, 2 );
			
			var renderedBitmapData:BitmapData = new BitmapData( viewWidth, viewHeight, true );
			renderContext.drawToBitmapData( renderedBitmapData );
			
			renderContext.present();
			
			//Add to stage
			bitmap = new Bitmap( renderedBitmapData );
			this.addChild( bitmap );
			bitmap.x = 55;
			bitmap.y = 25;
			bitmap.filters = [new DropShadowFilter( 8, 235, .4 )];
		}
	}
}

drawTriangles()method 
public function drawTriangles(indexBuffer:IndexBuffer3D, firstIndex:int = 0, numTriangles:int = -1):void

Language version: ActionScript 3.0
Runtime version: AIR 3

Render the specified triangles using the current buffers and state of this Context3D object.

For each triangle, the triangle vertices are processed by the vertex shader program and the triangle surface is processed by the pixel shader program. The output color from the pixel program for each pixel is drawn to the render target depending on the stencil operations, depth test, source and destination alpha, and the current blend mode. The render destination can be the main render buffer or a texture.

If culling is enabled, (with the setCulling() method), then triangles can be discarded from the scene before the pixel program is run. If stencil and depth testing are enabled, then output pixels from the pixel program can be discarded without updating the render destination. In addition, the pixel program can decide not to output a color for a pixel.

The rendered triangles are not displayed in the viewport until you call the present() method. After each present() call, the clear() method must be called before the first drawTriangles() call or rendering fails.

When enableErrorChecking is false, this function returns immediately, does not wait for results, and throws exceptions only if this Context3D instance has been disposed or there are too many draw calls. If the rendering context state is invalid rendering fails silently. When the enableErrorChecking property is true, this function returns after the triangles are drawn and throws exceptions for any drawing errors or invalid context state.

Parameters
indexBuffer:IndexBuffer3D — a set of vertex indices referencing the vertices to render.
 
firstIndex:int (default = 0) — the index of the first vertex index selected to render. Default 0.
 
numTriangles:int (default = -1) — the number of triangles to render. Each triangle consumes three indices. Pass -1 to draw all triangles in the index buffer. Default -1.

Throws
Error — Object Disposed: if this Context3D object has been disposed by a calling dispose() or because the underlying rendering hardware has been lost.
 
Error — If this method is called too many times between calls to present(). The maximum number of calls is 32,768.

The following errors are only thrown when enableErrorChecking property is true:

 
Error — Need To Clear Before Draw: If the buffer has not been cleared since the last present() call.
 
Error — If a valid Program3D object is not set.
 
Error — No Valid Index Buffer Set: If an IndexBuffer3D object is not set.
 
Error — Sanity Check On Parameters Failed: when the number of triangles to be drawn or the firstIndex exceed allowed values.
 
RangeError — Not Enough Indices In This Buffer: when there aren't enough indices in the buffer to define the number of triangles to be drawn.
 
Error — Sample Binds Texture Also Bound To Render: when the render target is a texture and that texture assigned to a texture input of the current fragment program.
 
Error — Sample Binds Invalid Texture: an invalid texture is specified as the input to the current fragment program.
 
Error — Sampler Format Does Not Match Texture Format: when the texture assigned as the input to the current fragment program has a different format than that specified for the sampler register. For example, a 2D texture is assigned to a cube texture sampler.
 
Error — Sample Binds Undefined Texture: The current fragment program accesses a texture register that has not been set (using setTextureAt()).
 
Error — Same Texture Needs Same Sampler Params: If a texture is used for more than one sampler register, all of the samplers must have the same settings. For example, you cannot set one sampler to clamp and another to wrap.
 
Error — Texture Bound But Not Used: A texture is set as a shader input, but it is not used.
 
Error — Stream Is Not Used: A vertex buffer is assigned to a vertex attribute input, but the vertex program does not reference the corresponding register.
 
Error — Stream Is Invalid: a VertexBuffer3D object assigned to a vertex program input is not a valid object.
 
RangeError — Stream Does Not Have Enough Vertices: A vertex buffer supplying data for drawing the specified triangles does not have enough data.
 
RangeError — Stream Vertex Offset Out Of Bounds: The offset specified in a setVertexBufferAt() call is negative or past the end of the buffer.
 
Error — Stream Read But Not Set: A vertex attribute used by the current vertex program is not set (using setVertexBufferAt()).

See also


Example
The following class draws two triangles to a Stage3D viewport on the stage. The triangles share one vertex, which is located at the origin (0,0,0).

The triangles are defined using the vertex buffer and the index buffer. The vertex buffer contains the position and color information for each triangle vertex. The index buffer contains indexes into the vertex buffer. Three indexes define a triangle. For example, a triangle that consisted of the first three points in the vertex buffer is listed as 0,1,2 in the index buffer.

In this simple example, no 3D transformation is performed. Only objects within the canonical viewing area (a 2x2x1 unit volume) can be displayed and the coordinates of the triangles are defined to be within this area. However, when rendering a typical 3D scene, you project the objects to be rendered from the "world" coordinate system into this viewing area using either a perspective or orthographic projection.

package
{
    import com.adobe.utils.AGALMiniAssembler;
	
	import flash.display.Sprite;
	import flash.display.Stage3D;
	import flash.display3D.Context3D;
	import flash.display3D.Context3DProgramType;
	import flash.display3D.Context3DRenderMode;
	import flash.display3D.Context3DVertexBufferFormat;
	import flash.display3D.IndexBuffer3D;
	import flash.display3D.Program3D;
	import flash.display3D.VertexBuffer3D;
	import flash.events.Event;
	
	public class Context3D_drawTriangles extends Sprite
	{
		public const viewWidth:Number = 320;
		public const viewHeight:Number = 200;
		
		private var stage3D:Stage3D;
		private var renderContext:Context3D;
		private var indexList:IndexBuffer3D;
		private var vertexes:VertexBuffer3D;
		
		private const VERTEX_SHADER:String =
			"mov op, va0	\n" +	//copy position to output 
			"mov v0, va1"; //copy color to varying variable v0
		
		private const FRAGMENT_SHADER:String = 
			"mov oc, v0"; //Set the output color to the value interpolated from the three triangle vertices 

		private var vertexAssembly:AGALMiniAssembler = new AGALMiniAssembler();
		private var fragmentAssembly:AGALMiniAssembler = new AGALMiniAssembler();
		private var programPair:Program3D;
		
		public function Context3D_drawTriangles()
		{
			stage3D = this.stage.stage3Ds[0];
			stage3D.x = 10;
			stage3D.y = 10;

			//Add event listener before requesting the context
			stage3D.addEventListener( Event.CONTEXT3D_CREATE, contextCreated );			
			stage3D.requestContext3D( Context3DRenderMode.AUTO );
			
			//Compile shaders
			vertexAssembly.assemble( Context3DProgramType.VERTEX, VERTEX_SHADER, false );
			fragmentAssembly.assemble( Context3DProgramType.FRAGMENT, FRAGMENT_SHADER, false );			
		}
		
		//Note, context3DCreate event can happen at any time, such as when the hardware resources are taken by another process
		private function contextCreated( event:Event ):void
		{
			renderContext = Stage3D( event.target ).context3D;
			trace( "3D driver: " + renderContext.driverInfo );

			renderContext.enableErrorChecking = true; //Can slow rendering - only turn on when developing/testing
			renderContext.configureBackBuffer( viewWidth, viewHeight, 2, false );
			
			//Create vertex index list for the triangles
			var triangles:Vector.<uint> = Vector.<uint>( [ 0, 1, 2, 0, 3, 4 ] );
			indexList = renderContext.createIndexBuffer( triangles.length );
			indexList.uploadFromVector( triangles, 0, triangles.length );
			
			//Create vertexes
			const dataPerVertex:int = 6;
			var vertexData:Vector.<Number> = Vector.<Number>(
				[
				  // x, y, z    r, g, b format
					 0, 0, 0,   1, 1, 1,
					-1, 1, 0,   0, 0,.5,
					 1, 1, 0,   0, 0, 1,
					 1,-1, 0,  .5, 0, 0,
					-1,-1, 0,   1, 0, 0
				]
			);
			vertexes = renderContext.createVertexBuffer( vertexData.length/dataPerVertex, dataPerVertex );
			vertexes.uploadFromVector( vertexData, 0, vertexData.length/dataPerVertex );
			
			//Identify vertex data inputs for vertex program
			renderContext.setVertexBufferAt( 0, vertexes, 0, Context3DVertexBufferFormat.FLOAT_3 ); //va0 is position
			renderContext.setVertexBufferAt( 1, vertexes, 3, Context3DVertexBufferFormat.FLOAT_3 ); //va1 is color
			
			//Upload programs to render context
			programPair = renderContext.createProgram();
			programPair.upload( vertexAssembly.agalcode, fragmentAssembly.agalcode );
			renderContext.setProgram( programPair );
			
			//Clear required before first drawTriangles() call
			renderContext.clear( .3,.3,.3 );
			
			//Draw the 2 triangles
			renderContext.drawTriangles( indexList, 0, 2 );
			
			//Show the frame
			renderContext.present();
		}
	}
}

drawTrianglesInstanced()method 
public function drawTrianglesInstanced(indexBuffer:IndexBuffer3D, numInstances:int, firstIndex:int = 0, numTriangles:int = -1):void

Language version: ActionScript 3.0
Runtime version: AIR 20.0

Render the specified instanced triangles using the current buffers and state of this Context3D object.

For each triangle of each instance, the triangle vertices are processed by the vertex shader program and the triangle surface is processed by the pixel shader program. The output color from the pixel program for each pixel is drawn to the render target depending on the stencil operations, depth test, source and destination alpha, and the current blend mode. The render destination can be the main render buffer or a texture.

If culling is enabled, (with the setCulling() method), then triangles can be discarded from the scene before the pixel program is run. If stencil and depth testing are enabled, then output pixels from the pixel program can be discarded without updating the render destination. In addition, the pixel program can decide not to output a color for a pixel.

The rendered instanced traingles are not displayed in the viewport until you call the present() method. After each present() call, the clear() method must be called before the first drawTrianglesInstanced() call or rendering fails.

When enableErrorChecking is false, this function returns immediately, does not wait for results, and throws exceptions only if this Context3D instance has been disposed or there are too many draw calls. If the rendering context state is invalid rendering fails silently. When the enableErrorChecking property is true, this function returns after the triangles are drawn and throws exceptions for any drawing errors or invalid context state.

This method may throw an exception if the instanced buffer is improperly sequenced with SetVertexAt(). With Direct 3D 9, for example, the indexed geometry data and the number of instances to draw must always be set in stream zero with SetStreamSourceFreq() API.

This means that the vertex buffer created using CreateVertexBufferForInstance() should not be placed with the minimal index number when arranged with SetVertexBufferAt() as input to the vertex shader program. The vertex buffer generated using CreateVertexBuffer() must be placed with a smaller index number than that for CreateVertexBufferForInstance(). In general, the geometry data must be placed before per-instance data, with SetVertexBufferAt().

Parameters
indexBuffer:IndexBuffer3D — a set of vertex indices referencing the vertices to render.
 
numInstances:int — number of instances to render.
 
firstIndex:int (default = 0) — the index of the first vertex index selected to render. Default 0.
 
numTriangles:int (default = -1) — the number of triangles to render. Each triangle consumes three indices. Pass -1 to draw all triangles in the index buffer. Default -1.

Throws
Error — Object Disposed: if this Context3D object has been disposed by a calling dispose() or because the underlying rendering hardware has been lost.
 
Error — If this method is called too many times between calls to present(). The maximum number of calls is 32,768.
 
Error — Requires Standard Extended Profile Or Above: if this method is called when the requested profile is less than standard extended profile.
 
Error — If this method is called with negative numInstances.

The following errors are only thrown when enableErrorChecking property is true:

 
Error — Need To Clear Before Draw: If the buffer has not been cleared since the last present() call.
 
Error — If a valid Program3D object is not set.
 
Error — No Valid Index Buffer Set: If an IndexBuffer3D object is not set.
 
Error — Sanity Check On Parameters Failed: when the number of triangles to be drawn or the firstIndex exceed allowed values.
 
RangeError — Not Enough Indices In This Buffer: when there aren't enough indices in the buffer to define the number of triangles to be drawn.
 
Error — Sample Binds Texture Also Bound To Render: when the render target is a texture and that texture assigned to a texture input of the current fragment program.
 
Error — Sample Binds Invalid Texture: an invalid texture is specified as the input to the current fragment program.
 
Error — Sampler Format Does Not Match Texture Format: when the texture assigned as the input to the current fragment program has a different format than that specified for the sampler register. For example, a 2D texture is assigned to a cube texture sampler.
 
Error — Sample Binds Undefined Texture: The current fragment program accesses a texture register that has not been set (using setTextureAt()).
 
Error — Same Texture Needs Same Sampler Params: If a texture is used for more than one sampler register, all of the samplers must have the same settings. For example, you cannot set one sampler to clamp and another to wrap.
 
Error — Texture Bound But Not Used: A texture is set as a shader input, but it is not used.
 
Error — Stream Is Not Used: A vertex buffer is assigned to a vertex attribute input, but the vertex program does not reference the corresponding register.
 
Error — Stream Is Invalid: a VertexBuffer3D object assigned to a vertex program input is not a valid object.
 
RangeError — Stream Does Not Have Enough Vertices: A vertex buffer supplying data for drawing the specified triangles does not have enough data.
 
RangeError — Stream Vertex Offset Out Of Bounds: The offset specified in a setVertexBufferAt() call is negative or past the end of the buffer.
 
Error — Stream Read But Not Set: A vertex attribute used by the current vertex program is not set (using setVertexBufferAt()).
 
Error — Vertex Buffer Stream Does Not Contain Enough Elements For Instances: If a vertex buffer stream does not contain enough elements for number of instances.
 
Error — Vertex Buffer Stream For Instances Is Improperly Set With The Minimal Index Attribute Register: If the vertex buffer generated using CreateVertexBuffer() is given a larger index number than that for the vertex buffer generated using CreateVertexBufferForInstance().

See also


Example
The following class draws three triangles using the feature instanced drawing using a single draw call instead of multiple draw calls.
package
{
    import com.adobe.utils.v3.AGALMiniAssembler;
	
	import flash.display.Sprite;
	import flash.display.Stage3D;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.display3D.Context3D;
	import flash.display3D.Context3DProgramType;
	import flash.display3D.Context3DTriangleFace;
	import flash.display3D.Context3DVertexBufferFormat;
	import flash.display3D.IndexBuffer3D;
	import flash.display3D.Program3D;
	import flash.display3D.VertexBuffer3D;
	import flash.events.Event;
	import flash.geom.Matrix3D;
	import flash.utils.ByteArray;
	
	public class Context3D_HelloInstancedDrawing extends Sprite
	{
		private var W:int;
		private var H:int;
		
		private var renderContext:Context3D;
		private var program:Program3D;
		private var vertexBuffer:VertexBuffer3D;
		private var instanceBufferColor:VertexBuffer3D;
		private var instanceBufferTranslation:VertexBuffer3D;
		private var indexBuffer:IndexBuffer3D;
		private var m:Matrix3D;
		private var vertexShader:ByteArray;
		private var fragmentShader:ByteArray;
		
		public function Context3D_HelloInstancedDrawing()
		{
			if (hasEventListener(Event.ADDED_TO_STAGE))
				removeEventListener(Event.ADDED_TO_STAGE, init);
			W = stage.stageWidth;
			H = stage.stageHeight;
			stage.scaleMode = StageScaleMode.NO_SCALE;
			stage.align = StageAlign.TOP_LEFT;
			stage.stage3Ds[0].addEventListener(Event.CONTEXT3D_CREATE, contextCreated);
			//We need to request context3D in standard extended profile as instanced drawing requires standard extended profile.
			stage.stage3Ds[0].requestContext3D("auto","standardExtended");			
			
		}
		
		//Note: <code>context3DCreate</code> event can happen at any time. For example, when the hardware resources are taken up by another process.
		private function contextCreated( event:Event ):void
		{
			var t:Stage3D = event.target as Stage3D;
			renderContext = t.context3D;
			trace( "3D driver: " + renderContext.driverInfo );
			setupScene();
		}
		
		
		private function setupScene():void
		{
			renderContext.enableErrorChecking = true;
			renderContext.configureBackBuffer( W, H, 2, false );
			renderContext.setCulling( Context3DTriangleFace.BACK );
			
			//create vertex buffer for geometry information of the instances (same geometry of the instances)
			vertexBuffer = renderContext.createVertexBuffer(3, 3);
			
			//The color and translation information varies across the instances. Use <code>createVertexBufferForInstances</code> for color and translation information.
			//the intancesPerElement parameter used is 1 which means that each instance will use unique element of the instances buffer
			//if the intancesPerElement is 3 then sets of 3 instances will use the same element of the instances buffer
			instanceBufferColor = renderContext.createVertexBufferForInstances(4,3,1);
			instanceBufferTranslation = renderContext.createVertexBufferForInstances(4,3,1);
			//create index buffer for the triangle
			indexBuffer = renderContext.createIndexBuffer(3);
			
			//create and compile program
			program = renderContext.createProgram();
			var assembler:AGALMiniAssembler = new AGALMiniAssembler();
			
			// VERTEX SHADER
			var code:String = "";
			//The vertex shader code runs for every vertex of each instance.
			//The vertex buffers uploaded for instance data (va1,va2) are used when the vertex shader for that particular instance is being executed.
			code += "add vt0, va0, va2\n";
			code += "mov op, vt0\n";
			code += "mov v0, va1\n";
			
			vertexShader = assembler.assemble(Context3DProgramType.VERTEX, code);
			
			//FRAGMENT SHADER
			code = "mov oc, v0\n"; 
			
			// Compile the agal code into bytecode using agalminiassembler
			fragmentShader = assembler.assemble(Context3DProgramType.FRAGMENT, code);
			
			//upload program to gpu
			program.upload(vertexShader, fragmentShader);
			
			//geometry data for the instances
			var vertexData:Vector.<Number>=Vector.<Number>([
				-0.3, -0.3, 0, 	// - 1st vertex x,y,z
				0, 0.3, 1, 	    // - 2nd vertex x,y,z 
				0.3, -0.3, 0    // - 3rd vertex x,y,z
			]);
			
			//per instance color data
			var instanceColorData:Vector.<Number>=Vector.<Number>([
				1.0, 0.0, 0.0, 	// - 1st instance r,g,b
				0.0, 1.0, 0.0,  // - 2nd instance r,g,b
				1.0, 1.0, 1.0,	// - 3rd instance r,g,b
				0.7, 0.0, 1.0   // - 4th instance r,g,b
			]);
			//per instance translation data
			var instanceTranslationData:Vector.<Number>=Vector.<Number>([
				-0.3, -0.3, 0.0, 	// - 1st instance x,y,z
				0.3, 0.3, 0.0, 		// - 2nd instance x,y,z
				-0.3, 0.3, 0.0,	    // - 3rd instance x,y,z
				0.3, -0.3, 0.0      // - 4th instance x,y,z
			]);
			
			vertexBuffer.uploadFromVector(vertexData, 0, 3);
			instanceBufferColor.uploadFromVector(instanceColorData, 0, 4);
			indexBuffer.uploadFromVector(Vector.<uint>([0, 1, 2]), 0, 3);
			instanceBufferTranslation.uploadFromVector(instanceTranslationData, 0, 4);
			
			//pass data to program
			renderContext.setVertexBufferAt(0, vertexBuffer, 0, Context3DVertexBufferFormat.FLOAT_3);
			renderContext.setVertexBufferAt(1, instanceBufferColor, 0, Context3DVertexBufferFormat.FLOAT_3);
			renderContext.setVertexBufferAt(2, instanceBufferTranslation, 0, Context3DVertexBufferFormat.FLOAT_3);
			
			//set active program
			renderContext.setProgram(program);
			renderContext.enableErrorChecking = true;
			addEventListener(Event.ENTER_FRAME, render);
			
		}
		
		private function render( event:Event ):void
		{
			renderContext.clear(0.3, 0.2, 1, 1); // Clear the backbuffer by filling it with the given color
			//Draw three instances of the same geometry but with varying instance data specified using <code>vertexBufferForInstances</code>.
			renderContext.drawTrianglesInstanced(indexBuffer,4);
			renderContext.present(); // render the backbuffer on screen.
		}	
	}
}

The following class draws three triangles using the feature instanced drawing using a single draw call instead of multiple draw calls.
package
{
    import com.adobe.utils.v3.AGALMiniAssembler;
	
	import flash.display.Sprite;
	import flash.display.Stage3D;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.display3D.Context3D;
	import flash.display3D.Context3DProgramType;
	import flash.display3D.Context3DTriangleFace;
	import flash.display3D.Context3DVertexBufferFormat;
	import flash.display3D.IndexBuffer3D;
	import flash.display3D.Program3D;
	import flash.display3D.VertexBuffer3D;
	import flash.events.Event;
	import flash.geom.Matrix3D;
	import flash.utils.ByteArray;
	
	public class Context3D_HelloInstanceIdRegister extends Sprite
	{
		private var W:int;
		private var H:int;
		
		private var renderContext:Context3D;
		private var program:Program3D;
		private var vertexBuffer:VertexBuffer3D;
		private var instanceBufferColor:VertexBuffer3D;
		private var instanceBufferTranslation:VertexBuffer3D;
		private var indexBuffer:IndexBuffer3D;
		private var m:Matrix3D;
		private var vertexShader:ByteArray;
		private var fragmentShader:ByteArray;
		
		public function Context3D_HelloInstanceIdRegister()
		{
			if (hasEventListener(Event.ADDED_TO_STAGE))
				removeEventListener(Event.ADDED_TO_STAGE, init);
			W = stage.stageWidth;
			H = stage.stageHeight;
			stage.scaleMode = StageScaleMode.NO_SCALE;
			stage.align = StageAlign.TOP_LEFT;
			stage.stage3Ds[0].addEventListener(Event.CONTEXT3D_CREATE, contextCreated);
			//We need to request context3D in standard extended profile as instanced drawing requires standard extended profile.
			stage.stage3Ds[0].requestContext3D("auto","standardExtended");			
			
		}
		
		//Note: <code>context3DCreate</code> event can happen at any time. For example, when the hardware resources are taken up by another process.
		private function contextCreated( event:Event ):void
		{
			var t:Stage3D = event.target as Stage3D;
			renderContext = t.context3D;
			trace( "3D driver: " + renderContext.driverInfo );
			setupScene();
		}
		
		
		private function setupScene():void
		{
			renderContext.enableErrorChecking = true;
			renderContext.configureBackBuffer( W, H, 2, false );
			renderContext.setCulling( Context3DTriangleFace.BACK );
			
			//create vertex buffer for geometry information of the instances (same geometry of the instances)
			vertexBuffer = renderContext.createVertexBuffer(3, 3);
			
			//The color and translation information varies across the instances. Use <code>createVertexBufferForInstances</code> for color and translation information.
			//the intancesPerElement parameter used is 1 which means that each instance will use unique element of the instances buffer
			//if the intancesPerElement is 3 then sets of 3 instances will use the same element of the instances buffer
			instanceBufferColor = renderContext.createVertexBufferForInstances(4,3,1);
			instanceBufferTranslation = renderContext.createVertexBufferForInstances(4,3,1);
			//create index buffer for the triangle
			indexBuffer = renderContext.createIndexBuffer(3);
			
			//create and compile program
			program = renderContext.createProgram();
			//Note : for instance id support , use the latest AgalMiniAssembler from github - https://github.com/adobe-flash/graphicscorelib/blob/master/src/com/adobe/utils/v3/AGALMiniAssembler.as
			var assembler:AGALMiniAssembler = new AGALMiniAssembler();
			
			// VERTEX SHADER
			var code:String = "";
			//the vertex shader code will run for every vertex of every instance , 
			//the vertex buffers uploaded for instance data (va1,va2) will be used when vertex shader for that particular instance is being executed 
			//the vertex shader code below indexes the program constants matrix using iid.x. iid is a new register introduced in vertex shader for instanced drawing
			//it is a read only register , iid.x gives the current instance id whose shader is being executed
			code += "add vt0, va0, va2\n";
			code += "mul vt1, vt0, vc[iid.x]\n"
			code += "mov op, vt1\n";
			code += "mov v0, va1\n";
			
			vertexShader = assembler.assemble(Context3DProgramType.VERTEX, code, 3);
			
			//FRAGMENT SHADER
			code = "mov oc, v0\n"; 
			
			// Compile the agal code into bytecode using agalminiassembler
			fragmentShader = assembler.assemble(Context3DProgramType.FRAGMENT, code, 3);
			
			//upload program to gpu
			program.upload(vertexShader, fragmentShader);
			
			//geometry data for the instances
			var vertexData:Vector.<Number>=Vector.<Number>([
				-0.3, -0.3, 0, 	// - 1st vertex x,y,z
				0, 0.3, 1, 	    // - 2nd vertex x,y,z 
				0.3, -0.3, 0    // - 3rd vertex x,y,z
			]);
			
			//per instance color data
			var instanceColorData:Vector.<Number>=Vector.<Number>([
				1.0, 0.0, 0.0, 	// - 1st instance r,g,b
				0.0, 1.0, 0.0,  // - 2nd instance r,g,b
				1.0, 1.0, 1.0,	// - 3rd instance r,g,b
				0.7, 0.0, 1.0   // - 4th instance r,g,b
			]);
			//per instance translation data
			var instanceTranslationData:Vector.<Number>=Vector.<Number>([
				-0.3, -0.3, 0.0, 	// - 1st instance x,y,z
				0.3, 0.3, 0.0, 		// - 2nd instance x,y,z
				-0.3, 0.3, 0.0,	    // - 3rd instance x,y,z
				0.3, -0.3, 0.0      // - 4th instance x,y,z
			]);
			
			vertexBuffer.uploadFromVector(vertexData, 0, 3);
			instanceBufferColor.uploadFromVector(instanceColorData, 0, 4);
			indexBuffer.uploadFromVector(Vector.<uint>([0, 1, 2]), 0, 3);
			instanceBufferTranslation.uploadFromVector(instanceTranslationData, 0, 4);
			
			//pass data to program
			renderContext.setVertexBufferAt(0, vertexBuffer, 0, Context3DVertexBufferFormat.FLOAT_3);
			renderContext.setVertexBufferAt(1, instanceBufferColor, 0, Context3DVertexBufferFormat.FLOAT_3);
			renderContext.setVertexBufferAt(2, instanceBufferTranslation, 0, Context3DVertexBufferFormat.FLOAT_3);
			
			//set active program
			renderContext.setProgram(program);
			renderContext.enableErrorChecking = true;
			addEventListener(Event.ENTER_FRAME, render);
			
		}
		
		private function render( event:Event ):void
		{
			renderContext.clear(0.3, 0.2, 1, 1); // Clear the backbuffer by filling it with the given color
			var instanceScalingData:Vector.<Number>=Vector.<Number>([
				1.0, 1.0, 1.0, 1.0, 	// - 1st instance x,y,z,w
				1.4, 1.4, 1.4, 1.0,		// - 2nd instance x,y,z,w
				0.6, 0.6, 0.6, 1.0,		// - 3rd instance x,y,z,w
				0.6, 0.6, 0.6, 1.0
			]);
			var m:Matrix3D = new Matrix3D();
			m.copyRawDataFrom(instanceScalingData);
			renderContext.setProgramConstantsFromMatrix("vertex",0,m,false);
			
			//Draw three instances of the same geometry but with varying instance data specified using <code>vertexBufferForInstances</code>.
			renderContext.drawTrianglesInstanced(indexBuffer,4);
			renderContext.present(); // render the backbuffer on screen.
		}	
	}
}

present()method 
public function present():void

Language version: ActionScript 3.0
Runtime version: AIR 3

Displays the back rendering buffer.

Calling the present() method makes the results of all rendering operations since the last present() call visible and starts a new rendering cycle. After calling present, you must call clear() before making another drawTriangles() call. Otherwise, this function will alternately clear the render buffer to yellow and green or, if enableErrorChecking has been set to true, an exception is thrown.

Calling present() also resets the render target, just like calling setRenderToBackBuffer().


Throws
Error — Need To Clear Before Draw: If the clear() has not been called since the previous call to present(). (Two consecutive present() calls are not allowed without calling clear() in between.)
 
Error — 3768: The Stage3D API may not be used during background execution.
setBlendFactors()method 
public function setBlendFactors(sourceFactor:String, destinationFactor:String):void

Language version: ActionScript 3.0
Runtime version: AIR 3

Specifies the factors used to blend the output color of a drawing operation with the existing color.

The output (source) color of the pixel shader program is combined with the existing (destination) color at that pixel according to the following formula:

result color = (source color * sourceFactor) + (destination color * destinationFactor)

The destination color is the current color in the render buffer for that pixel. Thus it is the result of the most recent clear() call and any intervening drawTriangles() calls.

Use setBlendFactors() to set the factors used to multiply the source and destination colors before they are added together. The default blend factors are, sourceFactor = Context3DBlendFactor.ONE, and destinationFactor = Context3DBlendFactor.ZERO, which results in the source color overwriting the destination color (in other words, no blending of the two colors occurs). For normal alpha blending, use sourceFactor = Context3DBlendFactor.SOURCE_ALPHA and destinationFactor = Context3DBlendFactor.ONE_MINUS_SOURCE_ALPHA.

Use the constants defined in the Context3DBlendFactor class to set the parameters of this function.

Parameters
sourceFactor:String — The factor with which to multiply the source color. Defaults to Context3DBlendFactor.ONE.
 
destinationFactor:String — The factor with which to multiply the destination color. Defaults to Context3DBlendFactor.ZERO.

Throws
Error — Invalid Enum: when sourceFactor or destinationFactor is not one of the recognized values, which are defined in the Context3DBlendFactor class.

See also


Example
The following class illustrates the various blend factors. The example draws four different colored rectangles to the render buffer. This set of rectangles is the blend "destination." Next, the source and destination blend modes are set and a larger rectangle, the blend "source," is drawn. Use the keys "1" and "2" to cycle through the source blend modes. Use the "3" and "4" keys to cycle through the destination blend modes.
package
{
    import com.adobe.utils.AGALMiniAssembler;
	
	import flash.display.Sprite;
	import flash.display.Stage3D;
	import flash.display3D.Context3D;
	import flash.display3D.Context3DBlendFactor;
	import flash.display3D.Context3DProgramType;
	import flash.display3D.Context3DRenderMode;
	import flash.display3D.Context3DVertexBufferFormat;
	import flash.display3D.IndexBuffer3D;
	import flash.display3D.Program3D;
	import flash.display3D.VertexBuffer3D;
	import flash.events.ErrorEvent;
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	import flash.ui.Keyboard;
	
	public class Context3D_setBlendMode extends Sprite
	{
		public const viewWidth:Number = 320;
		public const viewHeight:Number = 200;
		
		private var stage3D:Stage3D;
		private var renderContext:Context3D;
		private var indexList:IndexBuffer3D;
		private var vertexes:VertexBuffer3D;
		
		private const VERTEX_SHADER:String =
			"mov op, va0	\n" +	//copy position to output 
			"mov v0, va1"; //copy color to varying variable v0
		
		private const FRAGMENT_SHADER:String = 
			"mov oc, v0"; //Set the output color to the value interpolated from the three triangle vertices 

		private var vertexAssembly:AGALMiniAssembler = new AGALMiniAssembler();
		private var fragmentAssembly:AGALMiniAssembler = new AGALMiniAssembler();
		private var programPair:Program3D;
		
		private var sourceFactor:int = 6;
		private var destinationFactor:int = 4;
		private var blendFactors:Array = [Context3DBlendFactor.DESTINATION_ALPHA,
										  Context3DBlendFactor.DESTINATION_COLOR,
										  Context3DBlendFactor.ONE,
										  Context3DBlendFactor.ONE_MINUS_DESTINATION_ALPHA,
										  Context3DBlendFactor.ONE_MINUS_SOURCE_ALPHA,
										  Context3DBlendFactor.ONE_MINUS_SOURCE_COLOR,
										  Context3DBlendFactor.SOURCE_ALPHA,
										  Context3DBlendFactor.SOURCE_COLOR,
										  Context3DBlendFactor.ZERO];
			
		public function Context3D_setBlendMode()
		{
			this.stage.addEventListener( KeyboardEvent.KEY_DOWN, keyHandler );
			
			stage3D = this.stage.stage3Ds[0];
			stage3D.x = 10;
			stage3D.y = 10;

			//Add event listener before requesting the context
			stage3D.addEventListener( Event.CONTEXT3D_CREATE, contextCreated );
			stage3D.addEventListener( ErrorEvent.ERROR, contextError );
			stage3D.requestContext3D( Context3DRenderMode.AUTO );
			
			//Compile shaders
			vertexAssembly.assemble( Context3DProgramType.VERTEX, VERTEX_SHADER, false );
			fragmentAssembly.assemble( Context3DProgramType.FRAGMENT, FRAGMENT_SHADER, false );			
		}
		
		//Note, context3DCreate event can happen at any time, such as when the hardware resources are taken by another process
		private function contextCreated( event:Event ):void
		{
			renderContext = Stage3D( event.target ).context3D;
			trace( "3D driver: " + renderContext.driverInfo );

			renderContext.enableErrorChecking = true; //Can slow rendering - only turn on when developing/testing
			renderContext.configureBackBuffer( viewWidth, viewHeight, 2, false );
			
			//Create vertex index list for the triangles
			var triangles:Vector.<uint> = Vector.<uint>( [  0, 3 , 2, 
															0, 1, 3,
															6, 4, 5,
															5, 7, 6,
															10, 8, 9,
															9, 11, 10,
															12, 15, 14,
															12, 13, 15,
															16, 17, 19,
															16, 19, 18
														 ] );
			indexList = renderContext.createIndexBuffer( triangles.length );
			indexList.uploadFromVector( triangles, 0, triangles.length );
			
			//Create vertexes
			const dataPerVertex:int = 7;
			var vertexData:Vector.<Number> = Vector.<Number>(
				[
				  // x, y, z    r, g, b, a format
					-1, 1, 0,   1, 1, 1, .5,
					 0, 1, 0,   1, 1, 1, .5,
					-1, 0, 0,   1, 1, 1, .5,
					 0, 0, 0,   1, 1, 1, .5,
					 
					 0, 1, 0,  .8,.8,.8, .6,
					 1, 1, 0,  .8,.8,.8, .6,
					 0, 0, 0,  .8,.8,.8, .6,
					 1, 0, 0,  .8,.8,.8, .6,
					 
					-1, 0, 0,   1, 0, 0, .5,
					 0, 0, 0,   0, 1, 0, .5,
					-1,-1, 0,   0, 0, 1, .5,
					 0,-1, 0,   1, 0, 1, .5,
					 
					 0, 0, 0,   0, 0, 0, .5,
					 1, 0, 0,   0, 0, 0, .5,
					 0,-1, 0,   0, 0, 0, .5,
					 1,-1, 0,   0, 0, 0, .5,
					 
				   -.8,.8, 0,  .6,.4,.2,.4,
				    .8,.8, 0,  .6,.4,.2,.4,
				  -.8,-.8, 0,  .6,.4,.2,.4,
				   .8,-.8, 0,  .6,.4,.2,.4
				]
			);
			vertexes = renderContext.createVertexBuffer( vertexData.length/dataPerVertex, dataPerVertex );
			vertexes.uploadFromVector( vertexData, 0, vertexData.length/dataPerVertex );
			
			//Identify vertex data inputs for vertex program
			renderContext.setVertexBufferAt( 0, vertexes, 0, Context3DVertexBufferFormat.FLOAT_3 ); //va0 is position
			renderContext.setVertexBufferAt( 1, vertexes, 3, Context3DVertexBufferFormat.FLOAT_4 ); //va1 is color
			
			//Upload programs to render context
			programPair = renderContext.createProgram();
			programPair.upload( vertexAssembly.agalcode, fragmentAssembly.agalcode );
			renderContext.setProgram( programPair );
			
			render();
		}
		
		private function render():void
		{
			//Clear required before first drawTriangles() call
			renderContext.clear( 1, 1, 1, 1 );
			//Draw the back triangles
			renderContext.setBlendFactors( Context3DBlendFactor.ONE, Context3DBlendFactor.ZERO ); //No blending
			renderContext.drawTriangles( indexList, 0, 8 );

			//Set blend
			renderContext.setBlendFactors( blendFactors[sourceFactor], blendFactors[destinationFactor] );
			
			//Draw the front triangles
			renderContext.drawTriangles( indexList, 24, 2 );
			
			//Show the frame
			renderContext.present();
		}
		
		private function contextError( error:ErrorEvent ):void
		{
			trace( error.errorID + ": " + error.text );
		}
		
		private function keyHandler( event:KeyboardEvent ):void
		{
			switch ( event.keyCode )
			{
				case Keyboard.NUMBER_1:
					if( --sourceFactor < 0 ) sourceFactor = blendFactors.length - 1; 
					break;
				case Keyboard.NUMBER_2:
					if( ++sourceFactor > blendFactors.length - 1) sourceFactor = 0;
					break;
				case Keyboard.NUMBER_3:
					if( --destinationFactor < 0 ) destinationFactor = blendFactors.length - 1; 
					break;
				case Keyboard.NUMBER_4:
					if( ++destinationFactor > blendFactors.length - 1) destinationFactor = 0;
					break;
			}
			trace( "Source blend factor: " + blendFactors[sourceFactor] + ", destination blend factor: " + blendFactors[destinationFactor] );
			render();
		}
	}
}

setColorMask()method 
public function setColorMask(red:Boolean, green:Boolean, blue:Boolean, alpha:Boolean):void

Language version: ActionScript 3.0
Runtime version: AIR 3

Sets the mask used when writing colors to the render buffer.

Only color components for which the corresponding color mask parameter is true are updated when a color is written to the render buffer. For example, if you call: setColorMask( true, false, false, false ), only the red component of a color is written to the buffer until you change the color mask again. The color mask does not affect the behavior of the clear() method.

Parameters
red:Boolean — set false to block changes to the red channel.
 
green:Boolean — set false to block changes to the green channel.
 
blue:Boolean — set false to block changes to the blue channel.
 
alpha:Boolean — set false to block changes to the alpha channel.

Example
The following example illustrates the effect of setting the color mask. The example draws two triangles that are the same color. The top triangle is drawn before the mask is set and so is rendered as white. The bottom triangle is drawn after all the channels except the red channel are masked. Since only the red channel can be updated, the white triangle is rendered as red.
package
{
    import com.adobe.utils.AGALMiniAssembler;
	
	import flash.display.Sprite;
	import flash.display.Stage3D;
	import flash.display3D.Context3D;
	import flash.display3D.Context3DProgramType;
	import flash.display3D.Context3DRenderMode;
	import flash.display3D.Context3DVertexBufferFormat;
	import flash.display3D.IndexBuffer3D;
	import flash.display3D.Program3D;
	import flash.display3D.VertexBuffer3D;
	import flash.events.Event;
	
	public class Context3D_setColorMask extends Sprite
	{
		public const viewWidth:Number = 320;
		public const viewHeight:Number = 200;
		
		private var stage3D:Stage3D;
		private var renderContext:Context3D;
		private var indexList:IndexBuffer3D;
		private var vertexes:VertexBuffer3D;
		
		private const VERTEX_SHADER:String =
			"mov op, va0	\n" +	//copy position to output 
			"mov v0, va1"; //copy color to varying variable v0
		
		private const FRAGMENT_SHADER:String = 
			"mov oc, v0"; //Set the output color to the value interpolated from the three triangle vertices 

		private var vertexAssembly:AGALMiniAssembler = new AGALMiniAssembler();
		private var fragmentAssembly:AGALMiniAssembler = new AGALMiniAssembler();
		private var programPair:Program3D;
		
		public function Context3D_setColorMask()
		{
			stage3D = this.stage.stage3Ds[0];
			stage3D.x = 10;
			stage3D.y = 10;

			//Add event listener before requesting the context
			stage3D.addEventListener( Event.CONTEXT3D_CREATE, contextCreated );			
			stage3D.requestContext3D( Context3DRenderMode.AUTO );
			
			//Compile shaders
			vertexAssembly.assemble( Context3DProgramType.VERTEX, VERTEX_SHADER, false );
			fragmentAssembly.assemble( Context3DProgramType.FRAGMENT, FRAGMENT_SHADER, false );			
		}
		
		//Note, context3DCreate event can happen at any time, such as when the hardware resources are taken by another process
		private function contextCreated( event:Event ):void
		{
			renderContext = Stage3D( event.target ).context3D;
			trace( "3D driver: " + renderContext.driverInfo );

			renderContext.enableErrorChecking = true; //Can slow rendering - only turn on when developing/testing
			renderContext.configureBackBuffer( viewWidth, viewHeight, 2, false );
			
			//Create vertex index list for the triangles
			var triangles:Vector.<uint> = Vector.<uint>( [ 0, 1, 2, 0, 3, 4 ] );
			indexList = renderContext.createIndexBuffer( triangles.length );
			indexList.uploadFromVector( triangles, 0, triangles.length );
			
			//Create vertexes
			const dataPerVertex:int = 6;
			var vertexData:Vector.<Number> = Vector.<Number>(
				[
				  // x, y, z    r, g, b format
					 0, 0, 0,   1, 1, 1,
					-1, 1, 0,   1, 1, 1,
					 1, 1, 0,   1, 1, 1,
					 1,-1, 0,   1, 1, 1,
					-1,-1, 0,   1, 1, 1
				]
			);
			vertexes = renderContext.createVertexBuffer( vertexData.length/dataPerVertex, dataPerVertex );
			vertexes.uploadFromVector( vertexData, 0, vertexData.length/dataPerVertex );
			
			//Identify vertex data inputs for vertex program
			renderContext.setVertexBufferAt( 0, vertexes, 0, Context3DVertexBufferFormat.FLOAT_3 ); //va0 is position
			renderContext.setVertexBufferAt( 1, vertexes, 3, Context3DVertexBufferFormat.FLOAT_3 ); //va1 is color
			
			//Upload programs to render context
			programPair = renderContext.createProgram();
			programPair.upload( vertexAssembly.agalcode, fragmentAssembly.agalcode );
			renderContext.setProgram( programPair );
			
			renderContext.clear( .3,.3,.3,1 );
			renderContext.drawTriangles( indexList, 0, 1 ); //Top triangle draws all colors, so is white
			renderContext.setColorMask( true, false, false, false ); //Mask all but red channel			
			renderContext.drawTriangles( indexList, 3, 1 ); //Bottom triangle only updates red
			
			//Show the frame
			renderContext.present();
		}
	}
}

setCulling()method 
public function setCulling(triangleFaceToCull:String):void

Language version: ActionScript 3.0
Runtime version: AIR 3

Sets triangle culling mode.

Triangles may be excluded from the scene early in the rendering pipeline based on their orientation relative to the view plane. Specify vertex order consistently (clockwise or counter-clockwise) as seen from the outside of the model to cull correctly.

Parameters
triangleFaceToCull:String — the culling mode. Use one of the constants defined in the Context3DTriangleFace class.

Throws
Error — Invalid Enum Error: when triangleFaceToCull is not one of the values defined in the Context3DTriangleFace class.

See also

setDepthTest()method 
public function setDepthTest(depthMask:Boolean, passCompareMode:String):void

Language version: ActionScript 3.0
Runtime version: AIR 3

Sets type of comparison used for depth testing.

The depth of the source pixel output from the pixel shader program is compared to the current value in the depth buffer. If the comparison evaluates as false, then the source pixel is discarded. If true, then the source pixel is processed by the next step in the rendering pipeline, the stencil test. In addition, the depth buffer is updated with the depth of the source pixel, as long as the depthMask parameter is set to true.

Sets the test used to compare depth values for source and destination pixels. The source pixel is composited with the destination pixel when the comparison is true. The comparison operator is applied as an infix operator between the source and destination pixel values, in that order.

Parameters
depthMask:Boolean — the destination depth value will be updated from the source pixel when true.
 
passCompareMode:String — the depth comparison test operation. One of the values of Context3DCompareMode.

See also

setFillMode()method 
public function setFillMode(fillMode:String):void

Language version: ActionScript 3.0
Runtime version: AIR 16

Set fill mode used for render. The interface is only available in AIR desktop.

Parameters
fillMode:String — if the value is WIREFRAME, the object will be shown in a mesh of lines. if the value is SOLID, the object will be shown in solid shaded polygons.

See also

setProgram()method 
public function setProgram(program:Program3D):void

Language version: ActionScript 3.0
Runtime version: AIR 3

Sets vertex and fragment shader programs to use for subsequent rendering.

Parameters
program:Program3D — the Program3D object representing the vertex and fragment programs to use.

See also


Example
This example illustrates how to create, upload, and activate a pair of vertex and pixel programs to a rendering context. Note that the object, renderContext, is an instance of the Context3D class. The programs in the example are written in Adobe Graphics Assembly Language (AGAL).
//A simple vertex program in AGAL
const VERTEX_SHADER:String =
    "m44 op, va0, vc0 \n" +	
	"mov v0, va1"; 

//A simple fragment (or pixel) program in AGAL		
const FRAGMENT_SHADER:String = "mov oc, v0";  

var vertexAssembly:AGALMiniAssembler = new AGALMiniAssembler();
var fragmentAssembly:AGALMiniAssembler = new AGALMiniAssembler();
var programPair:Program3D;

//Compile shaders
vertexAssembly.assemble( Context3DProgramType.VERTEX, VERTEX_SHADER, false );
fragmentAssembly.assemble( Context3DProgramType.FRAGMENT, FRAGMENT_SHADER, false );			

//Upload programs to render context
programPair = renderContext.createProgram();
programPair.upload( vertexAssembly.agalcode, fragmentAssembly.agalcode );
renderContext.setProgram( programPair );

setProgramConstantsFromByteArray()method 
public function setProgramConstantsFromByteArray(programType:String, firstRegister:int, numRegisters:int, data:ByteArray, byteArrayOffset:uint):void

Language version: ActionScript 3.0
Runtime version: AIR 3.1

Set constants for use by shader programs using values stored in a ByteArray.

Sets constants that can be accessed from the vertex or fragment program.

Parameters
programType:String — one of Context3DProgramType.
 
firstRegister:int — the index of the first shader program constant to set.
 
numRegisters:int — the number of registers to set. Every register is read as four float values.
 
data:ByteArray — the source ByteArray object
 
byteArrayOffset:uint — an offset into the ByteArray for reading

Throws
TypeError — kNullPointerError when data is null.
 
RangeError — kConstantRegisterOutOfBounds when attempting to set more than the maximum number of shader constants.
 
RangeError — kBadInputSize if byteArrayOffset is greater than or equal to the length of data or no. of elements in data - byteArrayOffset is less than numRegisters*16

See also

setProgramConstantsFromFloatVector()method 
public function setProgramConstantsFromFloatVector(programType:String, firstRegister:int, data:Vector.<float>, numRegisters:int = -1):void

Language version: ActionScript 3.0
Runtime version: AIR 51.0

Sets the constant inputs for the shader programs.

Sets an array of constants to be accessed by a vertex or fragment shader program. Constants set in Program3D are accessed within the shader programs as constant registers. Each constant register is comprised of 4 floating point values (x, y, z, w). Therefore every register requires 4 entries in the data Vector. You can set 128 registers for a vertex program and 28 for a fragment program.

Parameters
programType:String — The type of shader program, either Context3DProgramType.VERTEX or Context3DProgramType.FRAGMENT.
 
firstRegister:int — the index of the first constant register to set.
 
data:Vector.<float> — the floating point constant values. There must be at least numRegisters 4 elements in data.
 
numRegisters:int (default = -1) — the number of constants to set. Specify -1, the default value, to set enough registers to use all of the available data.

Throws
TypeError — Null Pointer Error: when data is null.
 
RangeError — Constant Register Out Of Bounds: when attempting to set more than the maximum number of shader constant registers (128 for vertex programs; 28 for fragment programs).

See also

setProgramConstantsFromMatrix()method 
public function setProgramConstantsFromMatrix(programType:String, firstRegister:int, matrix:Matrix3D, transposedMatrix:Boolean = false):void

Language version: ActionScript 3.0
Runtime version: AIR 3

Sets constants for use by shader programs using values stored in a Matrix3D.

Use this function to pass a matrix to a shader program. The function sets 4 constant registers used by the vertex or fragment program. The matrix is assigned to registers row by row. The first constant register is assigned the top row of the matrix. You can set 128 registers for a vertex program and 28 for a fragment program.

Parameters
programType:String — The type of shader program, either Context3DProgramType.VERTEX or Context3DProgramType.FRAGMENT.
 
firstRegister:int — the index of the first constant register to set. Since a Matrix3D has 16 values, four registers are set.
 
matrix:Matrix3D — the matrix containing the constant values.
 
transposedMatrix:Boolean (default = false) — if true the matrix entries are copied to registers in transposed order. The default value is false.

Throws
TypeError — Null Pointer Error: when matrix is null.
 
RangeError — Constant Register Out Of Bounds: when attempting to set more than the maximum number of shader constant registers.

See also

setProgramConstantsFromVector()method 
public function setProgramConstantsFromVector(programType:String, firstRegister:int, data:Vector.<Number>, numRegisters:int = -1):void

Language version: ActionScript 3.0
Runtime version: AIR 3

Sets the constant inputs for the shader programs.

Sets an array of constants to be accessed by a vertex or fragment shader program. Constants set in Program3D are accessed within the shader programs as constant registers. Each constant register is comprised of 4 floating point values (x, y, z, w). Therefore every register requires 4 entries in the data Vector. The number of registers that you can set for vertex program and fragment program depends on the Context3DProfile.

Parameters
programType:String — The type of shader program, either Context3DProgramType.VERTEX or Context3DProgramType.FRAGMENT.
 
firstRegister:int — the index of the first constant register to set.
 
data:Vector.<Number> — the floating point constant values. There must be at least numRegisters 4 elements in data.
 
numRegisters:int (default = -1) — the number of constants to set. Specify -1, the default value, to set enough registers to use all of the available data.

Throws
TypeError — Null Pointer Error: when data is null.
 
RangeError — Constant Register Out Of Bounds: when attempting to set more than the maximum number of shader constant registers.
 
RangeError — Bad Input Size: When the number of elements in data is less than numRegisters*4

See also

setRenderToBackBuffer()method 
public function setRenderToBackBuffer():void

Language version: ActionScript 3.0
Runtime version: AIR 3

Sets the back rendering buffer as the render target. Subsequent calls to drawTriangles() and clear() methods result in updates to the back buffer. Use this method to resume normal rendering after using the setRenderToTexture() method.

setRenderToTexture()method 
public function setRenderToTexture(texture:TextureBase, enableDepthAndStencil:Boolean = false, antiAlias:int = 0, surfaceSelector:int = 0, colorOutputIndex:int = 0):void

Language version: ActionScript 3.0
Runtime version: AIR 3

Sets the specified texture as the rendering target.

Subsequent calls to drawTriangles() and clear() methods update the specified texture instead of the back buffer. Mip maps are created automatically. Use the setRenderToBackBuffer() to resume normal rendering to the back buffer.

No clear is needed before drawing. If there is no clear operation, the render content will be retained. depth buffer and stencil buffer will also not be cleared. But it is forced to clear when first drawing. Calling present() resets the target to the back buffer.

Parameters
texture:TextureBase — the target texture to render into. Set to null to resume rendering to the back buffer (setRenderToBackBuffer() and present also reset the target to the back buffer).
 
enableDepthAndStencil:Boolean (default = false) — if true, depth and stencil testing are available. If false, all depth and stencil state is ignored for subsequent drawing operations.
 
antiAlias:int (default = 0) — the antialiasing quality. Use 0 to disable antialiasing; higher values improve antialiasing quality, but require more calculations. The value is currently ignored by mobile platform and software rendering context.
 
surfaceSelector:int (default = 0) — specifies which element of the texture to update. Texture objects have one surface, so you must specify 0, the default value. CubeTexture objects have six surfaces, so you can specify an integer from 0 through 5.
 
colorOutputIndex:int (default = 0) — The output color register. Must be 0 for constrained or baseline mode. Otherwise specifies the output color register.

Throws
ArgumentError — for a mismatched surfaceSelector parameter. The value must be 0 for 2D textures and 0..5 for cube maps.
 
ArgumentError texture is not derived from the TextureBase class (either Texture or CubeTexture classes).
 
ArgumentError colorOutputIndex must be an integer is from 0 through 3.
 
ArgumentError — this call requires a Context3D that is created with the standard profile or above.

See also

setSamplerStateAt()method 
public function setSamplerStateAt(sampler:int, wrap:String, filter:String, mipfilter:String):void

Language version: ActionScript 3.0
Runtime version: AIR 3.6

Manually override texture sampler state.

Texture sampling state is typically set at the time setProgram is called. However, you can override texture sampler state with this function. If you do not want the program to change sampler state, set the ignoresamnpler bit in AGAL and use this function.

Parameters
sampler:int — sampler The sampler register to use. Maps to the sampler register in AGAL.
 
wrap:String — Wrapping mode. Defined in Context3DWrapMode. The default is repeat.
 
filter:String — Texture filtering mode. Defined in Context3DTextureFilter. The default is nearest.
 
mipfilter:String — Mip map filter. Defined in Context3DMipFilter. The default is none.

Throws
Error — sampler out of range
 
Error — wrap, filter, mipfilter bad enum
 
Error — Object Disposed: if this Context3D object has been disposed by a calling dispose() or because the underlying rendering hardware has been lost.

See also

setScissorRectangle()method 
public function setScissorRectangle(rectangle:Rectangle):void

Language version: ActionScript 3.0
Runtime version: AIR 3

Sets a scissor rectangle, which is type of drawing mask. The renderer only draws to the area inside the scissor rectangle. Scissoring does not affect clear operations.

Pass null to turn off scissoring.

Parameters
rectangle:Rectangle — The rectangle in which to draw. Specify the rectangle position and dimensions in pixels. The coordinate system origin is the top left corner of the viewport, with positive values increasing down and to the right (the same as the normal Flash display coordinate system).

Example
The following class draws two triangles to a 640x480 pixel view port on the stage. The triangles share one vertex, which is located at the origin (0,0,0).

The triangles are defined using the vertex buffer and the index buffer. The vertex buffer contains the position and color information for each triangle vertex. The index buffer contains indexes into the vertex buffer. Three indexes define a triangle. For example, a triangle that consisted of the first three points in the vertex buffer is listed as 0,1,2 in the index buffer.

In this simple example, no 3D transformation is performed. Only objects within the canonical viewing area (a 2x2x2 cube volume centered on the origin) are displayed. However, when rendering a typical 3D scene, you project the objects to be rendered into this viewing area using either a perspective or orthographic projection.

package
{
    import com.adobe.utils.AGALMiniAssembler;
	
	import flash.display.Sprite;
	import flash.display.Stage3D;
	import flash.display3D.Context3D;
	import flash.display3D.Context3DBlendFactor;
	import flash.display3D.Context3DProgramType;
	import flash.display3D.Context3DRenderMode;
	import flash.display3D.Context3DVertexBufferFormat;
	import flash.display3D.IndexBuffer3D;
	import flash.display3D.Program3D;
	import flash.display3D.VertexBuffer3D;
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	import flash.events.TimerEvent;
	import flash.geom.Rectangle;
	import flash.ui.Keyboard;
	import flash.utils.Timer;
	
	public class Context3D_ScissorRectangle extends Sprite
	{
		public const viewWidth:Number = 640;
		public const viewHeight:Number = 480;
		
		private var stage3D:Stage3D;
		private var renderContext:Context3D;
		private var indexList:IndexBuffer3D;
		private var vertexes:VertexBuffer3D;
		
		private const VERTEX_SHADER:String =
			"mov op, va0	\n" +	//copy position to output 
			"mov v0, va1"; //copy color to varying variable v0
		
		private const FRAGMENT_SHADER:String = 
			"mov oc, v0"; //Set the output color to the value interpolated from the three triangle vertices 

		private var vertexAssembly:AGALMiniAssembler = new AGALMiniAssembler();
		private var fragmentAssembly:AGALMiniAssembler = new AGALMiniAssembler();
		private var programPair:Program3D;
		
		private var scissorOn:Boolean = false;
		private var toggler:Timer = new Timer( 750 );
		
		public function Context3D_ScissorRectangle()
		{			
			stage3D = this.stage.stage3Ds[0];
			stage3D.x = 10;
			stage3D.y = 10;

			//Add event listener before requesting the context
			stage3D.addEventListener( Event.CONTEXT3D_CREATE, contextCreated );			
			stage3D.requestContext3D( Context3DRenderMode.AUTO );
			
			//Compile shaders
			vertexAssembly.assemble( Context3DProgramType.VERTEX, VERTEX_SHADER, false );
			fragmentAssembly.assemble( Context3DProgramType.FRAGMENT, FRAGMENT_SHADER, false );
			
			//Set up timer to turn scissoring on and off
			toggler.addEventListener( TimerEvent.TIMER, toggleScissor );
		}
		
		//Note, context3DCreate event can happen at any time, such as when the hardware resources are taken by another process
		private function contextCreated( event:Event ):void
		{
			renderContext = Stage3D( event.target ).context3D;
			trace( "3D driver: " + renderContext.driverInfo );

			renderContext.enableErrorChecking = true; //Can slow rendering - only turn on when developing/testing
			renderContext.configureBackBuffer( viewWidth, viewHeight, 2, false );
			
			//Create vertex index list for the triangles
			var triangles:Vector.<uint> = Vector.<uint>( [  0, 3 , 2, 
															0, 1, 3
														 ] );
			indexList = renderContext.createIndexBuffer( triangles.length );
			indexList.uploadFromVector( triangles, 0, triangles.length );
			
			//Create vertexes
			const dataPerVertex:int = 6;
			var vertexData:Vector.<Number> = Vector.<Number>(
				[
				  // x, y, z    r, g, b, a format 
				   -1, 1, 0,  1,0,0,
				    1, 1, 0,  0,0,1,
				   -1,-1, 0,  0,1,0,
				    1,-1, 0,  1,0,1
				]
			);
			vertexes = renderContext.createVertexBuffer( vertexData.length/dataPerVertex, dataPerVertex );
			vertexes.uploadFromVector( vertexData, 0, vertexData.length/dataPerVertex );
			
			//Identify vertex data inputs for vertex program
			renderContext.setVertexBufferAt( 0, vertexes, 0, Context3DVertexBufferFormat.FLOAT_3 ); //va0 is position
			renderContext.setVertexBufferAt( 1, vertexes, 3, Context3DVertexBufferFormat.FLOAT_3 ); //va1 is color
			
			//Upload programs to render context
			programPair = renderContext.createProgram();
			programPair.upload( vertexAssembly.agalcode, fragmentAssembly.agalcode );
			renderContext.setProgram( programPair );
			
			render();
			toggler.start();
		}
		
		private function render():void
		{
			//Clear required before first drawTriangles() call
			renderContext.clear();

			//Sciss a region excluding the outer 100 pixels of the viewport
			var scissor:Rectangle = new Rectangle( 100, 100, viewWidth - 200, viewHeight - 200 );
			if( scissorOn )	renderContext.setScissorRectangle( scissor ); //on
			else renderContext.setScissorRectangle( null ); //off

			//Draw the triangles
			renderContext.drawTriangles( indexList, 0, 2 );
			
			//Show the frame
			renderContext.present();
		}
		
		private function toggleScissor( event:Event ):void
		{
			scissorOn = !scissorOn;
			render();
		}
		
	}
}

setStencilActions()method 
public function setStencilActions(triangleFace:String = "frontAndBack", compareMode:String = "always", actionOnBothPass:String = "keep", actionOnDepthFail:String = "keep", actionOnDepthPassStencilFail:String = "keep"):void

Language version: ActionScript 3.0
Runtime version: AIR 3

Sets stencil mode and operation.

An 8-bit stencil reference value can be associated with each draw call. During rendering, the reference value can be tested against values stored previously in the frame buffer. The result of the test can control the draw action and whether or how the stored stencil value is updated. In addition, depth testing controls whether stencil testing is performed. A failed depth test can also be used to control the action taken on the stencil buffer.

In the pixel processing pipeline, depth testing is performed first. If the depth test fails, a stencil buffer update action can be taken, but no further evaluation of the stencil buffer value can be made. If the depth test passes, then the stencil test is performed. Alternate actions can be taken depending on the outcome of the stencil test.

The stencil reference value is set using setStencilReferenceValue().

Parameters
triangleFace:String (default = "frontAndBack") — the triangle orientations allowed to contribute to the stencil operation. One of Context3DTriangleFace.
 
compareMode:String (default = "always") — the test operator used to compare the current stencil reference value and the destination pixel stencil value. Destination pixel color and depth update is performed when the comparison is true. The stencil actions are performed as requested in the following action parameters. The comparison operator is applied as an infix operator between the current and destination reference values, in that order (in pseudocode: if stencilReference OPERATOR stencilBuffer then pass). Use one of the constants defined in the Context3DCompareMode class.
 
actionOnBothPass:String (default = "keep") — action to be taken when both depth and stencil comparisons pass. Use one of the constants defined in the Context3DStencilAction class.
 
actionOnDepthFail:String (default = "keep") — action to be taken when depth comparison fails. Use one of the constants defined in the Context3DStencilAction class.
 
actionOnDepthPassStencilFail:String (default = "keep") — action to be taken when depth comparison passes and the stencil comparison fails. Use one of the constants defined in the Context3DStencilAction class.

Throws
Error — Invalid Enum Error: when triangleFace is not one of the values defined in the Context3DTriangleFace class.
 
Error — Invalid Enum Error: when compareMode is not one of the values defined in the Context3DCompareMode class.
 
Error — Invalid Enum Error: when actionOnBothPass, actionOnDepthFail, or actionOnDepthPassStencilFail is not one of the values defined in the Context3DStencilAction class.

See also


Example
The following class illustrates how to draw a stencil and use it as a mask for subsequent drawing operations. The example performs the following steps:

Mouse over the example to see the main steps in sequence.

package
{
    import com.adobe.utils.AGALMiniAssembler;
	
	import flash.display.Sprite;
	import flash.display.Stage3D;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.display3D.Context3D;
	import flash.display3D.Context3DBlendFactor;
	import flash.display3D.Context3DCompareMode;
	import flash.display3D.Context3DProgramType;
	import flash.display3D.Context3DRenderMode;
	import flash.display3D.Context3DStencilAction;
	import flash.display3D.Context3DTriangleFace;
	import flash.display3D.Context3DVertexBufferFormat;
	import flash.display3D.IndexBuffer3D;
	import flash.display3D.Program3D;
	import flash.display3D.VertexBuffer3D;
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	import flash.events.MouseEvent;
	import flash.events.TimerEvent;
	import flash.geom.Rectangle;
	import flash.text.TextField;
	import flash.text.TextFormat;
	import flash.ui.Keyboard;
	import flash.utils.Timer;
	
	public class Context3D_Stencil extends Sprite
	{
		public const viewWidth:Number = 350;
		public const viewHeight:Number = 240;
		
		private var stage3D:Stage3D;
		private var renderContext:Context3D;
		private var indexList:IndexBuffer3D;
		private var vertexes:VertexBuffer3D;
		
		private const VERTEX_SHADER:String =
			"mov op, va0	\n" +	//copy position to output 
			"mov v0, va1"; //copy color to varying variable v0
		
		private const FRAGMENT_SHADER:String = 
			"mov oc, v0"; //Set the output color to the value interpolated from the three triangle vertices 

		private var vertexAssembly:AGALMiniAssembler = new AGALMiniAssembler();
		private var fragmentAssembly:AGALMiniAssembler = new AGALMiniAssembler();
		private var programPair:Program3D;
				
		public function Context3D_Stencil()
		{			
			stage3D = this.stage.stage3Ds[0];
			stage3D.x = 10;
			stage3D.y = 10;

			//Add event listener before requesting the context
			stage3D.addEventListener( Event.CONTEXT3D_CREATE, contextCreated );			
			stage3D.requestContext3D( Context3DRenderMode.AUTO );
			
			//Compile shaders
			vertexAssembly.assemble( Context3DProgramType.VERTEX, VERTEX_SHADER, false );
			fragmentAssembly.assemble( Context3DProgramType.FRAGMENT, FRAGMENT_SHADER, false );
		
			non3DSetup();
		}
		
		//Note, context3DCreate event can happen at any time, such as when the hardware resources are taken by another process
		private function contextCreated( event:Event ):void
		{
			renderContext = Stage3D( event.target ).context3D;
			trace( "3D driver: " + renderContext.driverInfo );

			renderContext.enableErrorChecking = true; //Can slow rendering - only turn on when developing/testing
			renderContext.configureBackBuffer( viewWidth, viewHeight, 2, true );
			
			//Create vertex index list for the triangles
			var triangles:Vector.<uint> = Vector.<uint>( [  0, 3, 2, 
															0, 1, 3,
															4, 7, 6,
															4, 5, 7,
															8, 9, 10
														 ] );
			indexList = renderContext.createIndexBuffer( triangles.length );
			indexList.uploadFromVector( triangles, 0, triangles.length );
			
			//Create vertexes
			const dataPerVertex:int = 6;
			var vertexData:Vector.<Number> = Vector.<Number>(
				[
				  //x, y, z  r,g,b format 
				   -1, 1, 0,  1,0,0,
				    1, 1, 0,  0,0,1,
				   -1,-1, 0,  0,1,0,
				    1,-1, 0,  1,0,1,

				   -1, 1, 0,  .5,0,0,
					1, 1, 0,  .5,0,0,
				   -1,-1, 0,  .5,0,0,
					1,-1, 0,  .5,0,0,
					
					0, .7,.1, 0,0,0,
				  -.7,-.7,.1, 0,0,0,
				   .7,-.7,.1, 0,0,0
				]);
			vertexes = renderContext.createVertexBuffer( vertexData.length/dataPerVertex, dataPerVertex );
			vertexes.uploadFromVector( vertexData, 0, vertexData.length/dataPerVertex );
			
			//Identify vertex data inputs for vertex program
			renderContext.setVertexBufferAt( 0, vertexes, 0, Context3DVertexBufferFormat.FLOAT_3 ); //va0 is position
			renderContext.setVertexBufferAt( 1, vertexes, 3, Context3DVertexBufferFormat.FLOAT_3 ); //va1 is color
			
			//Upload programs to render context
			programPair = renderContext.createProgram();
			programPair.upload( vertexAssembly.agalcode, fragmentAssembly.agalcode );
			renderContext.setProgram( programPair );
			render();
		}
		private function render():void
		{
			//Clear, setting stencil to 0
			renderContext.clear( .3, .3, .3, 1, 1, 0 );
			
			//Draw stencil, incrementing the stencil buffer value
			renderContext.setStencilReferenceValue( 0 );
			renderContext.setStencilActions( Context3DTriangleFace.FRONT_AND_BACK, 
				Context3DCompareMode.EQUAL, Context3DStencilAction.INCREMENT_SATURATE );			
			if( state > 0 ) renderContext.drawTriangles( indexList, 12, 1 );

			//Change stencil action when stencil passes so stencil buffer is not changed
			renderContext.setStencilActions( Context3DTriangleFace.FRONT_AND_BACK, 
				Context3DCompareMode.EQUAL, Context3DStencilAction.KEEP );
			
			//Draw quad -- doesn't draw where stencil has already drawn
			if( state > 1 ) renderContext.drawTriangles( indexList, 0, 2 );
			
			//Change the reference to 1 so this quad only draws into stenciled area
			renderContext.setStencilReferenceValue( 1 );
			if( state > 2 ) renderContext.drawTriangles( indexList, 6, 2 );
			
			//Show the frame
			renderContext.present();
		}
		
		//The rest of the code is for the example UI and timer 
		private function doState( event:TimerEvent ):void
		{
			switch (state)
			{
				case 0:
					description.text = "Draw triangle with stencil action == increment";
					state = 1;
					break;
				case 1:
					description.text = "Draw the first plane where stencil == 0";
					state = 2;
					break;
				case 2:
					description.text = "Draw second plane where stencil == 1";
					state = 3;
					break;
				case 3:
					description.text = "Clear, setting stencil to 0";
					state = 0;
					break;

				default:
					description.text = "";
					state = 0;		
			}
			render();
		}

		private var state:int = 3;
		private var stateTimer:Timer = new Timer( 1250 );
		private var description:TextField = new TextField();
		
		private function non3DSetup():void
		{
			//Setup timer to animate the stages of drawing the scene
			stateTimer.addEventListener( TimerEvent.TIMER, doState );
			this.stage.addEventListener( MouseEvent.MOUSE_OVER, function(event:Event):void{stateTimer.start()} );
			this.stage.addEventListener( MouseEvent.MOUSE_OUT, function(event:Event):void{stateTimer.stop()} );
			
			description.height = 30;
			description.width = viewWidth;
			this.addChild( description );
			description.y = viewHeight + 15;
			description.defaultTextFormat = new TextFormat( null, 18, 0xffffff );
			description.text = "Mouse over to view.";
			
			//Allows mouse-over events
			var coverSprite:Sprite = new Sprite();
			coverSprite.graphics.beginFill( 0, .01 )
			coverSprite.graphics.lineTo( stage.stageWidth, 0 );
			coverSprite.graphics.lineTo( stage.stageWidth, stage.stageHeight );
			coverSprite.graphics.lineTo( 0, stage.stageHeight );
			coverSprite.graphics.lineTo( 0, 0 );
			this.addChild( coverSprite );			
		}
	}
}

setStencilReferenceValue()method 
public function setStencilReferenceValue(referenceValue:uint, readMask:uint = 255, writeMask:uint = 255):void

Language version: ActionScript 3.0
Runtime version: AIR 3

Sets the stencil comparison value used for stencil tests.

Only the lower 8 bits of the reference value are used. The stencil buffer value is also 8 bits in length. Use the readMask and writeMask to use the stencil buffer as a bit field.

Parameters
referenceValue:uint — an 8-bit reference value used in reference value comparison tests.
 
readMask:uint (default = 255) — an 8-bit mask for applied to both the current stencil buffer value and the reference value before the comparison.
 
writeMask:uint (default = 255) — an 8-bit mask applied to the reference value before updating the stencil buffer.

See also

setTextureAt()method 
public function setTextureAt(sampler:int, texture:TextureBase):void

Language version: ActionScript 3.0
Runtime version: AIR 3

Specifies the texture to use for a texture input register of a fragment program.

A fragment program can read information from up to eight texture objects. Use this function to assign a Texture or CubeTexture object to one of the sampler registers used by the fragment program.

Note: if you change the active fragment program (with setProgram) to a shader that uses fewer textures, set the unused registers to null:


         setTextureAt( 7, null );

         
Parameters
sampler:int — the sampler register index, a value from 0 through 7.
 
texture:TextureBase — the texture object to make available, either a Texture or a CubeTexture instance.

See also

setVertexBufferAt()method 
public function setVertexBufferAt(index:int, buffer:VertexBuffer3D, bufferOffset:int = 0, format:String = "float4"):void

Language version: ActionScript 3.0
Runtime version: AIR 3

Specifies which vertex data components correspond to a single vertex shader program input.

Use the setVertexBufferAt method to identify which components of the data defined for each vertex in a VertexBuffer3D buffer belong to which inputs to the vertex program. The developer of the vertex program determines how much data is needed per vertex. That data is mapped from 1 or more VertexBuffer3D stream(s) to the attribute registers of the vertex shader program.

The smallest unit of data consumed by the vertex shader is a 32-bit data. Offsets into the vertex stream are specified in multiples of 32-bits.

As an example, a programmer might define each vertex with the following data:

position:  x    float32

           y    float32

           z    float32

color:     r    unsigned byte

           g    unsigned byte

           b    unsigned byte

           a    unsigned byte

Assuming the vertex was defined in a VertexBuffer3D object named buffer, it would be assigned to a vertex shader with the following code:

setVertexBufferAt( 0, buffer, 0, Context3DVertexBufferFormat.FLOAT_3 );   // attribute #0 will contain the position information

setVertexBufferAt( 1, buffer, 3, Context3DVertexBufferFormat.BYTES_4 );    // attribute #1 will contain the color information

Parameters
index:int — the index of the attribute register in the vertex shader (0 through 7).
 
buffer:VertexBuffer3D — the buffer that contains the source vertex data to be fed to the vertex shader.
 
bufferOffset:int (default = 0) — an offset from the start of the data for a single vertex at which to start reading this attribute. In the example above, the position data has an offset of 0 because it is the first attribute; color has an offset of 3 because the color attribute follows the three 32-bit position values. The offset is specified in units of 32 bits.
 
format:String (default = "float4") — a value from the Context3DVertexBufferFormat class specifying the data type of this attribute.

Throws
Error — Invalid Enum: when format is not one of the values defined in the Context3DVertexBufferFormat class.
 
RangeError — Attribute Register Out Of Bounds: when the index parameter is outside the range from 0 through 7. (A maximum of eight vertex attribute registers can be used by a shader.)

See also

Examples
examples\Context3DExample
The following class draws a rotating cube using a perspective projection.
package
{
    import com.adobe.utils.AGALMiniAssembler;
	import com.adobe.utils.PerspectiveMatrix3D;
	
	import flash.display.Sprite;
	import flash.display.Stage3D;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.display3D.Context3D;
	import flash.display3D.Context3DProgramType;
	import flash.display3D.Context3DRenderMode;
	import flash.display3D.Context3DTriangleFace;
	import flash.display3D.Context3DVertexBufferFormat;
	import flash.display3D.IndexBuffer3D;
	import flash.display3D.Program3D;
	import flash.display3D.VertexBuffer3D;
	import flash.events.ErrorEvent;
	import flash.events.Event;
	import flash.geom.Matrix3D;
	import flash.geom.Vector3D;
	
	public class Context3DExample extends Sprite
	{
		public const viewWidth:Number = 320;
		public const viewHeight:Number = 200;
		public const zNear:Number = 1;
		public const zFar:Number = 500;
		
		public const fov:Number = 45;
		
		private var stage3D:Stage3D;
		private var renderContext:Context3D;
		private var indexList:IndexBuffer3D;
		private var vertexes:VertexBuffer3D;
		
		private var projection:PerspectiveMatrix3D = new PerspectiveMatrix3D();
		private var model:Matrix3D = new Matrix3D();
		private var view:Matrix3D = new Matrix3D();
		private var finalTransform:Matrix3D = new Matrix3D();
		
		//For rotating the cube
		private const pivot:Vector3D = new Vector3D();
		
		private const VERTEX_SHADER:String =
			"m44 op, va0, vc0	\n" +	// 4x4 matrix transform 
			"mov v0, va1"; //copy color to varying variable v0
		
		private const FRAGMENT_SHADER:String = 
			"mov oc, v0"; //Set the output color to the value interpolated from the three triangle vertices 

		private var vertexAssembly:AGALMiniAssembler = new AGALMiniAssembler();
		private var fragmentAssembly:AGALMiniAssembler = new AGALMiniAssembler();
		private var programPair:Program3D;
		
		public function Context3DExample()
		{
			this.stage.scaleMode = StageScaleMode.NO_SCALE;
			this.stage.align = StageAlign.TOP_LEFT;
			this.stage.nativeWindow.activate(); //AIR only
			 			
			stage3D = this.stage.stage3Ds[0];
			stage3D.x = 10;
			stage3D.y = 10;

			//Add event listener before requesting the context
			stage3D.addEventListener( Event.CONTEXT3D_CREATE, contextCreated );
			stage3D.addEventListener( ErrorEvent.ERROR, contextCreationError );
			stage3D.requestContext3D( Context3DRenderMode.AUTO );
			
			//Compile shaders
			vertexAssembly.assemble( Context3DProgramType.VERTEX, VERTEX_SHADER, false );
			fragmentAssembly.assemble( Context3DProgramType.FRAGMENT, FRAGMENT_SHADER, false );			
		}
		
		//Note, context3DCreate event can happen at any time, such as when the hardware resources are taken by another process
		private function contextCreated( event:Event ):void
		{
				renderContext = Stage3D( event.target ).context3D;
				trace( "3D driver: " + renderContext.driverInfo );
				setupScene();
		}
		
		private function setupScene():void
		{
			renderContext.enableErrorChecking = true; //Can slow rendering - only turn on when developing/testing
			renderContext.configureBackBuffer( viewWidth, viewHeight, 2, false );
			renderContext.setCulling( Context3DTriangleFace.BACK );
			
			//Create vertex index list for the triangles forming a cube
			var triangles:Vector.<uint> = Vector.<uint>( [ 
				2,1,0, //front face
				3,2,0,
				4,7,5, //bottom face
				7,6,5,
				8,11,9, //back face
				9,11,10,
				12,15,13, //top face
				13,15,14,
				16,19,17, //left face
				17,19,18,
				20,23,21, //right face
				21,23,22
			] );
			indexList = renderContext.createIndexBuffer( triangles.length );
			indexList.uploadFromVector( triangles, 0, triangles.length );
			
			//Create vertexes - cube faces do not share vertexes
			const dataPerVertex:int = 6;
			var vertexData:Vector.<Number> = Vector.<Number>(
				[
					// x,y,z r,g,b format
					0,0,0, 1,0,0, //front face
					0,1,0, 1,0,0,
					1,1,0, 1,0,0,
					1,0,0, 1,0,0,
					
					0,0,0, 0,1,0, //bottom face
					1,0,0, 0,1,0,
					1,0,1, 0,1,0,
					0,0,1, 0,1,0,
					
					0,0,1, 1,0,0, //back face
					1,0,1, 1,0,0,
					1,1,1, 1,0,0,
					0,1,1, 1,0,0,
					
					0,1,1, 0,1,0, //top face
					1,1,1, 0,1,0,
					1,1,0, 0,1,0,
					0,1,0, 0,1,0,
					
					0,1,1, 0,0,1, //left face
					0,1,0, 0,0,1,
					0,0,0, 0,0,1,
					0,0,1, 0,0,1,
					
					1,1,0, 0,0,1, //right face
					1,1,1, 0,0,1,
					1,0,1, 0,0,1,
					1,0,0, 0,0,1
				]
			);
			vertexes = renderContext.createVertexBuffer( vertexData.length/dataPerVertex, dataPerVertex );
			vertexes.uploadFromVector( vertexData, 0, vertexData.length/dataPerVertex );
			
			//Identify vertex data inputs for vertex program
			renderContext.setVertexBufferAt( 0, vertexes, 0, Context3DVertexBufferFormat.FLOAT_3 ); //va0 is position
			renderContext.setVertexBufferAt( 1, vertexes, 3, Context3DVertexBufferFormat.FLOAT_3 ); //va1 is color
			
			//Upload programs to render context
			programPair = renderContext.createProgram();
			programPair.upload( vertexAssembly.agalcode, fragmentAssembly.agalcode );
			renderContext.setProgram( programPair );
			
			//Set up 3D transforms
			projection.perspectiveFieldOfViewRH( fov, viewWidth/viewHeight, zNear, zFar );			
			view.appendTranslation( 0, 0, -2 );	//Move view back
			model.appendTranslation( -.5, -.5, -.5 ); //center cube on origin
			this.stage.addEventListener( Event.ENTER_FRAME, render );
		}
		
		private function render( event:Event ):void
		{
			//Rotate model on each frame
			model.appendRotation( .5, Vector3D.Z_AXIS, pivot );
			model.appendRotation( .5, Vector3D.Y_AXIS, pivot );
			model.appendRotation( .5, Vector3D.X_AXIS, pivot );
			
			//Combine transforms
			finalTransform.identity();
			finalTransform.append( model );
			finalTransform.append( view );
			finalTransform.append( projection );
			
			//Pass the final transform to the vertex shader as program constant, vc0
			renderContext.setProgramConstantsFromMatrix( Context3DProgramType.VERTEX, 0, finalTransform, true );
			
			//Clear is required before drawTriangles on each frame
			renderContext.clear( .3,.3,.3 );
			
			//Draw the 12 triangles that make up the cube
			renderContext.drawTriangles( indexList, 0, 12 );
			
			//Show the frame
			renderContext.present();
		}
		
		private function contextCreationError( error:ErrorEvent ):void
		{
			trace( error.errorID + ": " + error.text );
		}
	}
}