2012年4月9日 星期一

OpenGL ES 入門: 四. 光效之三

since: 2012/04/09
update: 2012/04/10

reference:
1. 原文:
iPhone Development: OpenGL ES From the Ground Up, Part 4: Let There Be Light!
iPhone Development: setupView: from Part IV Rewritten

2. 翻譯:
從零開始學習OpenGL ES之四 – 光效
從零開始學習OpenGL ES之四補遺 – setupView重寫

光效之三: 頂點法線

A. 說明
      1. 法線 (Normal) 是一個垂直於指定多邊形表面的向量(或直線).

      2. OpenGL 渲染一個形狀時並不需要知道法線, 但在你使用定向光線時需要用到.
          OpenGL 需要表面法線來確定光線是怎樣與各多邊形交互作用的.

      3. 但是因為我們使用 GL_SMOOTH 渲染, 所以 OpenGL ES 需要知道頂點法線
          (vertex normal)
而不是表面法線. 因為頂點法線要求你計算使用了該頂點的
          所有表面法線的平均向量. 

---------------------------------------------------------------------------------------

B. 計算三角形的表面法線

     開啓 OpenGLESCommon.h 檔案, 修改如下:
....
#pragma mark -
#pragma mark Triangle3D
#pragma mark -
....
// 計算三角形的表面法線
//
// 向量外積(Vector Product 或 Cross Product):
// 假設現在有 u 向量與 v 向量, 藉由對 u, v 進行 cross product 可以幫我們找出
// 垂直於 u, v 兩個向量的另一個向量.
static inline Vector3D Triangle3DCalculateSurfaceNormal(Triangle3D triangle)
{
    // 取兩頂點值計算其標準化向量
    Vector3D u = Vector3DMakeWithStartAndEndPoints(triangle.v2, triangle.v1);
    Vector3D v = Vector3DMakeWithStartAndEndPoints(triangle.v3, triangle.v1);
   
    Vector3D ret;
    ret.x = (u.y * v.z) - (u.z * v.y);
    ret.y = (u.z * v.x) - (u.x * v.z);
    ret.z = (u.x * v.y) - (u.y * v.x);
   
    return ret;
}

---------------------------------------------------------------------------------------

C. 計算二十面體的各頂點法線
     1. 說明: 除非沒有替代方法, 否則儘量避免使用頂點法線的即時計算. 在這裡, 會在
                    ViewController 的 setupView: 中呼叫一個方法來計算二十面體的各頂點
                    法線, 它會循環處理每個頂點及三角形索引, 最後將結果儲存到指向
                     C struct 的位址裡(Vertex3D*) .

     2. 開啓 OpenGLESCommon.h 檔案, 修改如下:
....
#pragma mark -
#pragma mark Vector3D
#pragma mark -
....
static inline Vector3D Vector3DAdd(Vector3D vector1, Vector3D vector2)
{
    Vector3D ret;
    ret.x = vector1.x + vector2.x;
    ret.y = vector1.y + vector2.y;
    ret.z = vector1.z + vector2.z;
   
    return ret;
}
....
#pragma mark -
#pragma mark Used for icosahedron's vertices normal
#pragma mark -

//@add: Used for icosahedron's vertices normal
// 用來計算二十面體的頂點法線
//
static const Vertex3D vertices[]= {
    {0, -0.525731, 0.850651},             // vertices[0]
    {0.850651, 0, 0.525731},              // vertices[1]
    {0.850651, 0, -0.525731},             // vertices[2]
    {-0.850651, 0, -0.525731},            // vertices[3]
    {-0.850651, 0, 0.525731},             // vertices[4]
    {-0.525731, 0.850651, 0},             // vertices[5]
    {0.525731, 0.850651, 0},              // vertices[6]
    {0.525731, -0.850651, 0},             // vertices[7]
    {-0.525731, -0.850651, 0},            // vertices[8]
    {0, -0.525731, -0.850651},            // vertices[9]
    {0, 0.525731, -0.850651},             // vertices[10]
    {0, 0.525731, 0.850651}               // vertices[11]
};

static const GLubyte icosahedronFaces[] = {
    1, 2, 6,
    1, 7, 2,
    3, 4, 5,
    4, 3, 8,
    6, 5, 11,
    5, 6, 10,
    9, 10, 2,
    10, 9, 3,
    7, 8, 9,
    8, 7, 0,
    11, 0, 1,
    0, 11, 4,
    6, 2, 10,
    1, 6, 11,
    3, 5, 10,
    5, 4, 11,
    2, 7, 9,
    7, 1, 0,
    3, 9, 8,
    4, 8, 0,
};

//static const Vertex3D *normals = calloc(12, sizeof(Vertex3D));
//static Vertex3D normals[sizeof(Vertex3D)];

static Vertex3D *normals;

// 計算二十面體的頂點法線
static inline void computeVerticesNormal()
{
    NSLog(@"OpenGLESCommon => computeVerticesNormal()");

    NSMutableString *result = [NSMutableString string];
   
    // defined: static const Vertex3D vertices[]
    // defined: static const GLubyte icosahedronFaces[]
    Vector3D *surfaceNormals = calloc(20, sizeof(Vector3D));
   
    // Calculate the surface normal for each triangle
    for (int i = 0; i < 20; i++)
    {
        Vertex3D vertex1 = vertices[icosahedronFaces[(i*3)]];
        Vertex3D vertex2 = vertices[icosahedronFaces[(i*3)+1]];
        Vertex3D vertex3 = vertices[icosahedronFaces[(i*3)+2]];

        Triangle3D triangle = Triangle3DMake(vertex1, vertex2, vertex3);
        Vector3D surfaceNormal = Triangle3DCalculateSurfaceNormal(triangle);
        Vector3DNormalize(&surfaceNormal);
        surfaceNormals[i] = surfaceNormal;
    }
   
    //Vertex3D *normals = calloc(12, sizeof(Vertex3D));
    // defined: static Vertex3D *normals;
    normals = calloc(12, sizeof(Vertex3D));

    [result appendString:@"static const Vector3D normals[] = {\n"];
    
    for (int i = 0; i < 12; i++)
    {
        int faceCount = 0;
        for (int j = 0; j < 20; j++)
        {
            BOOL contains = NO;
            for (int k = 0; k < 3; k++)
            {
                if (icosahedronFaces[(j * 3) + k] == i)
                    contains = YES;
            }
            if (contains)
            {
                faceCount++;
                normals[i] = Vector3DAdd(normals[i], surfaceNormals[j]);
            }
        }
       
        normals[i].x /= (GLfloat)faceCount;
        normals[i].y /= (GLfloat)faceCount;
        normals[i].z /= (GLfloat)faceCount;
       
        [result appendFormat:@"\t{%f, %f, %f},\n", normals[i].x, normals[i].y, normals[i].z];
    }
   
    [result appendString:@"};\n"];
   
    NSLog(@"%@", result);
}

     3. 開啓 ViewController.m 檔案, 修改如下:
