圣叹@游戏开发

我们面对现实,我们终于理想

Tamarin笔记之一:内置常量的实现

| |
23:24 , Qizhi
  Tamarin很早就开源了,最近在读它的源代码,偶尔做做笔记.
  As3中有很多顶级常量,比如NaN, Infinity等.Adobe的文档解释NaN依据IEEE-754定义,该值表示不是数值. Infinity表示正无穷大.那么究竟As3是如何实现这些定义的呢?
  Tamarin中包含两部分代码实现,分别是C++和AS3(Python另有他用,几乎与语言实现无关).这些常量就是使用AS3实现的.
  这些常量实现只有一句话:

public const NaN:Number = 0/0;
public const Infinity:Number = 1/0;
public const undefined = void 0;

  很简单:)
Actionscript.lang.aa中定义了两个命名空间,"AS3"和"nativeHookNS".处于AS3命名空间下的代码就是我们平常见到的builtin代码,而nativeHookNS下的代码我们不可见.
  比如Object.as中, isPrototypeOf是AS3中所有Object都有的方法:

AS3 function isPrototypeOf(V=void 0):Boolean
{
  return _isPO(this,V)
}

  而tostringHook则处于nativeHookNS命名空间下.

nativeHookNS function tostringHook():*
    {
      var s = this.public::toString()
      if (!_isScriptObject(s))
        return s
      return this.public::valueOf()
    }

  最后,来看看Math.as的源代码就会知道为什么有的方法很慢了,因为他们压根也是用AS3实现滴,和我们自己去实现没有本质上的差别sweat

public static function max(x:Number = CONFIG::NegInfinity, y:Number = CONFIG::NegInfinity, ...args:Array):Number
  {
    if (x !== x) return x
      if (y !== y) return y
      if (y > x) {
          x = y
      } else {
          if (y === x)
              if (y === 0)
                  if (1/y > 0)
                      x = y  // -0
      }
    for each (y in args)
    {
      if (y !== y) return y // isNaN
      if (y > x)
      {
        x = y;
      }
      else if (y === x && y === 0)
      {
        /*
          Lars: "You can tell -0 from 0 by dividing 1 by the zero, -0 gives -Infinity
          and 0 gives Infinity, so if you know x is a zero the test for negative
          zero is (1/x < 0)."
        */
        if ((1 / y) > 0)
          x = y;  // pick up negative zero when appropriate
      }
    }
    return x;
  }

除了Math.max和Math.min以及一些常量定义,其他算法都是C++实现.比如:

//C++
AVMPLUS_NATIVE_METHOD(double, Math_abs)
  {
    return MathUtils::abs(args->x);
  }

  MathClass.cpp中的源代码还告诉了我们一些有意思的小插曲,比如Tamarin AVM2实现ES3 15.8.2定义时,所有函数的参数都要Call一次ToNumber方法.他们没有这么做(所以标记为ISSUE)而是换了一种更有效的方法,看注释:
  // ISSUE. ES3 15.8.2 says all these functions call ToNumber on its argument.
  // this is more forgiving than declaring the args to be Number.  We either
  // have to declare these Object and to ToNumber internally, or add some special
  // type support so compiler will have ToNumber.
  //
  // for E3 compatibility all args should be optional=NaN and rest args ignored,
  // except for min, max where rest args are processed.

  TO BE CONTINUED.
  
网友评论(4):
7yue
Email Homepage
2010/03/11 13:51
AS3的Math已经跟我没关系了,汗...我当时还是Flash3/4时代...tellTarget和Eval的时代
auzn
2010/02/02 13:38
Math貌似和7yue还有很大的渊源 *_*
heweitykc
Email
2010/01/23 14:40
哥们tamarin的源代码是怎么找到的哦,能不能发个下载链接
Neo
Email Homepage
2010/01/11 12:20
汗,对Math的实现很意外。。。
分页: 1/1 第一页 1 最后页
发表评论:

昵称: 
电邮:
网址: