Posted By

line-effect on 10/18/12


Tagged

test Stage3D


Versions (?)

Stage3D Test


 / Published in: ActionScript 3
 

This will allow us to use the power of stage 3D classes in Flash player The code will just show us how to create a plane and animate it in 3D space you will learn how to use AGAL and how a mesh can be created .

Note: you have to use Flash Builder to use this code and also you have to download the AGAL classes from adobe http://www.bytearray.org/wp-content/projects/agalassembler/com.zip

  1. package
  2. {
  3. import com.adobe.utils.*;
  4.  
  5. import flash.display.*;
  6. import flash.display3D.*;
  7. import flash.display3D.textures.*;
  8. import flash.events.*;
  9. import flash.geom.*;
  10. import flash.utils.*;
  11.  
  12. [SWF(width="640", height="480", frameRate="60", backgroundColor="#000000")]
  13.  
  14. public class Stage3DTest extends Sprite
  15. {
  16. // constants used during inits
  17. private const swfWidth:int = 640;
  18. private const swfHeight:int = 480;
  19. private const textureSize:int = 512;
  20.  
  21. // the 3d graphics window on the stage
  22. private var context3D:Context3D;
  23. // the compiled shader used to render our mesh
  24. private var shaderProgram:Program3D;
  25. // the uploaded verteces used by our mesh
  26. private var vertexBuffer:VertexBuffer3D;
  27. // the uploaded indeces of each vertex of the mesh
  28. private var indexBuffer:IndexBuffer3D;
  29. // the data that defines our 3d mesh model
  30. private var meshVertexData:Vector.<Number>;
  31. // the indeces that define what data is used by each vertex
  32. private var meshIndexData:Vector.<uint>;
  33.  
  34. // matrices that affect the mesh location and camera angles
  35. private var projectionMatrix:PerspectiveMatrix3D = new PerspectiveMatrix3D();
  36. private var modelMatrix:Matrix3D = new Matrix3D();
  37. private var viewMatrix:Matrix3D = new Matrix3D();
  38. private var modelViewProjection:Matrix3D = new Matrix3D();
  39.  
  40. // a simple frame counter used for animation
  41. private var t:Number = 0;
  42.  
  43. // TEXTURE: Pure AS3 and Flex version:
  44. [Embed (source = "texture.jpg")] private var myTextureBitmap:Class;
  45. private var myTextureData:Bitmap = new myTextureBitmap();
  46.  
  47. // The Stage3d Texture that uses the above myTextureData
  48. private var myTexture:Texture;
  49.  
  50. public function Stage3DTest()
  51. {
  52. //we do this coz stage3D takes time to load
  53. //so this is important to check if the stage is there or not before loading
  54. if (stage != null)
  55. init();
  56. else
  57. addEventListener(Event.ADDED_TO_STAGE, init);
  58. }
  59.  
  60. private function init(e:Event = null):void
  61. {
  62.  
  63. if (hasEventListener(Event.ADDED_TO_STAGE))
  64. removeEventListener(Event.ADDED_TO_STAGE, init);
  65.  
  66. stage.frameRate = 60;
  67. stage.scaleMode = StageScaleMode.NO_SCALE;
  68. stage.align = StageAlign.TOP_LEFT;
  69.  
  70. // and request a context3D from Stage3d
  71. stage.stage3Ds[0].addEventListener(
  72. Event.CONTEXT3D_CREATE, onContext3DCreate);
  73. stage.stage3Ds[0].requestContext3D();
  74. }
  75.  
  76. private function onContext3DCreate(event:Event):void
  77. {
  78. // Remove existing frame handler. Note that a context
  79. // loss can occur at any time which will force you
  80. // to recreate all objects we create here.
  81. // A context loss occurs for instance if you hit
  82. // CTRL-ALT-DELETE on Windows.
  83. // It takes a while before a new context is available
  84. // hence removing the enterFrame handler is important!
  85.  
  86. if (hasEventListener(Event.ENTER_FRAME))
  87. removeEventListener(Event.ENTER_FRAME,enterFrame);
  88.  
  89. // Obtain the current context
  90. var t:Stage3D = event.target as Stage3D;
  91. context3D = t.context3D;
  92.  
  93. if (context3D == null)
  94. {
  95. // Currently no 3d context is available (error!)
  96. return;
  97. }
  98.  
  99. // Disabling error checking will drastically improve performance.
  100. // If set to true, Flash will send helpful error messages regarding
  101. // AGAL compilation errors, uninitialized program constants, etc.
  102. context3D.enableErrorChecking = true;
  103.  
  104. // Initialize our mesh data
  105. initData();
  106.  
  107. // The 3d back buffer size is in pixels
  108. context3D.configureBackBuffer(swfWidth, swfHeight, 0, true);
  109.  
  110. // A simple vertex shader which does a 3D transformation
  111. //here we will use AGAL code, note: its not like AS3, its another language
  112. //1st part is the opCode, then the output, then the input
  113. var vertexShaderAssembler:AGALMiniAssembler = new AGALMiniAssembler();
  114. vertexShaderAssembler.assemble
  115. (
  116. Context3DProgramType.VERTEX,
  117. // 4x4 matrix multiply to get camera angle
  118. "m44 op, va0, vc0\n" +
  119. // tell fragment shader about XYZ
  120. "mov v0, va0\n" +
  121. // tell fragment shader about UV
  122. "mov v1, va1\n"
  123. );
  124.  
  125. // A simple fragment shader which will use the vertex position as a color
  126. var fragmentShaderAssembler:AGALMiniAssembler = new AGALMiniAssembler();
  127. fragmentShaderAssembler.assemble
  128. (
  129. Context3DProgramType.FRAGMENT,
  130. // grab the texture color from texture fs0
  131. // using the UV coordinates stored in v1
  132. "tex ft0, v1, fs0 <2d,repeat,miplinear>\n" +
  133. // move this value to the output color
  134. "mov oc, ft0\n"
  135. );
  136.  
  137. // combine shaders into a program which we then upload to the GPU
  138. shaderProgram = context3D.createProgram();
  139. shaderProgram.upload(vertexShaderAssembler.agalcode, fragmentShaderAssembler.agalcode);
  140.  
  141. // upload the mesh indexes
  142. indexBuffer = context3D.createIndexBuffer(meshIndexData.length);
  143. indexBuffer.uploadFromVector(meshIndexData, 0, meshIndexData.length);
  144.  
  145. // upload the mesh vertex data
  146. // since our particular data is
  147. // x, y, z, u, v, nx, ny, nz
  148. // each vertex uses 8 array elements
  149. vertexBuffer = context3D.createVertexBuffer(meshVertexData.length/8, 8);
  150. vertexBuffer.uploadFromVector(meshVertexData, 0, meshVertexData.length/8);
  151.  
  152. // Generate mipmaps
  153. myTexture = context3D.createTexture(textureSize, textureSize,
  154. Context3DTextureFormat.BGRA, false);
  155. var ws:int = myTextureData.bitmapData.width;
  156. var hs:int = myTextureData.bitmapData.height;
  157. var level:int = 0;
  158. var tmp:BitmapData;
  159. var transform:Matrix = new Matrix();
  160. tmp = new BitmapData(ws, hs, true, 0x00000000);
  161. while ( ws >= 1 && hs >= 1 )
  162. {
  163. tmp.draw(myTextureData.bitmapData, transform, null, null, null, true);
  164. myTexture.uploadFromBitmapData(tmp, level);
  165. transform.scale(0.5, 0.5);
  166. level++;
  167. ws >>= 1;
  168. hs >>= 1;
  169. //ws = ws/2;
  170. //hs = hs/2;
  171. if (hs && ws)
  172. {
  173. tmp.dispose();
  174. tmp = new BitmapData(ws, hs, true, 0x00000000);
  175. }
  176. }
  177. tmp.dispose();
  178.  
  179. // create projection matrix for our 3D scene
  180. projectionMatrix.identity();
  181. // 45 degrees FOV, 640/480 aspect ratio, 0.1=near, 100=far
  182. projectionMatrix.perspectiveFieldOfViewRH(45.0, swfWidth / swfHeight, 0.01, 100.0);
  183.  
  184. // create a matrix that defines the camera location
  185. viewMatrix.identity();
  186. // move the camera back a little so we can see the mesh
  187. viewMatrix.appendTranslation(0,0,-4);
  188.  
  189. // start animating
  190. addEventListener(Event.ENTER_FRAME,enterFrame);
  191. }
  192.  
  193. private function enterFrame(e:Event):void
  194. {
  195. // clear scene before rendering is mandatory
  196. context3D.clear(0,0,0);
  197.  
  198. context3D.setProgram ( shaderProgram );
  199.  
  200. // create the various transformation matrices
  201. modelMatrix.identity();
  202. modelMatrix.appendRotation(t*0.7, Vector3D.Y_AXIS);
  203. modelMatrix.appendRotation(t*0.6, Vector3D.X_AXIS);
  204. modelMatrix.appendRotation(t*1.0, Vector3D.Y_AXIS);
  205. modelMatrix.appendTranslation(0.0, 0.0, 0.0);
  206. modelMatrix.appendRotation(90.0, Vector3D.X_AXIS);
  207.  
  208. // rotate more next frame
  209. t += 2.0;
  210.  
  211. // clear the matrix and append new angles
  212. modelViewProjection.identity();
  213. modelViewProjection.append(modelMatrix);
  214. modelViewProjection.append(viewMatrix);
  215. modelViewProjection.append(projectionMatrix);
  216.  
  217. // pass our matrix data to the shader program
  218. context3D.setProgramConstantsFromMatrix(
  219. Context3DProgramType.VERTEX,
  220. 0, modelViewProjection, true );
  221.  
  222. // associate the vertex data with current shader program
  223. // position
  224. context3D.setVertexBufferAt(0, vertexBuffer, 0,
  225. Context3DVertexBufferFormat.FLOAT_3);
  226. // tex coord
  227. context3D.setVertexBufferAt(1, vertexBuffer, 3,
  228. Context3DVertexBufferFormat.FLOAT_3);
  229.  
  230. // which texture should we use?
  231. context3D.setTextureAt(0, myTexture);
  232.  
  233. // finally draw the triangles
  234. context3D.drawTriangles(indexBuffer, 0, meshIndexData.length/3);
  235.  
  236. // present/flip back buffer
  237. context3D.present();
  238. }
  239.  
  240. private function initData():void
  241. {
  242. // Defines which vertex is used for each polygon
  243. // In this example a square is made from two triangles
  244. meshIndexData = Vector.<uint>
  245. ([
  246. 0, 1, 2, 0, 2, 3,
  247. ]);
  248.  
  249. // Raw data used for each of the 4 verteces
  250. // Position XYZ, texture coordinate UV, normal XYZ
  251. meshVertexData = Vector.<Number>
  252. ( [
  253. //X, Y, Z, U, V, nX, nY, nZ
  254. -1, -1, 1, 0, 0, 0, 0, 1,
  255. 1, -1, 1, 1, 0, 0, 0, 1,
  256. 1, 1, 1, 1, 1, 0, 0, 1,
  257. -1, 1, 1, 0, 1, 0, 0, 1
  258. ]);
  259. }
  260. }
  261. }

Report this snippet  

You need to login to post a comment.