Buy us Beer
Categories
Pages

Augmented reality on the iPhone using NyARToolkit [w/ code]

nyarrrHi

I saw the stats for the blog a while ago and it seems that the augmented reality topic is hot! 400 clicks/day, that’s awesome!

So I wanted to share with you my latest development in this field – cross compiling the AR app to the iPhone. A job that proved easier than I originally thought, although it took a while to get it working smoothly.

Basically all I did was take NyARToolkit, compile it for armv6 arch, combine it with Norio Namura’s iPhone camera video feed code, slap on some simple OpenGL ES rendering, and bam – Augmented Reality on the iPhone.

This is how I did it…

I recommend you read my last post on this matter. I have some insights, however superficial, to working with NyARToolkit implementation for C++, that I also use here.

Getting NyARToolkit C++ to compile on iPhone

First of all, I needed to cross-compile NyARToolkit for iPhone’s CPU architecture (Arm), but this was a very simple task – it just compiled off the bat! No tweaking done, what so ever.
But that’s only the beginning, as iPhone apps are built using Objective-C and not C++ (maybe they can, but all the documentation is in obj-c). So I needed to write an Obj-C wrapper around NyARTk to allow my iPhone app to interact with it.

I only needed a very small set of functions out of NyARTk to get Aug.Reality – those that have to do with marker detection. I ended up with a lean API:

@interface NyARToolkitWrapper : NSObject {
	bool wasInit;
}

-(void)initNyARTwithWidth:(int)width andHeight:(int)height;
-(bool)detectMarker:(float[])resultMat;
-(void)setNyARTBuffer:(Byte*)buf;
-(void)getProjectionMatrix:(float[])m;

I also have some functions I used for debugging, and non-optimized stages. The inner works of the wrapper are not very interesting (and you can see them in the code yourself), they are mainly invoking NyARSingleDetectMarker functions.

In the beginning – there was only marker detection

OK, to get AR basically what I need to do is:

  1. initialize NyARTk inner structs
  2. set NyARTk’s RGBA buffer with each frame’s pixles
  3. get the extrinsic parameters of the camera, and draw the OpenGL scene accordingly

This is for full fledged AR, but let me start with a simpler case – detecting the market in a single image read from a file. No OpenGL, no camera. Just reading the file’s pixels data, and feeding it to NyARTk.

Now this is far more simple:

CGImageRef img = [[UIImage imageNamed:@"test_marker.png"] CGImage];
int width = CGImageGetWidth(img);
int height = CGImageGetHeight(img);
Byte* brushData = (Byte *) malloc(width * height * 4);
CGContextRef cgctx = CGBitmapContextCreate(brushData, width, height, 8, width * 4, CGImageGetColorSpace(img), kCGImageAlphaPremultipliedLast);
CGContextDrawImage(cgctx, CGRectMake(0, 0, (CGFloat)width, (CGFloat)height), img);
CGContextRelease(cgctx);

[nyartwrapper initNyARTwithWidth:width andHeight:height];
[nyartwrapper setNyARTBuffer:brushData];
[nyartwrapper detectMarker:ogl_camera_matrix];

First I read the image to UIImage, then get it’s respective CGImage. But what I need are bytes, so I create a temporary CGBitmapContext, draw the image into it and use the context pixel data (allocated by me).

Adding the 3D rendering

This is nice, but nothing is shown to the screen, which sux. So the next step will be to create an OpenGL scene, and draw some 3D using the calibration we now have. To do this I used EAGLView from Apple’s OpenGL ES docs.
This view will setup an environment to draw a 3D scene, by giving you a delegate to do the actual drawing while hiding all the perepherial code (frame buffers… and other creatures you wouldn’t want to meet in a dark 3D alley scene).

All I needed to implement in my code were two functions defined in the protocol:

@protocol _DGraphicsViewDelegate<NSObject>

@required

// Draw with OpenGL ES
-(void)drawView:(_DGraphicsView*)view;

@optional
-(void)setupView:(_DGraphicsView*)view;

@end

’setupView’ will initialize the scene, and ‘drawView’ will draw each frame. In setupView we’ll have the viewport setting, lighting, generating texture buffers etc., You can see all that in the code, it’s not very interesting…

In drawView we’ll draw the background and the 3D scene. Now this took some trickery. First I though i’ll take the easy route and just have the 3D scene be transparent, draw the view using a simple UIView of some kind, and overlay the 3D over it. I didn’t manage to get it to work, so I took a different path (harder? don’t know) and I decided to paint the background over a 3D plane, in the 3D scene itself, using textures. This is how I did it in all my AR app on other devices.
Now, the camera video feed is 304×400 pixels, and OpenGL textures are best optimized at power-of-2 sizes, so I created a 512×512 texture. But for now we’re talking about a single frame.

const GLfloat spriteTexcoords[] = {0,0.625f,   0.46f,0.625f,   0,0,   0.46f,0,};
const GLfloat spriteVertices[] =  {0,0,0,   1,0,0,   0,1,0   ,1,1,0};

glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
glOrthof(0, 1, 0, 1, -1000, 1);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();

// Sets up pointers and enables states needed for using vertex arrays and textures
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3, GL_FLOAT, 0, spriteVertices);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glTexCoordPointer(2, GL_FLOAT, 0, spriteTexcoords);	

glBindTexture(GL_TEXTURE_2D, spriteTexture);
glEnable(GL_TEXTURE_2D);

glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);

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

Basically, I go into orthographic mode and draw a rectangle with the texture on it, nothing fancy.

Next up – drawing the perspective part of the scene, the part that aligns with the actual camera…

//Load the projection matrix (intrinsic parameters)
glMatrixMode(GL_PROJECTION);
glLoadMatrixf(ogl_projection_matrix);

//Load the "camera" matrix (extrinsic parameters)
glMatrixMode(GL_MODELVIEW);
glLoadMatrixf(ogl_camera_matrix);

glLightfv(GL_LIGHT0, GL_POSITION, lightPosition);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);

glDisable(GL_TEXTURE_2D);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);

glPushMatrix();	

glScalef(kTeapotScale, kTeapotScale, kTeapotScale);

{
        static GLfloat spinZ = 0.0;
        glRotatef(spinZ, 0.0, 0.0, 1.0);
        glRotatef(90.0, 1.0, 0.0, 0.0);
        spinZ += 1.0;
}

glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
glVertexPointer(3 ,GL_FLOAT, 0, teapot_vertices);
glNormalPointer(GL_FLOAT, 0, teapot_normals);
glEnable(GL_NORMALIZE);

for(int i = 0; i < num_teapot_indices; i += new_teapot_indicies[i] + 1)
{
        glDrawElements(GL_TRIANGLE_STRIP, new_teapot_indicies[i], GL_UNSIGNED_SHORT, &new_teapot_indicies[i+1]);
}

glPopMatrix();

For this also I learned from Apple’s OpenGL ES docs (find it here). I ended up with this:
Picture 5

Tying it together with the camera

This runs on the simulator, since the camera is not involved just yet. I used it to fix the lighting and such, before moving to the device. But we’re here to get it work on the device, so next I plugged in the code from Norio Nomura.
Some people have asked me to post up a working version of Nomura’s code, so you can get it with the code for this app (scroll down). Nomura was kind enough to make it public under MIT license.

First, I set up a timer to fire in ~11fps, and initialize the camera hook to grab the frames from the internal buffers:

repeatingTimer = [NSTimer scheduledTimerWithTimeInterval:0.0909 target:self selector:@selector(load2DTexFromFile:) userInfo:nil repeats:YES];

ctad = [[CameraTestAppDelegate alloc] init];
[ctad doInit];

And then I take the pixel data and use it for the background texture and the marker detection:

-(void)load2DTexWithBytes:(NSTimer*) timer {
	if([ctad getPixelData] != NULL) {
		CGSize s = [ctad getVideoSize];
		glBindTexture(GL_TEXTURE_2D, spriteTexture);
		glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, s.width, s.height, GL_BGRA, GL_UNSIGNED_BYTE, [ctad getPixelData]);

		if(![nyartwrapper wasInit]) {
			[nyartwrapper initNyARTwithWidth:s.width andHeight:s.height];
			[nyartwrapper getProjectionMatrix:ogl_projection_matrix];

			[nyartwrapper setNyARTBuffer:[ctad getPixelData]];
		}

		[nyartwrapper detectMarker:ogl_camera_matrix];
	}
}

All this happens 11 times per second, so it must be concise.

Video proof time…

Well, looks like we are pretty much done! time for a video…

How did you get the phone to stand still so nicely?

An important issue… when it comes to shooting the phone w/o holding it.
Well I used a little piece of metal that’s used to block the PCI docks in the PC. In hebrew will call these scrap metal “Flakch”s (don’t try to pronounce this at home). I bended it in the middle to create a kind of “leg”, and the ledge to hold the phone already exists.
metal iPhone stand

The code

As promised, here’s the code (I omitted some files whose license is questionable).

That’s all folks!
See you when I get this to work on the Android…
Roy.

  • Share/Bookmark

59 Responses to “Augmented reality on the iPhone using NyARToolkit [w/ code]”

  • micah:

    Hey man, great post. Was gonna try implementing it myself, but was wondering if you did this with the SDK or with the open toolchain? If you were using SDK can you post the .xcodeproj file? Thanks.

  • Roy:

    Hi micah

    I did use the SDK (v2.1) for this, but with a small hack to use the internal camera buffers to get the frames in real-time speeds (Norio Nomura’s code).

    I can’t post the xcodeproj file, and I think you don’t really need it.
    All the code exists, so just add the .m, .mm and .cpp files to a new project in xcode and you’re golden.

    One more thing, I hear (and see) people doing augmented reality on the iPhone OS v3.x. So maybe Apple have released the camera APIs to the “public”, and the hack is no longer needed. I havn’t got to trying it myself, but it’s worth looking into.

    Good luck,
    Roy

  • Hi!
    I’m trying to download the code, but it seems that the link is not working.
    In the mean time I’ll try to follow step-by-step what you wrote to get it to work on my iPhone…
    By the way, any news on the iPhone OS v3.x camera APIs?

    Thanks,
    Daniele

  • Alex:

    Hey

    Very nice post . I also looked at the code and put it on Xcode and tried to compile it but i get errors in the NyARToolkitWrapper.mm . It doesn’t seem to recognize all the c++ syntax. Am I doing something wrong ?

    Thanks and keep up the good work

  • Roy:

    Hi

    The code is available via Google Code: http://code.google.com/p/morethantechnical/source/browse/#svn/trunk/NyARToolkit-iPhone
    Their site might be down…

    I haven’t yet explored the camera APIs of 3.0, but I imagine it will not be too different.
    The only change to do is manage how to get the camera’s video frame bytes, and the rest should stay the same.

    If you do get it to work with 3.0, please let me know

    Good luck
    Roy

  • [...] Augmented reality on the iPhone using NyARToolkit [w/ code] [...]

  • Eddy:

    Hey Roy,
    great post.
    I’ve been trying to build your code in XCode with no luck. I took all files threw them into an xcode project but I seem to be missing 3DGraphicsView.h.
    Is this part of a framework that I need to include?

    Any advice appreciated.

    thanks,
    Eddy

  • Roy:

    Hi Eddy
    The file is indeed missing. I noted in the post that removed files with questionable license, and this file comes from apple’s user guides and has a strict license.
    You can find the file in here (the link also appears in the post in “Adding 3D rendering”). Its the same file only the name was changed.

    good luck
    Roy

  • kimmy:

    Hi, I just got the code. Thank you first. Do i need cross-compile the library? If that, could you tell me how to cross-compile the library?

  • kimmy:

    Another thing is where is the file “teapot.h”?

  • Roy:

    Hi kimmy

    First, you are cross-compiling the NyARToolkit code if you do as instructued in the post (attach all the C++ code to the XCode project).
    Second, the teapot.h file comes from Apple’s documentation. (http://developer.apple.com/iphone/library/samplecode/GLGravity/listing6.html)

    good luck
    Roy

  • Ambroz:

    I have a problem with a missing file I suppose as a get the following error: _DGraphicsView undeclared.

    Any help appreciated

  • Ambroz:

    Has anyone managed to create a functional xCode project? Please post it. I just get too many errors if I import posted classes.

  • kimmy:

    Thank you for your fast responding!
    Yes, I should include all the c++ files and it pass compiling even if it reports warning: no rule to process file ‘$(PROJECT_DIR)/Classes/Classes/NyARToolkit/forLinux/libNyARToolkit/makefile’ of type sourcecode.make for architecture armv6

    Could I ask another question on the view” _DGraphicsView” which you defined in the program? Does it point to the EAGLView? I replace the 3DGraphicsView.h with the EAGLView.h, add your protocol into the EAGLView.h and delete its own drawview and setupview functions. Am i right in doing this? I cannot wait to see the teapot now! Thank you

  • kimmy:

    Hi I found the file used for implement the missed view. It is in the project GLGravity. I replace my view file with that file, but I still get nothing in my screen. It gives me a error “501 error” when i first draw the view.

  • Roy:

    Hi

    kimmy, I don’t know this “501 error”, perhaps it has a description or something a little more informative?

    Ambroz, I cannot post the XCode project file as it has information I’m not allowed to disclose by law.

    It shouldn’t be hard (I tried it myself) just add:
    - all the files to the project,
    - the PhotoLibrary private framework,
    - the 3DGraphicsView, which is exactly EAGLView from Apple’s docs with the name changed.
    and you’re good to go.

    Of course, it might take some tinkering around with the code, but it’s doable and you’ll learn a lot in the process.

    Good luck
    Roy.

  • kimmy:

    I am pretty sure there is the 501 error occuring at the following code.

    CGRect rect = view.bounds;//the following size is not right and generate an error
    glFrustumf(-size, size, -size / (rect.size.width / rect.size.height), size / (rect.size.width / rect.size.height), zNear, zFar);
    glViewport(0, 0, rect.size.width, rect.size.height);

    It is defined as GL_INVALID_VALUE. More information can be found at the following link:
    http://pyopengl.sourceforge.net/documentation/manual/glCopyTexImage2D.3G.html

  • kimmy:

    Could the problem be caused by the image size?:
    CGImageRef img = [[UIImage imageNamed:@"IMG_0020_small.png"] CGImage]; Because I don’t have this image file so I replace it with a different one

  • kimmy:

    Hi

    I change the znear from -1000 to 0.1 and the 501 error not there any more but I cannot see any animation for the image I choose. Even if I use an ipod touch I think I still can get an basic animation without camera, right? Sorry for so many questions.

  • Ambroz:

    OK, I am now stuck at the only error left:

    extra qualification”NYArtToolKitCPP::NyARDoubleMatrix33::” on member createArray

    How to solve that one?

  • Ambroz:

    Another problem:

    duplicate symbol _spriteVertices in

    build/CameraTest.build/Release-iphonesimulator/CameraTest.build/Objects-normal/i386/EAGLView.o

    and

    build/CameraTest.build/Release-iphonesimulator/CameraTest.build/Objects-normal/i386/NyARToolkitCrossCompileAppDelegate.o

  • Roy:

    Hi again guys

    Ambroz, you can try changing the name of the duplicate symbol so the compiler won’t scream at you.
    As for the NyARDoubleMatrix33, I don’t know, you’ll have to play around with the code to make it work.

    kimmy, I was able to get marker detection on a single image on the simulator (no camera needed).

    Anyway, I can’t really provide insight into your problems because I didn’t run into them myself, and I can’t reproduce them on my setup.
    My advice is – don’t give up. Keep trying to make it work and you’ll succeed.
    I think both of you are very close to getting it to work.
    Try to work incrementally like I did: first only marker detection w/o graphics at all (print results to console), then a single picture marker detection with the teapot, only then integrate camera.

    Good luck
    Roy

  • kimmy:

    Thank you Roy.

    Ambroz, for the problem ”NYArtToolKitCPP::NyARDoubleMatrix33::”, just delete the NYArtToolKitCPP::
    You may need delete the duplicate symbol in EAGLView file if you use it. You also need take a look at the view at the below link.
    http://developer.apple.com/iphone/library/samplecode/GLGravity/listing6.html

  • kimmy:

    Hi Roy

    Could you tell me what version the code works on? I know the camera part does not work for iphone OS 3.0. How about NyArttookit?

  • Roy:

    Hi kimmy
    NyARToolkit will work on any version, since your are building it from source and the compiler makes sure it works properly.
    For camera, iPhoneOS 3.1 should allow superimposing over live video feed from the camera, although I haven’t got to actually trying it (I will soon). Right now I got it to work on 2.1 and 2.2.1, using the camera callback hack.

    Roy.

  • Ambroz:

    Roy, one more question. In NyARToolkitCrossCompileAppDelegate.m method ApplicationDidFinishLaunching you set a delegate to EAGLView instance, but I get an error that says: request for member ‘delegate’ in something not a structure of union.
    Have you defined the delegate yourself?

    EAGLView *glView = [[EAGLView alloc] initWithFrame:rect];

    glView.delegate = self; ????

  • Ambroz:

    Well, I declared the @property (assign, nonatomic) id delegate; but app still crashes at glDeleteFramebuffersOES. It’s so frustrating.

  • Roy:

    Ambroz,
    Please use GLGravityView code from here

    The delegate is declared properly there (EAGLView is missing the delegate protocol declaration), it should work fine with the project.

    Roy.

  • Ambroz:

    Thanks for all your help. I managed to get as far as kimmy did. Roy, could you post your image “IMG_0020_small.png”, as my app threw exception after I replaced it by “hiro.png”. Or just post the url where you got the picture. Thanks

  • kimmy:

    Hi

    The camera code owner said he will not work on iphone os 3.0 or later version. I cannot get a camera view with his code now.

    I changed the code a lot and finally can detect the marker according to console output information. I am not sure if I did this right because I cannot get the result the same as the picture you show in the blog. Can you get the result the same as that in your blog’s picture just for image detection? I only can get a dark teapot rotating in front of a big “hiro” image in my ipod touch.

  • Roy:

    Good news kimmy, you are on the way…
    Your problem is with the lighting of the teapot? I think I mention something about it
    Indeed the lighting issue was complicated, it took a while until I got it right
    Make sure you’re enabling GL_LIGHTING and GL_LIGHT0, the position of the light is correct, and the material of the teapot is defined and applied (all this is in the beginning of NyARToolkitCrossCompileAppDelegate.m file)

    Ambroz, good job!
    For the picture, I took it myself with the iPhone’s camera.
    I suggest you print out a “hiro” marker yourself and attach it to a cardboard for easy manipulation.
    Anyway, here’s the picture, you can resize it to be smaller (300×400).

    Good luck guys!
    Roy.

  • Ambroz:

    kimmy could you email me the camera classes for OS 3.0 (ambroz[dot]homar[at]gmail[dot]com)? I’d really love to see how it works on iPhone!

  • kimmy:

    Hi Roy

    i use your picture and get a pretty close screen as yours, but the console shows that I fail to detect the image because it still offset a little of correct position. If possible, could you give me a email so that I can send you a snapshot. Maybe you can give me some clue on how to adjust the position. If not, it is ok. Thank you again. It is indeed a fun learning experience even if sometimes it is really frustrated.

    Hi Ambroz
    It is not for iphone os 3, but you can test it on iphone os 2 if you can use it with a camera.
    http://github.com/norio-nomura/iphonetest/tree/9713242dda6c6bc897da4bd639a1fdadc29b6fd7/CameraTest

  • kimmy:

    Hi Roy,

    I got it!!

    Your code has no problem. The only problem is you do not mention we need a image file you just post yesterday. Now it works well even if I still have no idea about the data file, camera file, and code file and their relationship with the library. Maybe you can explain them on next post. That will be much useful for learning this library. Thank you again! Nice job!

  • kimmy:

    Hi Roy,

    The image marker can be detected, but the teapot is still not at the center of the image. Why does it happen? What should I do so that I can adjust the position of the teapot?

  • Jon:

    So what devices (iPhone v1, 3G, 3GS) and OS’s (3.0, 3.1beta) have people gotten this to work on?

  • Roy:

    Hi Jon
    This works on any iPhone that runs OS 2.X (no support for 3.X yet, the camera private code needs to be hacked again).

    Roy.

  • Fawad:

    Hello,
    Thanks for a wonderful code. I am building the code iphone sdk 3.0
    But its throwing the following error. Kindly help me

    Command /Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/g++-4.2 failed with exit code 1

  • Roy:

    Hi Fawad

    This error does not supply any information as to what went wrong, only that the compiler wasn’t able to compile the code.
    Please supply the full error (the part that says which file and line is erroneous)

    Roy.

  • Fawad:

    Hello Roy,
    I have solved that problem,
    But roy the app is still throwing the 501 error

  • Fawad:

    Hey Roy,
    the app is throwing Bad access exception here

    in this method
    void NyARRasterFilter_ARToolkitThreshold::convert32BitRgbx(const NyAR_BYTE_t* i_in, int* i_out, const TNyARIntSize* i_size)const

    in this file.
    NyARRasterFilter_ARToolkitThreshold.cpp

    when i commented the code in this block, it runs just fine, but its only displaying the hiro.png on full screen, not the camera

  • Fawad:

    Hello Roy,
    can u tell me that which is the default delegate file to be used in Mainwindow.xib?
    CameraTestDelegate or NyARToolKitDelegateApp?

  • Fawad:

    somebody please upload the project or individual files, I need help :(
    I will be very thankful.

  • Roy:

    The NyARToolKitDelegateApp is the main delegate for the app.

    Roy.

  • Nico:

    Hi! has anybody got it working on iPhone OS 3.x??

  • noflux:

    Does any one has a working project on iPhone OS 3.x?

  • Hello Roy,

    I followed all the instructions of the comments above and I did compile
    your code successfully. However, every time I run it, it gives me a error “501 error” too.

    I discovered that the 501 error occurs in the setupView. To make sure, I put your setupView in the GLGravity project and the 501 error also occurs on that project.

    I’m running the code in the iPhone simulator 2.2, I want to ask what is the project behavior in the simulator. I was wondering if this code only runs on iPhone device 2.2..

    I also tried running the code on the device 3.1 but the same error occurred.. I do not know if it occurs because of any dependency on the camera.

  • Wes:

    Hey Roy,

    First of all, thanks a lot for sharing your findings with us!

    I’m trying to compile your code, but I’m currently stuck on a single error.
    I’ve followed every ’step’, imported your classes into a clean app.
    Then I created a 3DGraphicsView.h file based on GLGravityView.h/EAGLView.h, and added this code to it to declare the protocol:

    @protocol _DGraphicsViewDelegate
    @required
    // Draw with OpenGL ES
    -(void)drawView:(_DGraphicsView*)view;
    @optional
    -(void)setupView:(_DGraphicsView*)view;
    @end

    Now I keep running into this single error:
    “NyARToolkitCrossCompileAppDelegate.m:295: error: request for member ‘delegate’ in something not a structure or union”

    I’m quite stuck, and can’t figure out what’s wrong. I really need this to work, as it’s part of my graduation project which I want to demo/proof of concept.
    Can anyone help me out please?

  • Wes:

    Oh, FYI, the beforementioned error links to this line (NyARToolkitCrossCompileAppDelegate.m:295)

    glView.delegate = self;

  • Wes:

    I think I managed to solve the issue, I didn’t declare the delegate properly in the 3dGraphicsView header file or so it seemed.

    Now it compiles fine, yet I don’t see anything when the app starts. No camera-feed, no nothing. Just a black screen with a gray statusbar which shouldn’t even be there.
    The thing is, when I redirect the delegate file in Mainwindow.xib back to CameraTestAppDelegate I DO get a camera feed.

    Also, you mention some posts before that the default delegate file should be NyARToolKitDelegateApp, however I don’t ee such a file in your source code. There’s only a NyARToolKitCrossCompileAppDelegate , is this the file you mention or am I missing some files?

    Sorry to bother with all these questions, it’s just rather important for me to get a demo of this working for my exam next week ;)

Leave a Reply