iPhoneのサンプルプログラム その3

SATCHを用いたナビアプリ(1)

dispALL2.lua(SATCHのスクリプト)
local MLTPlugin = getMLTPluginManager()
local scene = getCurrentScene()
local camera = Camera(scene:getCurrentCamera())
local vidCap = VideoCapture(scene:getObjectByName("vidcap"))
local msg = Text2D(scene:getObjectByName("msg"))
local stage_no = Text2D(scene:getObjectByName("stage"))
	
local componentInterface = getComponentInterface()
	
local err_ret = eOk
local trackingIndex = -1
local targetStatus = {-1, -1, -1}
local action = {
"1101    found!", "1102    found!", "1103    found!",
"1104    found!", "1105    found!", "1106    found!",
"1107    found!", "1108    found!", "1109    found!",
"1110    found!", "1111    found!", "1112    found!",
"1113    found!", "1114    found!", "1115    found!",
"1116    found!", "1117    found!" }
local marker_no = {
1101, 1102, 1103,
1104, 1105, 1106,
1107, 1108, 1109,
1110, 1111, 1112,
1113, 1114, 1115,
1116, 1117
}
	
local found = -1
local i=0
local stage = 1
local found_marker = -1
local cand = 3
	
local dest = -1;
	
msg:setText("Marker   please!")
stage_no:setText("stage=1")
	
err_ret, trackingIndex = MLTPlugin:startTracking("B1/tracker.xml", vidCap:getVidCapID(), camera)
	
function gotoStage(n)
	MLTPlugin:stopTracking(trackingIndex)
    
	stage = n
	
	if n == 1 then
		stage_no:setText("stage=1")
		err_ret, trackingIndex = 
			MLTPlugin:startTracking("B1/tracker.xml", vidCap:getVidCapID(), camera)
	elseif n == 2 then
		stage_no:setText("stage=2")
		err_ret, trackingIndex =
			MLTPlugin:startTracking("B2/tracker.xml", vidCap:getVidCapID(), camera)
	elseif n == 3 then
		stage_no:setText("stage=3")
		err_ret, trackingIndex =
			MLTPlugin:startTracking("B3/tracker.xml", vidCap:getVidCapID(), camera)
	elseif n == 4 then
		stage_no:setText("stage=4")
		err_ret, trackingIndex =
			MLTPlugin:startTracking("B4/tracker.xml", vidCap:getVidCapID(), camera)
	elseif n == 5 then
		stage_no:setText("stage=5")
		err_ret, trackingIndex =
			MLTPlugin:startTracking("B5/tracker.xml", vidCap:getVidCapID(), camera)
	elseif n == 6 then
		stage_no:setText("stage=6")
		err_ret, trackingIndex =
			MLTPlugin:startTracking("B6/tracker.xml", vidCap:getVidCapID(), camera)
	end
end
	
repeat
	
  if (found_marker < 0) then
	
		if stage <= 5 then
			cand = 3
		else
			cand = 2
		end
	
		for i = 1,cand do
    		err_ret, targetStatus[i] = MLTPlugin:getTargetStatus(trackingIndex, i-1)		
		end
	
		found = -1
		for i = 1,cand do
			if (targetStatus[i] == 1) then
				found = i
				break
			end
		end
	
		if (found ~= -1) then
			msg:setText(action[found + 3*(stage-1)])
			found_marker = marker_no[found + 3*(stage-1)]
		else
			if (stage == 1) then
				gotoStage(2)
			elseif (stage == 2) then
				gotoStage(3)
			elseif (stage == 3) then
				gotoStage(4)
			elseif (stage == 4) then
				gotoStage(5)
			elseif (stage == 5) then
				gotoStage(6)
			elseif (stage == 6) then
				gotoStage(1)
			end
 			coroutine.yield()
		end
    else
    	if (dest < 0) then
    		if componentInterface then
    			componentInterface:executeAppFunc("setStartPosition", found_marker);
    		end
    		dest = 1
    	end
	end
until coroutine.yield()

AppDelegate.h
#import <Foundation/Foundation.h>

#import "Spot.h"

@class ViewController;

@interface AppDelegate : UIResponder 

@property (strong, nonatomic) UIWindow *window;

