Engineering Navi - ARToolkit 프로그래밍 1 - Camera Calibration.

 
** 이 글은 http://kougaku-navi.net/ARToolKit.html 의 기초 프로그래밍 부분을 해석한 것 입니다.

** 저처럼 ARToolKit에 막 입문하신 분들께 조금이나마 도움을 줄 수 있을 것 같아, 해석하게 되었습니다

** 글을 쓰신 Sunao Hashimoto 씨의 동의를 얻지 않고 해석한 점 죄송하게 생각합니다.

    (スナオ・ハシモト様、勝手に翻訳することになって本当に申し訳ございません。もし、問題になれば、
   消しますのでsega_kr@hotmail.comにご連絡してください。ありがとうございます。) 

** 처음 설치부분은 생략합니다. 예제 파일이 이상없이 돌아간 이후에 글을 참고해 주시기 바랍니다.
     (ARtoolkit이 들어있는 폴더는  Program File 폴더 내에 세팅하였음.)

 ** 이 글을 쓴 분은 로지텍 퀵 캠 For Notebook Pro를 사용했습니다.

 ** 자연스러운 표현을 위해, 의역하였습니다.




1. Camera Calibration을 해봅시다.


 1-1. Camera Calibration 라는 것은 무엇인가?
   사용하는 카메라에 따라, 초점 거리와 렌즈의 일그러짐 등 특성이 달라집니다. 이런 카메라의 특성값
(카메라 파라미터)는 영상으로 부터 마커의 3차원 위치상태를 구하는 계산과 3D 오브젝트를 정확하게
처리하는데 영향을 미치게 됩니다. 보다 정확한 계측을 하기 위해서는 사전에 카메라 파라미터를 구하는
작업
, 즉 Camera Calibration이 필요하게 됩니다.

 공식사이트(영문)에는 2가지 방법의 Calibration방법에 관하여 해설이 있습니다.
  ARToolKit Documentation - Camera Calibration 

  - 1. 1 Step Calibration(간단함)
   영상을 중첩시켜 표시한 다음 충분한 정확도를 얻어낼 수 있는 방법.
 
  - 2. 2 Step Calibration(복잡함)
    보다 높은 정밀도를 가진 결과를 얻어낼 수 있는 방법.(3차원 계측 방면)

여기에서는 간단한 방법인 '1 Step Calibration'에 대해 해설하겠습니다.

1-2. Calibration용 패턴을 인쇄한다.
   일반적인 Camera Calibration으로는 격자 모양과 등간격 점을 인쇄한 종이(Calibration 보드)를
사용합니다. 
이것을 카메라에 촬영하고, 영상 안에 격자모양의 점의 위치를 기록한 뒤, 약간의 계산을
실행함으로 카메라 
파라미터를 산출하는 것이 가능합니다. ARToolKit에는 그 Calibration용 패턴과
계산 툴이 들어가 있습니다.
  Calibration에서 사용하는 패턴은 아래의 PDF 파일 입니다.

 -> C:\Program Files\ARToolKit\patterns\calib_dist.pdf
     
  이 PDF 파일을 인쇄해 주세요.(프린트가 없다면, PC의 모니터에 패턴을 표시하는 것도 좋은 방법입니다.)

            Calibration용 패턴(calib_dist.pdf)

 인쇄한 점과 점사이의 길이(점의 중심에서의 길이)를 자로 측정해 주십시요. 이 때, 미리미터 단위로
측정하는
것에 주의하시기 바랍니다. A4의 종이에 인쇄를 한 경우에는 38mm~40mm정도가 될 것 입니다.
 이 수치는
다음에 사용하게 됩니다.

1-3. Calibration의 사용 방법.
  이제부터 Calibration을 사용해 봅시다. 1 Step Calibration에서는 아래의 프로그램을 사용했습니다.

 -> C:\Program Files\ARToolKit\bin\calib_camera2.exe
 
 1-3-1. calib_camera2.exe 파일을 더블 클릭하면, 아래와 같이 표시됩니다.

-> Input the distance between each marker dot, in millimeters:
  
 점과 점 사이의 거리를 미리미터 단위로 입력해 달라는 말이기 때문에, 여기에서는 방금전 자로 측정했던
길이를 입력하고 엔터를 눌러 주십시요. 그렇게 하면, 비디오 캡쳐 설정 다이얼로그가  표시되기 때문에
그대로 OK를 눌러 주세요.(※해상도를 변경하고 있은 경우는 '출력 사이즈'의 항목을 변경하세요.)

 값을 입력하면 이렇게 표시되어, 영상 윈도우가 표시됩니다.
Input the distance between each marker dot, in millimeters: 38
Camera image size (x,y) = (320,240)

-----------
Press mouse button to grab first image,
or press right mouse button or [esc] to quit.
argl error: Your OpenGL implementation and/or hardware's texturing capabilities
are insufficient to support rectangle textures.


  1-3-2. 다음은 4 X 6 개의 모든 점이 화면 안에 들어가도록 촬영를 하고, 그 상태로 화면에 1회 좌클릭
합시다. 이 때, Calibration용 패턴은 꼭 평평한 장소에 두시기 바랍니다.

  1-3-3 클릭하면, 화면이 정지하고 특징점 기록 모드에 들어갑니다.

-----------
Press mouse button and drag mouse to rubber-bound features (6 x 4),
or press right mouse button or [esc] to cancel rubber-bounding & retry grabbing.

"마우스 버튼을 눌러 드래그하고 6 X 4 개(총 24개)의 특징점을 선택하여 주십시요. 우클릭 또는 ESC키로
작업을 캔슬하고, 영상을 다시 찍을 수 있게 됩니다."
라는 의미의 메세지가 표시됩니다. 마우스의 드래그 조작으로 검은 점 한개 한개의 범위을 선택해 나갑니다.
범위 선택을 하고 있는 영역은 monochrome(흑백)으로 표시됩니다. 드래그하고 마우스 버튼을 떼면,
범위 내에 있는 점의 중심에 빨간 십자선이 표시됩니다. 표시된 24개의 모든 점에 이 작업을 합시다.
클릭하는 순서는 정해져 있기 때문에 주의하시기 바랍니다.
하단의 그림에서 청색 문자에 적혀있는 숫자가 클릭하는 순서입니다.  


좌클릭을 하면 화면이 정지합니다.

순서대로 점의 중심을 기록합시다.

  작업 중에는 이렇게 표시됩니다.

 
Marked feature position 1 of 24
Marked feature position 2 of 24
Marked feature position 3 of 24
Marked feature position 4 of 24
Marked feature position 5 of 24

                      .

                      .

                      .


 1-3-4. 모든 점에 대한 작업이 끝나게 되면 아래와 같이 표시됩니다.
"좌클릭으로 특징점을 보존합니다. 우클릭 또는 ESC키로 화면을 다시 찍습니다."
라는 의미이므로, 확실히 점을 찍었다면 한번 더 화면을 좌클릭 합니다.
Marked feature position 24 of 24
-----------
Press mouse button to save feature positions,or press right mouse button or [esc] to discard feature positions & retry grabbing.

 1-3-5. 좌클릭하면, 조금 전에 작업으로 지정한 점의 좌표값이 표시되어 영상의 정지상태가 해제됩니다.
화면에는 "좌클릭으로 다음 영상을 *얻어냅니다.('取り込みます: 거둬 들입니다. 수확합니다'의 의역인데,
뜻이 틀릴지도 모르겠네요.) 우클릭 또는 ESC키로 일그러진(뒤틀린) 상태의 파라미터를 구할 수 있습니다."
라고 나와있지만, Calibration에는 2장 이상의 영상을 필요로 하고 있기 때문에, 여기서 한번 더
1-3-2 ~ 1-3-4의 작업을 반복합니다.
  

-----------
Press mouse button to grab next image,or press right mouse button or [esc] to calculate distortion parameter.

 1-3-6. 두번째 특징점 클릭이 끝나면 화면을 우클릭합니다. 그러면 계산이 실행된 이후, 아래의 메세지와
함께, 점 사이를 빨간색으로 이은 영상이 표시됩니다.
-----------
Checking fit on image 1 of 2.Press mouse button to check fit of next image.
 이 그림과 같이, 대각선과 격자점이 확실하게 교차하고 있는 영상이 표시된다면, OK~.
영상을 좌클릭하면 다음 영상이 표시됩니다.
-----------
Checking fit on image   2 of   2.
Press mouse button to calculate parameter.


 2번째 작업한 영상에서도 대각선과 격자선이 정확히 표시되는 것을 확인할 수 있다면, 영상을 좌클릭합니다.

 1-3-7. 계산이 실행된 이후, 아래의 메세지가 표시된다면 성공입니다.
 "Calibration은 성공했습니다. 파일명을 입력해서 카메라 파라미터를 보존해 주세요"라는 뜻이므로,
 적당한 파일명을(예를 들어, my_camera_para.dat)를 입력하고, 엔터를 누릅니다.
Calibration succeeded. Enter filename to save camera parameter to below.
--------------------------------------
SIZE = 320, 240Distortion factor = 105.000000 81.500000 -30.700000 0.986381750.89434 0.00000 155.00000 0.000000.00000 1999.36684 32.50000 0.000000.00000 0.00000 1.00000 0.00000
--------------------------------------
Filename:

 1-3-8. 카메라 파라미터 파일은 C:\Program Files\ARToolKit\bin 안에 생성됩니다.
 이것으로 Calibration은 종료입니다.

 샘플 프로그램을 이용하고 있는 디폴트 카메라 파라미터 파일은 아래의 폴더의 파일입니다.

 C:\Program Files\ARToolKit\bin\Data\camera_para.dat

 이 파일과 현재 자신이 만든 파일을 옮겨놓으면, 현재 쓰고 있는 개인 카메라로 높은 정밀도를 가진
