2012年7月24日 星期二

Java Applet


用javac -encoding utf-8 neoApplet.java 編譯

neoApplet.java
   import java.awt.*; 
   import java.awt.event.*; 
   import java.applet.Applet; 
   import java.applet.AudioClip;
    
    public class neoApplet extends Applet implements ItemListener,ActionListener,MouseListener,MouseMotionListener{ 
        Button btn;                   //  宣告 Button 型態的變數 btn 
     int image_x=10,image_y=10,dx,dy; 
  Image img; 
  Image imgBackup;      //  宣告 Image 類別型態的變數 imgB 
        Graphics gBackup;      //  宣告 Graphics 類別型態的變數 gB 
     boolean clicked=false;  
  AudioClip midi[]=new AudioClip[2]; //  宣告 AudioClip 介面型態的陣列  
        AudioClip midiplayer;  //  宣告 AudioClip 介面型態的變數 current
        Choice chc=new Choice();   //  建立 Choice 元件    
  public void mouseMoved(MouseEvent e){}   //MouseMotionListener
     public void mouseEntered(MouseEvent e){} //MouseListener
        public void mouseExited(MouseEvent e){}  //MouseListener
        public void mouseReleased(MouseEvent e){}//MouseListener
  public void mousePressed(MouseEvent e) 
  { 
   dx=e.getX()-image_x;  //  取得按下之點與基準點 x 方向之距離
   dy=e.getY()-image_y;  //  取得按下之點與基準點 y 方向之距離 
        } 
  public void mouseDragged(MouseEvent e) 
  { 
     if(dx>0 && dx< Integer.valueOf(getParameter("imageWIDTH")) && dy>0 && dy< Integer.valueOf(getParameter("imageHEIGHT")))  //  如果指標落在圖形上方 
         { 
    image_x=e.getX()-dx;   //  取得拖曳時,基準點的 x 座標 
            image_y=e.getY()-dy;   //  取得拖曳時,基準點的 y 座標 
   paint(getGraphics()); 
            //Graphics g=getGraphics(); 
           // update(g);   //  清空畫面為背景顏色,再呼叫 paint() 
        } 
      } 
  public void mouseClicked(MouseEvent e)
        { 
   }  
      public void init() 
   {  
      midi[0]=getAudioClip(getCodeBase(),"sky.mid"); 
         midi[1]=getAudioClip(getCodeBase(),"panther.mid");   
   midiplayer=midi[0];
   midiplayer.play(); 
   chc.add(" sky "); 
         chc.add(" panther "); 
   add(chc);
   
         btn=new Button(getParameter("buttonCaption"));     //  建立 btn 物件  
         btn.addActionListener(this);  //  以 applet 本身當成 btn 的傾聽者  
   add(btn);  //  將 btn 按鈕加入 applet 視窗裡  
   img=getImage(getCodeBase(),getParameter("imageFileName"));  //  載入圖檔  
   imgBackup=createImage(getWidth(),getHeight()); 
   gBackup=imgBackup.getGraphics();
   
   addMouseListener(this);  //  設定 applet 為自己本身的傾聽者 
   addMouseMotionListener(this);     
         chc.addItemListener(this);   //  把 applet 當成 chc 的傾聽者   
      } 
    public void paint(Graphics g) 
      {
     gBackup.setColor(new Color(255,255,255));      //  設定繪圖顏色為白色  
        gBackup.fillRect(0,0,getWidth(),getHeight()); //  以白色填滿整個畫面  
  gBackup.setColor(Color.blue);     //  設定繪圖顏色為藍色  
        gBackup.fillOval(30,30,50,50);    //  繪出圓形並填滿藍色  
        gBackup.drawImage(img,image_x,image_y,this);  //  將 img 畫上    
  gBackup.setColor(Color.orange);   //  設定繪圖顏色為橘色  
        gBackup.fillOval(60,40,90,90);    //  繪出圓形並填滿橘色 
        g.drawImage(imgBackup,0,0,this);   //  將 imgB 的內容顯示在 applet 上  
  
    } 
      public void actionPerformed(ActionEvent e) 
      { 
   System.out.println("Button was clicked message show in the java console");
         if(btn.getLabel().equals(getParameter("buttonCaption"))) 
   {   
   btn.setLabel("clicked");    //  設定按鈕上方的文字為 Stop 
   }
   else {          
   btn.setLabel(getParameter("buttonCaption"));   //  設定按鈕上方的文字
   }
      } 
    public void itemStateChanged(ItemEvent e) 
       { 
        midiplayer.stop();                      //  停止播放歌曲  
        int index=chc.getSelectedIndex();      //  取得被選取的索引值  
 midiplayer=midi[index];     //  設定播放的歌曲為 midi[index] 
        midiplayer.play();          //  播放歌曲  
       }    
    } 

web.html.
<!-- web.htm --> 
   <HTML> 
   <BODY BGCOLOR = "FFFF00" > 
   <APPLET                      
      CODE    = "neoApplet.class"  
      WIDTH   = "180"           
      HEIGHT  = "180"
      ALT     = " 很抱歉,您的瀏覽器不支援 Java applet" 
      ALIGN   = "MIDDLE"     
      VSPACE  = "20"   
 >
   <PARAM NAME = "buttonCaption" VALUE = "按鈕"> 
   <PARAM NAME = "imageFileName" VALUE = "logo.jpg"> 
   <PARAM NAME = "imageWIDTH" VALUE = "55">
   <PARAM NAME = "imageHEIGHT" VALUE = "55"> 
   </APPLET> 
   </BODY> 
   </HTML> 

