Cubic Hermite Spline

Actionscript:
  1. var canvas:BitmapData = new BitmapData(400,400,false, 0x000000);
  2. addChild(new Bitmap(canvas));
  3.  
  4. // create some draggable dots
  5. var p0:Sprite = dot(100, 100);
  6. var p1:Sprite = dot(200, 200);
  7. var m0:Sprite = dot(200, 100, 0xFFFFFF, 3)
  8. var m1:Sprite = dot(100, 200, 0xFFFFFF, 3);
  9.  
  10. addEventListener(Event.ENTER_FRAME, onLoop);
  11. function onLoop(evt:Event):void {
  12.     canvas.fillRect(canvas.rect, 0x000000);
  13.     var px:Number = 0;
  14.     var py:Number = 0;
  15.     for (var t:Number = 0; t <1; t+=.01){
  16.         var t_2:Number = t * t;
  17.         var t_3:Number = t_2 * t;
  18.        
  19.         // some repetitive math for clarity
  20.         px = (2 * t_3  - 3 * t_2 + 1) * p0.x +(t_3 - 2 * t_2 + t) *
  21.                  m0.x + (-2 * t_3 + 3 * t_2) * p1.x + (t_3 - t_2) * m1.x;
  22.         py = (2 * t_3  - 3 * t_2 + 1) * p0.y +(t_3 - 2 * t_2 + t) *
  23.                  m0.y + (-2 * t_3 + 3 * t_2) * p1.y + (t_3 - t_2) * m1.y;
  24.         canvas.setPixel(px, py, 0xFF0000);
  25.     }
  26. }
  27. // draggable dot
  28. function dot(xp:Number, yp:Number, col:uint = 0x507399, rad:Number=5):Sprite {
  29.     var s:Sprite = Sprite(addChild(new Sprite()));
  30.     s.x = xp;
  31.     s.y = yp;
  32.     with(s.graphics) beginFill(col), drawCircle(0,0,rad);
  33.     s.buttonMode = true;
  34.     s.addEventListener(MouseEvent.MOUSE_DOWN, onDrag);
  35.     return s;
  36. }
  37. function onDrag(evt:MouseEvent):void {
  38.     evt.currentTarget.startDrag()
  39. }
  40. stage.addEventListener(MouseEvent.MOUSE_UP, onUp);
  41. function onUp(evt:MouseEvent):void{
  42.     stopDrag();
  43. }

This is the start of my exploration of Cubic Hermite Splines (like Catmull–Rom)... I wrote this snippet while skimming the wikipedia article on the subject.... at first I wasn't sure if this was correct, but I added tangent calculations for a Catmull-Rom and it worked nicely... will post that tomorrow.

This entry was posted in Math, graphics algorithms, setPixel and tagged , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*