....
-(void)setupView:(GLView *)view
{
    NSLog(@"step 05. ViewController => setupView:");
   
    //@add: 計算二十面體的頂點法線
    computeVerticesNormal();
....

}
     4. 編譯並執行:
         得到預先計算好的頂點法線, 所以就不需要在 OpenGL 執行時進行計算了.
---------------------------------------------------------------------------------------
2012-04-09 13:51:41.146 OpenGLESBegin[1308:fb03]
OpenGLESCommon => computeVerticesNormal()

2012-04-09 13:51:41.197 OpenGLESBegin[1308:fb03]
static const Vector3D normals[] = {
    {0.000000, -0.417775, 0.675974},
    {0.675973, 0.000000, 0.417775},
    {0.675973, -0.000000, -0.417775},
    {-0.675973, 0.000000, -0.417775},
    {-0.675973, -0.000000, 0.417775},
    {-0.417775, 0.675974, 0.000000},
    {0.417775, 0.675973, -0.000000},
    {0.417775, -0.675974, 0.000000},
    {-0.417775, -0.675974, 0.000000},
    {0.000000, -0.417775, -0.675973},
    {0.000000, 0.417775, -0.675974},
    {0.000000, 0.417775, 0.675973},
};

---------------------------------------------------------------------------------------


D. 啟動法線陣列
      1. 開啓 ViewController.m 檔案, 修改如下:
....
// 畫多面體光效
- (void)drawLight
{
    NSLog(@"ViewController => drawLight");
    // Draw code here
    //@update
    //
    // 1. 建立了一個靜態變數來跟蹤物體的旋轉
    static GLfloat rot = 0.0;
   
    // This is the same result as using Vertex3D, just faster to type and
    // can be made const this way
    //
    // 2. 定義頂點陣列:
    //
    // 使用了一個與前不同的方法, 但結果是一樣的. 由於我們的幾何體根本不會變化,
    // 所以我們將其定義為 const, 這樣就不需要每一 frame 都分配/清除記憶體:
    /*
    static const Vertex3D vertices[]= {
        {0, -0.525731, 0.850651},             // vertices[0]
        {0.850651, 0, 0.525731},              // vertices[1]
        {0.850651, 0, -0.525731},             // vertices[2]
        {-0.850651, 0, -0.525731},            // vertices[3]
        {-0.850651, 0, 0.525731},             // vertices[4]
        {-0.525731, 0.850651, 0},             // vertices[5]
        {0.525731, 0.850651, 0},              // vertices[6]
        {0.525731, -0.850651, 0},             // vertices[7]
        {-0.525731, -0.850651, 0},            // vertices[8]
        {0, -0.525731, -0.850651},            // vertices[9]
        {0, 0.525731, -0.850651},             // vertices[10]
        {0, 0.525731, 0.850651}               // vertices[11]
    };
    */
    //@update: defined in OpenGLESCommon.h

    // 3. 建立一個顏色陣列:
    //
    // 創建一個 Color3D 物件陣列, 每項對應於前一個陣列的頂點:
    static const Color3D colors[] = {
        {1.0, 0.0, 0.0, 1.0},
        {1.0, 0.5, 0.0, 1.0},
        {1.0, 1.0, 0.0, 1.0},
        {0.5, 1.0, 0.0, 1.0},
        {0.0, 1.0, 0.0, 1.0},
        {0.0, 1.0, 0.5, 1.0},
        {0.0, 1.0, 1.0, 1.0},
        {0.0, 0.5, 1.0, 1.0},
        {0.0, 0.0, 1.0, 1.0},
        {0.5, 0.0, 1.0, 1.0},
        {1.0, 0.0, 1.0, 1.0},
        {1.0, 0.0, 0.5, 1.0}
    };
   
    // 4. 建立二十面體:
    //
    // 上述十二個頂點本身並未描述形狀. OpenGL 需要知道怎樣將它們聯繫在一起,
    // 所以我們建立了一個整數陣列 (GLubyte) 指向構成各三角形的頂點.
    //
    // 二十面體的第一個面的三個數是 1,2,6 代表繪製處於索引1 (0.850651, 0, 0.525731),
    // 2 (0.850651, 0, 0.525731), 和 6 (0.525731, 0.850651, 0) 之間的三角形.
    /*
    static const GLubyte icosahedronFaces[] = {
        1, 2, 6,
        1, 7, 2,
        3, 4, 5,
        4, 3, 8,
        6, 5, 11,
        5, 6, 10,
        9, 10, 2,
        10, 9, 3,
        7, 8, 9,
        8, 7, 0,
        11, 0, 1,
        0, 11, 4,
        6, 2, 10,
        1, 6, 11,
        3, 5, 10,
        5, 4, 11,
        2, 7, 9,
        7, 1, 0,
        3, 9, 8,
        4, 8, 0,
    };
    */
    //@update: defined in OpenGLESCommon.h
   
    // 二十面體的頂點法線
    /*
    static const Vector3D normals[] = {
        {0.000000, -0.417775, 0.675974},
        {0.675973, 0.000000, 0.417775},
        {0.675973, -0.000000, -0.417775},
        {-0.675973, 0.000000, -0.417775},
        {-0.675973, -0.000000, 0.417775},
        {-0.417775, 0.675974, 0.000000},
        {0.417775, 0.675973, -0.000000},
        {0.417775, -0.675974, 0.000000},
        {-0.417775, -0.675974, 0.000000},
        {0.000000, -0.417775, -0.675973},
        {0.000000, 0.417775, -0.675974},
        {0.000000, 0.417775, 0.675973},
    };
    */
    //@update: defined in OpenGLESCommon.h
    //                  & compute in setupView: computeVerticesNormal()

   
    // 5.
    //
    // 加載單元矩陣
    glLoadIdentity();
   
    // 移動
    glTranslatef(0.0f,0.0f,-3.0f);
   
    // 旋轉
    glRotatef(rot,1.0f,1.0f,1.0f);
   
    // 設置背景色
    glClearColor(0.7, 0.7, 0.7, 1.0);
   
    // 清除緩存
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
   
    // 啟動頂點陣列
    glEnableClientState(GL_VERTEX_ARRAY);
   
    // 啟動顏色陣列
    glEnableClientState(GL_COLOR_ARRAY);
   
    //@add: 啟動法線陣列
    glEnableClientState(GL_NORMAL_ARRAY);
   
    // 提供頂點陣列內容給 OpenGL
    glVertexPointer(3, GL_FLOAT, 0, vertices);
   
    // 提供顏色陣列內容給 OpenGL
    glColorPointer(4, GL_FLOAT, 0, colors);
   
    //@add: 提供法線陣列內容給 OpenGL
    glNormalPointer(GL_FLOAT, 0, normals);
   
    // 6. 不使用 glDrawArrays(), 而是使用 glDrawElements():
    //
    // 備註: 如果你按繪製的正確次序提供頂點, 那麼你應該使用 glDrawArrays(),
    //       但是如果你提供一個陣列然後用另一個以索引值區分頂點次序的陣列的話,
    //       那麼你應該使用 glDrawElements().
    glDrawElements(GL_TRIANGLES, 60, GL_UNSIGNED_BYTE, icosahedronFaces);
   
    // 7. 執行禁止功能
    glDisableClientState(GL_VERTEX_ARRAY);
    glDisableClientState(GL_COLOR_ARRAY);
    //@add
    glDisableClientState(GL_NORMAL_ARRAY);
   
    // 8. 根據上一個 frame 繪製的時間增加旋轉變量值:
    static NSTimeInterval lastDrawTime;
    if (lastDrawTime)
    {
        NSTimeInterval timeSinceLastDraw = [NSDate timeIntervalSinceReferenceDate] - lastDrawTime;
        rot += 50 * timeSinceLastDraw;
    }
    lastDrawTime = [NSDate timeIntervalSinceReferenceDate];
}
....

      2. 編譯並執行:
         看到一個真實的三維旋轉物體, 顏色仍是灰暗的.