要想在前面加package neo.applet; 封裝起來的話
用JAR方式可用 jar cvf neoAppletExample.jar -C ./classes/* .
注意最後有個點,classes下是/classes/neo/applet/neoApplet.class
web_jar.html

   <HTML> 
   <BODY BGCOLOR = "FFFF00" > 
   <APPLET  
         
      CODEBASE   =   "."  
      CODE    = "neo.applet.neoApplet"  
      ARCHIVE = "neoAppletExample.jar"
      WIDTH   = "180"           
      HEIGHT  = "180"
      ALT     = " 很抱歉,您的瀏覽器不支援 Java applet" 
      ALIGN   = "MIDDLE"     
      VSPACE  = "20"   
 >
   <PARAM NAME = "buttonCaption" VALUE = "按鈕"> 
   <PARAM NAME = "imageFileName" VALUE = "logo.jpg"> 
   <PARAM NAME = "imageWIDTH" VALUE = "55">
   <PARAM NAME = "imageHEIGHT" VALUE = "55">
 </APPLET> 
   </BODY> 
   </HTML> 

2012年7月23日 星期一

Apache Ant


build.xml
<?xml version="1.0" encoding="UTF-8"?>
<project name="NEO TEST" default="run" basedir=".">
 <property name="src" value="src"/>
 <property name="dest" value="destfolder"/>
 <property name="hello_jar" value="hello1.jar"/>
 <target name="init">
  <mkdir dir="${dest}"/>
 </target>
 <target name="compile" depends="init">
  <javac srcdir="${src}" destdir="${dest}"/>
 </target>
 <target name="build" depends="compile">
  <jar jarfile="${hello_jar}" basedir="${dest}"/>
 </target>
 <target name="run" depends="build">
  <java classname="test.ant.neo" classpath="${hello_jar}"/>
 </target>
 <target name="clean">
  <delete dir="${dest}"/>
  <delete file="${hello_jar}"/>
 </target>
 <target name="rerun" depends="clean,run">
  <ant target="clean"/>
  <ant target="run"/>
 </target>
 </project>


neo.java在./src中

Box2D


CB的global compiler settings -> compiler settings -> Other options 填-fexceptions
#defines填FREEGLUT_STATIC
link libraries加入libFreeGLUT.a libGLUI.a GlU32(GlU32.Lib) Gdi32(Gdi32.Lib) OpenGL32(OpenGL32.Lib) User32(User32.Lib) WinMM(WinMM.Lib)
多加一個libBox2D.a
main.cpp
#include "gluiDraw.h"
#include "glui/GL/glui.h"
#include "myBox2D.h"

MyBox2D mybox2d;
GluiDraw draw;
GLint mainWindow;
GLint winWidth = 640;
GLint winHeight = 640;
int tx, ty, tw, th;
float viewCenterX=0,viewCenterY=0;
GLUI *glui;
int framePeriod = 16;
float viewZoom = 1.0f;
NeoVec2 mp,pre_mp;
bool isMouseRightPressed = false;
bool isMouseLeftPressed = false;

void Resize(int32 newWidth, int32 newHeight)
{
 winWidth = newWidth;
 winHeight = newHeight;
 GLUI_Master.get_viewport_area(&tx, &ty, &tw, &th);
 glViewport(tx, ty, tw, th);

 glMatrixMode(GL_PROJECTION);
 glLoadIdentity();
 float32 ratio = float32(tw) / float32(th);

 b2Vec2 extents(ratio * 25.0f, 25.0f);
 extents *= viewZoom;

 b2Vec2 lower(viewCenterX-extents.x,viewCenterY-extents.y);
 b2Vec2 upper(viewCenterX+extents.x,viewCenterY+extents.y);

 // L/R/B/T
 gluOrtho2D(lower.x, upper.x, lower.y, upper.y);
}

void Mouse(int button, int state, int x, int y)
{
 // Use the mouse to move things around.
 if (button == GLUT_LEFT_BUTTON)
 {
  int specialKey  = glutGetModifiers();
  if (state == GLUT_DOWN)
  {
   if (specialKey  == GLUT_ACTIVE_SHIFT)
   {
               //  cout << "GLUT_LEFT_BUTTON click with SHIFT" << endl;
   }
   else
   {
                // cout << "GLUT_LEFT_BUTTON click" << endl;
   }
  }

  if (state == GLUT_UP)
  {
               // cout << "GLUT_LEFT_BUTTON release" << endl;
  }
 }
 else if (button == GLUT_RIGHT_BUTTON)
 {
  if (state == GLUT_DOWN)
  {
      isMouseRightPressed = true;
           // cout << "GLUT_RIGHT_BUTTON click" << endl;
  }

  if (state == GLUT_UP)
  {
      isMouseRightPressed = false;
           // cout << "GLUT_RIGHT_BUTTON release" << endl;
  }
 }
}
b2Vec2 ConvertScreenToWorld(int32 x, int32 y)
{
 float32 u = x / float32(tw);
 float32 v = (th - y) / float32(th);

 float32 ratio = float32(tw) / float32(th);
 b2Vec2 extents(ratio * 25.0f, 25.0f);
 extents *= viewZoom;

 b2Vec2 lower(viewCenterX-extents.x,viewCenterY-extents.y);
 b2Vec2 upper(viewCenterX+extents.x,viewCenterY+extents.y);

 b2Vec2 p;
 p.x = (1.0f - u) * lower.x + u * upper.x;
 p.y = (1.0f - v) * lower.y + v * upper.y;
 return p;
}
void MouseMotion(int x, int y)
{
    b2Vec2 p = ConvertScreenToWorld(x, y);
    if(isMouseRightPressed)
    {
        float distanceX = p.x - pre_mp.x;
        float distanceY = p.y - pre_mp.y;
        viewCenterX -= distanceX;
  viewCenterY -= distanceY;
  Resize(winWidth, winHeight);
  p = ConvertScreenToWorld(x, y);
        pre_mp.x = p.x;
        pre_mp.y = p.y;
        glutPostRedisplay(); //要求重畫視窗
    }
    //cout << "Mouse clicked and x=" << mp.x << ",y=" << mp.y << endl;
}
void MouseWheel(int wheel, int direction, int x, int y)
{
 B2_NOT_USED(wheel);
 B2_NOT_USED(x);
 B2_NOT_USED(y);
 if (direction > 0)
 {
  viewZoom /= 1.1f;
 }
 else
 {
  viewZoom *= 1.1f;
 }
 Resize(winWidth, winHeight);
}
void Keyboard(unsigned char key, int x, int y)
{
switch (key)
 {
 case 27:
     exit(0);
  break;
    case 'a':
        mybox2d.m_bodies[2]->ApplyForce(b2Vec2(-400,0), mybox2d.m_bodies[2]->GetWorldPoint(b2Vec2(1,1)));
        break;
    case 'd':
        mybox2d.m_bodies[2]->ApplyForce(b2Vec2(400,0), mybox2d.m_bodies[2]->GetWorldPoint(b2Vec2(-1,1)));
        break;
    default:
        break;
 }
}
void KeyboardSpecial(int key, int x, int y)
{
 B2_NOT_USED(x);
 B2_NOT_USED(y);

 switch (key)
 {
 case GLUT_ACTIVE_SHIFT:
  // Press left to pan left.
 case GLUT_KEY_LEFT:
  viewCenterX -= 0.5f;
  Resize(winWidth, winHeight);
  break;

  // Press right to pan right.
 case GLUT_KEY_RIGHT:
  viewCenterX += 0.5f;
  Resize(winWidth, winHeight);
  break;

  // Press down to pan down.
 case GLUT_KEY_DOWN:
  viewCenterY -= 0.5f;
  Resize(winWidth, winHeight);
  break;

  // Press up to pan up.
 case GLUT_KEY_UP:
  viewCenterY += 0.5f;
  Resize(winWidth, winHeight);
  break;
 }
}

void drawWholeBody(b2World* world,b2Body* m_bodies[])
{
     int32 bodyCount = world->GetBodyCount();
     for(int number = 0; number < bodyCount; number++)  //扣掉地面一個body
    {
        const b2Transform& xf = m_bodies[number]->GetTransform();
        for (b2Fixture* fixture = m_bodies[number]->GetFixtureList();fixture; fixture = fixture->GetNext())
        {
            switch (fixture->GetType())
            {
                case b2Shape::e_circle:
                {
                    b2CircleShape* circle = (b2CircleShape*)fixture->GetShape();
                    b2Vec2 center = b2Mul(xf, circle->m_p);
                    float32 radius = circle->m_radius;
                    b2Vec2 axis = b2Mul(xf.q, b2Vec2(1.0f, 0.0f)); //還沒用到
                    draw.DrawSolidCircle(NeoVec2(center.x,center.y),radius,NeoVec2(axis.x,axis.y),NeoColor(1,1,1));
                }
                break;
                case b2Shape::e_edge:
                {
                    b2EdgeShape* edge = (b2EdgeShape*)fixture->GetShape();
                    b2Vec2 v1 = b2Mul(xf, edge->m_vertex1);
                    b2Vec2 v2 = b2Mul(xf, edge->m_vertex2);
                    draw.DrawLine(NeoVec2(v1.x,v1.y),NeoVec2(v2.x,v2.y),NeoColor(0,1,0));
                 }
                break;
                case b2Shape::e_chain:
                {
                    b2ChainShape* chain = (b2ChainShape*)fixture->GetShape();
                    int32 count = chain->GetVertexCount();
                    const b2Vec2* vertices = chain->GetVertices();

                    b2Vec2 v1 = b2Mul(xf, vertices[0]);
                    for (int32 i = 1; i < count; ++i)
                    {
                        b2Vec2 v2 = b2Mul(xf, vertices[i]);
                        draw.DrawLine(NeoVec2(v1.x,v1.y),NeoVec2(v2.x,v2.y),NeoColor(1,1,1));
                        draw.DrawCircle(NeoVec2(v1.x,v1.y),0.01,NeoColor(1,1,1));
                         v1 = v2;
                    }
                }
                break;
                case b2Shape::e_polygon:
                {
                    b2PolygonShape* poly = (b2PolygonShape*)fixture->GetShape();
                    int32 vertexCount = poly->m_vertexCount;
                    b2Assert(vertexCount <= b2_maxPolygonVertices);
                    b2Vec2 vertices[b2_maxPolygonVertices];
                    NeoVec2 v[b2_maxPolygonVertices];

                    for (int32 i = 0; i < vertexCount; ++i)
                    {
                    vertices[i] = b2Mul(xf, poly->m_vertices[i]);
                    v[i] = NeoVec2(vertices[i].x,vertices[i].y);
                    }
                    draw.DrawSolidPolygon(v,vertexCount,NeoColor(1,1,1));
                }
                break;
                default:
                break;
            }
        }
    }

}
void display()
{
    //glEnable(GL_DEPTH_TEST);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glPushMatrix();
    int32 bodyCount = mybox2d.m_world->GetBodyCount();
    float32 timeStep = 1.0f / 60.0f;
    int32 velocityIterations = 6;
    int32 positionIterations = 2;
    mybox2d.m_world->Step(timeStep, velocityIterations, positionIterations);
    drawWholeBody(mybox2d.m_world, mybox2d.m_bodies);
    glPopMatrix();
    glutSwapBuffers();
    glFlush();
}
void Timer(int)
{
 glutSetWindow(mainWindow);
    glutPostRedisplay(); //要求重畫視窗
 glutTimerFunc(framePeriod, Timer, 0); //Do Repeat
}
int main(int argc, char* argv[])
{
    glutInit(&argc, argv);
 glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE);
 glutInitWindowSize(winWidth, winHeight);
    mainWindow = glutCreateWindow("Neo Box2D");
 glutDisplayFunc(display);
    GLUI_Master.set_glutReshapeFunc(Resize);
 GLUI_Master.set_glutSpecialFunc(KeyboardSpecial);
    GLUI_Master.set_glutKeyboardFunc(Keyboard);
 GLUI_Master.set_glutMouseFunc(Mouse);
 glutMouseWheelFunc(MouseWheel);
    glutMotionFunc(MouseMotion);

 glutTimerFunc(framePeriod, Timer, 0);
 //glui->set_main_gfx_window( mainWindow );
 glutMainLoop();
 return 0;
}

myBox2d.h
#ifndef MYBOX2D_H
#define MYBOX2D_H
#include <Box2D/Box2D.h>
class MyBox2D : public b2ContactListener
{
public:
    b2World* m_world;
    b2Body* m_groundBody;
    b2Body* m_bodies[4];
 b2Joint* m_joints[8];
    MyBox2D()
    {
b2Vec2 gravity(0.0f, -10.0f);
bool doSleep = true;
m_world = new b2World(gravity, doSleep);

//宣告static物體定義
b2BodyDef staticBodyDef;
staticBodyDef.type = b2_staticBody;
//宣告dynamic物體定義
b2BodyDef dynamicBodyDef;
dynamicBodyDef.type = b2_dynamicBody;

//註冊地面(先新增shape,再利用BodyDef給出location)
//shape
b2EdgeShape groundShape;
groundShape.Set(b2Vec2(-50,0), b2Vec2(50,0));
//材質
b2FixtureDef groundFixtureDef;
groundFixtureDef.shape = &groundShape;
groundFixtureDef.density = 1.0f;
groundFixtureDef.friction = 1.0f;
//location
staticBodyDef.position.Set(0, -20);
m_groundBody = m_world->CreateBody(&staticBodyDef);
m_groundBody->CreateFixture(&groundFixtureDef);
m_bodies[0] = m_groundBody;

//球shape
b2CircleShape dynamicCircle;
dynamicCircle.m_p.Set(0.0f, 0.0f);
dynamicCircle.m_radius = 3.0f;
//location
dynamicBodyDef.position.Set(2, 20);
m_bodies[1] = m_world->CreateBody(&dynamicBodyDef);
m_bodies[1]->CreateFixture(&dynamicCircle,1.0f);


b2PolygonShape dynamicBox;
dynamicBox.SetAsBox(2, 2);
dynamicBodyDef.position.Set(0.0f, 10.0f);
m_bodies[2] = m_world->CreateBody(&dynamicBodyDef);
m_bodies[2]->CreateFixture(&dynamicBox, 1.0f);

/*
b2Vec2 vs[4];
vs[0].Set(0.7f, 0.0f);
vs[1].Set(1.0f, 0.02);
vs[2].Set(0.0f, 0.0f);
vs[3].Set(-0.7f, 0.4f);
b2ChainShape chain;
chain.CreateChain(vs, 4);
bodyDef.position.Set(0.0f, 0.0f);
m_bodies[4] = m_world->CreateBody(&bodyDef);
m_bodies[4]->CreateFixture(&chain, 0.01f);
*/
    }
 virtual ~MyBox2D()
 {
     delete m_world;
        m_world = NULL;
 }
};
#endif


gluiDraw.h
#ifndef GLUIDRAW_H
#define GLUIDRAW_H
#include <math.h>
#include <glui/GL/glui.h>
#define PI 3.141592653
const float deg2Rad = PI / 180.;
const float rad2Deg = 180. / PI;

struct NeoColor
{
    float r, g, b;
    NeoColor(){}
    NeoColor(float r_,float g_,float b_) : r(r_), g(g_), b(b_){}
    void Set(float r_,float g_,float b_) {r = r_; g = g_; b = b_;}
};
struct NeoVec2
{
    float x, y;
    NeoVec2(){}
    NeoVec2(float x_,float y_) : x(x_), y(y_){}
    void Set(float x_,float y_) {x = x_; y = y_;}
};
inline NeoVec2 operator + (const NeoVec2 &v1, const NeoVec2 &v2)
{
    return NeoVec2(v1.x + v2.x, v1.y + v2.y);
}
inline NeoVec2 operator * (float a, const NeoVec2 &v)
{
    return NeoVec2(v.x * a, v.y * a);
}

class GluiDraw
{
public:
    GluiDraw(){}
    ~GluiDraw(){}
    void DrawLine(const NeoVec2 &v1,const NeoVec2 &v2,const NeoColor &color)
    {
        glBegin(GL_LINES);
        glColor3f(color.r,color.g,color.b);
        glVertex2f(v1.x,v1.y);
        glVertex2f(v2.x,v2.y);
        glEnd();
    }
    void DrawCircle(const NeoVec2 ¢er, const float radius, const NeoColor &color)
    {
        const float segments = 16.;
        const float inc = 2 * PI / 16.;
        float theta = 0;
        glBegin(GL_LINE_LOOP);
        glColor3f(color.r,color.g,color.b);
        for (int i=0;i < segments;++i)
        {
            NeoVec2 real_v = center + radius * NeoVec2(cosf(theta),sinf(theta));
            glVertex2f(real_v.x,real_v.y);
            theta += inc;
        }
        glEnd();
    }
     void DrawSolidCircle(const NeoVec2 ¢er, const float radius,const NeoVec2 &axis, const NeoColor &color)
    {
        const float segments = 16.;
        const float inc = 2 * PI / 16.;
        float theta = 0;
        glBegin(GL_LINE_LOOP);
        glColor3f(color.r,color.g,color.b);
        for (int i=0;i < segments;++i)
        {
            NeoVec2 real_v = center + radius * NeoVec2(cosf(theta),sinf(theta));
            glVertex2f(real_v.x,real_v.y);
            theta += inc;
        }
        glEnd();
        DrawLine(center,center + (radius * axis),color);
    }
    void DrawPolygon(const NeoVec2* vertices, int vertexCount, const NeoColor& color)
    {
        glColor3f(color.r, color.g, color.b);
        glBegin(GL_LINE_LOOP);
        for (int i = 0; i < vertexCount; ++i)
        {
            glVertex2f(vertices[i].x, vertices[i].y);
        }
        glEnd();
    }
    void DrawSolidPolygon(const NeoVec2* vertices,  int vertexCount, const NeoColor& color)
    {
        glEnable(GL_BLEND);
        glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
        glColor4f(0.5f * color.r, 0.5f * color.g, 0.5f * color.b, 0.5f);
        glBegin(GL_TRIANGLE_FAN);
        for (int i = 0; i < vertexCount; ++i)
        {
            glVertex2f(vertices[i].x, vertices[i].y);
        }
        glEnd();
        glDisable(GL_BLEND);

        glColor4f(color.r, color.g, color.b, 1.0f);
        glBegin(GL_LINE_LOOP);
        for (int i = 0; i < vertexCount; ++i)
        {
            glVertex2f(vertices[i].x, vertices[i].y);
        }
        glEnd();
    }
    void DrawBox(const NeoVec2 ¢er,const float half_width,const float half_height, const NeoColor& color)
    {
        NeoVec2 list[4] = {
        NeoVec2(center.x-(half_width),center.y-(half_height)),
        NeoVec2(center.x+(half_width),center.y-(half_height)),
        NeoVec2(center.x+(half_width),center.y+(half_height)),
        NeoVec2(center.x-(half_width),center.y+(half_height))
        };
        DrawSolidPolygon(list, 4, color);
    }
};
#endif

2012年7月22日 星期日

GTK+2.0


CB的global compiler settings -> compiler settings -> Other options 填-mms-bitfields

include:
$(CODEBLOCKS)\build\gtk\include\gtk-2.0
$(CODEBLOCKS)\build\gtk\include\glib-2.0
$(CODEBLOCKS)\build\gtk\include\cairo
$(CODEBLOCKS)\build\gtk\include\pango-1.0
$(CODEBLOCKS)\build\gtk\include\atk-1.0

link目錄
$(CODEBLOCKS)\build\gtk\lib

link libraries加入
gdk-win32-2.0
gtk-win32-2.0
atk-1.0
gdk_pixbuf-2.0
pangowin32-1.0
gdi32
pangocairo-1.0
pango-1.0
cairo
gobject-2.0
gmodule-2.0
glib-2.0
intl

main.cpp
#include <gtk/gtk.h>
//#include <stdio.h>
#include <stdlib.h>

static GdkPixmap *pixmap = NULL;
/* 創建一個適當大小的後端位圖 */
static gboolean configure_event( GtkWidget         *widget, GdkEventConfigure *event )
{
  if (pixmap) g_object_unref (pixmap);
  pixmap = gdk_pixmap_new (widget->window, widget->allocation.width, widget->allocation.height, -1);
  gdk_draw_rectangle (pixmap, widget->style->white_gc, TRUE, 0, 0, widget->allocation.width, widget->allocation.height);
  return TRUE;
}
/*  從後端位圖重新繪製螢幕 */
static gboolean expose_event(GtkWidget *widget,GdkEventExpose *event )
{
  gdk_draw_drawable (widget->window, widget->style->fg_gc[GTK_WIDGET_STATE (widget)],pixmap,event->area.x, event->area.y,event->area.x, event->area.y,event->area.width, event->area.height);
  return FALSE;
}
/* 在螢幕上繪製一個矩形 */
static void draw_brush( GtkWidget *widget, gdouble    x,gdouble    y)
{
  GdkRectangle update_rect;
  update_rect.x = x - 5;
  update_rect.y = y - 5;
  update_rect.width = 10;
  update_rect.height = 10;
  gdk_draw_rectangle (pixmap,widget->style->black_gc,TRUE,update_rect.x, update_rect.y,update_rect.width, update_rect.height);
  gtk_widget_queue_draw_area (widget, update_rect.x, update_rect.y, update_rect.width, update_rect.height);
}

static gboolean button_press_event(GtkWidget *widget, GdkEventButton *event )
{
  if (event->button == 1 && pixmap != NULL)
    draw_brush(widget, event->x, event->y);
  return TRUE;
}

static gboolean motion_notify_event( GtkWidget *widget, GdkEventMotion *event )
{
  int x, y;
  GdkModifierType state;
  if (event->is_hint)
    gdk_window_get_pointer (event->window, &x, &y, &state);
  else
    {
      x = event->x;
      y = event->y;
      state =(GdkModifierType) event->state;
    }
  if (state & GDK_BUTTON1_MASK && pixmap != NULL)
    draw_brush (widget, x, y);
  return TRUE;
}

gint processDelete_event(GtkWidget *widget, GdkEvent  *event, gpointer   data)
{
g_print ("delete event occurred\n");
return FALSE;
}
static void processButton( GtkWidget *widget, gpointer data)
{
    g_print ("Hello again - %s was pressed\n", (gchar *) data);
    if (!g_strcmp0((gchar *)data ,"button 2"))
    {
        system("dir");
    }
}

void precessDestroy(GtkWidget *widget, gpointer data )
{
   gtk_main_quit();
}
int main(int argc, char* argv[])
{
    GtkWidget* window;
    gtk_init(&argc, &argv);
    window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    gtk_container_set_border_width(GTK_CONTAINER (window), 100);
    gtk_window_set_position (GTK_WINDOW(window), GTK_WIN_POS_CENTER);
    g_signal_connect(window, "delete_event", G_CALLBACK(processDelete_event), NULL);
    g_signal_connect(window, "destroy", G_CALLBACK(precessDestroy), NULL);
    gtk_window_set_title(GTK_WINDOW(window), "哈囉!GTK+!");
   //------------------------------------------------------
    GtkWidget *vbox = gtk_vbox_new(FALSE, 20);
    gtk_container_add (GTK_CONTAINER(window), vbox);
    gtk_widget_show (vbox);
    GtkWidget *label = gtk_label_new ("底下是塗鴉牆");
    gtk_box_pack_start (GTK_BOX(vbox), label, FALSE, FALSE, 0);
    gtk_widget_show (label);
    GtkWidget *button = gtk_button_new_with_label("Exit");
    gtk_box_pack_start(GTK_BOX(vbox), button, TRUE, TRUE, 0);
    g_signal_connect_swapped(button, "clicked", G_CALLBACK(gtk_widget_destroy), window);
    gtk_widget_show (button);
    //------------------------------------------------
    GtkWidget *hbox = gtk_hbox_new (TRUE, 30);
    gtk_box_pack_end (GTK_BOX(vbox), hbox, FALSE, FALSE, 0);
    gtk_widget_show (hbox);
    button = gtk_button_new_with_label("Button1");
    gtk_box_pack_start(GTK_BOX(hbox), button, TRUE, TRUE, 0);
    g_signal_connect(button, "clicked",G_CALLBACK (processButton), (gpointer)"button 1");
    gtk_widget_show (button);
    button = gtk_button_new_with_label("Button2-Do DIR");
    gtk_box_pack_end(GTK_BOX(hbox), button, TRUE, TRUE, 0);
    g_signal_connect(button, "clicked",G_CALLBACK (processButton), (gpointer)"button 2");
    gtk_widget_show (button);
    //-------------------------------------------------
    GtkWidget *drawing_area = gtk_drawing_area_new ();
    gtk_widget_set_size_request (GTK_WIDGET(drawing_area), 200, 200);
    gtk_box_pack_start (GTK_BOX(vbox), drawing_area, TRUE, TRUE, 0);
    g_signal_connect (drawing_area, "expose_event",G_CALLBACK(expose_event), NULL);
    g_signal_connect (drawing_area,"configure_event",G_CALLBACK (configure_event), NULL);
/* 事件信號 */
    g_signal_connect (drawing_area, "motion_notify_event",G_CALLBACK(motion_notify_event), NULL);
    g_signal_connect (drawing_area, "button_press_event",G_CALLBACK (button_press_event), NULL);
    gtk_widget_set_events (drawing_area, GDK_EXPOSURE_MASK| GDK_LEAVE_NOTIFY_MASK| GDK_BUTTON_PRESS_MASK| GDK_POINTER_MOTION_MASK| GDK_POINTER_MOTION_HINT_MASK);
    gtk_widget_show (drawing_area);

    gtk_widget_show(window);
    gtk_main();
    return 0;
}

GLUI


CB的global compiler settings -> compiler settings -> Other options 填-fexceptions
#defines填FREEGLUT_STATIC

link libraries加入libFreeGLUT.a libGLUI.a GlU32(GlU32.Lib) Gdi32(Gdi32.Lib) OpenGL32(OpenGL32.Lib) User32(User32.Lib) WinMM(WinMM.Lib)

main.cpp
//#define GLUT_DISABLE_ATEXIT_HACK //出ATEXIT_HACK錯要加
#include "iostream"
#include "math.h"
#include "glui/GL/glui.h"
#define PI 3.141592653
const float deg2Rad = PI / 180.;
const float rad2Deg = 180. / PI;

using namespace std;
//------------------------------------------------------------------------
struct neoColor
{
    float r, g, b;
 neoColor() {}
 neoColor(float r, float g, float b) : r(r), g(g), b(b) {}
 void Set(float ri, float gi, float bi) { r = ri; g = gi; b = bi; }
};
struct neoVec2
{
 float x, y;
 /// Default constructor does nothing (for performance).
 neoVec2() {}
 /// Construct using coordinates.
 neoVec2(float x, float y) : x(x), y(y) {}
 /// Set this vector to all zeros.
 void SetZero() { x = 0.0f; y = 0.0f; }
 /// Set this vector to some specified coordinates.
 void Set(float x_, float y_) { x = x_; y = y_; }
 /// Negate this vector.
 neoVec2 operator -() const { neoVec2 v; v.Set(-x, -y); return v; }
 /// Read from and indexed element.
 float operator () (int i) const
 {
  return (&x)[i];
 }

 /// Write to an indexed element.
 float& operator () (int i)
 {
  return (&x)[i];
 }
 /// Add a vector to this vector.
 void operator += (const neoVec2& v)
 {
  x += v.x; y += v.y;
 }
 /// Subtract a vector from this vector.
 void operator -= (const neoVec2& v)
 {
  x -= v.x; y -= v.y;
 }
 /// Multiply this vector by a scalar.
 void operator *= (float a)
 {
  x *= a; y *= a;
 }
 /*
 neoVec2 operator * (float a)
 {
  return neoVec2(x *= a, y *= a);
 }
 */
 /// Get the length of this vector (the norm).
 float Length() const
 {
  return sqrt(x * x + y * y);
 }
 /// Get the length squared. For performance, use this instead of
 /// b2Vec2::Length (if possible).
 float LengthSquared() const
 {
  return x * x + y * y;
 }
 /// Convert this vector into a unit vector. Returns the length.
 float Normalize()
 {
  float length = Length();
  float invLength = 1.0f / length;
  x *= invLength;
  y *= invLength;
  return length;
 }
 /// Get the skew vector such that dot(skew_vec, other) == cross(vec, other)
 neoVec2 Skew() const
 {
  return neoVec2(-y, x);
 }
};
    inline neoVec2 operator + (const neoVec2& a, const neoVec2& b)
    {
        return neoVec2(a.x + b.x, a.y + b.y);
    }
    inline neoVec2 operator - (const neoVec2& a, const neoVec2& b)
    {
        return neoVec2(a.x - b.x, a.y - b.y);
    }
    inline neoVec2 operator * (float s, const neoVec2& a)
    {
        return neoVec2(s * a.x, s * a.y);
    }
    inline bool operator == (const neoVec2& a, const neoVec2& b)
    {
        return a.x == b.x && a.y == b.y;
    }




struct neoVec3
{
    float x, y, z;
 /// Default constructor does nothing (for performance).
 neoVec3() {}
 /// Construct using coordinates.
 neoVec3(float x, float y, float z) : x(x), y(y), z(z) {}

 /// Set this vector to all zeros.
 void SetZero() { x = 0.0f; y = 0.0f; z = 0.0f; }

 /// Set this vector to some specified coordinates.
 void Set(float x_, float y_, float z_) { x = x_; y = y_; z = z_; }

 /// Negate this vector.
 neoVec3 operator -() const {neoVec3 v; v.Set(-x, -y, -z); return v; }

 /// Add a vector to this vector.
 void operator += (const neoVec3& v)
 {
  x += v.x; y += v.y; z += v.z;
 }

 /// Subtract a vector from this vector.
 void operator -= (const neoVec3& v)
 {
  x -= v.x; y -= v.y; z -= v.z;
 }

 /// Multiply this vector by a scalar.
 void operator *= (float s)
 {
  x *= s; y *= s; z *= s;
 }
};
//--------------------------------------------------------------------------------
namespace
{
int mainWindow;
GLint winWidth = 640;
GLint winHeight = 640;
GLUI *glui;
int listboxindx = 0;
int spinnerintegervar = 0;
int checkbox = false; //1=>checked 0=>cancle
float spinnerfloatvar;
neoVec2 mp,pre_mp;
int angToY=0, angToX=0;
bool isMouseRightPressed = false;
bool isMouseLeftPressed = false;

}
//-----------------------------------------------------------------------------
void Keyboard(unsigned char key, int x, int y)
{
switch (key)
 {
 case 27:
     exit(0);
  break;
    default:
        break;
 }
}
void KeyboardSpecial(int key, int x, int y)
{
    switch (key)
 {
 case GLUT_ACTIVE_SHIFT:
        break;
 case GLUT_KEY_LEFT:
        cout << checkbox << "," << listboxindx << endl;
  break;
 case GLUT_KEY_RIGHT:
  break;
 case GLUT_KEY_DOWN:
  break;
 case GLUT_KEY_UP:
  break;
 case GLUT_KEY_HOME:
  break;
 }
}
void Resize(int newWidth, int newHeight)
{
   glViewport(0, 0,(GLsizei) newWidth,(GLsizei) newHeight);
   winWidth  = newWidth;
   winHeight = newHeight;
   glClear(GL_COLOR_BUFFER_BIT);
}
void Mouse(int button, int state, int x, int y)
{
 // Use the mouse to move things around.
 if (button == GLUT_LEFT_BUTTON)
 {
  int specialKey  = glutGetModifiers();
  if (state == GLUT_DOWN)
  {
   if (specialKey  == GLUT_ACTIVE_SHIFT)
   {
                 cout << "GLUT_LEFT_BUTTON click with SHIFT" << endl;
   }
   else
   {
                 cout << "GLUT_LEFT_BUTTON click" << endl;
   }
  }

  if (state == GLUT_UP)
  {
                cout << "GLUT_LEFT_BUTTON release" << endl;
  }
 }
 else if (button == GLUT_RIGHT_BUTTON)
 {
  if (state == GLUT_DOWN)
  {
      isMouseRightPressed = true;
            cout << "GLUT_RIGHT_BUTTON click" << endl;
  }

  if (state == GLUT_UP)
  {
      isMouseRightPressed = false;
            cout << "GLUT_RIGHT_BUTTON release" << endl;
  }
 }
}
void MouseWheel(int wheel, int direction, int x, int y)
{
 if (direction > 0)
 {
   cout << "wheel in" << endl;
 }
 else
 {
   cout << "wheel out" << endl;
 }
}
void MouseMotion(int x, int y)
{
    if(isMouseRightPressed)
    {
        int distanceX = x - pre_mp.x;
        int distanceY = y - pre_mp.y;
        pre_mp.Set(x,y);
        angToY += distanceX;
        angToX += distanceY;
        glutPostRedisplay(); //要求重畫視窗
    }
    cout << "Mouse clicked and x=" << mp.x << ",y=" << mp.y << endl;
}
//glutPassiveMotionFunc(int x,int y);
//glutEntryFunc(processMouseEntryWindow);
void Exit(int code)
{
#ifndef __APPLE__
 glutLeaveMainLoop();
#endif
 exit(code);
}
void Timer(int)
{
    cout << "time up!" << endl;
 glutSetWindow(mainWindow);
    glutPostRedisplay(); //要求重畫視窗
 glutTimerFunc(16, Timer, 0); //Do Repeat
}
void DrawPoint(const neoVec2& p, float size, const neoColor& color)
{
    glPointSize(size);
    glBegin(GL_POINTS);
 glColor3f(color.r, color.g, color.b);
 glVertex2f(p.x, p.y);
    glEnd();
 glPointSize(1.0f);
}
void DrawCircle(const neoVec2& center, float radius, const neoColor& color)
{
 const float k_segments = 16.0f;
 const float k_increment = 2.0f * PI / k_segments;
 float theta = 0.0f;
 glColor3f(color.r, color.g, color.b);
 glBegin(GL_LINE_LOOP);
 for (int i = 0; i < k_segments; ++i)
 {
     neoVec2 v = center +  radius * neoVec2(cosf(theta), sinf(theta)) ;
  glVertex2f(v.x, v.y);
  theta += k_increment;
 }
 glEnd();
}

void DrawSegment(const neoVec2& p1, const neoVec2& p2, const neoColor& color,  bool realline)
{
     if (!realline)
    {
        glLineStipple (1, 0x1C47);
        glEnable(GL_LINE_STIPPLE);
    }
    glBegin(GL_LINES);
 glColor3f(color.r, color.g, color.b);
 glVertex2f(p1.x, p1.y);
 glVertex2f(p2.x, p2.y);
 glEnd();
 if (!realline) glDisable(GL_LINE_STIPPLE);
}
void DrawPolygon(const neoVec2* vertices, int vertexCount, const neoColor& color)
{
 glColor3f(color.r, color.g, color.b);
 glBegin(GL_LINE_LOOP);
 for (int i = 0; i < vertexCount; ++i)
 {
  glVertex2f(vertices[i].x, vertices[i].y);
 }
 glEnd();
}
void DrawString(int x, int y, const char *string, ...)
{
 char buffer[128];

 va_list arg;
 va_start(arg, string);
 vsprintf(buffer, string, arg);
 va_end(arg);

 glMatrixMode(GL_PROJECTION);
 glPushMatrix();
 glLoadIdentity();
 int w = glutGet(GLUT_WINDOW_WIDTH);
 int h = glutGet(GLUT_WINDOW_HEIGHT);
 gluOrtho2D(0, w, h, 0);
 glMatrixMode(GL_MODELVIEW);
 glPushMatrix();
 glLoadIdentity();

 glColor3f(0.9f, 0.6f, 0.6f);
 glRasterPos2i(x, y);
 int length = (int)strlen(buffer);
 for (int i = 0; i < length; ++i)
 {
  glutBitmapCharacter(GLUT_BITMAP_8_BY_13, buffer[i]);
 }

 glPopMatrix();
 glMatrixMode(GL_PROJECTION);
 glPopMatrix();
 glMatrixMode(GL_MODELVIEW);
}

void display()
{
    //glEnable(GL_DEPTH_TEST);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glPushMatrix();
    glRotatef(angToX, 1.0, 0.0, 0.0);
    glRotatef(angToY, 0.0, 1.0, 0.0);
//---------------------------------------------------------------------
DrawSegment(neoVec2(0,0),neoVec2(0.1,0.1),neoColor(0.5,1,1),false);
DrawPoint(neoVec2(0,0),5,neoColor(1,1,1));
DrawPoint(neoVec2(0.1,0.1),5,neoColor(1,0,1));
DrawCircle(neoVec2(0,0),0.1,neoColor(1,1,1));
neoVec2 list[3] = {neoVec2(0,0), neoVec2(-0.1,0.1), neoVec2(-0.1,0)};
DrawPolygon(list,3,neoColor(0.5,1,1));
DrawString(100,200,"abc");
//---------------------------------------------------------------------
    glPopMatrix();
    glutSwapBuffers();
    glFlush();
}
int main(int argc, char** argv)
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE);
 glutInitWindowSize(winWidth, winHeight);
    glutInitWindowPosition(200, 50);
    gluOrtho2D(0, winWidth,winHeight, 0);
    mainWindow = glutCreateWindow( "Neo Glui" );
    glClearColor(0.0, 0.0, 0.0, 0.0); //指定填視窗背景的顏色
    glViewport(0, 0, (GLsizei) winWidth, (GLsizei) winHeight);
    glutDisplayFunc(display);
    GLUI_Master.set_glutReshapeFunc(Resize);
 GLUI_Master.set_glutKeyboardFunc(Keyboard);
 GLUI_Master.set_glutSpecialFunc(KeyboardSpecial);
    GLUI_Master.set_glutMouseFunc(Mouse);
    glutMouseWheelFunc(MouseWheel);
    glutMotionFunc(MouseMotion);
    //------------------------------------------------
    glui = GLUI_Master.create_glui_subwindow(mainWindow, GLUI_SUBWINDOW_RIGHT );
 glui->add_statictext("Text");
 GLUI_Listbox* selectbox = glui->add_listbox("", &listboxindx);
 selectbox->add_item(0, "One");
 selectbox->add_item(1, "Two");
 selectbox->add_item(2, "Three");

 GLUI_Spinner* spinnerinteger = glui->add_spinner("spin1", GLUI_SPINNER_INT, &spinnerintegervar);
 spinnerinteger->set_int_limits(1,10);
    GLUI_Spinner* spinnerfloat = glui->add_spinner("spin2", GLUI_SPINNER_FLOAT, &spinnerfloatvar);
 spinnerfloat->set_float_limits(5.0f, 10.0f);

    glui->add_checkbox("checkbox", &checkbox);
  glui->add_separator();
    GLUI_Panel* panel = glui->add_panel("panel");
    glui->add_checkbox_to_panel(panel,"Panel checkbox",&checkbox);
 glui->add_separator();
 glui->add_button("Exit", 0, (GLUI_Update_CB)Exit);
 glui->set_main_gfx_window( mainWindow );
    glutTimerFunc(16, Timer, 0);

    glutMainLoop();
    cout << "中文!" << endl;
    return 0;

2012年7月21日 星期六

Lua with c++

main.cpp


extern "C"{
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
}
#define err_return(num,fmt,args...) do{printf("[%s:%d]"fmt"\n",__FILE__,__LINE__,##args);return(num);} while(0)
#define err_exit(num,fmt,args...) do{printf("[%s:%d]"fmt"\n",__FILE__,__LINE__,##args);exit(num);} while(0)

using namespace std;
int csum(lua_State* l)
{
    int a = lua_tointeger(l,1) ;
    int b = lua_tointeger(l,2) ;
    lua_pushinteger(l,a+b) ;
    return 1 ;
}
int main()
{
    lua_State* luaState = luaL_newstate() ;        //創建lua運行環境
    if (luaState == NULL) err_return(-1,"luaL_newstat() failed");
    int ret = 0 ;
    ret = luaL_loadfile(luaState,"func.lua") ;      //加載lua腳本文件
    if (ret != 0) err_return(-1,"luaL_loadfile failed") ;
    ret = lua_pcall(luaState,0,0,0) ;
    if (ret != 0) err_return(-1,"lua_pcall failed:%s",lua_tostring(luaState,-1)) ;
    //----------------------------------------------------------------------------------------
    lua_getglobal(luaState,"width");  //-2           //獲取lua中定義的變量
    lua_getglobal(luaState,"height"); //-1
    printf("height:%ld width:%ld\n",lua_tointeger(luaState,-1),lua_tointeger(luaState,-2)) ;
    lua_pop(luaState,1) ; //恢復lua的棧
    //----------------------------------------------------------------------------------------
    int a = 11 ;
    int b = 12 ;
    lua_getglobal(luaState,"sub");               //調用lua中的函數sub
    lua_pushinteger(luaState,a) ;
    lua_pushinteger(luaState,b) ;
    ret = lua_pcall(luaState,2,1,0) ;  //a-b
     if ( ret != 0 ) err_return(-1,"lua_pcall failed:%s",lua_tostring(luaState,-1)) ;
    printf("sum:%d - %d = %ld\n",a,b,lua_tointeger(luaState,-1)) ;
    lua_pop(luaState,1) ;
    //----------------------------------------------------------------------------------------
     const char str1[] = "hello" ;
    const char str2[] = "world" ;
    lua_getglobal(luaState,"mystrcat");          //調用lua中的函數mystrcat
    lua_pushstring(luaState,str1) ;
    lua_pushstring(luaState,str2) ;
    ret = lua_pcall(luaState,2,1,0) ;
    if ( ret != 0 ) err_return(-1,"lua_pcall failed:%s",lua_tostring(luaState,-1)) ;
    printf("mystrcat:%s%s = %s\n",str1,str2,lua_tostring(luaState,-1)) ;
    lua_pop(luaState,1) ;
    //----------------------------------------------------------------------------------------
    lua_pushcfunction(luaState,csum) ;         //註冊在lua中使用的c函數
    lua_setglobal(luaState,"csum") ;           //綁定到lua中的名字csum
    lua_getglobal(luaState,"mysum");           //調用lua中的mysum函數,該函數調用本程序中定義的csum函數實現加法
    lua_pushinteger(luaState,a) ;
    lua_pushinteger(luaState,b) ;
    ret = lua_pcall(luaState,2,1,0) ;
    if ( ret != 0 ) err_return(-1,"lua_pcall failed:%s",lua_tostring(luaState,-1)) ;
    printf("mysum:%d + %d = %ld\n",a,b,lua_tointeger(luaState,-1)) ;
    lua_pop(luaState,1) ;

    lua_close(luaState) ;                     //釋放lua運行環境
    return 0 ;
}

func.lua

--變量定義
width=1 ;
height=2 ;
--lua函數定義,實現減法
function sub(a,b)
    return a-b ;
end
--lua函數定義,實現字符串相加
function mystrcat(a,b)
    return a..b ;
end
--lua函數定義,通過調用c代碼中的csum函數實現加法
function mysum(a,b)
    return csum(a,b) ;
end

2012年7月20日 星期五

NeoOgreApplication

NeoOgreApplicaion.h


#ifndef _NEO_OGRE_APPLICATION_H_
#define _NEO_OGRE_APPLICATION_H_
#include "Ogre\Ogre.h"
#include "OIS\OIS.h"
class NeoFrameListener : public Ogre::FrameListener
{
public:
    NeoFrameListener(): _listener(NULL){}
    NeoFrameListener(Ogre::RenderWindow* win, Ogre::Camera* camera, Ogre::SceneNode* node, Ogre::Entity* ent)
    {
        _camMovementSpeed = 50.0f;
        _walkingSpeed = 10.0f;
        _walkingRotation = 0;
        _cam = camera;
        _node = node;
        _ent = ent;
        OIS::ParamList pl;
        unsigned int windowHandle = 0;
        std::ostringstream windowHandleString;
        win->getCustomAttribute("WINDOW",  &windowHandle);
        windowHandleString << windowHandle;
        pl.insert(std::make_pair("WINDOW",  windowHandleString.str()));
        _im = OIS::InputManager::createInputSystem(pl);
        _key = static_cast(_im->createInputObject(OIS::OISKeyboard,false ));
        _mouse = static_cast(_im->createInputObject( OIS::OISMouse, false ));

        _aniState = _ent->getAnimationState("RunBase");
        _aniState->setLoop(false);
        _aniStateTop = _ent->getAnimationState("RunTop");
        _aniStateTop->setLoop(false);
    }
    ~NeoFrameListener()
    {
        delete _listener;
        _im->destroyInputObject(_key);
        _im->destroyInputObject(_mouse);
        OIS::InputManager::destroyInputSystem(_im);
    }
    bool frameStarted(const Ogre::FrameEvent& evt)
    {
        bool walked = false;
        Ogre::Vector3 camTranslate(0,0,0);
        Ogre::Vector3 nodeTranslate(0,0,0);
        _key->capture();
        if(_key->isKeyDown(OIS::KC_ESCAPE))
        {
            return false;
        }
        if(_key->isKeyDown(OIS::KC_1) && !_downKey1)
        {
            _downKey1 = true;
            _comp1 = !_comp1;
            Ogre::CompositorManager::getSingleton().setCompositorEnabled(_cam->getViewport(),"Compositor1",_comp1);
            return true;
        }
         if(!_key->isKeyDown(OIS::KC_1))
        {
            _downKey1 = false;
        }
         if(_key->isKeyDown(OIS::KC_SPACE))
        {

          _isActionKeyPress = true;
          _aniStateTop = _ent->getAnimationState("SliceHorizontal");
          _aniStateTop->setLoop(false);
          _aniStateTop->setTimePosition(0.0f);

        }
        if(_key->isKeyDown(OIS::KC_UP))
        {
            nodeTranslate += Ogre::Vector3(0,0,-1);
            _walkingRotation = 3.14f;
            walked = true;
        }
        if(_key->isKeyDown(OIS::KC_DOWN))
        {
            nodeTranslate += Ogre::Vector3(0,0,1);
            _walkingRotation = 0.0f;
            walked = true;
        }
        if(_key->isKeyDown(OIS::KC_LEFT))
        {
            nodeTranslate += Ogre::Vector3(-1,0,0);
            _walkingRotation = -1.57f;
            walked = true;
        }
        if(_key->isKeyDown(OIS::KC_RIGHT))
        {
            nodeTranslate += Ogre::Vector3(1,0,0);
            _walkingRotation = 1.57f;
            walked = true;
        }
        if(_key->isKeyDown(OIS::KC_W))
        {
            camTranslate += Ogre::Vector3(0,0,-1);
        }
        if(_key->isKeyDown(OIS::KC_S))
        {
            camTranslate += Ogre::Vector3(0,0,1);
        }
        if(_key->isKeyDown(OIS::KC_A))
        {
            camTranslate += Ogre::Vector3(-1,0,0);
        }
        if(_key->isKeyDown(OIS::KC_D))
        {
            camTranslate += Ogre::Vector3(1,0,0);
        }

        if(walked){
             _aniStateTop->setEnabled(true);
             _aniState->setEnabled(true);
             if(_aniState->hasEnded())
            {
                _aniState->setTimePosition(0.0f);
            }
            if(_aniStateTop->hasEnded())
            {
                _aniStateTop->setTimePosition(0.0f);
            }
             _aniState->addTime(evt.timeSinceLastFrame*1);
             _aniStateTop->addTime(evt.timeSinceLastFrame*1);
        }
        else
        {
            if(_isActionKeyPress)
            {
                _aniStateTop->setEnabled(true);
                _aniStateTop->addTime(evt.timeSinceLastFrame*1);
                if(_aniStateTop->hasEnded())
                {
                    _isActionKeyPress = false;
                    _aniStateTop = _ent->getAnimationState("RunTop");
                    _aniStateTop->setLoop(false);
                    _aniStateTop->setTimePosition(0.0f);
                }
            }
            else
            {
                if(!_aniStateTop->hasEnded())
                {
                    _aniStateTop->addTime(evt.timeSinceLastFrame*1);
                }
                 if(!_aniState->hasEnded())
                {
                    _aniState->addTime(evt.timeSinceLastFrame*1);
                }
            }
        }
        _node->translate(nodeTranslate * evt.timeSinceLastFrame * _walkingSpeed);
        _node->resetOrientation();
        _node->yaw(Ogre::Radian(_walkingRotation));

        _cam->moveRelative(camTranslate*evt.timeSinceLastFrame * _camMovementSpeed);
        _mouse->capture();
        float mouseRotX = _mouse->getMouseState().X.rel * evt.timeSinceLastFrame* -1;
        float mouseRotY = _mouse->getMouseState().Y.rel * evt.timeSinceLastFrame * -1;
        _cam->yaw(Ogre::Radian(mouseRotX));
        _cam->pitch(Ogre::Radian(mouseRotY));
        return true;
    }
    bool frameEnded(const Ogre::FrameEvent& evt)
    {
        return true;
    }
    bool frameRenderingQueued(const Ogre::FrameEvent& evt)
    {
        return true;
    }
    float _camMovementSpeed;
    float _walkingSpeed;
    float _walkingRotation;
    Ogre::AnimationState* _aniState;
    Ogre::AnimationState* _aniStateTop;
    NeoFrameListener* _listener;
    OIS::InputManager* _im;
    OIS::Keyboard* _key;
    OIS::Mouse* _mouse;
    Ogre::Camera* _cam;
    Ogre::SceneNode* _node;
    Ogre::Entity* _ent;
    bool _downKey1;
    bool _comp1;
    bool _isActionKeyPress;

};

