Chapter 40 Example 1

by actionscriptbible
♥0 | Line 55 | Modified 2010-02-10 06:50:42 | MIT License
play

ActionScript3 source code

/**
 * Copyright actionscriptbible ( http://wonderfl.net/user/actionscriptbible )
 * MIT License ( http://www.opensource.org/licenses/mit-license.php )
 * Downloaded from: http://wonderfl.net/c/sYRD
 */

package {
  import flash.display.*;
  import flash.events.Event;
  import flash.geom.*;
  public class ch40ex1 extends Sprite {
    protected var perspective:PerspectiveProjection;
    protected var viewMatrix:Matrix3D;
    protected var modelMatrix:Matrix3D;
    protected var model:Plot3D;
    public function ch40ex1() {
      stage.quality = StageQuality.MEDIUM;
      //center coordinates
      this.x = stage.stageWidth/2;
      this.y = stage.stageHeight/2;
      //set up "camera" perspective projection
      perspective = new PerspectiveProjection();
      perspective.fieldOfView = 50;
      perspective.projectionCenter = new Point(0, 0);
      //set up view projection
      //move camera up, back and angle down before projecting
      viewMatrix = new Matrix3D();
      viewMatrix.appendTranslation(0, 4, 11);
      viewMatrix.appendRotation(26, Vector3D.X_AXIS);
      viewMatrix.append(perspective.toMatrix3D());
      //set up model transformation
      modelMatrix = new Matrix3D();
      //set up model
      model = new Plot3D();
      model.plot(new Rectangle(-3, -3, 6, 6), 70);
      //render loop
      addEventListener(Event.ENTER_FRAME, onEnterFrame);
    }
    protected function onEnterFrame(event:Event):void {
      //rotate model progressively
      modelMatrix.appendRotation(2, Vector3D.Y_AXIS);
      //when we project, first apply the model matrix and then the
      //view/projection matrix. Precalculate into one matrix here.
      var concatenatedMatrix:Matrix3D = modelMatrix.clone();
      concatenatedMatrix.append(viewMatrix);
      
      var v:Vector3D;
      graphics.clear();
      graphics.beginFill(0, 1);
      for each (v in model.vertices) {
        v = Utils3D.projectVector(concatenatedMatrix, v);
        graphics.drawRect(v.x, v.y, 1, 1);
      }
    }
  }
}
import flash.geom.Rectangle;
import flash.geom.Vector3D;
class Plot3D {
  public var vertices:Vector.<Vector3D>;
  public var tOffset:Number = 0;
  public function plot(xzBounds:Rectangle, resolution:Number = 200):void {
    vertices = new Vector.<Vector3D>();
    var r:Rectangle = xzBounds;
    for (var z:Number = r.top; z < r.bottom; z += r.height/resolution) {
      for (var x:Number = r.left; x < r.right; x += r.width/resolution) {
        var y:Number = Math.sin(Math.pow(x, 2) + Math.pow(z, 2) + tOffset);
        vertices.push(new Vector3D(x, y, z));
      } 
    }
  }
}