---------------------------------------------------------------------------------------

E. 建立簡單的材質
      1. 說明: 當你使用光效和平滑陰影時, OpenGL 期待你為多邊形提供材質(material)
                  
或紋理(texture). 材質比在顏色陣列中提供簡單顏色要複雜得多. 材質像光
                   一樣由許多元素構成, 可以產生不同的表面效果. 物體的表面效果實際上是由
                   場景中的光和多邊形的材質決定的.

      2. 開啓 ViewController.m 檔案, 修改如下:
....
- (void)drawLight
{
....
    //@add: 啟動法線陣列
    glEnableClientState(GL_NORMAL_ARRAY);
   
    //@add: 啟動顏色材質
    // OpenGL 將使用我們提供的顏色陣列來創建簡單的材質
    glEnable(GL_COLOR_MATERIAL);
....
    // 7. 執行禁止功能
    glDisableClientState(GL_VERTEX_ARRAY);
    glDisableClientState(GL_COLOR_ARRAY);
    //@add
    glDisableClientState(GL_NORMAL_ARRAY);
    glDisableClientState(GL_COLOR_MATERIAL);
....
}
....

      3. 編譯並執行:

---------------------------------------------------------------------------------------

F. 重寫 setupView:
(update: 2012/04/10)
     1. 說明:
         a. 在此將使用 OpenGLESCommon.h 中定義的 Vertex3D, Vector3D 和 Color3D
             資料結構
來重寫 setupView: 方法. 因為使用頂點, 顏色和三角形的術語比可變
             長度浮點數陣列更容易理解.

         b. 另外, 減少了環境光元素的數量並將光源向右移動了一點.

         c. 並且, 使用 Vector3DMakeWithStartAndEndPoints() 將移動的光源指向二十
             面體. 這樣做使得光效更為生動一點
.

     2. 開啓 ViewController.m 檔案, 修改如下:
....
//@add for <GLViewDelegate> method
-(void)setupView:(GLView *)view
{
    NSLog(@"step 05. ViewController => setupView:");
   
    //@add: 計算二十面體的頂點法線
    computeVerticesNormal();
   
    const GLfloat zNear = 0.01, zFar = 1000.0, fieldOfView = 45.0; // 設定為 45 度視野
    GLfloat size;
    glEnable(GL_DEPTH_TEST);
    glMatrixMode(GL_PROJECTION);
    size = zNear * tanf(DEGREES_TO_RADIANS(fieldOfView) / 2.0);   
   
    CGRect rect = view.bounds;

    // 設定透視 viewport (基於視野角度計算錐台)
    glFrustumf(-size, size, -size / (rect.size.width / rect.size.height), size /
               (rect.size.width / rect.size.height), zNear, zFar);
   
    // 設定正交 viewport (基於視野角度計算錐台)   
    /*
    glOrthof(-1.0,                                // Left
             1.0,                                          // Right
             -1.0 / (rect.size.width / rect.size.height),   // Bottom
             1.0 / (rect.size.width / rect.size.height),   // Top
             0.01,                                         // Near
             10000.0);                                     // Far   
    */
   
    // 建構一個對應的座標系統
    glViewport(0, 0, rect.size.width, rect.size.height); 
   
    glMatrixMode(GL_MODELVIEW);
   
    //@add for 啟動光效
    glEnable(GL_LIGHTING);
   
    //@add for 啟動第一個光源
    glEnable(GL_LIGHT0);
   
    //@add for setup light
    //
    // 定義第一個光源的環境光
    // Define the ambient component of the first light
    /*
    const GLfloat light0Ambient[] = {0.1, 0.1, 0.1, 1.0};
    glLightfv(GL_LIGHT0, GL_AMBIENT, light0Ambient);
    */
    //@update
    static const Color3D light0Ambient[] = {{0.05, 0.05, 0.05, 1.0}};
    glLightfv(GL_LIGHT0, GL_AMBIENT, (const GLfloat *)light0Ambient);
   
    // 定義第一個光源的散射光
    // Define the diffuse component of the first light
    /*
    const GLfloat light0Diffuse[] = {0.7, 0.7, 0.7, 1.0};
    glLightfv(GL_LIGHT0, GL_DIFFUSE, light0Diffuse);
    */
    //@update
    static const Color3D light0Diffuse[] = {{0.4, 0.4, 0.4, 1.0}};
    glLightfv(GL_LIGHT0, GL_DIFFUSE, (const GLfloat *)light0Diffuse);
   
    // 定義第一個光源的鏡射光與亮度
    // Define the specular component and shininess of the first light
    /*
    const GLfloat light0Specular[] = {0.7, 0.7, 0.7, 1.0};
    const GLfloat light0Shininess = 0.4;
    glLightfv(GL_LIGHT0, GL_SPECULAR, light0Specular);
    glLightfv(GL_LIGHT0, GL_SHININESS, &light0Shininess);
    */
    //@update
    static const Color3D light0Specular[] = {{0.7, 0.7, 0.7, 1.0}};
    glLightfv(GL_LIGHT0, GL_SPECULAR, (const GLfloat *)light0Specular);
    glLightf(GL_LIGHT0, GL_SHININESS, 0.4);
   
    // 定義第一個光源的位置
    // Define the position of the first light
    /*
    const GLfloat light0Position[] = {0.0, 10.0, 10.0, 0.0};
    glLightfv(GL_LIGHT0, GL_POSITION, light0Position);
    */
    //@update
    static const Vertex3D light0Position[] = {{10.0, 10.0, 10.0}};
    glLightfv(GL_LIGHT0, GL_POSITION, (const GLfloat *)light0Position);    
   
    // 定義第一個光源的方向向量: 沿 z 軸而下
    // Define a direction vector for the light, this one points right down the Z axis
    /*
    const GLfloat light0Direction[] = {0.0, 0.0, -1.0};
    glLightfv(GL_LIGHT0, GL_SPOT_DIRECTION, light0Direction);
    */
    //@update
    // Calculate light vector so it points at the object
    static const Vertex3D objectPoint[] = {{0.0, 0.0, -3.0}};

    const Vertex3D lightVector = Vector3DMakeWithStartAndEndPoints(light0Position[0], objectPoint[0]);

    glLightfv(GL_LIGHT0, GL_SPOT_DIRECTION, (GLfloat *)&lightVector);
   
    // 定義第一個光源的遮光角: 限制角度為 90 度(使用 45 度遮光角)
    // Define a cutoff angle. This defines a 90度 field of vision, since the cutoff
    // is number of degrees to each side of an imaginary line drawn from the light's
    // position along the vector supplied in GL_SPOT_DIRECTION above
    //glLightf(GL_LIGHT0, GL_SPOT_CUTOFF, 45.0);
    // @update
    // This defines a 50度 field of vision
    glLightf(GL_LIGHT0, GL_SPOT_CUTOFF, 25.0);
   
    glLoadIdentity();
   
    // 清除緩存用的灰色
    glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
}
....

     3. 編譯並執行

2012年4月8日 星期日

OpenGL ES 入門: 四. 光效之二

since: 2012/04/08
update: 2012/04/08

reference:
1. 原文:
iPhone Development: OpenGL ES From the Ground Up, Part 4: Let There Be Light!

2. 翻譯:
從零開始學習OpenGL ES之四 – 光效

光效之二: 光源位置與點光源

A. 位置
      1. 光源 3D 空間中的位置, 是光效的另一個重要屬性. 它不會影響環境元素,
          但對於散射與鏡射元素而言, 只有在 OpenGL 知道了場景中物體與光的
          相對位置
後才能計算.

          例如: 將第一個光源放置在觀察者後方的右上角
          const GLfloat light0Position[] = {10.0, 10.0, 10.0, 0.0};
          glLightfv(GL_LIGHT0, GL_POSITION, light0Position);


      2. 光線的屬性設定: 環境, 散射, 鏡射與位置等. 如果你沒有設定其中一個元素,
          那麼它就採用預設值: 黑色 {0.0, 0.0, 0.0, 1.0}. 如果你沒有定義位置, 那麼
          它就處於原點.

      3. 在計算散射光確定光線是怎樣反射時, 需要用到 alpha 值. 現在先將 alpha
          設為1.0, 之後當討論到材質時會說明它的作用.

-----------------------------------------------------------------------------------

B. 建立點光源(聚光燈)

      1. 說明: 如果你希望建立一個定向點光源 (一種指向特定方向並照亮特定角度範圍
                    的光源, 本質上, 它與燈泡照亮各個方向相反, 它只照亮一個錐台的範圍),
                    那麼你需要設定兩個額外參數: GL_SPOT_DIRECTION 與 GL_SPOT_CUTOFF.

                    a. 設定 GL_SPOT_DIRECTION 允許你指定光照的方向.

                    b. 設定 GL_SPOT_CUTOFF 定義了光的擴張範圍, 它類似於之前文章中介紹的
                        視野角度的計算. 窄角度將產生很小範圍的點光源, 而寬角度則產生像
                        泛光燈一樣的效果.

----------------------------------------------------------------------------------
      2. 指定光的方向:
           a. 通過指定來定義光線指向的 x, y 和 z 值以使 GL_SPOT_DIRECTION 工作.
               然而, 光線並不指向
你在空間中定義的那一點. 你提供的三個坐標值是向量
              
(vector)
, 而非頂點. 這是一個很細微但十分重要的區別. 一個代表向量的
               資料結構與一個頂點的資料結構完全一樣 (都有三個 GLfloats,其中每一個
               分別是笛卡爾的一個軸) 然而, 向量的資料是用來表示方向而不是空間中的一點.

           b. 兩點可以定義一條線段, 那麼空間中的一點怎麼可能指定方向? 這是因為存在
               一個隱性的第二點作為起點, 即原點. 如果你從原點畫一條線到向量定義的點,
               那就是向量代表的方向. 向量還可用於表示速度和距離, 一個遠離原點的點
               表示速度越快或距離更遠. 在大部分的 OpenGL 應用中, 並未使用距離原點
               的距離. 實際上, 在大部分使用向量的情況下, 我們需要將向量標準化
               (normaliz)
為長度 1.0. 目前, 如果你希望定義一個定向光, 那麼就必須建立
               一個定義了光的方向的向量.

               例如: 定義一個沿 z 軸而下的光源:
               const
GLfloat light0Direction = {0.0, 0.0, -1.0};
              
glLightfv(GL_LIGHT0, GL_SPOT_DIRECTION, light0Direction);


           c. 讓光線指向一個特定物體
               (1). 開啓 OpenGLESCommon.h 檔案, 修改如下:
....
#pragma mark -
#pragma mark Vector3D
#pragma mark -

typedef Vertex3D Vector3D;
#define Vector3DMake(x,y,z) (Vector3D)Vertex3DMake(x, y, z)
#define Vector3DSet(vector,x,y,z) Vertex3DSet(vector, x, y, z)

static inline GLfloat Vector3DMagnitude(Vector3D vector)
{
    return sqrtf((vector.x * vector.x) + (vector.y * vector.y) + (vector.z * vector.z));
}

static inline void Vector3DNormalize(Vector3D *vector)
{
    GLfloat vecMag = Vector3DMagnitude(*vector);
    if ( vecMag == 0.0 )
    {
        vector->x = 1.0;
        vector->y = 0.0;
        vector->z = 0.0;

        return;
    }
   
    vector->x /= vecMag;
    vector->y /= vecMag;
    vector->z /= vecMag;
}

static inline Vector3D Vector3DMakeWithStartAndEndPoints(Vertex3D start, Vertex3D end)
{
    Vector3D ret;
   
    ret.x = end.x - start.x;
    ret.y = end.y - start.y;
    ret.z = end.z - start.z;
   
    Vector3DNormalize(&ret);
   
    return ret;
}
....

               (2). 使用方式:
                      將光的位置和物體的位置傳入 Vector3DMakeWithStartAndEndPoints()
                      方法中, 它將傳回一個被光照射到的指定點的標準化向量. 然後, 再將其
                      作為
GL_SPOT_DIRECTION 的值.
----------------------------------------------------------------------------------
      3. 指定光的角度:
           a. 說明: 除非你限制光照的角度, 否則指定光的方向並不會產生顯著的效果.
                          因為當你指定 GL_SPOT_CUTOFF 值時, 它定義了中心線兩邊的角度,
                          所以如果你指定遮光角(cutoff angle)時, 它必須小於 180 度. 如果你的
                          定義為 45 度, 那麼實際上你創建了一個總角度為 90 度的點光源.
                          這意味著你可設定的 GL_SPOT_CUTOFF 的最大值為 180 度.

           b. 例子:
               限制角度為 90 度(使用 45 度遮光角):
               glLightf(GL_LIGHT0, GL_SPOT_CUTOFF, 45.0);
             
           c. 備註: 還有三個光的屬性可以設置, 它們是一起配合使用的. 有機會的話, 會在
                         有關光衰減 (光線隨着遠離光源而減弱) 的文章中討論到. 通過調整
                         衰減值可以產生很漂亮的效果.

-----------------------------------------------------------------------------------

C. 設定光源
     1. 開啓 ViewController.m 檔案, 修改如下:
....
-(void)setupView:(GLView *)view
{
    NSLog(@"step 05. ViewController => setupView:");
   
    const GLfloat zNear = 0.01, zFar = 1000.0, fieldOfView = 45.0; // 設定為 45 度視野
    GLfloat size;
    glEnable(GL_DEPTH_TEST);
    glMatrixMode(GL_PROJECTION);
    size = zNear * tanf(DEGREES_TO_RADIANS(fieldOfView) / 2.0);   
   
    CGRect rect = view.bounds;

    // 設定透視 viewport (基於視野角度計算錐台)
    glFrustumf(-size, size, -size / (rect.size.width / rect.size.height), size /
               (rect.size.width / rect.size.height), zNear, zFar);
   
    // 建構一個對應的座標系統
    glViewport(0, 0, rect.size.width, rect.size.height); 
   
    glMatrixMode(GL_MODELVIEW);
   
    //@add for 啟動光效
    glEnable(GL_LIGHTING);
   
    //@add for 啟動第一個光源
    glEnable(GL_LIGHT0);
   
    //@add for setup light
    //
    // 定義第一個光源的環境光
    // Define the ambient component of the first light
    const GLfloat light0Ambient[] = {0.1, 0.1, 0.1, 1.0};
    glLightfv(GL_LIGHT0, GL_AMBIENT, light0Ambient);
   
    // 定義第一個光源的散射光
    // Define the diffuse component of the first light
    const GLfloat light0Diffuse[] = {0.7, 0.7, 0.7, 1.0};
    glLightfv(GL_LIGHT0, GL_DIFFUSE, light0Diffuse);
   
    // 定義第一個光源的鏡射光與亮度
    // Define the specular component and shininess of the first light
    const GLfloat light0Specular[] = {0.7, 0.7, 0.7, 1.0};
    const GLfloat light0Shininess = 0.4;
    glLightfv(GL_LIGHT0, GL_SPECULAR, light0Specular);
    glLightfv(GL_LIGHT0, GL_SHININESS, &light0Shininess);
   
    // 定義第一個光源的位置
    // Define the position of the first light
    const GLfloat light0Position[] = {0.0, 10.0, 10.0, 0.0};
    glLightfv(GL_LIGHT0, GL_POSITION, light0Position);
   
    // 定義第一個光源的方向向量: 沿 z 軸而下
    // Define a direction vector for the light, this one points right down the Z axis
    const GLfloat light0Direction[] = {0.0, 0.0, -1.0};
    glLightfv(GL_LIGHT0, GL_SPOT_DIRECTION, light0Direction);
   
    // 定義第一個光源的遮光角: 限制角度為 90 度(使用 45 度遮光角)
    // Define a cutoff angle. This defines a 90° field of vision, since the cutoff
    // is number of degrees to each side of an imaginary line drawn from the light's
    // position along the vector supplied in GL_SPOT_DIRECTION above
    glLightf(GL_LIGHT0, GL_SPOT_CUTOFF, 45.0);
   
    glLoadIdentity();
}
....

     2. 編譯並執行:
         結果還是跟之前一樣: 白, 灰, 黑的循環效果.

OpenGL ES 入門: 四. 光效之一

since: 2012/04/05
update: 2012/04/08

reference:
1. 原文:
iPhone Development: OpenGL ES From the Ground Up, Part 4: Let There Be Light!

2. 翻譯:
從零開始學習OpenGL ES之四 – 光效

3. 清大資工-楊熙年老師-多媒體技術與應用-圖形

光效之一: 啟動光效與光源, 光源屬性

A. 說明:
     1. OpenGL 在沒有設置光效的情況下仍然可以看見東西, 它只提供一種十分單調
        的整體光.

     2. Shade Model(陰影模型):
          OpenGL ES 定義了兩種 shade model, GL_FLAT 和 GL_SMOOTH.

          a. 從發光的角度來看, GL_FLAT 將指定三角形上的每個像素都同等對待.
              多邊形上的每個像素都具有相同的顏色, 陰影等. 它提供了足夠的視覺暗示
              使其看上去有立體感而且它的計算比每個像素按不同方法計算更為廉價,
              但是在這種方式下, 物體看上去極為不真實. 因此, 將不會討論 GL_FLAT.

          b. 要讓 3D 物體盡量真實, 應該使用 GL_SMOOTH 繪圖模式, 它使用了一種
              平滑但較快速的陰影算法, 稱為 Gouraud 算法.  GL_SMOOTH 是繪圖模式
              的預設值.

              備註: Gouraud 著色法是以發明人來命名, 這個方法和平面著色法相差並不多,
                        不同的地方在於 Gouraud 著色法是計算表面上每個端點的方向向量來
                        計算該點的亮度, 再利用內插法 (interpolation) 計算出面上每個點 (pixel)
                        的亮度. 利用這個方法, 可讓面與面之間的接合處並不那麼明顯. 但這個
                        方法也會使物體看起來較為模糊, 同時需時更長的計算時間. (reference 3.)

-----------------------------------------------------------------------------

B. 繪製多面體光效的前置作業
      1. 說明: 我們將參考 OpenGL ES 新手入門: 二. 簡單繪圖之五 的畫圖為基礎,
                    來新增另一個畫圖的方法.

      2. 開啓 GLView.h 檔案, 修改如下:
....
@protocol GLViewDelegate

@required
- (void)setupView:(GLView *)view;

@optional
//@update for drawing
- (void)drawView:(GLView *)view;
- (void)drawTriangle3D; // 畫三角形
- (void)drawSquare; // 畫正方形
- (void)drawVertexColor; // 畫頂點顏色
- (void)drawIcosahedron; // 畫二十面體
- (void)drawPerspective; // 畫透視多面體
- (void)drawLight; // 畫多面體光效

@end
....

      3. 開啓 ViewController.m 檔案, 修改如下:
....
// 畫多面體光效
- (void)drawLight
{
    NSLog(@"ViewController => drawLight");
    // Draw code here
    //@update
    //
    // 1. 建立了一個靜態變數來跟蹤物體的旋轉
    static GLfloat rot = 0.0;
   
    // This is the same result as using Vertex3D, just faster to type and
    // can be made const this way
    //
    // 2. 定義頂點陣列:
    //
    // 使用了一個與前不同的方法, 但結果是一樣的. 由於我們的幾何體根本不會變化,
    // 所以我們將其定義為 const, 這樣就不需要每一 frame 都分配/清除記憶體:
    static const Vertex3D vertices[]= {
        {0, -0.525731, 0.850651},             // vertices[0]
        {0.850651, 0, 0.525731},              // vertices[1]
        {0.850651, 0, -0.525731},             // vertices[2]
        {-0.850651, 0, -0.525731},            // vertices[3]
        {-0.850651, 0, 0.525731},             // vertices[4]
        {-0.525731, 0.850651, 0},             // vertices[5]
        {0.525731, 0.850651, 0},              // vertices[6]
        {0.525731, -0.850651, 0},             // vertices[7]
        {-0.525731, -0.850651, 0},            // vertices[8]
        {0, -0.525731, -0.850651},            // vertices[9]
        {0, 0.525731, -0.850651},             // vertices[10]
        {0, 0.525731, 0.850651}               // vertices[11]
    };
   
    // 3. 建立一個顏色陣列:
    //
    // 創建一個 Color3D 物件陣列, 每項對應於前一個陣列的頂點:
    static const Color3D colors[] = {
        {1.0, 0.0, 0.0, 1.0},
        {1.0, 0.5, 0.0, 1.0},
        {1.0, 1.0, 0.0, 1.0},
        {0.5, 1.0, 0.0, 1.0},
        {0.0, 1.0, 0.0, 1.0},
        {0.0, 1.0, 0.5, 1.0},
        {0.0, 1.0, 1.0, 1.0},
        {0.0, 0.5, 1.0, 1.0},
        {0.0, 0.0, 1.0, 1.0},
        {0.5, 0.0, 1.0, 1.0},
        {1.0, 0.0, 1.0, 1.0},
        {1.0, 0.0, 0.5, 1.0}
    };
   
    // 4. 建立二十面體:
    //
    // 上述十二個頂點本身並未描述形狀. OpenGL 需要知道怎樣將它們聯繫在一起,
    // 所以我們建立了一個整數陣列 (GLubyte) 指向構成各三角形的頂點.
    //
    // 二十面體的第一個面的三個數是 1,2,6 代表繪製處於索引1 (0.850651, 0, 0.525731),
    // 2 (0.850651, 0, 0.525731), 和 6 (0.525731, 0.850651, 0) 之間的三角形.
    static const GLubyte icosahedronFaces[] = {
        1, 2, 6,
        1, 7, 2,
        3, 4, 5,
        4, 3, 8,
        6, 5, 11,
        5, 6, 10,
        9, 10, 2,
        10, 9, 3,
        7, 8, 9,
        8, 7, 0,
        11, 0, 1,
        0, 11, 4,
        6, 2, 10,
        1, 6, 11,
        3, 5, 10,
        5, 4, 11,
        2, 7, 9,
        7, 1, 0,
        3, 9, 8,
        4, 8, 0,
    };
   
    // 5.
    //
    // 加載單元矩陣
    glLoadIdentity();
   
    // 移動
    glTranslatef(0.0f,0.0f,-3.0f);
   
    // 旋轉
    glRotatef(rot,1.0f,1.0f,1.0f);
   
    // 設置背景色
    glClearColor(0.7, 0.7, 0.7, 1.0);
   
    // 清除緩存
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
   
    // 啟動頂點陣列
    glEnableClientState(GL_VERTEX_ARRAY);
   
    // 啟動顏色陣列
    glEnableClientState(GL_COLOR_ARRAY);
   
    // 提供頂點陣列內容給 OpenGL
    glVertexPointer(3, GL_FLOAT, 0, vertices);
   
    // 提供顏色陣列內容給 OpenGL
    glColorPointer(4, GL_FLOAT, 0, colors);
   
    // 6. 不使用 glDrawArrays(), 而是使用 glDrawElements():
    //
    // 備註: 如果你按繪製的正確次序提供頂點, 那麼你應該使用 glDrawArrays(),
    //       但是如果你提供一個陣列然後用另一個以索引值區分頂點次序的陣列的話,
    //       那麼你應該使用 glDrawElements().
    glDrawElements(GL_TRIANGLES, 60, GL_UNSIGNED_BYTE, icosahedronFaces);
   
    // 7. 執行禁止功能
    glDisableClientState(GL_VERTEX_ARRAY);
    glDisableClientState(GL_COLOR_ARRAY);
   
    // 8. 根據上一個 frame 繪製的時間增加旋轉變量值:
    static NSTimeInterval lastDrawTime;
    if (lastDrawTime)
    {
        NSTimeInterval timeSinceLastDraw = [NSDate timeIntervalSinceReferenceDate] - lastDrawTime;
        rot += 50 * timeSinceLastDraw;
    }
    lastDrawTime = [NSDate timeIntervalSinceReferenceDate];
}
....

      4. 開啓 GLView.m 檔案, 修改如下:
....
- (void)drawView
{
    NSLog(@"step 06. GLView => drawView");
   
    glBindFramebufferOES(GL_FRAMEBUFFER_OES, viewFrameBuffer);
    glBindRenderbufferOES(GL_RENDERBUFFER_OES, viewRenderBuffer);
   
    // GO: step 07. ViewController => drawView:
    //[self.delegate drawView:self];
    //@update for drawing
    //[self.delegate drawTriangle3D]; // 畫三角形
    //[self.delegate drawSquare]; // 畫正方形
    //[self.delegate drawVertexColor]; // 畫頂點顏色
    //[self.delegate drawIcosahedron]; // 畫二十面體
    //[self.delegate drawPerspective]; // 畫透視多面體
    [self.delegate drawLight]; // 畫多面體光效
   
    [self.glContext presentRenderbuffer:GL_RENDERBUFFER_OES];
   
    //@add for Rendering Frequency
    int intCount = [self.currentRunCount intValue] + 1;
    self.currentRunCount = [NSNumber numberWithInt:intCount];
   
    if (intCount >= self.totalRunTime * kRenderingFrequency) {

        [self stopAnimation];
    }
   
    //@update for run once
    //[self stopAnimation];
}
....

-----------------------------------------------------------------------------

C. 啟動光效
      1. 開啓 ViewController.m 檔案, 修改如下:
....
-(void)setupView:(GLView *)view
{
    NSLog(@"step 05. ViewController => setupView:");
   
    const GLfloat zNear = 0.01, zFar = 1000.0, fieldOfView = 45.0; // 設定為 45 度視野
    GLfloat size;
    glEnable(GL_DEPTH_TEST);
    glMatrixMode(GL_PROJECTION);
    size = zNear * tanf(DEGREES_TO_RADIANS(fieldOfView) / 2.0);
   
    CGRect rect = view.bounds;

    // 設定透視 viewport (基於視野角度計算錐台)
    glFrustumf(-size, size, -size / (rect.size.width / rect.size.height), size /
               (rect.size.width / rect.size.height), zNear, zFar);
   
    // 建構一個對應的座標系統
    glViewport(0, 0, rect.size.width, rect.size.height); 
   
    glMatrixMode(GL_MODELVIEW);
   
    //@add for 啟動光效
    glEnable(GL_LIGHTING);
   
    glLoadIdentity();
}
....

    說明: 通常, 光效只需在設定時啟動一次. 不需要在繪圖開始前後打開和關閉.
              可能有些特效的情況需要在程序執行時打開或關閉, 但是大部分情況下,
              你只需在程序啟動時打開它.

      2. 編譯並執行:
    啟動了光效, 但是沒有創建任何光源. 因此, 繪製的物體都被渲染成絕對的黑色.

-----------------------------------------------------------------------------

D. 啟動光源
      1. 說明: OpenGL ES 允許你創建 8 個光源. 有一個常數對應於這些光源中的一個,
                   常數為 GL_LIGHT0 到 GL_LIGHT7 . 可以任意組合這些光源中的五個,
                   儘管習慣上從 GL_LIGHT0 作為第一個光源, 然後是 GL_LIGHT1 等等.

      2. 開啓 ViewController.m 檔案, 修改如下:
....
-(void)setupView:(GLView *)view
{
    NSLog(@"step 05. ViewController => setupView:");
   
    const GLfloat zNear = 0.01, zFar = 1000.0, fieldOfView = 45.0; // 設定為 45 度視野
    GLfloat size;
    glEnable(GL_DEPTH_TEST);
    glMatrixMode(GL_PROJECTION);
    size = zNear * tanf(DEGREES_TO_RADIANS(fieldOfView) / 2.0);
   
    CGRect rect = view.bounds;

    // 設定透視 viewport (基於視野角度計算錐台)
    glFrustumf(-size, size, -size / (rect.size.width / rect.size.height), size /
               (rect.size.width / rect.size.height), zNear, zFar);
   
    // 建構一個對應的座標系統
    glViewport(0, 0, rect.size.width, rect.size.height); 
   
    glMatrixMode(GL_MODELVIEW);
   
    //@add for 啟動光效
    glEnable(GL_LIGHTING);
   
    //@add for 啟動光源
    glEnable(GL_LIGHT0);
   
    glLoadIdentity();
}
....

      3. 編譯並執行:


    說明: 結果為 "白" 轉 "灰" 轉 "黑" 的循環效果, 需要再設定光源的一些屬性.

-----------------------------------------------------------------------------

E. 光源屬性
     1. 說明:
          a. 在 OpenGL ES中, 光由三個元素組成, 分別是環境元素(ambient component),
              散射元素(diffuse component)和鏡射元素(specular component)

          b. 鏡射元素(specular component):
              鏡射元素定義了光線直接照射並反射到觀察者從而形成了物體上的 "熱點"
              或光澤. 

          c. 散射元素(diffuse component):
              散射元素定義了比較平均的定向光源, 在物體面向光線的一面具有光澤.

          d. 環境元素(ambient component):
              環境光則沒有明顯的光源. 其光線折射於許多物體, 因此無法確定其來源.
              環境元素平均作用於場景中的所有物體的所有面.

     2. 環境光
         a. 說明: 在光效中有越多的環境元素, 那麼就越不會產生引人注目的效果. 所有
                       光線的環境元素會融合在一起產生效果
, 意思是場景中的總環境光效是由
                       所有啟動光源的環境光組合在一起所決定的, 如果你使用了不止一個光源,
                       那麼最好是只指定一個光源的環境元素, 而設定其他所有光源的環境因素
                       為黑 ({0.0, 0.0, 0.0, 1.0}), 從而很容易地調整場景的環境光效.

         b. 例子:
             指定一個很暗的白色光源:
             const GLfloat light0Ambient[] = {0.05, 0.05, 0.05, 1.0};
             glLightfv(GL_LIGHT0, GL_AMBIENT, light0Ambient);

             備註: 使用像這樣的很低的環境元素值使場景看上去更引人注目, 但同時也
                       意味着物體沒有面向光線的面或者有其他物體擋住的物體將在場景中
                       看得不是很清楚.

     3. 散射光
          a. 說明: 在現實世界中, 散射光線是諸如穿透光纖或從一堵白牆反射的光線.
                        散射光線是發散的, 因而參數較柔和的光, 一般不會像直射光一樣產生光斑.
                        在 OpenGL ES 中, 散射元素它使光線均勻地散布到物體之上. 然而, 不像
                        環境光, 由於它是定向光, 只有面向光線的物體面才會反射散射光, 而場景中
                        的所有多面體都會被環境光照射.

          b. 例子:
             設定場景中的第一個散射元素:
             const GLfloat light0Diffuse[] = {0.5, 0.5, 0.5, 1.0};
             glLightfv
(GL_LIGHT0, GL_DIFFUSE, light0Diffuse);


     4. 鏡射光
          a. 說明: 這種類型的光是十分直接的, 它們會以熱點和光暈的形式反射到觀察者
                        的眼中. 如果你想產生聚光燈的效果, 那麼應該設置一個很大的鏡射元素
                        值及很小的散射和環境元素值(還需要定義其它一些參數).

           b. 例子:
               const GLfloat light0Specular[] = {0.7, 0.7, 0.7, 1.0};
               glLightfv(GL_LIGHT0, GL_SPECULAR, light0Specular);

2012年4月7日 星期六

OpenGL ES 入門: 番外篇之 UIView 元件

since: 2012/04/06
update: 2012/04/07


A. 說明
    1. 目的: 要在本專案功能上加上 UIView 元件, ex: UIButton, UIToolBar ...

    2. 嘗試用加入 storyboard / xib 的方式, 發現畫面都會被 OpenGL ES 覆蓋掉.

    3. 因此決定, 全用 coding 的方式來處理.

    4. 方式有二種:
        a. 在 viewController 上新加入一個要放 UIView 元件的 subview, 接著在此 subview
            上放上原本的 glView, 並限制 glView 的大小, 如此可以保證 glView 上所繪製的
            東西不會被其它
UIView 元件所覆蓋到.  

        b. 或著, 直接在 glView 上, 加上你所需要的 UIView 元件. 這樣會覆蓋到部分的
             OpenGL ES 畫面, 但不需要去調整背景色, 來讓畫面一致.

------------------------------------------------------------------------------------------------------

B. 開啓 AppDelegate.h 檔案, 修改如下:
#import <UIKit/UIKit.h>
//@add
#import "ViewController.h"
#import "GLView.h"

@interface AppDelegate : UIResponder <UIApplicationDelegate>
{
    UIWindow *window;
    //@add
    ViewController *viewController;
    GLView *glView;
   
    //@add for UIView overlay
    UILabel *label;   
    UIToolbar *toolbar;
}

@property (strong, nonatomic) UIWindow *window;
//@add
@property (strong, nonatomic) ViewController *viewController;
@property (strong, nonatomic) GLView *glView;

//@add for UIView overlay
@property (strong, nonatomic) UILabel *label;   
@property (strong, nonatomic) UIToolbar *toolbar;

//@add for UIView overlay
//
// Action methods for toolbar buttons
- (void)addButtonPressed:(id)sender; // Add
- (void)actionButtonPressed:(id)sender; // Action
- (void)cameraButtonPressed:(id)sender; // Camera


@end

------------------------------------------------------------------------------------------------------

C. 開啓 AppDelegate.m 檔案, 修改如下:
....
//@add for UIView overlay
@synthesize label = _label;
@synthesize toolbar = _toolbar;
....
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    NSLog(@"step 01. AppDelegate => didFinishLaunchingWithOptions");
    /*
    CGRect screenBounds = [[UIScreen mainScreen] bounds];
     ....
     return YES;
    */

    //@update for UIView overlay
    CGRect screenBounds = [[UIScreen mainScreen] bounds];
   
    self.window = [[UIWindow alloc] initWithFrame:screenBounds];
    self.viewController = [[ViewController alloc] init];
    self.window.rootViewController = viewController;
   
   
    //@add UIView overlay
    UIView *myUIView = [[UIView alloc] initWithFrame:screenBounds];
    // 將背景色設成跟 OpenGL 的背景色相同(在此為不透明灰)
    myUIView.backgroundColor = [UIColor colorWithRed:0.7f green:0.7f blue:0.7f alpha:1.0];

    self.viewController.view = myUIView;
   
   
    //@add label
    self.label = [[UILabel alloc] init];
    self.label.frame = CGRectMake(10, 10, 300, 40);
    self.label.textAlignment = UITextAlignmentCenter;
    self.label.text = @"Press Button";
   
    [myUIView addSubview:self.label];
   
   
    //@add toolbar
    self.toolbar = [UIToolbar new];
    self.toolbar.barStyle = UIBarStyleDefault;
    [self.toolbar sizeToFit];
    self.toolbar.frame = CGRectMake(0, 430, 320, 50);
   
    //@buttons
    // Add
    UIBarButtonItem *addItem = [[UIBarButtonItem alloc]
                                initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
                                target:self
                                action:@selector(addButtonPressed:)];
   
    // Action
    UIBarButtonItem *actionItem = [[UIBarButtonItem alloc]
                                   initWithBarButtonSystemItem:UIBarButtonSystemItemAction
                                   target:self
                                   action:@selector(actionButtonPressed:)];
   
    // Camera
    UIBarButtonItem *cameraItem = [[UIBarButtonItem alloc]
                                   initWithBarButtonSystemItem:UIBarButtonSystemItemCamera
                                   target:self
                                   action:@selector(cameraButtonPressed:)];
   
    //Use this to put space in between your toolbox buttons
    UIBarButtonItem *flexItem = [[UIBarButtonItem alloc]
                                 initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
                                 target:nil
                                 action:nil];
   
    //Add buttons to the array
    NSArray *items = [NSArray arrayWithObjects: addItem, flexItem, actionItem, flexItem, cameraItem, nil];
   
    //add array of buttons to toolbar
    [self.toolbar setItems:items animated:NO];
   
    [myUIView addSubview:self.toolbar];
   

    //@for glView: 原始寬高 320 x 480, 須扣除 UIView 所佔的高度  
    self.glView = [[GLView alloc] initWithFrame:CGRectMake(0, 40, 320, 390)]; 
   
    //@add for delegate
    self.glView.delegate = self.viewController;


    [myUIView addSubview:self.glView];
   

    [self.window addSubview:self.viewController.view];
    [self.window makeKeyAndVisible];
   
    return YES;
}
....
//@add for UIView overlay
//
// Action methods for toolbar buttons

// Add
- (void)addButtonPressed:(id)sender
{
    self.label.text = @"Add";
}

// Action
- (void)actionButtonPressed:(id)sender
{
    self.label.text = @"Take Action";
}

// Camera
- (void)cameraButtonPressed:(id)sender
{
    self.label.text = @"Camera";
}
....

------------------------------------------------------------------------------------------------------

D. 編譯並執行
     1. 按下: "新增"

     2. 按下: "動作"

     3. 按下: "相機"

------------------------------------------------------------------------------------------------------

E. 直接在 glView 上, 加上你所需要的 UIView 元件
    1. 開啓 AppDelegate.h 檔案, 修改如下:
....
//@add for UIView overlay
//
// Action methods for toolbar buttons
- (void)addButtonPressed:(id)sender; // Add
- (void)actionButtonPressed:(id)sender; // Action
- (void)cameraButtonPressed:(id)sender; // Camera
- (void)myButtonPressed:(id)sender; // myButton
....

    2. 開啓 AppDelegate.m 檔案, 修改如下:
....
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
....
    [myUIView addSubview:self.glView];
   
   
    //@add button for glView
    UIButton *myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];

    [myButton addTarget:self
               action:@selector(myButtonPressed:)
     forControlEvents:UIControlEventTouchDown];
   
    [myButton setTitle:@"myButton" forState:UIControlStateNormal];
    myButton.frame = CGRectMake(10, 340.0, 160.0, 40.0);
    [self.glView addSubview:myButton];
   
   
    [self.window addSubview:self.viewController.view];
    [self.window makeKeyAndVisible];
   
    return YES;
}
....
// myButton
- (void)myButtonPressed:(id)sender
{
    self.label.text = @"myButton";
}
....

    3. 編譯並執行:
        按下 glView 上的 button

2012年4月5日 星期四

Installing an updated version of OpenSSL on your Mac OS X

since: 2012/04/05
update: 2012/04/05

reference: OpenSSL on OS X -- Alexei Czeskis

說明: MacPorts 可以用來編譯, 安裝及維護 Open Source 軟體, 它會自動處理軟體之間
          的相依性問題, 若有缺少則會自動幫忙補安裝.

A. 查詢目前 Mac OS X 上所安裝的 OpenSSL 版本.
     $ openssl version

----------------------------------------------------------------------------

B. 先安裝 MacPorts
     1. 下載網址: The MacPorts Project -- Download & Installation
     2. 採用版本: MacPorts-2.0.4-10.7-Lion.dmg
     3. 安裝完成後, 先執行:
          $ sudo port sync


----------------------------------------------------------------------------

C. 更新 MacPorts 軟體本身與 ports tree (軟體清單樹)
     $ sudo port -d selfupdate

----------------------------------------------------------------------------

D. 安裝 / 更新 OpenSSL
     $ sudo port install openssl

----------------------------------------------------------------------------

E. 其它指令
      1. 列出已經安裝的軟體:
          $ port installed

      2. 列出所有可安裝的軟體:(分頁顯示)
          $ port list | more

      3. 搜尋某個可安裝的軟體:(分頁顯示)
          $ port search openssl | more