class NeoOgreApplication
{
public:
     NeoOgreApplication(): mSceneMgr(NULL),mRoot(NULL),mCamera(NULL),mWindow(NULL){}
    ~NeoOgreApplication(){if (mRoot) delete mRoot;}
    void runFirstFrame()
    {
        if(!initinalize())
        {
            exit(-1);
        }
        createCamera();
        loadResources();
        createScene();
        createCompositor();
        createFrameListener();
        runOneFrame();
    }
    void runOneFrame()
    {
          Ogre::WindowEventUtilities::messagePump();
          _keepRunning = mRoot->renderOneFrame();
    }
    bool keepRunning()
    {
        return _keepRunning;
    }
    void run()
    {
        if(!initinalize())
        {
            exit(-1);
        }
        createCamera();
        createCompositor();
        loadResources();
        createScene();
        createFrameListener();
        mRoot->startRendering();
    }
protected:
    void loadGroupResources(void)
    {
        Ogre::ConfigFile cf;
        cf.load("resources.cfg");
        Ogre::ConfigFile::SectionIterator sectionIter = cf.getSectionIterator();
        Ogre::String sectionName, typeName,  dataName;
        while (sectionIter.hasMoreElements())
        {
            sectionName = sectionIter.peekNextKey();
            Ogre::ConfigFile::SettingsMultiMap *settings = sectionIter.getNext();
            Ogre::ConfigFile::SettingsMultiMap::iterator i;
            for (i = settings->begin(); i != settings->end(); ++i)
            {
                typeName = i->first;
                dataName = i->second;
                Ogre::ResourceGroupManager::getSingleton().addResourceLocation(dataName,typeName, sectionName);
            }
        }
        Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
    }
    virtual void loadResources(void)
    {
        //Ogre::ResourceGroupManager::getSingleton().addResourceLocation("./Media/packs/Sinbad.zip","Zip");
        //Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
        loadGroupResources();
    }
    bool initinalize(void)
    {
        //Load Pluging
        /*
        mRoot = new Ogre::Root("plugins.cfg","ogre.cfg","Ogre.log");
        if(!mRoot->showConfigDialog())
            return -1;
        */
        mRoot = new Ogre::Root("","");
        //mRoot->loadPlugin( "RenderSystem_Direct3D9" );
        mRoot->loadPlugin("RenderSystem_GL");
        mRoot->loadPlugin("Plugin_ParticleFX");
        mRoot->loadPlugin("Plugin_CgProgramManager");
       // mRoot->loadPlugin("Plugin_OctreeSceneManager");

        const Ogre::RenderSystemList &render_sys_list = mRoot->getAvailableRenderers();//for 1.7
        Ogre::RenderSystemList::const_iterator it_render_sys( render_sys_list.begin() );//for 1.7
        while ( it_render_sys != render_sys_list.end() )                                //for 1.7
        {
            Ogre::RenderSystem* render_sys = *(it_render_sys++);
            //if(render_sys->getName().find("Direct3D9") != Ogre::String::npos)
            if(render_sys->getName().find("OpenGL") != Ogre::String::npos)
            {
                mRoot->setRenderSystem(render_sys);
                break;
            }
        }
        if(mRoot == NULL)
        {
            delete mRoot;
            return false;
        }

        Ogre::NameValuePairList opts;
        opts["resolution"] = "1024x768";
        opts["Full Screen"] = "Yes";
        opts["vsync"] = "false";
        opts["Colour Depth"] = "2";

        mRoot->initialise(false);//false表示不自動產生視窗,手動產生
        mWindow = mRoot->createRenderWindow("Neo Ogre", 800, 600, false,&opts); //false表非全螢幕模式
        Ogre::RenderSystem* rs = mRoot->getRenderSystemByName("Neo Ogre");

        //mWindow = mRoot->initialise(true,"Neo Ogre");
        mSceneMgr = mRoot->createSceneManager(Ogre::ST_GENERIC);
        //設定camera和vierport----------------------------------------------------------------------
        mCamera = mSceneMgr->createCamera("MyCamera");
        return true;
    }
    virtual void createCompositor()
    {
        Ogre::CompositorManager::getSingleton().addCompositor(mCamera->getViewport(),"Compositor1");
    }
     virtual void createCamera()
    {
        mCamera->setPosition(Ogre::Vector3(0,0,50));
        mCamera->lookAt(Ogre::Vector3(0,0,0));
        mCamera->setNearClipDistance(5);
        mCamera->setFarClipDistance(10000);
        mCamera->setFOVy(Ogre::Degree(45));
        Ogre::Viewport* vp = mWindow->addViewport(mCamera);
        vp->setBackgroundColour(Ogre::ColourValue(0,0,0));
        mCamera->setAspectRatio(Ogre::Real(vp->getActualWidth())/Ogre::Real(vp->getActualHeight()));
    }
     virtual void createScene()
    {
       mEnt = mSceneMgr->createEntity("NeoEntity","Sinbad.mesh");
       mNode = mSceneMgr->getRootSceneNode()->createChildSceneNode("NeoNode");
       mNode->attachObject(mEnt);
    }
    virtual void createFrameListener()
    {
        NeoFrameListener* _listener = new NeoFrameListener(mWindow,mCamera,mNode, mEnt);
        mRoot->addFrameListener(_listener);
    }
protected:
    bool _keepRunning;
    Ogre::Root* mRoot;
    Ogre::SceneManager* mSceneMgr;
    Ogre::Camera* mCamera;
    Ogre::RenderWindow* mWindow;
    Ogre::SceneNode* mNode;
    Ogre::Entity* mEnt;
};
#endif

main.cpp
#include "NeoOgreApplication.h"
class MyOgre : public NeoOgreApplication
{
    void loadResources()
    {
        Ogre::ResourceGroupManager::getSingleton().createResourceGroup( "test" );
        Ogre::ResourceGroupManager::getSingleton().addResourceLocation("./neoResource/packs/Sinbad.zip","Zip","test");
        Ogre::ResourceGroupManager::getSingleton().addResourceLocation("./neoResource/resource","FileSystem","test");
        Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
    }

    void createScene()
    {
       mEnt = mSceneMgr->createEntity("NeoEntity","Sinbad.mesh");
       mNode = mSceneMgr->getRootSceneNode()->createChildSceneNode("NeoNode");
       mNode->attachObject(mEnt);
       Ogre::Entity* sword1 = mSceneMgr->createEntity("Sword1","Sword.mesh");
       Ogre::Entity* sword2 = mSceneMgr->createEntity("Sword2","Sword.mesh");
       mEnt->attachObjectToBone("Handle.L",sword1);
       mEnt->attachObjectToBone("Handle.R", sword2);
       Ogre::Plane plane(Ogre::Vector3::UNIT_Y,-5);
       Ogre::MeshManager::getSingleton().createPlane("plane",Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,plane,1500,1500,20,20,true,1,5,5,Ogre::Vector3::UNIT_Z);
       Ogre::Entity* ground = mSceneMgr->createEntity("LightPlaneEntity", "plane");
       mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(ground);
       ground->setMaterialName("Examples/BeachStones");
       Ogre::Light* light = mSceneMgr->createLight("Light1");
       light->setType(Ogre::Light::LT_DIRECTIONAL);
       light->setDirection(Ogre::Vector3(1,-1,0));
       mSceneMgr->setShadowTechnique(Ogre::SHADOWTYPE_STENCIL_ADDITIVE);
    }

};
int main (void)
{
MyOgre a;
//a.run();
a.runFirstFrame();
while(a.keepRunning())
{
    a.runOneFrame();
}
return 0;
}