@property (strong, nonatomic) ViewController *viewController;

@property (strong, nonatomic) UINavigationController *navController;

@property (strong, nonatomic) NSMutableArray *spots;

@property (retain, nonatomic) Spot *startSpot;

@property (retain, nonatomic) Spot *destSpot;

- (void)showInfo;

@end

AppDelegeta.mm
#import "AppDelegate.h"
#import "ViewController.h"
#import "Spot.h"

@implementation AppDelegate

@synthesize window = _window;
@synthesize viewController = _viewController;
@synthesize navController = _navController;
@synthesize spots = _spots;

@synthesize startSpot;
@synthesize destSpot;

- (void)dealloc
{
    [_window release];
    [_viewController release];
    [_spots release];
    [super dealloc];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    // Override point for customization after application launch.

    Spot *s1 = [[Spot alloc] init];
    s1.spotID = @"1";
    s1.spotName = @"入り口(K2号館側)";

    Spot *s2 = [[Spot alloc] init];
    s2.spotID = @"2";
    s2.spotName = @"入り口(マクドナルド側)";
    
    Spot *s1101 = [[Spot alloc] init];
    s1101.spotID = @"1101";
    s1101.spotName = @"西村(広)教員室(1101)";

    Spot *s1102 = [[Spot alloc] init];
    s1102.spotID = @"1102";
    s1102.spotName = @"春日教員室(1102)";

    Spot *s1103 = [[Spot alloc] init];
    s1103.spotID = @"1103";
    s1103.spotName = @"共通教員室(1103)";

    Spot *s1104 = [[Spot alloc] init];
    s1104.spotID = @"1104";
    s1104.spotName = @"富川研究室・山内研究室(1104)";

    Spot *s1105 = [[Spot alloc] init];
    s1105.spotID = @"1105";
    s1105.spotName = @"富川教員室(1105)";

    Spot *s1106 = [[Spot alloc] init];
    s1106.spotID = @"1106";
    s1106.spotName = @"谷中教員室(1106)";

    Spot *s1107 = [[Spot alloc] init];
    s1107.spotID = @"1107";
    s1107.spotName = @"谷中研究室(1107)";

    Spot *s1108 = [[Spot alloc] init];
    s1108.spotID = @"1108";
    s1108.spotName = @"佐藤研究室・鈴木(浩)研究室(1108)";

    Spot *s1109 = [[Spot alloc] init];
    s1109.spotID = @"1109";
    s1109.spotName = @"佐藤教員室(1109)";

    self.spots = [[NSMutableArray alloc] 
                  initWithObjects:s1, s2, 
                  s1101, s1102, s1103, s1104, s1105,
                  s1106, s1107, s1108, s1109, nil];
    
    self.viewController = [[[ViewController alloc] initWithNibName:@"ViewController" bundle:nil] autorelease];
    self.navController = [[UINavigationController alloc] 
                          initWithRootViewController:self.viewController];
    self.window.rootViewController = self.navController;
    
    [self.window makeKeyAndVisible];
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

- (void)showInfo
{
    self.viewController.txtMsg.text = [NSString stringWithFormat:@"出発地:%@, 目的地:%@",
                                        startSpot.spotName, destSpot.spotName];
}
     

@end

ViewController.h
#import <UIKit/UIKit.h>
#import "satchARViewer.h"
#import "Spot.h"

@interface ViewController : UIViewController {
    IBOutlet UIButton *btnCorner;
    SatchARViewer *mPlayer;
}

@property (retain, nonatomic) IBOutlet UIView *mRender;
@property (retain, nonatomic) IBOutlet UITextView *txtMsg;

- (IBAction)pushCornerButton:(id)sender;

- (void)start;
- (void)stop;

@end

ViewController.m
#import "AppDelegate.h"
#import "ViewController.h"
#import "DestController.h"

@interface ViewController ()

@end

@implementation ViewController
@synthesize mRender;
@synthesize txtMsg;

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"メイン画面";
    
    //メッセージのローカライズ
    [SatchARViewer        setDialogMessageLoading:@"ローディング..."];
    [SatchARViewer        setToastMessageNoNetworkConnection:@"ネットワークに接続されていません。"];
    [SatchARViewer        setToastMessageNetworkError:@"通信中にエラーが発生しました。"];
    [SatchARViewer        setToastMessageLicenceError:@"認証に失敗しました"];
    
    mPlayer = [[[SatchARViewer alloc] init] initialize:mRender];
    [self start];
    
    btnCorner.enabled = NO;
    txtMsg.text = @"出発地のマーカをかざしてください!";
	// Do any additional setup after loading the view, typically from a nib.
}