오버레이 표시가 가능합니다.
===========================================================

 

동기식, 비동기식의 차이점.

*동기식 synchronous (transmission) 

동기식 전송은 한 문자 단위가 아니라 미리 정해진 수 만큼의 문자열을 한 묶음으로 만들어서 일시에 전송하는 방법이다. 이 방법에서는 데이터와는 별도로 송신측과 수신측이 하나의 기준 클록으로 동기신호를 맞추어 동작한다. 수신측에서는 클록에 의해 비트를 구별하게 되므로, 동기식 전송을 위해서는 데이터와 클록을 위한 2회선이 필요하다. 송신측에서 2진 데이터들을 정상적인 속도로 내 보내면, 수신측에서는 클록의 한 사이클 간격으로 데이터를 인식하는 것이다. 

동기식 전송은 비동기식에 비해 전송효율이 높다는 것이 장점이지만 수신측에서 비트 계산을 해야하며, 문자를 조립하는 별도의 기억장치가 필요하므로 가격이 다소 높은 것이 단점이다

*비동기식 asynchronous (transmission) 

에디터 내에 동기신호를 포함시켜 데이터를 전송한다. 송신측의 송신 클록에 관계없이 수신신호 클록으로 타임 슬롯의 간격을 식별하여 한번에 한 문자씩 송수신한다. 

이때 문자는 7~8 비트로 구성되며, 문자의 앞에 시작비트 (start bit)를, 끝에는 정지비트 (stop bit)를 첨가해서 보내는 방법이다. 

비동기식 전송은 시작비트와 정지비트 사이의 간격이 가변적이므로 불규칙적인 전송에 적합하다. 또한 필요한 접속장치와 기기들이 간단하므로 동기식전송 장비보다 값이 싸다는 장점이 있다.

<출처 : http://kin.naver.com>

[퍼옴] Hash란?

DRM 관련 라이브러리를 포팅하다 보면 Hash란 용어가 자주 나오는데 대략의 의미는 알면서도 정리가 잘 안되더라구요 그래서 찾아봤습니다. 그리고 스크랩합니다.

 

일반적인 용어로는 다음 의미를 갖더군요

 

1. 데이터를 저장하고 찾기를 하는데 사용되는 자료 구조의 한 종류. 찾고자 하는 문자열을 특정한 함수(hash function)로 처리하여 얻은 값으로 데이터의 위치를 찾는 방법. 데이터를 찾는 속도가 데이터의 개수의 영향을 거의 받지 않는 특성을 지니고 있어, 효율적이고 빠르게 데이터의 위치를 찾을 수 있다.

2. 데이터베이스에서 임의의 레코드를 빠르게 찾아가기 위한 직접 파일 구조.

3. 메모리에 블럭 단위로 정보를 저장할 때 블럭의 길이에 맞추기 위해 쓰는 의미가 없는 정보를 나타낸다. 더 넓게는 전기 분야에서 전기 잡음 등 의미없는 것을 가리킨다.

 

 

설명이 충분치 않은 것 같아서 다른 설명을 보면 DRM 관련해서 Hash의 의미가 잘 정리된 것 같습니다.


해싱 알고리즘을 해시 함수라고 부른다. 해싱은 빠른 속도의 데이터 검색 외에도, 전자서명을 암호화하고 복호화하는 데에도 사용된다. 전자서명은 해시 함수를 이용하여 변환된 다음, 해시 값(이를 요약 메시지라고 부른다)과 전자서명이 별도로 전송된다. 수신자는 송신자가 사용한 해시함수와 같은 것을 사용하여, 서명으로부터 요약 메시지를 뽑아내어 그것을 이미 수신한 요약 메시지와 비교한다. 그 비교 결과는 같아야만 전자서명이 유효한 것이다.


해시 함수는 원래의 값이나 키를 색인하는데 사용되며, 그 값이 관련된 데이터가 검색될 때마다 다시 사용된다. 그러나, 해싱은 항상 한 쪽 방향으로만 연산된다. 따라서, 해시된 값을 분석함으로써 해시 함수를 추출해내는 역방향 공학은 필요가 없다. 사실, 이상적인 해시함수는 그러한 분석에 의해 추론할 수 없어야 한다. 또한, 우수한 해시 함수는 서로 다른 두 개의 입력에 대해, 동일한 해시 값을 생산해서는 안된다. 만약 그렇게 되면, 충돌이 생긴다. 충돌 위험성이 매우 적은 해시 함수라야 훌륭한 해시 함수로 평가된다.

다음에 나열한 것들은, 그 동안 사용되어 온 비교적 단순한 해시 함수들이다.

1. 나눗셈-나머지 방식 : 먼저 테이블 내에 들어갈 항목의 개수를 추정한다. 그 숫자는 원래의 값이나 키에서 몫과 나머지를 추출해 내기 위해 각각을 나누는 제수(除數)로 사용된다. 계산의 나머지가 해시 값이 된다 (이 방식은 얼마간의 충돌이 일어나는 것을 피할 수 없으며, 어떠한 검색 방식이라도 충돌 여부를 인식하고, 대체 검색 방법을 제공할 수 있어야만 한다).
2. 접기 : 이 방식은 원래의 값을 여러 부분으로 나누어, 그 부분들을 함께 더하고 나서, 마지막 네 자리를 해시 값이나 키로 삼는 것이다.
3. 기수변환 : 값이나 키가 디지털이라면, 다른 순서의 숫자열을 만들도록 기수(基數)를 변경할 수 있다. 즉, 10진수의 키를 16진수의 키로 변경할 수 있는 것이다. 변경 후, 해시 값의 길이를 일정하게 유지하기 위해 상위 자리수의 일부는 버려질 수 있다.
4. 자리수 재배열 : 이것은 단순히 세 번째부터 여섯 번째 자리까지 등과 같이 원래 값이나 키의 일부를 취하여 그 순서를 역으로 한 다음, 그 것을 해시 값이나 키로 사용하는 것이다.

데 이터베이스 저장이나 검색에 잘 적용되는 해시 함수는 오히려 암호화나 에러검출 목적으로는 잘 듣지 않을 수도 있다. 암호화에 사용되는 잘 알려진 해시 함수들이 몇 개 있다. 이러한 것들에는 전자서명을 요약 메시지라고 불리는 더 짧은 값으로 바꾸는 데 사용되는 요약 메시지 해시 함수 MD2, MD4, MD5 등과, 더 큰 요약 메시지 (60 비트)를 만드는 표준 알고리즘인 SHA 등이 포함된다.


좀더 엔지니어적인 접근으로 참고할 만한 싸이트는

 

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dv_vstechart/html/datastructures_guide2.asp


<출처 : http://blog.daum.net/_blog/BlogView.do?blogid=0CNH3&articleno=7641836&categoryId=469579#ajax_history_home>

파워포인트에 virtools 실행하기


파워포인트에 Viewpoint 및 Virtools 콘텐츠 등이 삽입된 웹페이지를 상대경로로 삽입하고 슬라이드가 시작될 때 자동으로 실행시키는 방법은 다음과 같다.
  1. 파워포인트을 실행시킨다.
  2. 콘트롤도구상자에서 기타 콘트롤 아이콘을 누른다.
  3. 표시되는 콘트롤 목록에서 Microsoft 웹 브라우저를 선택한다.
  4. 파워포인트 슬라이드 영역에서 드래그하여 웹 브라우저를 삽입한다.
  5. 웹 브라우저를 우클릭하여 팝업 메뉴에서 코드보기를 항목을 선택한다.
  6. 비주얼베이직 편집창이 나타나면 편집창 상단 위의 두개의 콤보 박스 중 오른쪽에서 DocumentComplete를 선택한다.(잘 찾아보면 찾을 수 있을 것이다)
  7. 편집창에 함수가 자동으로 삽입되면 아래와 같이 코드를 완성한다. 이때 세번째 줄의 webpage.html 을 연결하고자 하는 웹페이지의 상대 경로를 입력한다.
Private Sub WebBrowser1_DocumentComplete(ByVal pDisp As Object, URL As Variant) 
  If URL = "" Then 
    sURL = ActivePresentation.Path & "\WebPage.html" 
    sURL = Replace(sURL, "\\", "\") 
    WebBrowser1.Navigate (sURL) 
  End If 
End Sub 
* 참고 : 절대경로를 입력할 경우에는 다음과 같이 하면 된다.
Private Sub WebBrowser1_DocumentComplete(ByVal pDisp As Object, URL As Variant) 
  If URL = "" Then 
    WebBrowser1.Navigate ("http://www.naver.com") 
  End If 
End Sub 
또는
Private Sub WebBrowser1_DocumentComplete(ByVal pDisp As Object, URL As Variant) 
  If URL = "" Then 
    WebBrowser1.Navigate ("c:\WebPage.html") 
  End If 
End Sub 








<출처 : http://blog.naver.com/chaehj72/20032570576>

Virtools - Texture Scroller





    Per Second : POut을 더블클릭하여 Vector 2D를 선택.
                       BB 클릭 후, X = 0, Y =  -1

   Texture Scroller : BB 클릭 후, 해당 Mesh 선택.

블루투스 없이 적외선 센싱하는 프로젝트


(출처: http://cafe.naver.com/wiiremote.cafe 의  욱스님)
 
 혹시 이 글에 관심을 가지고 계시지만, 일본어로 되어있어 이해하지 못하신 분들이 계실까봐
 
 저의 미약한 일본어 실력으로 해석해보고자 생각했습니다.
 
 혹시 해석상 문제가 있다고 생각하시는 분들은 바로 글 남겨주시면 감사하겠습니다.
 
 그럼, 욱스님 글 그대로에 해석하도록 하겠습니다.
 
-------------------------------------------------------------------------------------------------------------

일본내 프로젝트 사이트 인데, 해석이 불편하여 전체를 긁어 왔습니다.
I2C방식의 WiiRemote 방식의 IR 센서 카메라를 적출하여,
다른 MCU에 장착해서 USB 타입으로 PC에 연결하여 사용할 수 있는 제품을 만드는 프로젝트입니다.
(회로도 및 소스코드도 제공하니 간단히 여러 프로젝트에 응용이 가능합니다.) 

 
* 이 프로젝트 덕분에 눈차크 등의 extension port가 I2C 형식 임을 알게 됐습니다.

去年(2007年)、Wiiリモコンのポインティング用赤外線センサを解析して、他の機器に接続する方法を試した。
その続きで、今回は、AVRマイコンを使った
Arduinoキットに接続する回路を試作してみた。(2008-04-13)
작년(2007년), wii리모컨 포인팅용 적외선 센서를 분석하여, 다른 기기에 접속하는 방법을 시험했다.
그 연장선으로 이번에는 AVR마이콘을 사용한 Arduino 키트에 접속하는 회로를 시험적으로 만들어 보았다.


1. ハードウェア
1. 하드웨어

   
 

   基板はArduinoキットに試作用のユニバーサル基板を重ねている。
 白い棒状のケースにはWiiリモコンから取り出したセンサと
自作回路が入っている。
   기판은 Arduino키트에 시험 작품용 유니버셜 기판을 겹쳐 놓았다.
   흰색 막대기 모양 케이스에는 wii리모컨으로 빼낸 센서와 자작 회로가 들어 있다.


 接続は、この図のように接続している。
   접속은 이 그림과 같이 접속하고 있다.

 ・Wiiリモコン赤外線センサ回路

 ・I2C電圧変換シールド
 ・Arduino Diecimila
    wii 리모컨 적외선 센서 회로
    I2C전압교환실드
    Arduino Diecimila

 以上の3つの部分で構成されている。
   이상 3개의 부분으로 구성되어 있다.
 3.3Vで動作する赤外線センサを、5Vで動作するマイコンに接続するために電圧変換が必要である。
   3.3V로 동작하는 적외선 센서를 5V로 동작하는 마이콘에 접속하기 위해서 전압교환이 필요하다.

 Wiiリモコン赤外線センサ回路は、
前に作った回路と同じものを小型にして作り直した。
 I2C電圧変換シールドは、試作用のPrototype Shieldというユニバーサル基板を使って作った。
   wii리모컨 전외선 센서 회로는 앞에서 제작한 회로와 같은 것을 소형으로 다시 만들었다.
   I2C전압 교환 실드는 시험 제작 용 Prototype Shield라고 불리는 유니버셜 기판을 사용하여 만들었다.

 
 I2C電圧変換シールドは、Aruduinoの基板の上に重ねるように接続する。
   I2C 전압교환 실드는 Aruduino의 기판 위에 겹친 것처럼 접속한다.

 
 I2C電圧変換の回路は、LTC4301LというICを使用して作った。
 このICは、I2Cバスの電圧を変換する。 LTC4301Lでなく、LTC4301でも動くはず。
   I2C전압교환 회로는 'LTC4301L'이라는 IC를 사용해서 만들었다.
   이 IC는 I2C버스의 전압을 교환한다. 'LTC4301L'이 아닌, 'LTC4301'에서도 움직일 것이다.

2. ソフトウェア
2. 소프트 웨어

  前回のソースコードを元にして、Arduino用のソフトを作成した。

 [
wii_remote_ir_sensor_sample.zip - source code (download) ]
   이전의 소스코드를 바탕으로 해, Arduino용 소프트를 작성했다.

 (後日加筆 2008-09-21)
   (2008-09-21 수정)
 WinAVRを使ってソフトを書き直してみた。
 [
wii_remote_ir_sensor_sample2.zip - source code (download) ]
   WinAVR을 사용해 소프트를 고쳐 써 보았다.


Wiiリモコンの赤外線センサの使い方
Wii리모컨 적외선 센서의 사용방법

 簡単にセンサの使い方の解説を書いてみる。
   간단히 센서를 이용하는 방법을 풀어 써 보았다.

I2Cバス規格のプロトコルでは、デバイスとの通信には、デバイスのアドレス番号を最初に送信する必要がある。
   I2C버스 규격의 프로토콜에서 디바이스와의 통신에는 디바이스 어드레스 번호를 최초에 송신하는 필요성이 있다.

Wiiリモコンに使われている赤外線センサのアドレスは、0x58である。
Wii 리모컨에 사용되어지는 적외선 센서의 어드레스는 0x58이다.
 ソースコードには0xB0と書いてあったりするが、これは上位7ビットがアドレスで、下位1ビットがR/W指定ビットとなるように、シフトするからである。
  소스 코드에는 0xB0라고 써있기도 하지만, 이것은 상위 7비트가 어드레스에서 하위 1비트가 R/W지정비트라고 되는 것처럼 위치변경하기 때문이다.

   センサの初期化は、Wiiリモコン内部のセンサにBluetooth経由でアクセスする場合より簡単である。
 なぜなら、チップイネーブル制御や、クロック発振回路のON/OFF制御をしないからである。
   센서 초기화는 Wii 리모컨 내부의 센서에 Bluetooth 경유로 접속하는 경우보다 간단하다.
   왜냐면, chip enable 제어와 Clock(시계) 발진 회로의 ON/OFF 제어를 하지 않기 때문이다.

 初期化のためのコマンドの送信は、次の形式で行う。
   초기화를 위해 커맨드 송신은 다음의 형식으로 이동한다.
 [STARTコンディション] [0xB0] [制御レジスタアドレス] [書き込みデータ] [STOPコンディション]
   [START 컨디션] [0xB0] [제어 레지스터 어드레스] [기입된 데이터] [STOP 컨디션]
 制御レジスタのアドレスは、8bitで指定する。
   제어 레지스터 어드레스는, 8bit로 지정한다.
 どのアドレスがどういう機能なのかは、まだ詳しく分かっていない。
   어떤 어드레스가 어떤 기능인가는 아직 상세하게 알고 있지 않다.
 とりあえず、ある決まった値と手順で書き込むとセンサを動作させることができる。
   우선 정해져 있는 값과 순서롤 쓰면 센서를 동작시킬 수 있다.


 初期化コマンド手順
   초기화 커맨드 순서

 (1) 制御レジスタアドレス0x30に対して、データ0x01を書き込む
        제어 레지스터 어드레스 0x30에 대해, 데이터 0x01를 기입
 (2) 制御レジスタアドレス0x30に対して、データ0x08を書き込む
        제어 레지스터 어드레스 0x30에 대해, 데이터 0x08를 기입
 (3) 制御レジスタアドレス0x06に対して、データ0x90を書き込む
      제어 레지스터 어드레스 0x06에 대해, 데이터 0x90를 기입
   (4) 制御レジスタアドレス0x08に対して、データ0xC0を書き込む
        제어 레지스터 어드레스 0x08에 대해, 데이터 0xC0를 기입
 (5) 制御レジスタアドレス0x1Aに対して、データ0x40を書き込む
        제어 레지스터 어드레스 0x1A에 대해, 데이터 0x40를 기입 
 (6) 制御レジスタアドレス0x33に対して、データ0x33を書き込む
        제어 레지스터 어드레스 0x33에 대해, 데이터 0x40를 기입

   これは、以下で説明する感度設定の手順を簡略にしたようなものらしい。
   이것은 밑에 설명하는 감도 설정의 순서를 간략하게 한 것 같다.
 赤外線センサの感度の設定方法について
   적외선 센서의 감도 설정방법에 대하여
 上記で簡易的に設定されているようだが、ちゃんと設定したい場合には、4つのパラメータp0,p1,p2,p3を指定して、次の手順で書き込む
   상기에 간이식(*간이 우체국의 '간이')으로 설정되어 있는 것 같지만, 확실히 설정하고 싶은 경우에는 네 개의 파라미터  p0,p1,p2,p3를 지정하여 다음 순서를 기입 
 
    (1) 制御レジスタアドレス0x30に対して、データ0x01を書き込む
        제어 레지스터 어드레스 0x30에 대해, 데이터 0x01를 기입
 (2) 制御レジスタアドレス0x00に対して、データ0x02,0x00,0x00,0x71,0x01,0x00,p0を書き込む
        (7バイトの書き込み)
        제어 레지스터 어드레스 0x00에 대해, 데이터 0x02,0x00,0x00,0x71,0x01,0x00,p0를 기입
        (7바이트로 기입)

 (3) 制御レジスタアドレス0x07に対して、データ0x00,p1を書き込む (2バイトの書き込み)
        제어 레지스터 어드레스 0x07에 대해, 데이터 0x00,p1를 기입(2바이트로 기입)
 (4) 制御レジスタアドレス0x1Aに対して、データp2,p3を書き込む (2バイトの書き込み)
        제어 레지스터 어드레스 0x1A에 대해, 데이터 p2,p3를 기입(2바이트로 기입)
 (5) 制御レジスタアドレス0x33に対して、データ0x03を書き込む
      제어 레지스터 어드레스 0x33에 대해, 데이터 0x03를 기입
   (6) 制御レジスタアドレス0x30に対して、データ0x08を書き込む
        제어 레지스터 어드레스 0x30에 대해, 데이터 0x08를 기입
 複数バイトの書き込み時はレジスタアドレスが自動インクリメントされるので連続で書き込み可能である。
   복수 바이트 기입시는 레지스터 어드레스가 자동 인크리먼트(increment; 주어진 수에서 일정한 수량을
  증가)
시키는 것에 연속하여 기입이 가능하다.

 感度のパラメータは、
   감도 파라미터는
 感度1の場合、p0=0x72 , p1=0x20 , p2=0x1F,p3=0x03
   감도 1의 경우, p0=0x72 , p1=0x20 , p2=0x1F,p3=0x03
 感度2の場合、p0=0xC8 , p1=0x36 , p2=0x35,p3=0x03
   감도 2의 경우, p0=0xC8 , p1=0x36 , p2=0x35,p3=0x03
 感度3の場合、p0=0xAA , p1=0x64 , p2=0x63,p3=0x03
   감도 3의 경우, p0=0xAA , p1=0x64 , p2=0x63,p3=0x03
 感度4の場合、p0=0x96 , p1=0xB4 , p2=0xB3,p3=0x04
   감도 4의 경우, p0=0x96 , p1=0xB4 , p2=0xB3,p3=0x04
 感度5の場合、p0=0x96 , p1=0xFE , p2=0xFE,p3=0x05
   감도 5의 경우, p0=0x96 , p1=0xFE , p2=0xFE,p3=0x05

 初期化後(感度設定後)は、センサで検知した光点の座標を読み出すことができる。
   초기화 후(감도 설정 후)는, 센서 검지(검사하여 알아냄)한 광점의 좌표를 읽어내는 일이 가능하다.

 センサ出力の読み出し方法
   센서 출력을 읽어내는 방법
  [STARTコンディション] [0xB0] [0x36] [STOPコンティション]
      [START 컨디션] [0xB0] [0x36] [STOPコンティション]
  というコマンドを送信後、次のとおり読み出す。
      라고 커맨드를 송신한 후, 다음과 같이 읽어 낸다.
  [STARTコンディション] [0xB1] [データの読み出し] x 16bytes
      [START 컨디션] [0xB1] [데이터의 읽어냄] x 16bytes

 読み出したデータの形式
   읽어 낸 데이터 형식
  3バイトずつ下記の順に格納されている。
      3바이트 씩 밑에 적힌 순서로 격납(집어 넣어둠)되어 있다.
  [先頭1byte] [座標1... 3bytes] [座標2 ... 3bytes] [座標3 ... 3bytes] [座標4 ... 3bytes]
      [앞머리 1byte][좌표1... 3bytes][좌표2 ... 3bytes][좌표3 ... 3bytes][좌표4 ... 3bytes]
  
  この3バイトを、XX,YY,SSとすると、
      이 3바이트를 XX,YY,SS라고 한다면,
  X座標 = (SS & 0x30) <<4 + XX
  Y座標 = (SS & 0xC0) <<2 + YY
      X좌표 = (SS & 0x30) <<4 + XX
      Y좌표 = (SS & 0xC0) <<2 + YY
  という計算をすることで、座標の値を得ることが出来る。
      라고 계산 하는 것으로 좌표의 값을 얻을 수 있다.
  座標値が無効な場合に0x3FFが返ってくる。
      좌표값이 무효인 경우에는 0x3FF이 반환된다.


 制御レジスタの役割
   제어 레지스터의 역할
  アドレス 0x00~0x08 --- 検出のためのパラメータ設定
      어드레스 0x00~0x08 ---검출을 위해 파라미터 설정
  アドレス 0x1A~0x1B --- 検出のためのパラメータ設定(2)
      어드레스 0x1A~0x1B ---검출을 위해 파라미터 설정(2)
  アドレス 0x30 --- センサの動作モード(?) 最初に0x01を書き込んで, 次に0x08を書き込む
      어드레스 0x30 --- 센서의 동작모드(?) 최초에 0x01를 기입하고 나서, 0x08를 기입
  アドレス 0x33 --- センサの動作モード(?) 0x03 ( あるいは0x33 ? ) を書き込む
      어드레스 0x33 --- 센서의 동작모드(?)   0x03 ( 혹은 0x33 ? )를 기입

 検出のためのパラメータ設定
   검출을 위해 파라미터 설정
  不明
      불명
  カメラで撮影した画像を画像処理して光点を検出するためのセンサ内部のソフトウェアのパラメータ設定
      카메라에서 촬영한 영상을 영상처리하여 광점을 검출하기 위해 센서 내부의 소프트 웨어 파라미터 설정
  2値化の敷居値とか光点の大きさの敷居値とかのパラメータがあるのではないかと推測される。
      2치화(*2 + 수치화의 의미로 보임)의 문턱치(*일정수치 이상으로 넘어가야 다음 단계로 넘어간다는 의미로 보임) 라던가 광점 크기의 문턱치라던가의 파라미터가 있는 것은 아닐지 추측된다.


  (後日加筆 2008-10-06)

  (2008-10-06 수정)
 いくつかのパラメータは判明してきているらしい。
   몇 개의 파라미터는 판명된 것 같다.
 http://wiki.wiimoteproject.com/IR_Sensorというページに色々と情報が出ている。
                                                                     라는 페이지에 여러가지 정보가 나온다.

 

 

1.  *는 확실치 않은 단어의 뜻으로 문맥상과 단어의 검색으로 추측해본 단어입니다.

2.  커맨드, 파라미터와 같이 영문의 뜻은 한글로 바꾸지 않고 그대로 사용하였습니다.


 

Topology(위상)에 대한 정의


위상에 대한 정의는 다음과 같습니다.

어떤 집합 X가 있을 때 다음의 3가지 조건을 만족하는  Power Set(멱집합)의 부분집합이 있을 때 그 부분집합을 "위상"이라 부릅니다. 이 때, 그 부분집합인 위상을 T라 합시다.

위상이 정해지면 (X, T)를 위상공간이라 합니다.
(참고. 멱집합이란 부분집합들을 모두 모아놓은 집합입니다.)

 T가 만족해야 하는건 다음 3가지 조건입니다.

1) 공집합, X 을 가진다.

2) T의 임의의 두 원소에 대해 그 유한 교집합은 T에 속한다.

3) T의 임의의 원소들에 대해 그 무한 합집합은 T에 속한다.

 예로 1차원 공간인 실수집합의 위상은 (a, b) 을 합집합 해 놓은 것들을 위상으로 가집니다.

3차원공간인 R^3 공간에서도 이런식으로 위상을 정의하는데 이것은 우리가 보통 생각하는공간입니다. 따라서 이 때의 위상을 보통위상이라고도 하죠.

하지만 한 집합에 하나의 위상만 존재하는 것은 아닙니다. 여러 위상이 존재하여 우리가 생각하는 것과 전혀 다른 공간이 나올 수도 있습니다.

 (네이버 지식인 :
pnumath)

http://www.wikipedia.org/ 참고할 것!

Ogre Engine SettingUpAnApplication - 오거 엔진 셋업 방법 (번역 진행중)

우선, 이 글은 http://www.ogre3d.org/wiki/index.php/SettingUpAnApplication 의 내용을 그대로
가져와서, 번역하였습니다.

중간에 틀린 부분이 많이 있으리라 생각이 됩니다. 이 글을 보시는 분을 생각하기보다는 제 자신이 지금 세팅
문제로 어려움을 겪고 있어, 제대로 된 문서화가 필요하다는 생각에 해석하게 되었습니다.

부디 너그러운 마음으로 글을 읽어주셨으면 좋겠습니다.

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

This page is a guide to setting up your first application. Be sure that you've already installed OGRE by
either Installing An SDK or Building From Source. Beginners should use the first option if available.

이 페이지는 당신이 처음으로 오우거 엔진을 세팅할 때 필요한 가이드 입니다. Installing An SDK 과 Building From Source 가 이미 설치되어 있어야 합니다. 처음 설치 하시는 분 들에게는 가능하다면 첫번째 옵션을 사용 해야 합니다.

Contents

[hide]

Prerequisites (전제 조건)


By this time you should have already worked through Installing An SDK or Building From Source and have OGRE installed on your system. If not, go back to the appropriate page to finish configuring your OGRE.

당신은 이미 SDK를 설치했거나, 빌딩을 통해 성공했어야 하고, OGRE가 여러분의 시스템에 설치되어 있어야 합니다. 만약 그렇지 않다면, 다시 해당 파일로 가서 OGRE 구성을 끝내시기 바랍니다. 

In order to run your application, there are various files that need to be locatable by your system. The list below details these files. [_d] denotes an optional reference to a debug library (ie OgreMain_d.dll instead of OgreMain.dll). These files should be in your working directory, or accessible by an appropriate path.

어플리케이션을 진행하기 위해서는 당신의 시스템에서 설치되어야 하는 여러가지의 파일이 있습니다. 다음 리스트는 그 파일들에 대한 상세한 내용입니다.  [_d] 디버그 라이브러리에 대한 선택적 참조 (즉, OgreMain_d.dll 대신 OgreMain.dll의) 를 의미합니다. 이러한 파일은 여러분의 작업 디렉토리, 또는 적절한 경로로 액세스할 수 있어야 합니다.

On Mac OS X, your project must be run from an application bundle (aka ".app"), otherwise Ogre will not initialise properly. XCode does this for you automatically, but if you don't use XCode you will have to build the bundle manually.
 
Mac OS X에서, 당신의 프로젝트가 응용 프로그램 번들에서 (일명 ".app") 실행되어져야만 합니다. 그렇지 않으면 제대로 초기화되지 않습니다.  Xcode가 자동으로 실행되게 되지만, Xcode를 사용하지 않는 경우에는 수동으로 번들을 구축해야 합니다.

The easiest way to get everything configured is to copy an existing OGRE sample and the media directory into your own working directory. If using Windows, copy all the necessary runtime DLLs to this directory. Edit plugins.cfg and resources.cfg so that the file locations they contain match this new directory.

모든 구성하기 위해 가장 쉬운 방법은 자신이 작업하는 디렉토리에 기존 오우거 샘플과 media 디렉토리를 복사하는 것입니다. 윈도우즈를 사용하는 경우, 모든 필요한 런타임 DLL을 이 디렉토리에 복사합니다. plugins.cfg 편집하고, 이 새로운 디렉토리에  resources.cfg 일치가 들어있는 파일의 위치.