- (void)viewDidUnload
{
    [self setMRender:nil];
    [self setTxtMsg:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

- (void)dealloc {
    if (mPlayer) {
        [mPlayer terminate];
        [mPlayer release];
        mPlayer = nil;
    }
    
    [mRender release];
    [txtMsg release];
    [super dealloc];
}

- (void)start
{
    if (mPlayer) {
        [mPlayer loadScenario:@"Nov4_iphone/Nov4.dpd"
                     callback:@selector(callback:)
                          obj:self];
    }
}


- (void)callback:(NSNumber*)num
{
    switch ([num intValue]) {
        case LOAD_SCENARIO_STATUS_COMPLETE:
            [mPlayer registerCommunicationCallback:@"setStartPosition" 
                                    callbackObject:self 
                                    callbackMethod:@"TI_SetStartPosNotification"];
            [[NSNotificationCenter defaultCenter] addObserver:self
                                                     selector:@selector(setStartPosition:) 
                                                         name:@"TI_SetStartPosNotification" 
                                                       object:nil];
            [mPlayer playScenario];
            break;
    }
}

- (void)stop
{
    if (mPlayer && ![mPlayer isScenarioPaused]) {
        [mPlayer pauseScenario];
    }    
}

- (IBAction)pushCornerButton:(id)sender 
{
}

- (void)setStartPosition:(NSNotification *)notification
{
    AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    
    NSDictionary* l_userInfo = [notification userInfo];
    NSString *s1 = (NSString *)[l_userInfo objectForKey:@"arg0"];
    
    NSUInteger idx = [delegate.spots indexOfObjectPassingTest:
                      ^BOOL(id obj, NSUInteger idx, BOOL *stop) {
                          Spot *cur_spot = (Spot *)obj;
                          return [cur_spot.spotID isEqualToString:s1];
                      }];
    delegate.startSpot = (Spot *)[delegate.spots objectAtIndex:idx];
    txtMsg.text = [NSString stringWithFormat:@"出発地:%@", delegate.startSpot.spotName];    
    
    DestController *dest = [[DestController alloc] init];
    [delegate.navController pushViewController:dest animated:YES];
}

@end

DestController.h
#import <UIKit/UIKit.h>

@interface DestController : UIViewController <UITableViewDataSource, UITableViewDelegate> {
    NSMutableArray *spots;
}

@property (retain, nonatomic) IBOutlet UITableView *tableView;

@end

DestController.m
#import "AppDelegate.h"
#import "DestController.h"
#import "Spot.h"

@interface DestController ()

@end

@implementation DestController
@synthesize tableView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"目的地の選択";
    
    AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    spots = delegate.spots;
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidUnload
{
    [self setTableView:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)dealloc {
    [tableView release];
    [super dealloc];
}

#pragma mark UITableViewDataSource Methods

- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tv dequeueReusableCellWithIdentifier:@"cell"];
    if (nil == cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    
    Spot *thisSpot = [spots objectAtIndex:indexPath.row];
    cell.textLabel.text = thisSpot.spotName;
    return cell;
}

- (NSInteger)tableView:(UITableView *)tv numberOfRowsInSection:(NSInteger)section
{
    return [spots count];
}

#pragma mark UITableViewDelegate Methods

- (void)tableView:(UITableView *)tv didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    Spot *thisSpot = [spots objectAtIndex:indexPath.row];
    AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    delegate.destSpot = thisSpot;
    [delegate showInfo];
}
@end

Spot.h
#import <UIKit/UIKit.h>

@interface Spot : NSObject

@property (nonatomic, strong) NSString *spotID;
@property (nonatomic, strong) NSString *spotName;

@end

Spot.m
#import "Spot.h"

@implementation Spot

@synthesize spotID;
@synthesize spotName;

@end