OGRE Libraries & Files
  • OGRE libraries (OgreMain[_d].dll, libOgreMain.so for linux).
  • plugins.cfg - Text file specifying the rendering libraries available to Ogre (ie DX9, OpenGL).
  • All the plugin libraries listed in plugins.cfg (you can remove items from plugins.cfg if you don't wish to use them).
  • resources.cfg - If using the ExampleApplication, a text file specifing paths to materials, textures, models, etc.
  • OgreCore.zip - Ensure resources.cfg has the proper path to this file if you plan to use the OGRE debug panel or profiler.
  • Other Resources used in your program (*.zip; *.png; *.particle; *.mesh; ...).
3rd Party Libraries

The following packages also need to be installed if building from source (not SDK). The libraries (.lib; .a) and header files (.h) will be required for linking and the runtime libraries (win32 .dll; linux .so) necessary for running. If on the Windows platform, it is highly recommended to use the precompiled dependencies available on Source releases. Grab the correct package for your compiler.

These are required:

  • Zlib: zlib1.dll; libz.so (debian: zlib1g, zlib1g-dev)

These are optional:

  • CEGUI: OgreGUIRenderer[_d].dll, CEGUIBase[_d].dll, CEGUITaharezLook[_d].dll, CEGUIWindowsLook[_d].dll, xerces-c_2_5_0.dll
  • CEGUI: libCEGUIBase.so, libCEGUIOgreRenderer.so, libxerces-c.so (debian: libcegui-mk2-0, libcegui-mk2-dev, libxerces26, libxerces26-dev)
  • Cg: cg.dll; libCg.so (debian: nvidia-cg-toolkit)
  • OpenEXR: openexr.dll??; (debian: libopenexr-dev libopenexr2 )
  • ReferenceApp: ReferenceAppLayer.dll
Extras for Microsoft Visual C++ 6 (SP3+)
  • stlport_vc6[_stldebug]46.dll
  • msvcp60[D].dll
  • msvcrt[D].dll
Extras for Microsoft Visual C++.Net 2002
  • stlport_vc7[_stldebug]46.dll
  • msvcp70[d].dll
  • msvcr70[d].dll
Extras for Microsoft Visual C++.Net 2003
  • msvcp71[d].dll
  • msvcr71[d].dll
Extras for Mingw + STLPort
  • libstlport[stlg].5.0.dll
  • mingwm10.dll

Environment Settings

You may want to register an environment variable pointing at the root of the OGRE installation so you can express all your paths relative to that. It can be easier if you ever move things around or onto a different machine. For information on checking and updating environment variables, see the documentation for Windows, Linux and Mac OSX.

  • If you downloaded and installed the precompiled OGRE SDK, you should already have an environment variable called 'OGRE_HOME' registered already, pointing at the folder where you installed. If it isn't there you probably installed under a different user, so define OGRE_HOME manually
  • If you downloaded the source distribution, you should register a new environment variable OGRE_SRC pointing at the 'ogrenew' folder from the OGRE source

Create A Project File

This section is not for extensive compiler/IDE settings. It is only for very short steps to start a new project. This should be very easy to do in any IDE. The source code that will go into the project is below. Create a working directory to store your source code. A standard directory structure separates headers, source files and project files as follows:

work_dir    include       *.h    src       *.cpp    scripts       *.vcproj

Microsoft Visual C++ 6 (SP3+)

Ogre does not provide support for VC6. It's from 1998, and rather old. It does not support ISO C++. It will only cause you pain.

It's recommended to use Visual C++ 2005 Express (also called VC8) instead.

If you absolutely must use that ancient thing, proceed on your own. You are not going to receive any support, other than people telling you to upgrade.


Microsoft Visual C++ .NET

Important:

If you use Visual Studio 2005 (VC8) make sure to get service pack #1 to go with it.


Note: If you are using VC++ .NET 2003 or later, you can use the Ogre Application Wizard and you are ready to create OGRE apps - feel free to skip down to the code section, as the application wizard will set up the project for you. Also see The Complete Blanks Guide To Using The OGRE SDK AppWizard.

Otherwise, to manually configure the IDE, follow these steps:

  1. Create a new project

  2. Choose 'Visual C++ Projects' / 'Win32' then 'Win32 Project'.

  3. Enter a name for your project and change the location to point to a work directory (separate from the runtime directory).
  4. Select 'Windows Application' and 'Empty project' when prompted for the type of project to create.

  5. Create a new source file by selecting 'Project -> Add New Item...'. Make sure the file is in the work directory. This step must be performed before editing project properties (otherwise the 'C/C++' page will be unavailable).
  6. Save the project.

If you named your project "Testproject" and selected a location like C:\Work, and checked the box called "Create directory for solution", with a solution name of "Testsolution", then the directory structure will be: C:\Work\Testsolution\Testproject. If you do not create a directory for the solution, the structure will simply be: C:\Work\Testproject.

To clarify where the DLL files should be, an easy way is to copy the \bin folder (containing \debug and \release) and the \media folder from the OGRE installation directory to your Testproject folder (note: in this case you might be copying DLLs that won't be needed, but it's the hassle-free way). If you follow the convention presented above and you created folders for the header, scripts and source files, you have the following folders under \Testproject (excluding subfolders): 'bin', 'include', 'media', 'testsolution', 'scripts', and 'src'.

If you follow the next few steps carefully, your project should compile without errors.

Configure your project with the following settings. All of these are for the Debug configuration. To set up the Release configuration just change the directories from '\Debug\' to '\Release\'. Select "project properties" and under "configuration properties" add the following:

Debugging : Command                                 = $(OutDir)\$(ProjectName).exeDebugging : Working Directory                       = $(OutDir)C/C++ : Preprocessor : Preprocessor Definitions += _STLP_DEBUG (only in Debug mode, not needed for .Net 2003 and 2005)C/C++ : Code Generation : Use runtime library 	 = Multithreaded Debug DLL (Multithreaded DLL in Release)Linker : General : Output File                            = ..\bin\Debug\[appname].exeLinker : Input : Additional Dependencies                += OgreMain_d.lib (OgreMain.lib in Release)

And, for those using Ogre3D 1.4.x

Linker : Input : Additional Dependencies                += OIS_d.lib (OIS.lib in Release)

And, for those using the SDK:

C/C++ : General : Additional Include Directories 	 = ..\include;$(OGRE_HOME)\include;$(OGRE_HOME)\samples\includeLinker : General : Additional Library Directories         = $(OGRE_HOME)\lib

Or, for those using the source release:

C/C++ : General : Additional Include Directories 	 = ..\include;$(OGRE_SRC)\OgreMain\include;$(OGRE_SRC)\Samples\Common\IncludeLinker : General : Additional Library Directories         = $(OGRE_SRC)\OgreMain\Lib\Debug

Additional hints on getting your application to run from within the IDE:
Visual Studio Debugging Settings

Code::Blocks + MinGW 3.4.5 + STLPort 5.0

Have a look at the build options for Demo_CameraTrack, most of the demos use the same build options.

Note: with MinGW gcc 3.4.5 you can link directly against dll's built by gcc 3.4.5 and do not require an import lib. This is the same setup on Linux where you link directly to the shared object (.so). This is why the SDK does not come with import libs for Ogre. You don't need them.

Build options that you should use:

Normally you will have two targets: Debug and Release.

To create a new target:

  1. Right click on the project in the Management window and select Properties in the popup and this will open up the properties window for your project.
  2. Select the Target tab.
  3. Select Add to define a new target.
  4. Type in the target name ie Debug.
  5. Select OK.

Select Build Options to modify build options for a target.

Project build options

will be used for both Debug and Release target build options:

Image:CB_PCOS.jpg

ensure Selected compiler is: GNU GCC Compiler

  • Compiler
    • Other options
      • -mthreads
      • -fmessage-length=0
      • -fexceptions
      • -fident
    • '#defines'
      • _STLP_NO_CUSTOM_IO
        If your app does not define any custom IO templates then this define will speed up compiles.
      • _STLP_USE_DYNAMIC_LIB
        this ensures that the DLL version of STLPort is used.
  • Linker
    • Other linker options:
      • -Wl,--enable-auto-image-base
      • -Wl,--add-stdcall-alias
  • Directories
    • Compiler
      • $(OGRE_HOME)\stlport\stlport
        VERY IMPORTANT: The stlport include directory has to be first in the include directories. If it is not then headers used for libstdc++ could get included which will cause conflicts with stlport during the link stage. You will most likely get undefined reference error messages with member methods saying they require std::string (method parameters). You should never see std:: in an error message and if you do then it means that the STLPort headers were not found and libstdc++ headers were used instead. If you do end up in this scenerio, after you correct the directory problem you must do a rebuild so that everything gets recompiled with the proper headers. Selecting build won't do it since CB will just attempt to do the link stage again since it doesn't detect any changes in the source and will fail again.
      • $(OGRE_HOME)\include
      • Your project include directories
    • Linker
      • $(OGRE_HOME)\bin\$(TARGET_NAME)
        this is the path to OgreMain.dll or OgreMain_d.dll along with stlport.5.0.dll or stlportstlg.5.0.dll depending on TARGET_NAME state. $(TARGET_NAME) is a built in Code::Blocks macro that you can use in your project settings. It gives you the active project target build name.

Debug build target options:

Image:CB_DTOS.jpg

ensure Selected compiler is: GNU GCC Compiler
set Policy to 'Append target options to project options'

  • Compiler
    • '#defines'
      • WIN32
      • _DEBUG
      • _WINDOWS
      • _STLP_DEBUG
        this tells STLPort to use the special debug build version of the dll
  • Linker
    • Link libraries:
      • Your project dll's or static libs (.a)
      • OgreMain_d
        this is the name of the debug build of OgreMain dll.
      • stlportstlg.5.0
        this must be the last entry

Release build target options:

ensure Selected compiler is: GNU GCC Compiler
set Policy to 'Append target options to project options'

  • Compiler
    • '#defines'
      • WIN32
      • NDEBUG
      • _WINDOWS
  • Linker
    • Link libraries:
      • Your project dll's or static libs (.a)
      • OgreMain
        this is the name of the release build of OgreMain dll.
      • stlport.5.0
        this must be the last entry

Note: OGRE_HOME is a pre-defined environment variable setup by the SDK installer. OGRE_HOME points to the directory where the SDK is installed. You can use $(OGRE_HOME) within your build options when setting up paths to specific directories with the SDK that you will need to access.

WARNING Do not mix dll and static object builds using different STL implementations. Here is an example: You build a dll using stdlibc++ but your exe is built using STLPort. Everything that is c++ must be built using STLPort. This does not apply to C static libs and dll's.

Gnu Compiler Collection (gcc) v3.x (using make)

Make sure you are using gcc 3.x. Many Linux distributions still come with gcc 2.95.x which does not have as good support for the ISO C++ standard and will probably cause you problems. Please install the latest stable version of gcc 3.x.

Create a file called 'Makefile' in your application folder, with the following contents. Later you can replace SampleApp with your own program file name.

DEFINES =LIBS = OGRECXX = g++CXXFLAGS = $(shell pkg-config --cflags $(LIBS)) $(DEFINES)LD = g++LDFLAGS = $(shell pkg-config --libs $(LIBS))all:	$(CXX) $(CXXFLAGS) $(LDFLAGS) -o SampleApp SampleApp.cppclean:	rm -f SampleApp

When you are ready to start working with multiple files and even incorporating CEGUI, your Makefile might look like the following example. Make will expect to find SampleApp.cpp, camera.cpp and listener.cpp:

## Compiler and linker settingsDEFINES = -gLIBS = OGRE CEGUI-OGRE CEGUICXX = g++CXXFLAGS = $(shell pkg-config --cflags $(LIBS)) $(DEFINES)LD = g++LDFLAGS = $(shell pkg-config --libs $(LIBS))## Files to include in yourApp projectSAMPLEAPP = SampleApp.o camera.o listener.o## Compilation and linking occurs hereall: SampleApp	$(LD) $(LDFLAGS) $(SAMPLEAPP) -o SampleAppSampleApp: $(SAMPLEAPP)## Clean upclean:	rm -f $(SAMPLEAPP) SampleApp

XCode

  • In XCode, select menu File > New project > Carbon Application.
  • Place your project wherever you want and name it, then click finish
  • Remove main.nib and *_Prefix.pch (note: if you wish to use a precompiled prefix header, you may, just adapt the instructions as needed)
  • rename main.c to main.cpp. Remove its content and replace it with Ogre code (for instance http://www.ogre3d.org/wiki/index.php/BasicTutorial2Source).


  • Add Ogre.framework and Cg.framework to your project by right-clicking on your project name in the tree and selecting Add > Existing frameworks. Add the IOKit framework from system directories the same way.
  • Add static library libois.a the same way (libFreeImage.a, libfreetype.a libzzip.a were also previously required but apparently are no more).

(These libraries are all provided in the Ogre dependencies download except Ogre.framework that you either got from the mac SDK or built from source.) (As of Ogre 1.4.5, I had better success with the CVS version of OIS on mac. OIS versions greater than 1.0 should be all okay though.)

Now you must add the required config files to your project. You can find these files in Ogre/Mac/Samples/config Just drag and drop them to the file tree and they should automatically be copied to the Resources directory of your app. Whenever you add data or source files to the project, make sure you check the copy items checkbox in the dialog that pops-up before confirming file addition because you don't want to modify the original files. There is no need to do that with libraries though.

  • plugins.cfg
  • media.cfg
  • resources.cfg : you will need to edit this one to point inside your application. here is an example of resources.cfg file to work with the samples and tutorials
# Resource locations to be added to the 'boostrap' path# This also contains the minimum you need to use the Ogre example framework[Bootstrap]Zip=Contents/Resources/Media/packs/OgreCore.zip# Resource locations to be added to the default path[General]FileSystem=Contents/Resources/MediaFileSystem=Contents/Resources/Media/fontsFileSystem=Contents/Resources/Media/materials/programsFileSystem=Contents/Resources/Media/materials/scriptsFileSystem=Contents/Resources/Media/materials/texturesFileSystem=Contents/Resources/Media/modelsFileSystem=Contents/Resources/Media/overlaysFileSystem=Contents/Resources/Media/particleFileSystem=Contents/Resources/Media/guiFileSystem=Contents/Resources/Media/DeferredShadingMediaZip=Contents/Resources/Media/packs/cubemap.zipZip=Contents/Resources/Media/packs/cubemapsJS.zipZip=Contents/Resources/Media/packs/dragon.zipZip=Contents/Resources/Media/packs/fresneldemo.zipZip=Contents/Resources/Media/packs/ogretestmap.zipZip=Contents/Resources/Media/packs/skybox.zip
  • Media : found in Ogre/Samples (if you want to run the samples or tutorials. make sure you create folder references and not group references - you can choose that in the dialog that pops-up just after you dragged and dropped the folder onto the tree)


  • Open targets in the file tree
  • Right-click on your target, select get info, go in tab build
  • In configuration, make sure to select all configurations when you make changes that should apply to both debug and release
  • In collection architectures, double-click on element Architectures in the list and select the architectures you wish to build (and have built Ogre for). If you build Universal binary, make sure the SDK path in build locations is a universal one (for instance /Developer/SDKs/MacOSX10.4u.sdk. This template should set it to universal by default.).
  • In linking, disable ZeroLink
  • In language, remove the file in Prefix Header and uncheck Precompile prefix header
  • In search paths, add the path to includes provided in Ogre dependencies (double-click on header search paths, drag and drop the OgreDependencies-1.4.5/include folder there)


Existing projects will try to include Ogre.h and not <Ogre/Ogre.h> like frameworks usually require, so you may want to set up an additional header search path pointing inside your Ogre framework headers directory.

If you want to use the samples or tutorials you will also need to copy example application header files from /ogre-1.4.5/Samples/Common/include/

You will now need a copy files build step in your target:

  • Right-click on your target
  • select Add > New Build Phase > New Copy File Build Phase
  • In the window that pops up, select Frameworks in the destination field, don't change any other settings.
  • Now expand your target in the tree view and you should see the new step you just added as a child of your target, by befault named something like Copy Files.
  • Drag and drop all Ogre-related frameworks (including those from Ogre dependencies) inside the new build step you just created.
  • Warning, files you add to the project from now on will tend to add themselves to the copy files build step, make sure only frameworks find their way there.

You are now ready to build and run!

Once you're done, put a copy of your project in ~/Library/Application Support/Developer/Shared/Xcode/Project Templates/Application/, so next time you can just select New project and choose this one from the template list (in older versions of OSX/Xcode, the templates directoy was at ~/Library/Application Support/Apple/Developer Tools/Project Templates)

Autotools

To build your application using the ubiquitous GNU autotools (autoconf + automake + libtool), create these files in your project folder with the following content:

bootstrap
#!/bin/shrm -rf autom4te.cachelibtoolize --force --copy && \aclocal && \autoheader && \automake --add-missing --force-missing --copy --foreign && \autoconf
configure.ac
AC_INIT(configure.ac)AM_INIT_AUTOMAKE(SampleApp, 0.1)AM_CONFIG_HEADER(config.h)AC_LANG_CPLUSPLUSAC_PROG_CXXAM_PROG_LIBTOOLPKG_CHECK_MODULES(OGRE, [OGRE >= 1.2])AC_SUBST(OGRE_CFLAGS)AC_SUBST(OGRE_LIBS)PKG_CHECK_MODULES(OIS, [OIS >= 1.0])AC_SUBST(OIS_CFLAGS)AC_SUBST(OIS_LIBS)AC_CONFIG_FILES(Makefile include/Makefile src/Makefile)AC_OUTPUT
Makefile.am
SUBDIRS = include srcEXTRA_DIST = bootstrapAUTOMAKE_OPTIONS = foreign
include/Makefile.am
noinst_HEADERS= SampleApp.h
src/Makefile.am
bin_PROGRAMS= SampleAppSampleApp_CPPFLAGS= -I$(top_srcdir)/includeSampleApp_SOURCES= SampleApp.cppSampleApp_CXXFLAGS= $(OGRE_CFLAGS) $(OIS_CFLAGS)SampleApp_LDADD= $(OGRE_LIBS) $(OIS_LIBS)

See Your First Application or Minimal Application to create include/SampleApp.h and src/SampleApp.cpp.
You probably want to add plugins.cfg and resources.cfg to the executable folder (src) (see Prerequisites).

To build your app run ./bootstrap && ./configure && make. Subsequent builds only need running make.
To execute your app go to the src folder and run ./SampleApp.

Scons

Scons is a multiplatform building tool programmed in Python, designed to replace GNU Make and other similar tools (autoconf, automake, etc).

For compiling using scons, you'll only need to type:

 scons

in your command line. The scons building tool will automatically check for all needed libraries and include files in your system before trying to compile.

For using scons, you'll need to create a SConstruct file. You'll had to pay a visit to scons.org to learn the directives for building with that tool. But here we provide a sample SConstruct file, that will build both in Ubuntu Linux and in Windows (using Visual Studio 2003 at least).

For a simple program composed by a file named main.cpp, using Ogre Eihort and OIS, this would be the SConstruct file needed:

platform = ARGUMENTS.get('OS', Platform())mode = ARGUMENTS.get('mode', "release")if platform.name == "linux":   listinc=[      # our main include directory      'include',      # location of ogre includes      '/usr/local/include/OGRE',      # location of ois includes      '/usr/local/include/OIS',      ]else:   listinc=[      # our main include directory      'include',      # location of ogre includes      'E:/ogre-eihort/ogrenew/OgreMain/include',      # location of ois includes      'E:/ogre-eihort/ogrenew/Dependencies/include/OIS',      ]if platform.name == "linux":   debugcflags=['-g']   releasecflags=[]   if mode=="debug":      env=Environment(CPPPATH=listinc, LIBPATH='.', CCFLAGS = debugcflags)   else:      env=Environment(CPPPATH=listinc, LIBPATH='.', CCFLAGS = releasecflags)else:   debugcflags = ['-W1', '-GX', '-EHsc', '-D_DEBUG', '/MDd', '/Zi']   #extra compile flags for debug   releasecflags = ['-O2', '-EHsc', '-DNDEBUG', '/MD']         #extra compile flags for release   if mode=="debug":      env=Environment(CPPPATH=listinc, LIBPATH='bin/windows/debug'          , CCFLAGS = debugcflags, CPPDEFINES=["WIN32", "_DEBUG", "_WINDOWS"], LINKFLAGS='/DEBUG'           )   else:      env=Environment(CPPPATH=listinc, LIBPATH='bin/windows/release'          , CCFLAGS = releasecflags, CPPDEFINES=["WIN32", "NDEBUG", "_WINDOWS"]           )# check for required include files and librariesconf = Configure(env)if not conf.CheckCXXHeader('Ogre.h'):   print 'Ogre must be installed!'   Exit(1)if not conf.CheckCXXHeader('OISPrereqs.h'):   print 'OIS must be installed!'   Exit(1)if platform.name == "linux":   if not conf.CheckLib('OgreMain'):      print 'OgreMain library must be in path'      Exit(1)   if not conf.CheckLib('OIS'):      print 'OIS library must be in path'      Exit(1)# list of files needed for compiling the programmain_program_list=Split("""   src/main.cpp   """)if platform.name == "linux":   # list of libraries needed for linking   libs_list=Split("""      OgreMain      OIS      """)else:   # list of libraries needed for release   libs_release_list=Split("""      c:/ogre-eihort/ogrenew/OgreMain/lib/Release/OgreMain      c:/ogre-eihort/ogrenew/Dependencies/lib/Release/OIS      kernel32.lib      user32.lib      gdi32.lib      winspool.lib      comdlg32.lib      advapi32.lib      shell32.lib      ole32.lib      oleaut32.lib      uuid.lib      odbc32.lib      odbccp32.lib      """)   # list of libraries needed for debug   libs_debug_list=Split("""      c:/ogre-eihort/ogrenew/OgreMain/lib/Debug/OgreMain_d      c:/ogre-eihort/ogrenew/Dependencies/lib/Debug/OIS_d      kernel32.lib      user32.lib      gdi32.lib      winspool.lib      comdlg32.lib      advapi32.lib      shell32.lib      ole32.lib      oleaut32.lib      uuid.lib      odbc32.lib      odbccp32.lib      """)if platform.name == "linux":   if mode=="debug":      env.Program('bin/linux/debug/main_d', main_program_list, LIBS=libs_list, LIBPATH='.')   else:      env.Program('bin/linux/release/main', main_program_list, LIBS=libs_list, LIBPATH='.')else:   if mode=="debug":      env.Program('bin/windows/debug/main_d', main_program_list, LIBS=libs_debug_list, LIBPATH='.')   else:      env.Program('bin/windows/release/main', main_program_list, LIBS=libs_release_list, LIBPATH='.')


You might need to change the file paths in the file though.

Use:

  • Put your main.cpp file in directory src; create the following empty directories:
includebin/windows/debugbin/windows/releasebin/linux/debugbin/linux/release
  • In linux, write any of the following lines in the command line:
scons OS=linux mode=debug # build in debug modescons OS=linux # build in release modescons OS=linux mode=debug -c # clean in debug modescons OS=linux -c # clean in release mode

In windows, use the following lines:

  • For debug build:
scons MSTOOLKIT=yes OS=windows mode=debug
  • For release build:
scons MSTOOLKIT=yes OS=windows
  • For debug clean:
scons MSTOOLKIT=yes OS=windows mode=debug -c
  • For release clean:
scons MSTOOLKIT=yes OS=windows -c

Alternate Scons File

Please actually read this file, it's easy to understand and will require some modification for use.

# A Linux Ogre/CEGUI/OIS/OgreOde build Script by Grey, with many thanks to keir from #scons on freenode.# Setup our Build Environment, Smarter scripts might be able to change this at the command line,env = Environment(   CCFLAGS='-ggdb -pg -g3 -DEXT_HASH',   LDFLAGS='-pg')# Our External Libs# Got some fugly stuff ( || true ) in there to supress unreadable crashes, it# ends up using the nicer formatted error messages below env.ParseConfig('pkg-config --silence-errors --libs --cflags OGRE || true')env.ParseConfig('pkg-config --silence-errors --libs --cflags OIS || true')env.ParseConfig('pkg-config --silence-errors --libs --cflags CEGUI-OGRE || true')env.ParseConfig('pkg-config --silence-errors --libs --cflags OgreOde_Core || true')# Get out current config so we can verify we have everything we need.# There is an autoadd method here, but then we'd have to specify full paths for # the libs and headers, which is lame.config = Configure(env);# Everyone needs OIS :)if not config.CheckLibWithHeader('OIS', 'OISPrereqs.h', 'C++'): print 'OIS must be installed!' Exit(1)# this should work to get Ogre includedif not config.CheckLibWithHeader( 'OgreMain', 'Ogre.h', 'C++' ): print "Ogre Must be installed!" Exit(1)# Any other component libraries you use can be added and tested in this mannerif not config.CheckLibWithHeader( 'OgreOde_Core', 'OgreOde_Core.h', 'C++'): print 'OgreOde must be installed!' Exit(1);# Substitute with your GUI of choiceif not config.CheckLibWithHeader('CEGUIBase', 'CEGUI.h', 'C++'): print "You need CEGUI to compile this program" Exit(1);if not config.CheckLibWithHeader('CEGUIOgreRenderer', 'OgreCEGUIRenderer.h', 'C++'): print "You need OGRE-CEGUI to compile this program" Exit(1);# Validate the configuration and assign it to our envenv = config.Finish(); # Build our main programenv.Program(   target = 'main',   # Replace these with your source files of course   source = [       'main.cpp', 'GUISystem.cpp', 'EventQueue.cpp', 'InputManager.cpp',       'CommandListener.cpp', 'CameraController.cpp', 'KeyMap.cpp',       'OdeManager.cpp', 'PhysModel.cpp', 'ODECharacterController.cpp', 'RayCharacterController.cpp',       'ChaseCameraController.cpp'])

Eclipse

See the Eclipse setup pages for Ogre IDE Eclipse.

Anjuta IDE

A complete working project and sample can be found here: http://waxor.com/page/ogre-dome.tgz

  1. Create a new Generic/Terminal App project.
  2. Choose c++ and Executable target when prompted.
  3. Delete all of the included template code in main.cc. It will be replaced with the sample code below.
  4. Go to the Settings Menu and choose Compilier and Linker Settings.
  5. Open the following tabs and add each entry one line at a time: replace $OGRE_HOME/ with the full path to the ogrenew folder you compiled from. Also note you may have Ogre in /usr/local/include and /usr/local/lib depending on how you installed it.
Include Paths:
        $OGRE_HOME/Samples/Common/include        /usr/include/OGRE               (Not necessary if you include like this '#include <OGRE/Ogre.h>')        /usr/include/CEGUI        /usr/include/OIS
Library paths:
        /usr/local/lib
Libraries:
        OgreMain        CEGUIBase        CEGUIOgreRenderer        OIS
Options
         check "Enable Debugging" (adds -g to the command line)
Options | Compilier flags (CFLAGS):
        -DEXT_HASH

KDevelop IDE

KDevelop is a nice flexible IDE for Linux, and it is easy to set up with OGRE.

  • Create a new C++ "Simple Hello world program" project.
  • Open "configure.in" and add the following line above the AC_OUTPUT statement.
PKG_CHECK_MODULES(OGRE, [OGRE >= 1.2.0])
  • Open "src/Makefile.am" and add the following lines.
LDADD = @OGRE_LIBS@AM_CXXFLAGS = @OGRE_CFLAGS@ 
  • To avoid linker errors, add these lines to src/Makefile.am
sampleapp_LDADD = /usr/local/lib/libOIS.so \/usr/local/lib/libOgreMain.so
  • You may need to change /usr/local/lib/ to the location of your OGRE/OIS libs. Also, you if you get errors about missing libs later, you will have to link/copy them to /lib or /lib64.
  • You may wish to have the program run in the sample apps directory when debuging so you do not have to copy all the runtime resource files over. To do this go into project options (top menu) then click run options, then select the custom directory option and put in "<insert ogre root dir here>/Samples/Common/bin/"
  • If you choose to derive your application from the ExampleApplication class that comes with OGRE, open the automake manager, right click on your target, choose "Add Existing Files..." and add the files ExampleFrameListener.h and ExampleApplication.h from ogrenew/Samples/Common/include.
  • You also need to tell KDevelop where to find the OGRE specific headers. Click on Project->Project Settings->Configure Options, click on the C++ tab and add the following line to "Compiler flags (CXXFLAGS)" :

-I <insert ogre root dir here>OgreMain/include -I <insert ogre root dir here>OgreMain/include/GLX

  • Insert the SampleApp code below for the application, build and run the project.
  • To use the debugger, open the projects options, choose the debugger tab and select "Enable separate terminal for application IO".

Cross compiling Win32 applications in Linux

How to compile applications for MS Windows platform from within Linux: Article.

Your First Application

Now we will create a basic source file for starting an OGRE application. This program, like the included samples, uses the example framework.


Copy the following code and include it as a new file in your project settings. Following our conventions, you'd put it in work_dir/src and name it SampleApp.cpp. Since this is dependent upon ExampleApplication.h and ExampleFrameListener.h make sure these files are accessible by your project. Our convention would have you put them in work_dir/include. You can copy them from the Samples directory.

#include "ExampleApplication.h"// Declare a subclass of the ExampleFrameListener classclass MyListener : public ExampleFrameListener{public:    MyListener(RenderWindow* win, Camera* cam) : ExampleFrameListener(win, cam)    {    }    bool frameStarted(const FrameEvent& evt)    {        return ExampleFrameListener::frameStarted(evt);            }    bool frameEnded(const FrameEvent& evt)    {        return ExampleFrameListener::frameEnded(evt);            }};// Declare a subclass of the ExampleApplication classclass SampleApp : public ExampleApplication {public:   SampleApp()    {   }protected:   // Define what is in the scene   void createScene(void)   {       // put your scene creation in here   }     // Create new frame listener   void createFrameListener(void)   {       mFrameListener = new MyListener(mWindow, mCamera);       mRoot->addFrameListener(mFrameListener);   }};#ifdef __cplusplusextern "C" {#endif#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 #define WIN32_LEAN_AND_MEAN #include "windows.h" INT WINAPI WinMain(HINSTANCE hInst, HINSTANCE, LPSTR strCmdLine, INT) #else int main(int argc, char **argv) #endif {    // Instantiate our subclass    SampleApp myApp;    try {        // ExampleApplication provides a go method, which starts the rendering.        myApp.go();    }    catch (Ogre::Exception& e) {#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32         MessageBoxA(NULL, e.getFullDescription().c_str(), "An exception has occured!", MB_OK | MB_ICONERROR | MB_TASKMODAL);#else        std::cerr << "Exception:\n";        std::cerr << e.getFullDescription().c_str() << "\n";#endif        return 1;    }return 0;}#ifdef __cplusplus}#endif

Compile this code now. However before running the program, make sure you have a plugins.cfg and a resources.cfg in the same directory as the executable. Review the Prerequisites section for the purpose of these files. Edit them and make sure the paths are correct. Otherwise your OGRE setup dialog box may not have any rendering libraries in it, or you may recieve an error on your screen or in Ogre.log that looks something like this:

Description: ../../Media/packs/OgreCore.zip - error whilst opening archive: Unable to read zip file

When the program starts it will display the OGRE setup dialog and start the application with a blank, black screen containing little more than the OGRE logo and an FPS (frame per second) display. We haven't added anything to this scene yet, as evidenced by the empty createScene method. Press ESC to quit the application.

If you didn't get this, something is not right in your setup. See the Prerequisites and the Getting Help sections to review your installation.

The ExampleApplication framework will boot the OGRE system, displaying a configuration dialog, create a window, setup a camera and respond to the standard mouselook & WSAD controls. All you have to do is to fill in the 'createScene' implementation. If you want to do more advanced things like adding extra controls, choosing a different scene manager, setting up different resource locations, etc, you will need to override more methods of ExampleApplication and maybe introduce a subclass of ExampleFrameListener.

As mentioned before, you don't have to use the ExampleApplication and ExampleFrameListener base classes. Use them to work through the tutorials and to test things out. For larger projects you'll want to write your own framework, or use one of the frameworks or engines available on Projects using OGRE.

Note for American readers

Sinbad the lead developer and creator of OGRE, is British. Naturally he uses British spellings such as "Colour", "Initialise" and "Normalise". Watch out for these spellings in the API.

See below to learn about your resources for getting help. Then your next step is to work through the Ogre Tutorials.

Getting Help

Probably the top two problems people have with Ogre are not being able to compile or a missing dependency. For the first, you are going to need to learn how to use your compiler. If you barely know C++ then expect a challenge, but don't give up! Thousands of people have successfully gotten Ogre to work with both the GCC and MSVC compilers, so look in the wiki and forums for what they have done that you haven't. For missing dependencies, these are libraries that aren't installed, that aren't linked against your program, or that aren't in your runtime path. Other dependencies are incorrect rendering plugins in your plugins.cfg file or incorrect paths in your resources.cfg file, or missing one of the files all together.

If you have problems reread this page as well as Installing An SDK and Building From Source and look in the Ogre.log file. You may also find your problem answered in the Build FAQ. If you need further help, search the forums. It is likely your problem has happened to others many times. If this is a new issue, read the forum rules then ask away. Make sure to provide relevant details from your Ogre.log, exceptions, error messages, and/or debugger back traces. Be specific and people will be more able to help you.

JScript 란?

 
 JavaScript를 기초로 하여 만든 언어이다. JScript 도 VBScript 와 같이 일괄작업 처리 프로그래밍

언어 이지만, 요즘엔 의미가 모호해져 JavaScript=JScript 의 의미로 쓰인다.


[출처]
VBScript의 기초|작성자 김병진

c - 포인터의 이해

- 포인터의 선언

*** 포인터 변수임을 알리는 '*'는 뒤에 따르는 포인터 변수가 가르키는
메모리 공간속의 실질적인 값이다.
*** '&'는 뒤에 따르는 변수의 주소값을 나타낸다.

데이터형 *변수이름;
  ex)  int *temp;

기본적인 사용 예)
 int *temp;    //  정수형의 temp 포인터 변수의 선언.
 int a = 10;    //  정수형의 변수 a에 10의 값을 대입.
 temp = &a;    // 'a'의 주소값을 temp에 대입.
 printf("%d", *temp)  // *temp의 값을 출력한다.

 -> 추리순서 1)  temp의 값에는 a의 물리적인 주소값이 입력된다.
                   2)  temp는 a의 물리적인 주소값을 가지고 있다.
                   3)  '*'는 실질적인 값을 나타낸다.
                   4)   temp는 a의 주소값을 가지는데, '*temp'라고 하면
                        temp의 주소값이 가지는 실질적인 값이 된다.
     
         결국, '*temp'는 'a'와 동일한 값을 가진다.

**주의할 점
 포인터 변수인 temp의 데이터 형은 실제로 포인터 변수가 가리키게 될 대상인
a의 데이터 형과 일치해야 한다!

**포인터의 기본개념
데이터가 있는 메모리 주소를 기억하고 있다가, 필요할 때 참조하겠다는 의미.

**포인터의 사용이유
대상의 메모리 주소를 참고하여, 물리적인 메모리에 직접 접근함으로 인해,
처리 속도를 향상시킬 수 있다.
                   
  

◀ PREV 123 NEXT ▶