summaryrefslogtreecommitdiff
path: root/platform/iphone
diff options
context:
space:
mode:
authorJuan Linietsky <reduzio@gmail.com>2014-02-09 22:10:30 -0300
committerJuan Linietsky <reduzio@gmail.com>2014-02-09 22:10:30 -0300
commit0b806ee0fc9097fa7bda7ac0109191c9c5e0a1ac (patch)
tree276c4d099e178eb67fbd14f61d77b05e3808e9e3 /platform/iphone
parent0e49da1687bc8192ed210947da52c9e5c5f301bb (diff)
GODOT IS OPEN SOURCE
Diffstat (limited to 'platform/iphone')
-rw-r--r--platform/iphone/Appirater.h227
-rw-r--r--platform/iphone/Appirater.m383
-rw-r--r--platform/iphone/SCsub45
-rw-r--r--platform/iphone/app_delegate.h42
-rw-r--r--platform/iphone/app_delegate.mm268
-rw-r--r--platform/iphone/audio_driver_iphone.cpp157
-rw-r--r--platform/iphone/audio_driver_iphone.h63
-rw-r--r--platform/iphone/detect.py130
-rw-r--r--platform/iphone/game_center.h68
-rw-r--r--platform/iphone/game_center.mm163
-rwxr-xr-xplatform/iphone/gl_view.h100
-rwxr-xr-xplatform/iphone/gl_view.mm457
-rw-r--r--platform/iphone/globals/global_defaults.cpp11
-rw-r--r--platform/iphone/globals/global_defaults.h3
-rw-r--r--platform/iphone/godot_iphone.cpp86
-rw-r--r--platform/iphone/in_app_store.h66
-rw-r--r--platform/iphone/in_app_store.mm264
-rw-r--r--platform/iphone/logo.pngbin0 -> 1899 bytes
-rw-r--r--platform/iphone/main.m22
-rw-r--r--platform/iphone/os_iphone.cpp507
-rw-r--r--platform/iphone/os_iphone.h193
-rw-r--r--platform/iphone/platform_config.h32
-rw-r--r--platform/iphone/rasterizer_iphone.cpp2762
-rw-r--r--platform/iphone/rasterizer_iphone.h894
-rw-r--r--platform/iphone/sem_iphone.cpp115
-rw-r--r--platform/iphone/sem_iphone.h60
-rw-r--r--platform/iphone/view_controller.h40
-rw-r--r--platform/iphone/view_controller.mm107
28 files changed, 7265 insertions, 0 deletions
diff --git a/platform/iphone/Appirater.h b/platform/iphone/Appirater.h
new file mode 100644
index 0000000000..d11b2f7793
--- /dev/null
+++ b/platform/iphone/Appirater.h
@@ -0,0 +1,227 @@
+/*************************************************************************/
+/* Appirater.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* http://www.godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+ This file is part of Appirater.
+
+ Copyright (c) 2010, Arash Payan
+ All rights reserved.
+
+ Permission is hereby granted, free of charge, to any person
+ obtaining a copy of this software and associated documentation
+ files (the "Software"), to deal in the Software without
+ restriction, including without limitation the rights to use,
+ copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the
+ Software is furnished to do so, subject to the following
+ conditions:
+
+ The above copyright notice and this permission notice shall be
+ included in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
+ OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+ OTHER DEALINGS IN THE SOFTWARE.
+ */
+/*
+ * Appirater.h
+ * appirater
+ *
+ * Created by Arash Payan on 9/5/09.
+ * http://arashpayan.com
+ * Copyright 2010 Arash Payan. All rights reserved.
+ */
+
+#import <Foundation/Foundation.h>
+#import <UIKit/UIKit.h>
+
+extern NSString *const kAppiraterFirstUseDate;
+extern NSString *const kAppiraterUseCount;
+extern NSString *const kAppiraterSignificantEventCount;
+extern NSString *const kAppiraterCurrentVersion;
+extern NSString *const kAppiraterRatedCurrentVersion;
+extern NSString *const kAppiraterDeclinedToRate;
+
+/*
+ Place your Apple generated software id here.
+ */
+#define APPIRATER_APP_ID 301377083
+
+/*
+ Your app's name.
+ */
+#define APPIRATER_APP_NAME [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString*)kCFBundleNameKey]
+
+/*
+ This is the message your users will see once they've passed the day+launches
+ threshold.
+ */
+#define APPIRATER_MESSAGE [NSString stringWithFormat:@"If you enjoy using %@, would you mind taking a moment to rate it? It won't take more than a minute. Thanks for your support!", APPIRATER_APP_NAME]
+
+/*
+ This is the title of the message alert that users will see.
+ */
+#define APPIRATER_MESSAGE_TITLE [NSString stringWithFormat:@"Rate %@", APPIRATER_APP_NAME]
+
+/*
+ The text of the button that rejects reviewing the app.
+ */
+#define APPIRATER_CANCEL_BUTTON @"No, Thanks"
+
+/*
+ Text of button that will send user to app review page.
+ */
+#define APPIRATER_RATE_BUTTON [NSString stringWithFormat:@"Rate %@", APPIRATER_APP_NAME]
+
+/*
+ Text for button to remind the user to review later.
+ */
+#define APPIRATER_RATE_LATER @"Remind me later"
+
+/*
+ Users will need to have the same version of your app installed for this many
+ days before they will be prompted to rate it.
+ */
+#define APPIRATER_DAYS_UNTIL_PROMPT 30 // double
+
+/*
+ An example of a 'use' would be if the user launched the app. Bringing the app
+ into the foreground (on devices that support it) would also be considered
+ a 'use'. You tell Appirater about these events using the two methods:
+ [Appirater appLaunched:]
+ [Appirater appEnteredForeground:]
+
+ Users need to 'use' the same version of the app this many times before
+ before they will be prompted to rate it.
+ */
+#define APPIRATER_USES_UNTIL_PROMPT 20 // integer
+
+/*
+ A significant event can be anything you want to be in your app. In a
+ telephone app, a significant event might be placing or receiving a call.
+ In a game, it might be beating a level or a boss. This is just another
+ layer of filtering that can be used to make sure that only the most
+ loyal of your users are being prompted to rate you on the app store.
+ If you leave this at a value of -1, then this won't be a criteria
+ used for rating. To tell Appirater that the user has performed
+ a significant event, call the method:
+ [Appirater userDidSignificantEvent:];
+ */
+#define APPIRATER_SIG_EVENTS_UNTIL_PROMPT -1 // integer
+
+/*
+ Once the rating alert is presented to the user, they might select
+ 'Remind me later'. This value specifies how long (in days) Appirater
+ will wait before reminding them.
+ */
+#define APPIRATER_TIME_BEFORE_REMINDING 1 // double
+
+/*
+ 'YES' will show the Appirater alert everytime. Useful for testing how your message
+ looks and making sure the link to your app's review page works.
+ */
+#define APPIRATER_DEBUG NO
+
+@interface Appirater : NSObject <UIAlertViewDelegate> {
+
+ UIAlertView *ratingAlert;
+}
+
+@property(nonatomic, retain) UIAlertView *ratingAlert;
+
+/*
+ DEPRECATED: While still functional, it's better to use
+ appLaunched:(BOOL)canPromptForRating instead.
+
+ Calls [Appirater appLaunched:YES]. See appLaunched: for details of functionality.
+ */
++ (void)appLaunched:(int)p_app_id;
+
+/*
+ Tells Appirater that the app has launched, and on devices that do NOT
+ support multitasking, the 'uses' count will be incremented. You should
+ call this method at the end of your application delegate's
+ application:didFinishLaunchingWithOptions: method.
+
+ If the app has been used enough to be rated (and enough significant events),
+ you can suppress the rating alert
+ by passing NO for canPromptForRating. The rating alert will simply be postponed
+ until it is called again with YES for canPromptForRating. The rating alert
+ can also be triggered by appEnteredForeground: and userDidSignificantEvent:
+ (as long as you pass YES for canPromptForRating in those methods).
+ */
++ (void)appLaunched:(BOOL)canPromptForRating app_id:(int)p_app_id;
+
+/*
+ Tells Appirater that the app was brought to the foreground on multitasking
+ devices. You should call this method from the application delegate's
+ applicationWillEnterForeground: method.
+
+ If the app has been used enough to be rated (and enough significant events),
+ you can suppress the rating alert
+ by passing NO for canPromptForRating. The rating alert will simply be postponed
+ until it is called again with YES for canPromptForRating. The rating alert
+ can also be triggered by appLaunched: and userDidSignificantEvent:
+ (as long as you pass YES for canPromptForRating in those methods).
+ */
++ (void)appEnteredForeground:(BOOL)canPromptForRating;
+
+/*
+ Tells Appirater that the user performed a significant event. A significant
+ event is whatever you want it to be. If you're app is used to make VoIP
+ calls, then you might want to call this method whenever the user places
+ a call. If it's a game, you might want to call this whenever the user
+ beats a level boss.
+
+ If the user has performed enough significant events and used the app enough,
+ you can suppress the rating alert by passing NO for canPromptForRating. The
+ rating alert will simply be postponed until it is called again with YES for
+ canPromptForRating. The rating alert can also be triggered by appLaunched:
+ and appEnteredForeground: (as long as you pass YES for canPromptForRating
+ in those methods).
+ */
++ (void)userDidSignificantEvent:(BOOL)canPromptForRating;
+
+/*
+ Tells Appirater to open the App Store page where the user can specify a
+ rating for the app. Also records the fact that this has happened, so the
+ user won't be prompted again to rate the app.
+
+ The only case where you should call this directly is if your app has an
+ explicit "Rate this app" command somewhere. In all other cases, don't worry
+ about calling this -- instead, just call the other functions listed above,
+ and let Appirater handle the bookkeeping of deciding when to ask the user
+ whether to rate the app.
+ */
++ (void)rateApp;
+
+@end
diff --git a/platform/iphone/Appirater.m b/platform/iphone/Appirater.m
new file mode 100644
index 0000000000..d9144eda3e
--- /dev/null
+++ b/platform/iphone/Appirater.m
@@ -0,0 +1,383 @@
+#ifdef APPIRATER_ENABLED
+
+/*
+ This file is part of Appirater.
+
+ Copyright (c) 2010, Arash Payan
+ All rights reserved.
+
+ Permission is hereby granted, free of charge, to any person
+ obtaining a copy of this software and associated documentation
+ files (the "Software"), to deal in the Software without
+ restriction, including without limitation the rights to use,
+ copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the
+ Software is furnished to do so, subject to the following
+ conditions:
+
+ The above copyright notice and this permission notice shall be
+ included in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
+ OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+ OTHER DEALINGS IN THE SOFTWARE.
+ */
+/*
+ * Appirater.m
+ * appirater
+ *
+ * Created by Arash Payan on 9/5/09.
+ * http://arashpayan.com
+ * Copyright 2010 Arash Payan. All rights reserved.
+ */
+
+#import "Appirater.h"
+#import <SystemConfiguration/SCNetworkReachability.h>
+#include <netinet/in.h>
+
+NSString *const kAppiraterFirstUseDate = @"kAppiraterFirstUseDate";
+NSString *const kAppiraterUseCount = @"kAppiraterUseCount";
+NSString *const kAppiraterSignificantEventCount = @"kAppiraterSignificantEventCount";
+NSString *const kAppiraterCurrentVersion = @"kAppiraterCurrentVersion";
+NSString *const kAppiraterRatedCurrentVersion = @"kAppiraterRatedCurrentVersion";
+NSString *const kAppiraterDeclinedToRate = @"kAppiraterDeclinedToRate";
+NSString *const kAppiraterReminderRequestDate = @"kAppiraterReminderRequestDate";
+
+NSString *templateReviewURL = @"itms-apps://ax.itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=APP_ID";
+
+static int app_id = 0;
+
+@interface Appirater (hidden)
+- (BOOL)connectedToNetwork;
++ (Appirater*)sharedInstance;
+- (void)showRatingAlert;
+- (BOOL)ratingConditionsHaveBeenMet;
+- (void)incrementUseCount;
+@end
+
+@implementation Appirater (hidden)
+
+- (BOOL)connectedToNetwork {
+ // Create zero addy
+ struct sockaddr_in zeroAddress;
+ bzero(&zeroAddress, sizeof(zeroAddress));
+ zeroAddress.sin_len = sizeof(zeroAddress);
+ zeroAddress.sin_family = AF_INET;
+
+ // Recover reachability flags
+ SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
+ SCNetworkReachabilityFlags flags;
+
+ BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
+ CFRelease(defaultRouteReachability);
+
+ if (!didRetrieveFlags)
+ {
+ NSLog(@"Error. Could not recover network reachability flags");
+ return NO;
+ }
+
+ BOOL isReachable = flags & kSCNetworkFlagsReachable;
+ BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;
+ BOOL nonWiFi = flags & kSCNetworkReachabilityFlagsTransientConnection;
+
+ NSURL *testURL = [NSURL URLWithString:@"http://www.apple.com/"];
+ NSURLRequest *testRequest = [NSURLRequest requestWithURL:testURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:20.0];
+ NSURLConnection *testConnection = [[NSURLConnection alloc] initWithRequest:testRequest delegate:self];
+
+ return ((isReachable && !needsConnection) || nonWiFi) ? (testConnection ? YES : NO) : NO;
+}
+
++ (Appirater*)sharedInstance {
+ static Appirater *appirater = nil;
+ if (appirater == nil)
+ {
+ @synchronized(self) {
+ if (appirater == nil) {
+ appirater = [[Appirater alloc] init];
+ [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillResignActive) name:@"UIApplicationWillResignActiveNotification" object:nil];
+ }
+ }
+ }
+
+ return appirater;
+}
+
+- (void)showRatingAlert {
+ UIAlertView *alertView = [[[UIAlertView alloc] initWithTitle:APPIRATER_MESSAGE_TITLE
+ message:APPIRATER_MESSAGE
+ delegate:self
+ cancelButtonTitle:APPIRATER_CANCEL_BUTTON
+ otherButtonTitles:APPIRATER_RATE_BUTTON, APPIRATER_RATE_LATER, nil] autorelease];
+ self.ratingAlert = alertView;
+ [alertView show];
+}
+
+- (BOOL)ratingConditionsHaveBeenMet {
+ if (APPIRATER_DEBUG)
+ return YES;
+
+ NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
+
+ NSDate *dateOfFirstLaunch = [NSDate dateWithTimeIntervalSince1970:[userDefaults doubleForKey:kAppiraterFirstUseDate]];
+ NSTimeInterval timeSinceFirstLaunch = [[NSDate date] timeIntervalSinceDate:dateOfFirstLaunch];
+ NSTimeInterval timeUntilRate = 60 * 60 * 24 * APPIRATER_DAYS_UNTIL_PROMPT;
+ if (timeSinceFirstLaunch < timeUntilRate)
+ return NO;
+
+ // check if the app has been used enough
+ int useCount = [userDefaults integerForKey:kAppiraterUseCount];
+ if (useCount <= APPIRATER_USES_UNTIL_PROMPT)
+ return NO;
+
+ // check if the user has done enough significant events
+ int sigEventCount = [userDefaults integerForKey:kAppiraterSignificantEventCount];
+ if (sigEventCount <= APPIRATER_SIG_EVENTS_UNTIL_PROMPT)
+ return NO;
+
+ // has the user previously declined to rate this version of the app?
+ if ([userDefaults boolForKey:kAppiraterDeclinedToRate])
+ return NO;
+
+ // has the user already rated the app?
+ if ([userDefaults boolForKey:kAppiraterRatedCurrentVersion])
+ return NO;
+
+ // if the user wanted to be reminded later, has enough time passed?
+ NSDate *reminderRequestDate = [NSDate dateWithTimeIntervalSince1970:[userDefaults doubleForKey:kAppiraterReminderRequestDate]];
+ NSTimeInterval timeSinceReminderRequest = [[NSDate date] timeIntervalSinceDate:reminderRequestDate];
+ NSTimeInterval timeUntilReminder = 60 * 60 * 24 * APPIRATER_TIME_BEFORE_REMINDING;
+ if (timeSinceReminderRequest < timeUntilReminder)
+ return NO;
+
+ return YES;
+}
+
+- (void)incrementUseCount {
+ // get the app's version
+ NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString*)kCFBundleVersionKey];
+
+ // get the version number that we've been tracking
+ NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
+ NSString *trackingVersion = [userDefaults stringForKey:kAppiraterCurrentVersion];
+ if (trackingVersion == nil)
+ {
+ trackingVersion = version;
+ [userDefaults setObject:version forKey:kAppiraterCurrentVersion];
+ }
+
+ if (APPIRATER_DEBUG)
+ NSLog(@"APPIRATER Tracking version: %@", trackingVersion);
+
+ if ([trackingVersion isEqualToString:version])
+ {
+ // check if the first use date has been set. if not, set it.
+ NSTimeInterval timeInterval = [userDefaults doubleForKey:kAppiraterFirstUseDate];
+ if (timeInterval == 0)
+ {
+ timeInterval = [[NSDate date] timeIntervalSince1970];
+ [userDefaults setDouble:timeInterval forKey:kAppiraterFirstUseDate];
+ }
+
+ // increment the use count
+ int useCount = [userDefaults integerForKey:kAppiraterUseCount];
+ useCount++;
+ [userDefaults setInteger:useCount forKey:kAppiraterUseCount];
+ if (APPIRATER_DEBUG)
+ NSLog(@"APPIRATER Use count: %d", useCount);
+ }
+ else
+ {
+ // it's a new version of the app, so restart tracking
+ [userDefaults setObject:version forKey:kAppiraterCurrentVersion];
+ [userDefaults setDouble:[[NSDate date] timeIntervalSince1970] forKey:kAppiraterFirstUseDate];
+ [userDefaults setInteger:1 forKey:kAppiraterUseCount];
+ [userDefaults setInteger:0 forKey:kAppiraterSignificantEventCount];
+ [userDefaults setBool:NO forKey:kAppiraterRatedCurrentVersion];
+ [userDefaults setBool:NO forKey:kAppiraterDeclinedToRate];
+ [userDefaults setDouble:0 forKey:kAppiraterReminderRequestDate];
+ }
+
+ [userDefaults synchronize];
+}
+
+- (void)incrementSignificantEventCount {
+ // get the app's version
+ NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString*)kCFBundleVersionKey];
+
+ // get the version number that we've been tracking
+ NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
+ NSString *trackingVersion = [userDefaults stringForKey:kAppiraterCurrentVersion];
+ if (trackingVersion == nil)
+ {
+ trackingVersion = version;
+ [userDefaults setObject:version forKey:kAppiraterCurrentVersion];
+ }
+
+ if (APPIRATER_DEBUG)
+ NSLog(@"APPIRATER Tracking version: %@", trackingVersion);
+
+ if ([trackingVersion isEqualToString:version])
+ {
+ // check if the first use date has been set. if not, set it.
+ NSTimeInterval timeInterval = [userDefaults doubleForKey:kAppiraterFirstUseDate];
+ if (timeInterval == 0)
+ {
+ timeInterval = [[NSDate date] timeIntervalSince1970];
+ [userDefaults setDouble:timeInterval forKey:kAppiraterFirstUseDate];
+ }
+
+ // increment the significant event count
+ int sigEventCount = [userDefaults integerForKey:kAppiraterSignificantEventCount];
+ sigEventCount++;
+ [userDefaults setInteger:sigEventCount forKey:kAppiraterSignificantEventCount];
+ if (APPIRATER_DEBUG)
+ NSLog(@"APPIRATER Significant event count: %d", sigEventCount);
+ }
+ else
+ {
+ // it's a new version of the app, so restart tracking
+ [userDefaults setObject:version forKey:kAppiraterCurrentVersion];
+ [userDefaults setDouble:0 forKey:kAppiraterFirstUseDate];
+ [userDefaults setInteger:0 forKey:kAppiraterUseCount];
+ [userDefaults setInteger:1 forKey:kAppiraterSignificantEventCount];
+ [userDefaults setBool:NO forKey:kAppiraterRatedCurrentVersion];
+ [userDefaults setBool:NO forKey:kAppiraterDeclinedToRate];
+ [userDefaults setDouble:0 forKey:kAppiraterReminderRequestDate];
+ }
+
+ [userDefaults synchronize];
+}
+
+@end
+
+
+@interface Appirater ()
+- (void)hideRatingAlert;
+@end
+
+@implementation Appirater
+
+@synthesize ratingAlert;
+
+- (void)incrementAndRate:(NSNumber*)_canPromptForRating {
+ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
+
+ [self incrementUseCount];
+
+ if ([_canPromptForRating boolValue] == YES &&
+ [self ratingConditionsHaveBeenMet] &&
+ [self connectedToNetwork])
+ {
+ [self performSelectorOnMainThread:@selector(showRatingAlert) withObject:nil waitUntilDone:NO];
+ }
+
+ [pool release];
+}
+
+- (void)incrementSignificantEventAndRate:(NSNumber*)_canPromptForRating {
+ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
+
+ [self incrementSignificantEventCount];
+
+ if ([_canPromptForRating boolValue] == YES &&
+ [self ratingConditionsHaveBeenMet] &&
+ [self connectedToNetwork])
+ {
+ [self performSelectorOnMainThread:@selector(showRatingAlert) withObject:nil waitUntilDone:NO];
+ }
+
+ [pool release];
+}
+
++ (void)appLaunched:(int)p_app_id {
+ app_id = p_app_id;
+ [Appirater appLaunched:YES];
+}
+
++ (void)appLaunched:(BOOL)canPromptForRating app_id:(int)p_app_id {
+ app_id = p_app_id;
+ NSNumber *_canPromptForRating = [[NSNumber alloc] initWithBool:canPromptForRating];
+ [NSThread detachNewThreadSelector:@selector(incrementAndRate:)
+ toTarget:[Appirater sharedInstance]
+ withObject:_canPromptForRating];
+ [_canPromptForRating release];
+}
+
+- (void)hideRatingAlert {
+ if (self.ratingAlert.visible) {
+ if (APPIRATER_DEBUG)
+ NSLog(@"APPIRATER Hiding Alert");
+ [self.ratingAlert dismissWithClickedButtonIndex:-1 animated:NO];
+ }
+}
+
++ (void)appWillResignActive {
+ if (APPIRATER_DEBUG)
+ NSLog(@"APPIRATER appWillResignActive");
+ [[Appirater sharedInstance] hideRatingAlert];
+}
+
++ (void)appEnteredForeground:(BOOL)canPromptForRating {
+ NSNumber *_canPromptForRating = [[NSNumber alloc] initWithBool:canPromptForRating];
+ [NSThread detachNewThreadSelector:@selector(incrementAndRate:)
+ toTarget:[Appirater sharedInstance]
+ withObject:_canPromptForRating];
+ [_canPromptForRating release];
+}
+
++ (void)userDidSignificantEvent:(BOOL)canPromptForRating {
+ NSNumber *_canPromptForRating = [[NSNumber alloc] initWithBool:canPromptForRating];
+ [NSThread detachNewThreadSelector:@selector(incrementSignificantEventAndRate:)
+ toTarget:[Appirater sharedInstance]
+ withObject:_canPromptForRating];
+ [_canPromptForRating release];
+}
+
++ (void)rateApp {
+#if TARGET_IPHONE_SIMULATOR
+ NSLog(@"APPIRATER NOTE: iTunes App Store is not supported on the iOS simulator. Unable to open App Store page.");
+#else
+ NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
+ NSString *reviewURL = [templateReviewURL stringByReplacingOccurrencesOfString:@"APP_ID" withString:[NSString stringWithFormat:@"%d", app_id]];
+ [userDefaults setBool:YES forKey:kAppiraterRatedCurrentVersion];
+ [userDefaults synchronize];
+ [[UIApplication sharedApplication] openURL:[NSURL URLWithString:reviewURL]];
+#endif
+}
+
+- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
+ NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
+
+ switch (buttonIndex) {
+ case 0:
+ {
+ // they don't want to rate it
+ [userDefaults setBool:YES forKey:kAppiraterDeclinedToRate];
+ [userDefaults synchronize];
+ break;
+ }
+ case 1:
+ {
+ // they want to rate it
+ [Appirater rateApp];
+ break;
+ }
+ case 2:
+ // remind them later
+ [userDefaults setDouble:[[NSDate date] timeIntervalSince1970] forKey:kAppiraterReminderRequestDate];
+ [userDefaults synchronize];
+ break;
+ default:
+ break;
+ }
+}
+
+@end
+
+#endif
diff --git a/platform/iphone/SCsub b/platform/iphone/SCsub
new file mode 100644
index 0000000000..0113f75697
--- /dev/null
+++ b/platform/iphone/SCsub
@@ -0,0 +1,45 @@
+Import('env')
+
+iphone_lib = [
+
+ 'os_iphone.cpp',
+ #'rasterizer_iphone.cpp',
+ 'audio_driver_iphone.cpp',
+ 'sem_iphone.cpp',
+ 'gl_view.mm',
+ 'main.m',
+ 'app_delegate.mm',
+ 'view_controller.mm',
+ 'game_center.mm',
+ 'in_app_store.mm',
+ 'Appirater.m',
+]
+
+#env.Depends('#core/math/vector3.h', 'vector3_psp.h')
+
+#iphone_lib = env.Library('iphone', iphone_lib)
+
+env_ios = env.Clone();
+
+
+if env['ios_gles22_override'] == "yes":
+ env_ios.Append(CPPFLAGS=['-DGLES2_OVERRIDE'])
+
+if env['ios_GLES1_override'] == "yes":
+ env_ios.Append(CPPFLAGS=['-DGLES1_OVERRIDE'])
+
+if env['ios_appirater'] == "yes":
+ env_ios.Append(CPPFLAGS=['-DAPPIRATER_ENABLED'])
+
+
+obj = env_ios.Object('godot_iphone.cpp')
+
+prog = None
+if env["target"]=="release":
+ prog = env_ios.Program('#bin/godot_opt', [obj] + iphone_lib)
+ #action = "dsymutil "+File(prog)[0].path+" -o ../build/script_exec/build/Debug-iphoneos/script_exec.app.dSYM"
+ #env.AddPostAction(prog, action)
+else:
+ prog = env_ios.Program('#bin/godot', [obj] + iphone_lib)
+ action = "dsymutil "+File(prog)[0].path+" -o bin/godot.iphone.dSYM"
+ env.AddPostAction(prog, action)
diff --git a/platform/iphone/app_delegate.h b/platform/iphone/app_delegate.h
new file mode 100644
index 0000000000..db641b1f78
--- /dev/null
+++ b/platform/iphone/app_delegate.h
@@ -0,0 +1,42 @@
+/*************************************************************************/
+/* app_delegate.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* http://www.godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+#import <UIKit/UIKit.h>
+#import "gl_view.h"
+#import "view_controller.h"
+
+@interface AppDelegate : NSObject <UIApplicationDelegate, UIAccelerometerDelegate, GLViewDelegate> {
+ UIWindow *window;
+ ViewController* view_controller;
+ UIAccelerationValue accel[3];
+ UIAccelerationValue last_accel[3];
+};
+
++ (ViewController*)getViewController;
+
+@end
diff --git a/platform/iphone/app_delegate.mm b/platform/iphone/app_delegate.mm
new file mode 100644
index 0000000000..f80a855ef0
--- /dev/null
+++ b/platform/iphone/app_delegate.mm
@@ -0,0 +1,268 @@
+/*************************************************************************/
+/* app_delegate.mm */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* http://www.godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+#import "app_delegate.h"
+#import "gl_view.h"
+
+#include "os_iphone.h"
+#include "core/globals.h"
+#include "main/main.h"
+
+#ifdef FACEBOOK_ENABLED
+#include "modules/FacebookScorer_ios/FacebookScorer.h"
+#endif
+
+#define kFilteringFactor 0.1
+#define kRenderingFrequency 30
+#define kAccelerometerFrequency 100.0 // Hz
+
+#ifdef APPIRATER_ENABLED
+#import "Appirater.h"
+#endif
+
+Error _shell_open(String p_uri) {
+ NSString* url = [[NSString alloc] initWithUTF8String:p_uri.utf8().get_data()];
+
+ if (![[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:url]])
+ return ERR_CANT_OPEN;
+
+ printf("opening url %ls\n", p_uri.c_str());
+ [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
+ [url release];
+ return OK;
+};
+
+@implementation AppDelegate
+
+extern int gargc;
+extern char** gargv;
+extern int iphone_main(int, int, int, char**);
+extern void iphone_finish();
+
+static ViewController* mainViewController = nil;
++ (ViewController*) getViewController
+{
+ return mainViewController;
+}
+
+static int frame_count = 0;
+- (void)drawView:(GLView*)view; {
+
+ switch (frame_count) {
+
+ case 0: {
+
+ int backingWidth;
+ int backingHeight;
+ glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &backingWidth);
+ glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &backingHeight);
+
+ iphone_main(backingWidth, backingHeight, gargc, gargv);
+
+ OS::VideoMode vm;
+ vm.fullscreen = true;
+ vm.width = backingWidth;
+ vm.height = backingHeight;
+ vm.resizable = false;
+ OS::get_singleton()->set_video_mode(vm);
+
+ if (!OS::get_singleton()) {
+ exit(0);
+ };
+ ++frame_count;
+
+ NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
+ NSString *documentsDirectory = [paths objectAtIndex:0];
+ //NSString *documentsDirectory = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
+ OSIPhone::get_singleton()->set_data_dir(String::utf8([documentsDirectory UTF8String]));
+
+ NSString *locale_code = [[[NSLocale preferredLanguages] objectAtIndex:0] substringToIndex:2];
+ OSIPhone::get_singleton()->set_locale(String::utf8([locale_code UTF8String]));
+
+ NSString* uuid;
+ if ([[UIDevice currentDevice]respondsToSelector:@selector(identifierForVendor)]) {
+ uuid = [UIDevice currentDevice].identifierForVendor.UUIDString;
+ }else{
+ // return [UIDevice currentDevice]. uniqueIdentifier
+ uuid = [[UIDevice currentDevice] performSelector:@selector(uniqueIdentifier)];
+ }
+
+ OSIPhone::get_singleton()->set_unique_ID(String::utf8([uuid UTF8String]));
+
+ }; // break;
+/*
+ case 1: {
+ ++frame_count;
+ } break;
+*/
+ case 1: {
+
+ Main::setup2();
+ ++frame_count;
+
+ } break;
+/*
+ case 3: {
+ ++frame_count;
+ } break;
+*/
+ case 2: {
+
+ Main::start();
+ ++frame_count;
+
+ #ifdef APPIRATER_ENABLED
+ int aid = Globals::get_singleton()->get("ios/app_id");
+ [Appirater appLaunched:YES app_id:aid];
+ #endif
+
+ }; // break; fallthrough
+
+ default: {
+
+ if (OSIPhone::get_singleton()) {
+ OSIPhone::get_singleton()->update_accelerometer(accel[0], accel[1], accel[2]);
+ bool quit_request = OSIPhone::get_singleton()->iterate();
+ };
+
+ };
+
+ };
+};
+
+- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
+
+ printf("****************** did receive memory warning!\n");
+};
+
+- (void)applicationDidFinishLaunching:(UIApplication*)application {
+
+ printf("**************** app delegate init\n");
+ CGRect rect = [[UIScreen mainScreen] bounds];
+
+ application.statusBarHidden = YES;
+ // disable idle timer
+ application.idleTimerDisabled = YES;
+
+ //Create a full-screen window
+ window = [[UIWindow alloc] initWithFrame:rect];
+ //window.autoresizesSubviews = YES;
+ //[window setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleWidth];
+
+ //Create the OpenGL ES view and add it to the window
+ GLView *glView = [[GLView alloc] initWithFrame:rect];
+ printf("glview is %p\n", glView);
+ //[window addSubview:glView];
+ glView.delegate = self;
+ //glView.autoresizesSubviews = YES;
+ //[glView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleWidth];
+
+ view_controller = [[ViewController alloc] init];
+ view_controller.view = glView;
+ window.rootViewController = view_controller;
+
+ glView.animationInterval = 1.0 / kRenderingFrequency;
+ [glView startAnimation];
+
+ //Show the window
+ [window makeKeyAndVisible];
+
+ //Configure and start accelerometer
+ last_accel[0] = 0;
+ last_accel[1] = 0;
+ last_accel[2] = 0;
+ [[UIAccelerometer sharedAccelerometer] setUpdateInterval:(1.0 / kAccelerometerFrequency)];
+ [[UIAccelerometer sharedAccelerometer] setDelegate:self];
+
+ //OSIPhone::screen_width = rect.size.width - rect.origin.x;
+ //OSIPhone::screen_height = rect.size.height - rect.origin.y;
+
+ mainViewController = view_controller;
+};
+
+- (void)applicationWillTerminate:(UIApplication*)application {
+
+ printf("********************* will terminate\n");
+ iphone_finish();
+};
+
+- (void)applicationDidEnterBackground:(UIApplication *)application
+{
+ printf("********************* did enter background\n");
+ [view_controller.view stopAnimation];
+}
+
+- (void)applicationWillEnterForeground:(UIApplication *)application
+{
+ printf("********************* did enter foreground\n");
+ [view_controller.view startAnimation];
+}
+
+- (void) applicationWillResignActive:(UIApplication *)application
+{
+ printf("********************* will resign active\n");
+ [view_controller.view stopAnimation]; // FIXME: pause seems to be recommended elsewhere
+}
+
+- (void) applicationDidBecomeActive:(UIApplication *)application
+{
+ printf("********************* did become active\n");
+ [view_controller.view startAnimation]; // FIXME: resume seems to be recommended elsewhere
+}
+
+- (void)accelerometer:(UIAccelerometer*)accelerometer didAccelerate:(UIAcceleration*)acceleration {
+ //Use a basic low-pass filter to only keep the gravity in the accelerometer values
+ accel[0] = acceleration.x; // * kFilteringFactor + accel[0] * (1.0 - kFilteringFactor);
+ accel[1] = acceleration.y; // * kFilteringFactor + accel[1] * (1.0 - kFilteringFactor);
+ accel[2] = acceleration.z; // * kFilteringFactor + accel[2] * (1.0 - kFilteringFactor);
+}
+
+- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
+#ifdef FACEBOOK_ENABLED
+ return [[[FacebookScorer sharedInstance] facebook] handleOpenURL:url];
+#else
+ return false;
+#endif
+}
+
+// For 4.2+ support
+- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
+#ifdef FACEBOOK_ENABLED
+ return [[[FacebookScorer sharedInstance] facebook] handleOpenURL:url];
+#else
+ return false;
+#endif
+}
+
+- (void)dealloc
+{
+ [window release];
+ [super dealloc];
+}
+
+@end
diff --git a/platform/iphone/audio_driver_iphone.cpp b/platform/iphone/audio_driver_iphone.cpp
new file mode 100644
index 0000000000..d39b8f3c4d
--- /dev/null
+++ b/platform/iphone/audio_driver_iphone.cpp
@@ -0,0 +1,157 @@
+/*************************************************************************/
+/* audio_driver_iphone.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* http://www.godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+#include "audio_driver_iphone.h"
+
+Error AudioDriverIphone::init() {
+
+ active = false;
+ channels = 2;
+
+ AudioStreamBasicDescription strdesc;
+ strdesc.mFormatID = kAudioFormatLinearPCM;
+ strdesc.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked;
+ strdesc.mChannelsPerFrame = channels;
+ strdesc.mSampleRate = 44100;
+ strdesc.mFramesPerPacket = 1;
+ strdesc.mBitsPerChannel = 16;
+ strdesc.mBytesPerFrame =
+ strdesc.mBitsPerChannel * strdesc.mChannelsPerFrame / 8;
+ strdesc.mBytesPerPacket =
+ strdesc.mBytesPerFrame * strdesc.mFramesPerPacket;
+
+ OSStatus result = noErr;
+ AURenderCallbackStruct callback;
+ AudioComponentDescription desc;
+ AudioComponent comp = NULL;
+ const AudioUnitElement output_bus = 0;
+ const AudioUnitElement bus = output_bus;
+ const AudioUnitScope scope = kAudioUnitScope_Input;
+
+ zeromem(&desc, sizeof(desc));
+ desc.componentType = kAudioUnitType_Output;
+ desc.componentSubType = kAudioUnitSubType_RemoteIO; /* !!! FIXME: ? */
+ comp = AudioComponentFindNext(NULL, &desc);
+ desc.componentManufacturer = kAudioUnitManufacturer_Apple;
+
+ result = AudioComponentInstanceNew(comp, &audio_unit);
+ ERR_FAIL_COND_V(result != noErr, FAILED);
+ ERR_FAIL_COND_V(comp == NULL, FAILED);
+
+ result = AudioUnitSetProperty(audio_unit,
+ kAudioUnitProperty_StreamFormat,
+ scope, bus, &strdesc, sizeof(strdesc));
+ ERR_FAIL_COND_V(result != noErr, FAILED);
+
+ zeromem(&callback, sizeof(AURenderCallbackStruct));
+ callback.inputProc = &AudioDriverIphone::output_callback;
+ callback.inputProcRefCon = this;
+ result = AudioUnitSetProperty(audio_unit,
+ kAudioUnitProperty_SetRenderCallback,
+ scope, bus, &callback, sizeof(callback));
+ ERR_FAIL_COND_V(result != noErr, FAILED);
+
+ result = AudioUnitInitialize(audio_unit);
+ ERR_FAIL_COND_V(result != noErr, FAILED);
+
+ result = AudioOutputUnitStart(audio_unit);
+ ERR_FAIL_COND_V(result != noErr, FAILED);
+
+ const int samples = 1024;
+ samples_in = memnew_arr(int32_t, samples); // whatever
+ buffer_frames = samples / channels;
+
+ return FAILED;
+};
+
+OSStatus AudioDriverIphone::output_callback(void *inRefCon,
+ AudioUnitRenderActionFlags * ioActionFlags,
+ const AudioTimeStamp * inTimeStamp,
+ UInt32 inBusNumber, UInt32 inNumberFrames,
+ AudioBufferList * ioData) {
+
+
+ AudioBuffer *abuf;
+ AudioDriverIphone* ad = (AudioDriverIphone*)inRefCon;
+
+ if (!ad->active) {
+ for (unsigned int i = 0; i < ioData->mNumberBuffers; i++) {
+ abuf = &ioData->mBuffers[i];
+ zeromem(abuf->mData, abuf->mDataByteSize);
+ };
+ return 0;
+ };
+
+ int frames_left;
+
+ for (unsigned int i = 0; i < ioData->mNumberBuffers; i++) {
+
+ abuf = &ioData->mBuffers[i];
+ frames_left = inNumberFrames;
+ int16_t* out = (int16_t*)abuf->mData;
+
+ while (frames_left) {
+
+ int frames = MIN(frames_left, ad->buffer_frames);
+ ad->lock();
+ ad->audio_server_process(frames, ad->samples_in);
+ ad->unlock();
+
+ for(int i = 0; i < frames * ad->channels; i++) {
+
+ out[i] = ad->samples_in[i]>>16;
+ }
+
+ frames_left -= frames;
+ out += frames * ad->channels;
+ };
+ };
+
+ return 0;
+};
+
+void AudioDriverIphone::start() {
+ active = true;
+};
+
+int AudioDriverIphone::get_mix_rate() const {
+ return 44100;
+};
+
+AudioDriverSW::OutputFormat AudioDriverIphone::get_output_format() const {
+ return OUTPUT_STEREO;
+};
+
+void AudioDriverIphone::lock() {};
+void AudioDriverIphone::unlock() {};
+
+void AudioDriverIphone::finish() {
+
+ memdelete_arr(samples_in);
+};
+
diff --git a/platform/iphone/audio_driver_iphone.h b/platform/iphone/audio_driver_iphone.h
new file mode 100644
index 0000000000..eec54d9ee3
--- /dev/null
+++ b/platform/iphone/audio_driver_iphone.h
@@ -0,0 +1,63 @@
+/*************************************************************************/
+/* audio_driver_iphone.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* http://www.godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+#include "servers/audio/audio_server_sw.h"
+
+#include <AudioUnit/AudioUnit.h>
+
+class AudioDriverIphone : public AudioDriverSW {
+
+ AudioComponentInstance audio_unit;
+ bool active;
+
+ int channels;
+ int32_t* samples_in;
+ int buffer_frames;
+
+ static OSStatus output_callback(void *inRefCon,
+ AudioUnitRenderActionFlags * ioActionFlags,
+ const AudioTimeStamp * inTimeStamp,
+ UInt32 inBusNumber, UInt32 inNumberFrames,
+ AudioBufferList * ioData);
+
+
+public:
+
+ const char* get_name() const {
+ return "IPhone";
+ };
+
+ virtual Error init();
+ virtual void start();
+ virtual int get_mix_rate() const;
+ virtual OutputFormat get_output_format() const;
+ virtual void lock();
+ virtual void unlock();
+ virtual void finish();
+};
+
diff --git a/platform/iphone/detect.py b/platform/iphone/detect.py
new file mode 100644
index 0000000000..ed935839d8
--- /dev/null
+++ b/platform/iphone/detect.py
@@ -0,0 +1,130 @@
+import os
+import sys
+
+
+def is_active():
+ return True
+
+def get_name():
+ return "iOS"
+
+def can_build():
+
+ import sys
+ if sys.platform == 'darwin':
+ return True
+
+ return False
+
+def get_opts():
+
+ return [
+ ('IPHONEPLATFORM', 'name of the iphone platform', 'iPhoneOS'),
+ ('IPHONEPATH', 'the path to iphone toolchain', '/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain'),
+ ('IPHONESDK', 'path to the iphone SDK', '/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS7.0.sdk/'),
+ ('game_center', 'Support for game center', 'yes'),
+ ('store_kit', 'Support for in-app store', 'yes'),
+ ('ios_gles22_override', 'Force GLES2.0 on iOS', 'yes'),
+ ('ios_GLES1_override', 'Force legacy GLES (1.1) on iOS', 'no'),
+ ('ios_appirater', 'Enable Appirater', 'no'),
+ ('ios_exceptions', 'Use exceptions when compiling on playbook', 'no'),
+ ]
+
+def get_flags():
+
+ return [
+ ('lua', 'no'),
+ ('tools', 'yes'),
+ ('nedmalloc', 'no'),
+ ('webp', 'yes'),
+ ('module_FacebookScorer_ios_enabled', 'no'),
+ ]
+
+
+
+def configure(env):
+
+ env.Append(CPPPATH=['#platform/iphone', '#platform/iphone/include'])
+
+ env['OBJSUFFIX'] = ".iphone.o"
+ env['LIBSUFFIX'] = ".iphone.a"
+ env['PROGSUFFIX'] = ".iphone"
+
+ env['ENV']['PATH'] = env['IPHONEPATH']+"/Developer/usr/bin/:"+env['ENV']['PATH']
+
+# env['CC'] = '$IPHONEPATH/Developer/usr/bin/gcc'
+# env['CXX'] = '$IPHONEPATH/Developer/usr/bin/g++'
+ env['CC'] = '$IPHONEPATH/usr/bin/clang'
+ env['CXX'] = '$IPHONEPATH/usr/bin/clang++'
+ env['AR'] = 'ar'
+
+ import string
+ #env['CCFLAGS'] = string.split('-arch armv7 -Wall -fno-strict-aliasing -fno-common -D__IPHONE_OS_VERSION_MIN_REQUIRED=20000 -isysroot $IPHONESDK -fvisibility=hidden -mmacosx-version-min=10.5 -DCUSTOM_MATRIX_TRANSFORM_H=\\\"build/iphone/matrix4_iphone.h\\\" -DCUSTOM_VECTOR3_TRANSFORM_H=\\\"build/iphone/vector3_iphone.h\\\" -DNO_THUMB')
+ env['CCFLAGS'] = string.split('-fno-objc-arc -arch armv7 -fmessage-length=0 -fno-strict-aliasing -fdiagnostics-print-source-range-info -fdiagnostics-show-category=id -fdiagnostics-parseable-fixits -Wno-trigraphs -fpascal-strings -Wmissing-prototypes -Wreturn-type -Wparentheses -Wswitch -Wno-unused-parameter -Wunused-variable -Wunused-value -Wno-shorten-64-to-32 -isysroot /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS5.0.sdk -gdwarf-2 -fvisibility=hidden -Wno-sign-conversion -mthumb "-DIBOutlet=__attribute__((iboutlet))" "-DIBOutletCollection(ClassName)=__attribute__((iboutletcollection(ClassName)))" "-DIBAction=void)__attribute__((ibaction)" -miphoneos-version-min=4.3 -MMD -MT dependencies -isysroot $IPHONESDK')
+
+
+#/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/clang++ fno-objc-arc -arch armv7 -fmessage-length=0 -fdiagnostics-print-source-range-info -fdiagnostics-show-category=id -fdiagnostics-parseable-fixits -Wno-trigraphs -fpascal-strings -Wmissing-prototypes -Wreturn-type -Wparentheses -Wswitch -Wno-unused-parameter -Wunused-variable -Wunused-value -Wno-shorten-64-to-32 -isysroot /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS5.0.sdk -gdwarf-2 -fvisibility=hidden -Wno-sign-conversion -mthumb "-DIBOutlet=__attribute__((iboutlet))" "-DIBOutletCollection(ClassName)=__attribute__((iboutletcollection(ClassName)))" "-DIBAction=void)__attribute__((ibaction)" -miphoneos-version-min=4.3 -MMD -MT dependencies -v -Os -ffast-math -DSTOREKIT_ENABLED -DIPHONE_ENABLED -DUNIX_ENABLED -DGLES2_ENABLED -DNO_THREADS -DMODULE_GRIDMAP_ENABLED -DMUSEPACK_ENABLED -DOLD_SCENE_FORMAT_ENABLED -DSQUIRREL_ENABLED -DVORBIS_ENABLED -DTHEORA_ENABLED -DPNG_ENABLED -DDDS_ENABLED -DPVR_ENABLED -DJPG_ENABLED -DSPEEX_ENABLED -DTOOLS_ENABLED -DGDSCRIPT_ENABLED -DMINIZIP_ENABLED -DXML_ENABLED -Icore -Icore/math -Itools -Idrivers -I. -Iplatform/iphone -Iplatform/iphone/include -Iplatform/iphone/scoreloop/SDKs -I/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS5.0.sdk/System/Library/Frameworks/OpenGLES.framework/Headers -Iscript/squirrel/src -Iscript/vorbis script/gdscript/gd_script.cpp
+#/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/clang -x objective-c -arch armv7 -fmessage-length=0 -fdiagnostics-print-source-range-info -fdiagnostics-show-category=id -fdiagnostics-parseable-fixits -std=gnu99 -fobjc-arc -Wno-trigraphs -fpascal-strings -Os -Wmissing-prototypes -Wreturn-type -Wparentheses -Wswitch -Wno-unused-parameter -Wunused-variable -Wunused-value -Wno-shorten-64-to-32 -isysroot /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS5.0.sdk -gdwarf-2 -fvisibility=hidden -Wno-sign-conversion -mthumb "-DIBOutlet=__attribute__((iboutlet))" "-DIBOutletCollection(ClassName)=__attribute__((iboutletcollection(ClassName)))" "-DIBAction=void)__attribute__((ibaction)" -miphoneos-version-min=4.3 -iquote /Users/red/test2/build/test2.build/Release-iphoneos/test2.build/test2-generated-files.hmap -I/Users/red/test2/build/test2.build/Release-iphoneos/test2.build/test2-own-target-headers.hmap -I/Users/red/test2/build/test2.build/Release-iphoneos/test2.build/test2-all-target-headers.hmap -iquote /Users/red/test2/build/test2.build/Release-iphoneos/test2.build/test2-project-headers.hmap -I/Users/red/test2/build/Release-iphoneos/include -I/Users/red/test2/build/test2.build/Release-iphoneos/test2.build/DerivedSources/armv7 -I/Users/red/test2/build/test2.build/Release-iphoneos/test2.build/DerivedSources -F/Users/red/test2/build/Release-iphoneos -DNS_BLOCK_ASSERTIONS=1 -include /var/folders/LX/LXYXHTeSHSqbkhuPJRIsuE+++TI/-Caches-/com.apple.Xcode.501/SharedPrecompiledHeaders/test2-Prefix-dvdhnltoisfpmyalexovdrmfyeky/test2-Prefix.pch -MMD -MT dependencies -MF /Users/red/test2/build/test2.build/Release-iphoneos/test2.build/Objects-normal/armv7/main.d -c /Users/red/test2/test2/main.m -o /Users/red/test2/build/test2.build/Release-iphoneos/test2.build/Objects-normal/armv7/main.o
+
+
+
+
+
+ env.Append(LINKFLAGS=['-arch', 'armv7', '-Wl,-dead_strip', '-miphoneos-version-min=4.3',
+ '-isysroot', '$IPHONESDK',
+ #'-mmacosx-version-min=10.5',
+ '-framework', 'Foundation',
+ '-framework', 'UIKit',
+ '-framework', 'CoreGraphics',
+ '-framework', 'OpenGLES',
+ '-framework', 'QuartzCore',
+ '-framework', 'CoreAudio',
+ '-framework', 'AudioToolbox',
+ '-framework', 'SystemConfiguration',
+ '-framework', 'Security',
+ '-framework', 'AdSupport',
+ ])
+
+ if env['game_center'] == 'yes':
+ env.Append(CPPFLAGS=['-fblocks', '-DGAME_CENTER_ENABLED'])
+ env.Append(LINKFLAGS=['-framework', 'GameKit'])
+
+ if env['store_kit'] == 'yes':
+ env.Append(CPPFLAGS=['-DSTOREKIT_ENABLED'])
+ env.Append(LINKFLAGS=['-framework', 'StoreKit'])
+
+ env.Append(CPPPATH = ['$IPHONESDK/usr/include', '$IPHONESDK/System/Library/Frameworks/OpenGLES.framework/Headers', '$IPHONESDK/System/Library/Frameworks/AudioUnit.framework/Headers'])
+
+ if (env["target"]=="release"):
+
+ env.Append(CCFLAGS=['-Os', '-ffast-math', '-DNS_BLOCK_ASSERTIONS=1','-Wall'])
+ env.Append(LINKFLAGS=['-Os', '-ffast-math'])
+ env['OBJSUFFIX'] = "_opt"+env['OBJSUFFIX']
+ env['LIBSUFFIX'] = "_opt"+env['LIBSUFFIX']
+
+ elif (env["target"]=="debug"):
+
+ env.Append(CCFLAGS=['-D_DEBUG', '-DDEBUG=1', '-gdwarf-2', '-Wall', '-O0', '-DDEBUG_ENABLED'])
+ env.Append(CPPFLAGS=['-DDEBUG_MEMORY_ALLOC'])
+
+ elif (env["target"]=="profile"):
+
+ env.Append(CCFLAGS=['-g','-pg', '-Os', '-ffast-math'])
+ env.Append(LINKFLAGS=['-pg'])
+
+
+ env['ENV']['CODESIGN_ALLOCATE'] = '/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/codesign_allocate'
+ env.Append(CPPFLAGS=['-DIPHONE_ENABLED', '-DUNIX_ENABLED', '-DGLES2_ENABLED', '-DGLES1_ENABLED', '-DMPC_FIXED_POINT'])
+ if env['ios_exceptions'] == 'yes':
+ env.Append(CPPFLAGS=['-fexceptions'])
+ else:
+ env.Append(CPPFLAGS=['-fno-exceptions'])
+ #env['neon_enabled']=True
+ env['S_compiler'] = '$IPHONEPATH/Developer/usr/bin/gcc'
+
+ if env['lua'] == "yes":
+ env.Append(CCFLAGS=['-DLUA_USE_FLOAT'])
+
+
+# /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang -x objective-c-header -arch armv7s -fmessage-length=0 -std=gnu99 -fobjc-arc -Wno-trigraphs -fpascal-strings -Os -Wno-missing-field-initializers -Wno-missing-prototypes -Wreturn-type -Wno-implicit-atomic-properties -Wno-receiver-is-weak -Wduplicate-method-match -Wformat -Wno-missing-braces -Wparentheses -Wswitch -Wno-unused-function -Wno-unused-label -Wno-unused-parameter -Wunused-variable -Wunused-value -Wempty-body -Wuninitialized -Wno-unknown-pragmas -Wno-shadow -Wno-four-char-constants -Wno-conversion -Wno-shorten-64-to-32 -Wpointer-sign -Wno-newline-eof -Wno-selector -Wno-strict-selector-match -Wno-undeclared-selector -Wno-deprecated-implementations -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS6.0.sdk -Wprotocol -Wdeprecated-declarations -g -fvisibility=hidden -Wno-sign-conversion "-DIBOutlet=__attribute__((iboutlet))" "-DIBOutletCollection(ClassName)=__attribute__((iboutletcollection(ClassName)))" "-DIBAction=void)__attribute__((ibaction)" -miphoneos-version-min=4.3 -iquote /Users/lucasgondolo/test/build/test.build/Release-iphoneos/test.build/test-generated-files.hmap -I/Users/lucasgondolo/test/build/test.build/Release-iphoneos/test.build/test-own-target-headers.hmap -I/Users/lucasgondolo/test/build/test.build/Release-iphoneos/test.build/test-all-target-headers.hmap -iquote /Users/lucasgondolo/test/build/test.build/Release-iphoneos/test.build/test-project-headers.hmap -I/Users/lucasgondolo/test/build/Release-iphoneos/include -I/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include -I/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include -I/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include -I/Users/lucasgondolo/test/build/test.build/Release-iphoneos/test.build/DerivedSources/armv7s -I/Users/lucasgondolo/test/build/test.build/Release-iphoneos/test.build/DerivedSources -F/Users/lucasgondolo/test/build/Release-iphoneos -DNS_BLOCK_ASSERTIONS=1 --serialize-diagnostics /var/folders/9r/_65jj9457bgb4n4nxcsm0xl80000gn/C/com.apple.Xcode.501/SharedPrecompiledHeaders/test-Prefix-esrzoamhgruxcxbhemvvlrjmmvoh/test-Prefix.pch.dia -c /Users/lucasgondolo/test/test/test-Prefix.pch -o /var/folders/9r/_65jj9457bgb4n4nxcsm0xl80000gn/C/com.apple.Xcode.501/SharedPrecompiledHeaders/test-Prefix-esrzoamhgruxcxbhemvvlrjmmvoh/test-Prefix.pch.pth -MMD -MT dependencies -MF /var/folders/9r/_65jj9457bgb4n4nxcsm0xl80000gn/C/com.apple.Xcode.501/SharedPrecompiledHeaders/test-Prefix-esrzoamhgruxcxbhemvvlrjmmvoh/test-Prefix.pch.d
+
diff --git a/platform/iphone/game_center.h b/platform/iphone/game_center.h
new file mode 100644
index 0000000000..58a040eb6d
--- /dev/null
+++ b/platform/iphone/game_center.h
@@ -0,0 +1,68 @@
+/*************************************************************************/
+/* game_center.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* http://www.godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+#ifdef GAME_CENTER_ENABLED
+
+#ifndef GAME_CENTER_H
+#define GAME_CENTER_H
+
+#include "core/object.h"
+
+class GameCenter : public Object {
+
+ OBJ_TYPE(GameCenter, Object);
+
+ static GameCenter* instance;
+ static void _bind_methods();
+
+ List<Variant> pending_events;
+
+ bool connected;
+
+public:
+
+ Error connect();
+ bool is_connected();
+
+ Error post_score(Variant p_score);
+
+ Error award_achievement(Variant p_params);
+
+ int get_pending_event_count();
+ Variant pop_pending_event();
+
+ static GameCenter* get_singleton();
+
+ GameCenter();
+ ~GameCenter();
+};
+
+
+#endif
+
+#endif
diff --git a/platform/iphone/game_center.mm b/platform/iphone/game_center.mm
new file mode 100644
index 0000000000..d517ddd105
--- /dev/null
+++ b/platform/iphone/game_center.mm
@@ -0,0 +1,163 @@
+/*************************************************************************/
+/* game_center.mm */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* http://www.godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+#ifdef GAME_CENTER_ENABLED
+
+#include "game_center.h"
+
+extern "C" {
+#import <GameKit/GameKit.h>
+};
+
+GameCenter* GameCenter::instance = NULL;
+
+void GameCenter::_bind_methods() {
+ ObjectTypeDB::bind_method(_MD("connect"),&GameCenter::connect);
+ ObjectTypeDB::bind_method(_MD("is_connected"),&GameCenter::is_connected);
+
+ ObjectTypeDB::bind_method(_MD("post_score"),&GameCenter::post_score);
+ ObjectTypeDB::bind_method(_MD("award_achievement"),&GameCenter::award_achievement);
+
+ ObjectTypeDB::bind_method(_MD("get_pending_event_count"),&GameCenter::get_pending_event_count);
+ ObjectTypeDB::bind_method(_MD("pop_pending_event"),&GameCenter::pop_pending_event);
+};
+
+
+Error GameCenter::connect() {
+
+ GKLocalPlayer* player = [GKLocalPlayer localPlayer];
+ [player authenticateWithCompletionHandler:^(NSError* error) {
+
+ Dictionary ret;
+ ret["type"] = "authentication";
+ if (player.isAuthenticated) {
+ ret["result"] = "ok";
+ GameCenter::get_singleton()->connected = true;
+ } else {
+ ret["result"] = "error";
+ ret["error_code"] = error.code;
+ ret["error_description"] = [error.localizedDescription UTF8String];
+ GameCenter::get_singleton()->connected = false;
+ };
+
+ pending_events.push_back(ret);
+ }];
+ return OK;
+};
+
+bool GameCenter::is_connected() {
+ return connected;
+};
+
+Error GameCenter::post_score(Variant p_score) {
+
+ Dictionary params = p_score;
+ ERR_FAIL_COND_V(!params.has("score") || !params.has("category"), ERR_INVALID_PARAMETER);
+ float score = params["score"];
+ String category = params["category"];
+
+ NSString* cat_str = [[[NSString alloc] initWithUTF8String:category.utf8().get_data()] autorelease];
+ GKScore* reporter = [[[GKScore alloc] initWithCategory:cat_str] autorelease];
+ reporter.value = score;
+
+ [reporter reportScoreWithCompletionHandler:^(NSError* error) {
+
+ Dictionary ret;
+ ret["type"] = "post_score";
+ if (error == nil) {
+ ret["result"] = "ok";
+ } else {
+ ret["result"] = "error";
+ ret["error_code"] = error.code;
+ ret["error_description"] = [error.localizedDescription UTF8String];
+ };
+
+ pending_events.push_back(ret);
+ }];
+
+ return OK;
+};
+
+Error GameCenter::award_achievement(Variant p_params) {
+
+ Dictionary params = p_params;
+ ERR_FAIL_COND_V(!params.has("name") || !params.has("progress"), ERR_INVALID_PARAMETER);
+ String name = params["name"];
+ float progress = params["progress"];
+
+ NSString* name_str = [[[NSString alloc] initWithUTF8String:name.utf8().get_data()] autorelease];
+ GKAchievement* achievement = [[[GKAchievement alloc] initWithIdentifier: name_str] autorelease];
+ ERR_FAIL_COND_V(!achievement, FAILED);
+
+ achievement.percentComplete = progress;
+ [achievement reportAchievementWithCompletionHandler:^(NSError* error) {
+
+ Dictionary ret;
+ ret["type"] = "award_achievement";
+ if (error == nil) {
+ ret["result"] = "ok";
+ } else {
+ ret["result"] = "error";
+ ret["error_code"] = error.code;
+ };
+
+ pending_events.push_back(ret);
+ }];
+
+ return OK;
+};
+
+int GameCenter::get_pending_event_count() {
+
+ return pending_events.size();
+};
+
+Variant GameCenter::pop_pending_event() {
+
+ Variant front = pending_events.front()->get();
+ pending_events.pop_front();
+
+ return front;
+};
+
+GameCenter* GameCenter::get_singleton() {
+ return instance;
+};
+
+GameCenter::GameCenter() {
+ ERR_FAIL_COND(instance != NULL);
+ instance = this;
+ connected = false;
+};
+
+
+GameCenter::~GameCenter() {
+
+};
+
+#endif
diff --git a/platform/iphone/gl_view.h b/platform/iphone/gl_view.h
new file mode 100755
index 0000000000..0d95af9ab1
--- /dev/null
+++ b/platform/iphone/gl_view.h
@@ -0,0 +1,100 @@
+/*************************************************************************/
+/* gl_view.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* http://www.godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#import <UIKit/UIKit.h>
+#import <OpenGLES/EAGL.h>
+#import <OpenGLES/ES1/gl.h>
+#import <OpenGLES/ES1/glext.h>
+
+@protocol GLViewDelegate;
+
+@interface GLView : UIView<UIKeyInput>
+{
+ @private
+ // The pixel dimensions of the backbuffer
+ GLint backingWidth;
+ GLint backingHeight;
+
+ EAGLContext *context;
+
+ // OpenGL names for the renderbuffer and framebuffers used to render to this view
+ GLuint viewRenderbuffer, viewFramebuffer;
+
+ // OpenGL name for the depth buffer that is attached to viewFramebuffer, if it exists (0 if it does not exist)
+ GLuint depthRenderbuffer;
+
+ // An animation timer that, when animation is started, will periodically call -drawView at the given rate.
+ NSTimer *animationTimer;
+ NSTimeInterval animationInterval;
+
+ // Delegate to do our drawing, called by -drawView, which can be called manually or via the animation timer.
+ id<GLViewDelegate> delegate;
+
+ // Flag to denote that the -setupView method of a delegate has been called.
+ // Resets to NO whenever the delegate changes.
+ BOOL delegateSetup;
+ BOOL active;
+ float screen_scale;
+}
+
+@property(nonatomic, assign) id<GLViewDelegate> delegate;
+
+-(void)startAnimation;
+-(void)stopAnimation;
+-(void)drawView;
+
+- (BOOL)canBecomeFirstResponder;
+
+- (void)open_keyboard;
+- (void)hide_keyboard;
+- (void)deleteBackward;
+- (BOOL)hasText;
+- (void)insertText:(NSString *)p_text;
+
+- (id)initGLES;
+- (BOOL)createFramebuffer;
+- (void)destroyFramebuffer;
+
+@property NSTimeInterval animationInterval;
+
+@end
+
+@protocol GLViewDelegate<NSObject>
+
+@required
+
+// Draw with OpenGL ES
+-(void)drawView:(GLView*)view;
+
+@optional
+
+// Called whenever you need to do some initialization before rendering.
+-(void)setupView:(GLView*)view;
+
+@end
diff --git a/platform/iphone/gl_view.mm b/platform/iphone/gl_view.mm
new file mode 100755
index 0000000000..07f5b39fac
--- /dev/null
+++ b/platform/iphone/gl_view.mm
@@ -0,0 +1,457 @@
+/*************************************************************************/
+/* gl_view.mm */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* http://www.godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#import <QuartzCore/QuartzCore.h>
+#import <OpenGLES/EAGLDrawable.h>
+#include "os_iphone.h"
+#include "core/os/keyboard.h"
+
+#import "gl_view.h"
+
+/*
+@interface GLView (private)
+
+- (id)initGLES;
+- (BOOL)createFramebuffer;
+- (void)destroyFramebuffer;
+@end
+*/
+
+int gl_view_base_fb;
+static String keyboard_text;
+static GLView* _instance = NULL;
+
+void _show_keyboard(String p_existing) {
+ keyboard_text = p_existing;
+ printf("instance on show is %p\n", _instance);
+ [_instance open_keyboard];
+};
+
+void _hide_keyboard() {
+ printf("instance on hide is %p\n", _instance);
+ [_instance hide_keyboard];
+ keyboard_text = "";
+};
+
+@implementation GLView
+
+@synthesize animationInterval;
+
+static const int max_touches = 8;
+static UITouch* touches[max_touches];
+
+static void init_touches() {
+
+ for (int i=0; i<max_touches; i++) {
+ touches[i] = NULL;
+ };
+};
+
+static int get_touch_id(UITouch* p_touch) {
+
+ int first = -1;
+ for (int i=0; i<max_touches; i++) {
+ if (first == -1 && touches[i] == NULL) {
+ first = i;
+ continue;
+ };
+ if (touches[i] == p_touch)
+ return i;
+ };
+
+ if (first != -1) {
+ touches[first] = p_touch;
+ return first;
+ };
+
+ return -1;
+};
+
+static int remove_touch(UITouch* p_touch) {
+
+ int remaining = 0;
+ for (int i=0; i<max_touches; i++) {
+
+ if (touches[i] == NULL)
+ continue;
+ if (touches[i] == p_touch)
+ touches[i] = NULL;
+ else
+ ++remaining;
+ };
+ return remaining;
+};
+
+static int get_first_id(UITouch* p_touch) {
+
+ for (int i=0; i<max_touches; i++) {
+
+ if (touches[i] != NULL)
+ return i;
+ };
+ return -1;
+};
+
+static void clear_touches() {
+
+ for (int i=0; i<max_touches; i++) {
+
+ touches[i] = NULL;
+ };
+};
+
+// Implement this to override the default layer class (which is [CALayer class]).
+// We do this so that our view will be backed by a layer that is capable of OpenGL ES rendering.
++ (Class) layerClass
+{
+ return [CAEAGLLayer class];
+}
+
+//The GL view is stored in the nib file. When it's unarchived it's sent -initWithCoder:
+- (id)initWithCoder:(NSCoder*)coder
+{
+ active = FALSE;
+ if((self = [super initWithCoder:coder]))
+ {
+ self = [self initGLES];
+ }
+ return self;
+}
+
+-(id)initGLES
+{
+ // Get our backing layer
+ CAEAGLLayer *eaglLayer = (CAEAGLLayer*) self.layer;
+
+ // Configure it so that it is opaque, does not retain the contents of the backbuffer when displayed, and uses RGBA8888 color.
+ eaglLayer.opaque = YES;
+ eaglLayer.drawableProperties = [NSDictionary dictionaryWithObjectsAndKeys:
+ [NSNumber numberWithBool:FALSE], kEAGLDrawablePropertyRetainedBacking,
+ kEAGLColorFormatRGBA8, kEAGLDrawablePropertyColorFormat,
+ nil];
+
+ // Create our EAGLContext, and if successful make it current and create our framebuffer.
+#ifdef GLES1_OVERRIDE
+ context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES1];
+#else
+ context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];
+#endif
+
+ if(!context || ![EAGLContext setCurrentContext:context] || ![self createFramebuffer])
+ {
+ [self release];
+ return nil;
+ }
+
+ // Default the animation interval to 1/60th of a second.
+ animationInterval = 1.0 / 60.0;
+ return self;
+}
+
+-(id<GLViewDelegate>)delegate
+{
+ return delegate;
+}
+
+// Update the delegate, and if it needs a -setupView: call, set our internal flag so that it will be called.
+-(void)setDelegate:(id<GLViewDelegate>)d
+{
+ delegate = d;
+ delegateSetup = ![delegate respondsToSelector:@selector(setupView:)];
+}
+
+// If our view is resized, we'll be asked to layout subviews.
+// This is the perfect opportunity to also update the framebuffer so that it is
+// the same size as our display area.
+-(void)layoutSubviews
+{
+ [EAGLContext setCurrentContext:context];
+ [self destroyFramebuffer];
+ [self createFramebuffer];
+ [self drawView];
+}
+
+- (BOOL)createFramebuffer
+{
+ // Generate IDs for a framebuffer object and a color renderbuffer
+ UIScreen* mainscr = [UIScreen mainScreen];
+ if (mainscr.currentMode.size.width == 640 || mainscr.currentMode.size.width == 960) // modern iphone, can go to 640x960
+ self.contentScaleFactor = 2.0;
+
+ glGenFramebuffersOES(1, &viewFramebuffer);
+ glGenRenderbuffersOES(1, &viewRenderbuffer);
+
+ glBindFramebufferOES(GL_FRAMEBUFFER_OES, viewFramebuffer);
+ glBindRenderbufferOES(GL_RENDERBUFFER_OES, viewRenderbuffer);
+ // This call associates the storage for the current render buffer with the EAGLDrawable (our CAEAGLLayer)
+ // allowing us to draw into a buffer that will later be rendered to screen whereever the layer is (which corresponds with our view).
+ [context renderbufferStorage:GL_RENDERBUFFER_OES fromDrawable:(id<EAGLDrawable>)self.layer];
+ glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, viewRenderbuffer);
+
+ glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &backingWidth);
+ glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &backingHeight);
+
+ // For this sample, we also need a depth buffer, so we'll create and attach one via another renderbuffer.
+ glGenRenderbuffersOES(1, &depthRenderbuffer);
+ glBindRenderbufferOES(GL_RENDERBUFFER_OES, depthRenderbuffer);
+ glRenderbufferStorageOES(GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, backingWidth, backingHeight);
+ glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthRenderbuffer);
+
+ if(glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES) != GL_FRAMEBUFFER_COMPLETE_OES)
+ {
+ NSLog(@"failed to make complete framebuffer object %x", glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES));
+ return NO;
+ }
+
+ if (OS::get_singleton()) {
+ OS::VideoMode vm;
+ vm.fullscreen = true;
+ vm.width = backingWidth;
+ vm.height = backingHeight;
+ vm.resizable = false;
+ OS::get_singleton()->set_video_mode(vm);
+ OSIPhone::get_singleton()->set_base_framebuffer(viewFramebuffer);
+ };
+ gl_view_base_fb = viewFramebuffer;
+
+ return YES;
+}
+
+// Clean up any buffers we have allocated.
+- (void)destroyFramebuffer
+{
+ glDeleteFramebuffersOES(1, &viewFramebuffer);
+ viewFramebuffer = 0;
+ glDeleteRenderbuffersOES(1, &viewRenderbuffer);
+ viewRenderbuffer = 0;
+
+ if(depthRenderbuffer)
+ {
+ glDeleteRenderbuffersOES(1, &depthRenderbuffer);
+ depthRenderbuffer = 0;
+ }
+}
+
+- (void)startAnimation
+{
+ if (active)
+ return;
+ active = TRUE;
+ printf("start animation!\n");
+ animationTimer = [NSTimer scheduledTimerWithTimeInterval:animationInterval target:self selector:@selector(drawView) userInfo:nil repeats:YES];
+}
+
+- (void)stopAnimation
+{
+ if (!active)
+ return;
+ active = FALSE;
+ printf("******** stop animation!\n");
+ [animationTimer invalidate];
+ animationTimer = nil;
+ clear_touches();
+}
+
+- (void)setAnimationInterval:(NSTimeInterval)interval
+{
+ animationInterval = interval;
+
+ if(animationTimer)
+ {
+ [self stopAnimation];
+ [self startAnimation];
+ }
+}
+
+// Updates the OpenGL view when the timer fires
+- (void)drawView
+{
+ if (!active) {
+ printf("draw view not active!\n");
+ return;
+ };
+
+ // Make sure that you are drawing to the current context
+ [EAGLContext setCurrentContext:context];
+
+ // If our drawing delegate needs to have the view setup, then call -setupView: and flag that it won't need to be called again.
+ if(!delegateSetup)
+ {
+ [delegate setupView:self];
+ delegateSetup = YES;
+ }
+
+ glBindFramebufferOES(GL_FRAMEBUFFER_OES, viewFramebuffer);
+
+ [delegate drawView:self];
+
+ glBindRenderbufferOES(GL_RENDERBUFFER_OES, viewRenderbuffer);
+ [context presentRenderbuffer:GL_RENDERBUFFER_OES];
+
+ GLenum err = glGetError();
+ if(err)
+ NSLog(@"%x error", err);
+}
+
+- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
+{
+ NSArray* tlist = [[event allTouches] allObjects];
+ for (unsigned int i=0; i< [tlist count]; i++) {
+
+ if ( [touches containsObject:[tlist objectAtIndex:i]] ) {
+
+ UITouch* touch = [tlist objectAtIndex:i];
+ if (touch.phase != UITouchPhaseBegan)
+ continue;
+ int tid = get_touch_id(touch);
+ ERR_FAIL_COND(tid == -1);
+ CGPoint touchPoint = [touch locationInView:self];
+ OSIPhone::get_singleton()->mouse_button(tid, touchPoint.x * self.contentScaleFactor, touchPoint.y * self.contentScaleFactor, true, touch.tapCount > 1, tid == 0);
+ };
+ };
+}
+
+- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
+{
+
+ NSArray* tlist = [[event allTouches] allObjects];
+ for (unsigned int i=0; i< [tlist count]; i++) {
+
+ if ( [touches containsObject:[tlist objectAtIndex:i]] ) {
+
+ UITouch* touch = [tlist objectAtIndex:i];
+ if (touch.phase != UITouchPhaseMoved)
+ continue;
+ int tid = get_touch_id(touch);
+ ERR_FAIL_COND(tid == -1);
+ int first = get_first_id(touch);
+ CGPoint touchPoint = [touch locationInView:self];
+ CGPoint prev_point = [touch previousLocationInView:self];
+ OSIPhone::get_singleton()->mouse_move(tid, prev_point.x * self.contentScaleFactor, prev_point.y * self.contentScaleFactor, touchPoint.x * self.contentScaleFactor, touchPoint.y * self.contentScaleFactor, first == tid);
+ };
+ };
+
+}
+
+- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
+{
+ NSArray* tlist = [[event allTouches] allObjects];
+ for (unsigned int i=0; i< [tlist count]; i++) {
+
+ if ( [touches containsObject:[tlist objectAtIndex:i]] ) {
+
+ UITouch* touch = [tlist objectAtIndex:i];
+ if (touch.phase != UITouchPhaseEnded)
+ continue;
+ int tid = get_touch_id(touch);
+ ERR_FAIL_COND(tid == -1);
+ int rem = remove_touch(touch);
+ CGPoint touchPoint = [touch locationInView:self];
+ OSIPhone::get_singleton()->mouse_button(tid, touchPoint.x * self.contentScaleFactor, touchPoint.y * self.contentScaleFactor, false, false, rem == 0);
+ };
+ };
+}
+
+- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
+
+ OSIPhone::get_singleton()->touches_cancelled();
+ clear_touches();
+};
+
+- (BOOL)canBecomeFirstResponder {
+ return YES;
+};
+
+
+- (void)open_keyboard {
+ //keyboard_text = p_existing;
+ [self becomeFirstResponder];
+};
+
+- (void)hide_keyboard {
+ //keyboard_text = p_existing;
+ [self resignFirstResponder];
+};
+
+- (void)deleteBackward {
+ if (keyboard_text.length())
+ keyboard_text.erase(keyboard_text.length() - 1, 1);
+ OSIPhone::get_singleton()->key(KEY_BACKSPACE, true);
+};
+
+- (BOOL)hasText {
+ return keyboard_text.length() ? YES : NO;
+};
+
+- (void)insertText:(NSString *)p_text {
+ String character;
+ character.parse_utf8([p_text UTF8String]);
+ keyboard_text = keyboard_text + character;
+ OSIPhone::get_singleton()->key(character[0] == 10 ? KEY_ENTER : character[0] , true);
+ printf("inserting text with character %i\n", character[0]);
+};
+
+
+// When created via code however, we get initWithFrame
+-(id)initWithFrame:(CGRect)frame
+{
+ self = [super initWithFrame:frame];
+ _instance = self;
+ printf("after init super %p\n", self);
+ if(self != nil)
+ {
+ self = [self initGLES];
+ printf("after init gles %p\n", self);
+ }
+ init_touches();
+ self. multipleTouchEnabled = YES;
+
+ //self.autoresizesSubviews = YES;
+ //[self setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleWidth];
+
+ return self;
+}
+
+// Stop animating and release resources when they are no longer needed.
+- (void)dealloc
+{
+ [self stopAnimation];
+
+ if([EAGLContext currentContext] == context)
+ {
+ [EAGLContext setCurrentContext:nil];
+ }
+
+ [context release];
+ context = nil;
+
+ [super dealloc];
+}
+
+@end
diff --git a/platform/iphone/globals/global_defaults.cpp b/platform/iphone/globals/global_defaults.cpp
new file mode 100644
index 0000000000..63463ab366
--- /dev/null
+++ b/platform/iphone/globals/global_defaults.cpp
@@ -0,0 +1,11 @@
+
+#include "global_defaults.h"
+#include "globals.h"
+
+
+void register_iphone_global_defaults() {
+
+ GLOBAL_DEF("rasterizer.iOS/use_fragment_lighting",false);
+ GLOBAL_DEF("display.iOS/driver","GLES2");
+ Globals::get_singleton()->set_custom_property_info("display.iOS/driver",PropertyInfo(Variant::STRING,"display.iOS/driver",PROPERTY_HINT_ENUM,"GLES1,GLES2"));
+}
diff --git a/platform/iphone/globals/global_defaults.h b/platform/iphone/globals/global_defaults.h
new file mode 100644
index 0000000000..25f1ae687e
--- /dev/null
+++ b/platform/iphone/globals/global_defaults.h
@@ -0,0 +1,3 @@
+
+
+void register_iphone_global_defaults(); \ No newline at end of file
diff --git a/platform/iphone/godot_iphone.cpp b/platform/iphone/godot_iphone.cpp
new file mode 100644
index 0000000000..eb3f17736a
--- /dev/null
+++ b/platform/iphone/godot_iphone.cpp
@@ -0,0 +1,86 @@
+/*************************************************************************/
+/* godot_iphone.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* http://www.godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+#include "os_iphone.h"
+#include "main/main.h"
+
+#include <stdio.h>
+#include <unistd.h>
+#include <string.h>
+
+static OSIPhone* os = NULL;
+
+extern "C" {
+int add_path(int p_argc, char** p_args);
+};
+
+int iphone_main(int width, int height, int argc, char** argv) {
+
+ int len = strlen(argv[0]);
+
+ while (len--){
+ if (argv[0][len] == '/') break;
+ }
+
+ if (len>=0) {
+ char path[512];
+ memcpy(path, argv[0], len>sizeof(path)?sizeof(path):len);
+ path[len]=0;
+ printf("Path: %s\n", path);
+ chdir(path);
+ }
+
+ printf("godot_iphone %s\n", argv[0]);
+ char cwd[512];
+ getcwd(cwd, sizeof(cwd));
+ printf("cwd %s\n", cwd);
+ os = new OSIPhone(width, height);
+
+ char* fargv[64];
+ for (int i=0; i<argc; i++) {
+ fargv[i] = argv[i];
+ };
+ fargv[argc] = NULL;
+ argc = add_path(argc, fargv);
+
+ printf("os created\n");
+ Error err = Main::setup(fargv[0], argc - 1, &fargv[1], false);
+ printf("setup %i\n", err);
+ if (err!=OK)
+ return 255;
+
+ return 0;
+};
+
+
+void iphone_finish() {
+
+ printf("iphone_finish\n");
+ Main::cleanup();
+ delete os;
+};
diff --git a/platform/iphone/in_app_store.h b/platform/iphone/in_app_store.h
new file mode 100644
index 0000000000..dba1a1a5a1
--- /dev/null
+++ b/platform/iphone/in_app_store.h
@@ -0,0 +1,66 @@
+/*************************************************************************/
+/* in_app_store.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* http://www.godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+#ifdef STOREKIT_ENABLED
+
+#ifndef IN_APP_STORE_H
+#define IN_APP_STORE_H
+
+#include "core/object.h"
+
+class InAppStore : public Object {
+
+ OBJ_TYPE(InAppStore, Object);
+
+ static InAppStore* instance;
+ static void _bind_methods();
+
+ List<Variant> pending_events;
+
+public:
+
+ Error request_product_info(Variant p_params);
+ Error purchase(Variant p_params);
+
+ int get_pending_event_count();
+ Variant pop_pending_event();
+
+ void _post_event(Variant p_event);
+ void _record_purchase(String product_id);
+
+ static InAppStore* get_singleton();
+
+ InAppStore();
+ ~InAppStore();
+};
+
+#endif
+
+
+#endif
+
diff --git a/platform/iphone/in_app_store.mm b/platform/iphone/in_app_store.mm
new file mode 100644
index 0000000000..316e619e11
--- /dev/null
+++ b/platform/iphone/in_app_store.mm
@@ -0,0 +1,264 @@
+/*************************************************************************/
+/* in_app_store.mm */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* http://www.godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+#ifdef STOREKIT_ENABLED
+
+#include "in_app_store.h"
+
+extern "C" {
+#import <StoreKit/StoreKit.h>
+};
+
+@interface SKProduct (LocalizedPrice)
+@property (nonatomic, readonly) NSString *localizedPrice;
+@end
+
+//----------------------------------//
+// SKProduct extension
+//----------------------------------//
+@implementation SKProduct (LocalizedPrice)
+- (NSString *)localizedPrice
+{
+ NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
+ [numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
+ [numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
+ [numberFormatter setLocale:self.priceLocale];
+ NSString *formattedString = [numberFormatter stringFromNumber:self.price];
+ [numberFormatter release];
+ return formattedString;
+}
+@end
+
+
+InAppStore* InAppStore::instance = NULL;
+
+void InAppStore::_bind_methods() {
+ ObjectTypeDB::bind_method(_MD("request_product_info"),&InAppStore::request_product_info);
+ ObjectTypeDB::bind_method(_MD("purchase"),&InAppStore::purchase);
+
+ ObjectTypeDB::bind_method(_MD("get_pending_event_count"),&InAppStore::get_pending_event_count);
+ ObjectTypeDB::bind_method(_MD("pop_pending_event"),&InAppStore::pop_pending_event);
+};
+
+@interface ProductsDelegate : NSObject<SKProductsRequestDelegate> {
+
+};
+
+@end
+
+@implementation ProductsDelegate
+
+- (void)productsRequest:(SKProductsRequest*)request didReceiveResponse:(SKProductsResponse*)response {
+
+ NSArray* products = response.products;
+ Dictionary ret;
+ ret["type"] = "product_info";
+ ret["result"] = "ok";
+ StringArray titles;
+ StringArray descriptions;
+ RealArray prices;
+ StringArray ids;
+ StringArray localized_prices;
+
+ for (int i=0; i<[products count]; i++) {
+
+ SKProduct* product = [products objectAtIndex:i];
+
+ const char* str = [product.localizedTitle UTF8String];
+ titles.push_back(String::utf8(str != NULL ? str : ""));
+
+ str = [product.localizedDescription UTF8String];
+ descriptions.push_back(String::utf8(str != NULL ? str : ""));
+ prices.push_back([product.price doubleValue]);
+ ids.push_back(String::utf8([product.productIdentifier UTF8String]));
+ localized_prices.push_back(String::utf8([product.localizedPrice UTF8String]));
+ };
+ ret["titles"] = titles;
+ ret["descriptions"] = descriptions;
+ ret["prices"] = prices;
+ ret["ids"] = ids;
+ ret["localized_prices"] = localized_prices;
+
+ StringArray invalid_ids;
+
+ for (NSString* ipid in response.invalidProductIdentifiers) {
+
+ invalid_ids.push_back(String::utf8([ipid UTF8String]));
+ };
+ ret["invalid_ids"] = invalid_ids;
+
+ InAppStore::get_singleton()->_post_event(ret);
+
+ [request release];
+};
+
+@end
+
+Error InAppStore::request_product_info(Variant p_params) {
+
+ Dictionary params = p_params;
+ ERR_FAIL_COND_V(!params.has("product_ids"), ERR_INVALID_PARAMETER);
+
+ StringArray pids = params["product_ids"];
+ printf("************ request product info! %i\n", pids.size());
+
+ NSMutableArray* array = [[[NSMutableArray alloc] initWithCapacity:pids.size()] autorelease];
+ for (int i=0; i<pids.size(); i++) {
+ printf("******** adding %ls to product list\n", pids[i].c_str());
+ NSString* pid = [[[NSString alloc] initWithUTF8String:pids[i].utf8().get_data()] autorelease];
+ [array addObject:pid];
+ };
+
+ NSSet* products = [[[NSSet alloc] initWithArray:array] autorelease];
+ SKProductsRequest* request = [[SKProductsRequest alloc] initWithProductIdentifiers:products];
+
+ ProductsDelegate *delegate = [[ProductsDelegate alloc] init];
+
+ request.delegate = delegate;
+ [request start];
+
+ return OK;
+};
+
+@interface TransObserver : NSObject<SKPaymentTransactionObserver> {
+
+};
+@end
+
+@implementation TransObserver
+
+- (void)paymentQueue:(SKPaymentQueue*)queue updatedTransactions:(NSArray*) transactions {
+
+ printf("transactions updated!\n");
+ for (SKPaymentTransaction* transaction in transactions) {
+
+ switch (transaction.transactionState) {
+
+ case SKPaymentTransactionStatePurchased: {
+ printf("status purchased!\n");
+ String pid = String::utf8([transaction.payment.productIdentifier UTF8String]);
+ InAppStore::get_singleton()->_record_purchase(pid);
+ Dictionary ret;
+ ret["type"] = "purchase";
+ ret["result"] = "ok";
+ ret["product_id"] = pid;
+ InAppStore::get_singleton()->_post_event(ret);
+ [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
+ } break;
+ case SKPaymentTransactionStateFailed: {
+ printf("status transaction failed!\n");
+ String pid = String::utf8([transaction.payment.productIdentifier UTF8String]);
+ Dictionary ret;
+ ret["type"] = "purchase";
+ ret["result"] = "error";
+ ret["product_id"] = pid;
+ InAppStore::get_singleton()->_post_event(ret);
+ [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
+ } break;
+ case SKPaymentTransactionStateRestored: {
+ printf("status transaction restored!\n");
+ String pid = String::utf8([transaction.originalTransaction.payment.productIdentifier UTF8String]);
+ InAppStore::get_singleton()->_record_purchase(pid);
+ [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
+ } break;
+
+ default:
+ printf("status default %i!\n", (int)transaction.transactionState);
+
+ break;
+ };
+ };
+};
+
+@end
+
+
+Error InAppStore::purchase(Variant p_params) {
+
+ ERR_FAIL_COND_V(![SKPaymentQueue canMakePayments], ERR_UNAVAILABLE);
+ if (![SKPaymentQueue canMakePayments])
+ return ERR_UNAVAILABLE;
+
+ printf("purchasing!\n");
+ Dictionary params = p_params;
+ ERR_FAIL_COND_V(!params.has("product_id"), ERR_INVALID_PARAMETER);
+
+ NSString *pid = [[[NSString alloc] initWithUTF8String:String(params["product_id"]).utf8().get_data()] autorelease];
+ SKPayment *payment = [SKPayment paymentWithProductIdentifier:pid];
+ SKPaymentQueue* defq = [SKPaymentQueue defaultQueue];
+ [defq addPayment:payment];
+ printf("purchase sent!\n");
+
+ return OK;
+};
+
+
+int InAppStore::get_pending_event_count() {
+ return pending_events.size();
+};
+
+Variant InAppStore::pop_pending_event() {
+
+ Variant front = pending_events.front()->get();
+ pending_events.pop_front();
+
+ return front;
+};
+
+void InAppStore::_post_event(Variant p_event) {
+
+ pending_events.push_back(p_event);
+};
+
+void InAppStore::_record_purchase(String product_id) {
+
+ String skey = "purchased/"+product_id;
+ NSString* key = [[[NSString alloc] initWithUTF8String:skey.utf8().get_data()] autorelease];
+ [[NSUserDefaults standardUserDefaults] setBool:YES forKey:key];
+ [[NSUserDefaults standardUserDefaults] synchronize];
+};
+
+InAppStore* InAppStore::get_singleton() {
+
+ return instance;
+};
+
+InAppStore::InAppStore() {
+ ERR_FAIL_COND(instance != NULL);
+ instance = this;
+
+ TransObserver* observer = [[TransObserver alloc] init];
+ [[SKPaymentQueue defaultQueue] addTransactionObserver:observer];
+};
+
+InAppStore::~InAppStore() {
+
+};
+
+
+#endif
diff --git a/platform/iphone/logo.png b/platform/iphone/logo.png
new file mode 100644
index 0000000000..d1851d7a5e
--- /dev/null
+++ b/platform/iphone/logo.png
Binary files differ
diff --git a/platform/iphone/main.m b/platform/iphone/main.m
new file mode 100644
index 0000000000..055e6a63c8
--- /dev/null
+++ b/platform/iphone/main.m
@@ -0,0 +1,22 @@
+#import <UIKit/UIKit.h>
+#import "app_delegate.h"
+#include <stdio.h>
+
+int gargc;
+char** gargv;
+
+int main(int argc, char *argv[])
+{
+ printf("*********** main.m\n");
+ gargc = argc;
+ gargv = argv;
+
+ NSAutoreleasePool *pool = [NSAutoreleasePool new];
+ AppDelegate* app = [AppDelegate alloc];
+ printf("running app main\n");
+ UIApplicationMain(argc, argv, nil, @"AppDelegate");
+ printf("main done, pool release\n");
+ [pool release];
+ return 0;
+}
+
diff --git a/platform/iphone/os_iphone.cpp b/platform/iphone/os_iphone.cpp
new file mode 100644
index 0000000000..3b3b30cb86
--- /dev/null
+++ b/platform/iphone/os_iphone.cpp
@@ -0,0 +1,507 @@
+/*************************************************************************/
+/* os_iphone.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* http://www.godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+#ifdef IPHONE_ENABLED
+
+#include "os_iphone.h"
+
+#include "drivers/gles2/rasterizer_gles2.h"
+#include "drivers/gles1/rasterizer_gles1.h"
+
+#include "servers/visual/visual_server_raster.h"
+#include "servers/visual/visual_server_wrap_mt.h"
+
+#include "main/main.h"
+#include "audio_driver_iphone.h"
+
+#include "core/os/dir_access.h"
+#include "core/globals.h"
+
+#include "sem_iphone.h"
+
+int OSIPhone::get_video_driver_count() const {
+
+ return 1;
+};
+
+const char * OSIPhone::get_video_driver_name(int p_driver) const {
+
+ return "openglES";
+};
+
+OSIPhone* OSIPhone::get_singleton() {
+
+ return (OSIPhone*)OS::get_singleton();
+};
+
+
+OS::VideoMode OSIPhone::get_default_video_mode() const {
+
+ return video_mode;
+};
+
+uint8_t OSIPhone::get_orientations() const {
+
+ return supported_orientations;
+};
+
+extern int gl_view_base_fb; // from gl_view.mm
+
+void OSIPhone::set_data_dir(String p_dir) {
+
+ DirAccess* da = DirAccess::open(p_dir);
+
+ data_dir = da->get_current_dir();
+
+ memdelete(da);
+};
+
+void OSIPhone::set_unique_ID(String p_ID) {
+
+ unique_ID = p_ID;
+};
+
+String OSIPhone::get_unique_ID() const {
+
+ return unique_ID;
+};
+
+void OSIPhone::initialize_core() {
+
+ OS_Unix::initialize_core();
+ SemaphoreIphone::make_default();
+};
+
+void OSIPhone::initialize(const VideoMode& p_desired,int p_video_driver,int p_audio_driver) {
+
+ supported_orientations = 0;
+ supported_orientations |= ((GLOBAL_DEF("video_mode/allow_horizontal", true)?1:0) << LandscapeLeft);
+ supported_orientations |= ((GLOBAL_DEF("video_mode/allow_horizontal_flipped", false)?1:0) << LandscapeRight);
+ supported_orientations |= ((GLOBAL_DEF("video_mode/allow_vertical", false)?1:0) << PortraitDown);
+ supported_orientations |= ((GLOBAL_DEF("video_mode/allow_vertical_flipped", false)?1:0) << PortraitUp);
+
+#ifdef GLES1_OVERRIDE
+ rasterizer = memnew( RasterizerGLES1 );
+#else
+ rasterizer_gles22 = memnew( RasterizerGLES2(false, false, false) );
+ rasterizer = rasterizer_gles22;
+ rasterizer_gles22->set_base_framebuffer(gl_view_base_fb);
+#endif
+
+ visual_server = memnew( VisualServerRaster(rasterizer) );
+ if (get_render_thread_mode() != RENDER_THREAD_UNSAFE) {
+
+ visual_server = memnew(VisualServerWrapMT(visual_server, false));
+ };
+ visual_server->init();
+
+ visual_server->init();
+ visual_server->cursor_set_visible(false, 0);
+
+ audio_driver = memnew(AudioDriverIphone);
+ audio_driver->set_singleton();
+ audio_driver->init();
+
+ sample_manager = memnew( SampleManagerMallocSW );
+ audio_server = memnew( AudioServerSW(sample_manager) );
+ audio_server->init();
+ spatial_sound_server = memnew( SpatialSoundServerSW );
+ spatial_sound_server->init();
+
+ spatial_sound_2d_server = memnew( SpatialSound2DServerSW );
+ spatial_sound_2d_server->init();
+
+ //
+ physics_server = memnew( PhysicsServerSW );
+ physics_server->init();
+ physics_2d_server = memnew( Physics2DServerSW );
+ physics_2d_server->init();
+
+ input = memnew( InputDefault );
+
+ /*
+#ifdef IOS_SCORELOOP_ENABLED
+ scoreloop = memnew(ScoreloopIOS);
+ Globals::get_singleton()->add_singleton(Globals::Singleton("Scoreloop", scoreloop));
+ scoreloop->connect();
+#endif
+ */
+
+#ifdef GAME_CENTER_ENABLED
+ game_center = memnew(GameCenter);
+ Globals::get_singleton()->add_singleton(Globals::Singleton("GameCenter", game_center));
+ game_center->connect();
+#endif
+
+#ifdef STOREKIT_ENABLED
+ store_kit = memnew(InAppStore);
+ Globals::get_singleton()->add_singleton(Globals::Singleton("InAppStore", store_kit));
+#endif
+};
+
+MainLoop *OSIPhone::get_main_loop() const {
+
+ return main_loop;
+};
+
+
+void OSIPhone::set_main_loop( MainLoop * p_main_loop ) {
+
+ main_loop = p_main_loop;
+
+ if (main_loop) {
+ input->set_main_loop(p_main_loop);
+ main_loop->init();
+ }
+};
+
+
+bool OSIPhone::iterate() {
+
+ if (!main_loop)
+ return true;
+
+ if (main_loop) {
+ for (int i=0; i<event_count; i++) {
+
+ input->parse_input_event(event_queue[i]);
+ };
+ };
+ event_count = 0;
+
+ return Main::iteration();
+};
+
+void OSIPhone::key(uint32_t p_key, bool p_pressed) {
+
+ InputEvent ev;
+ ev.type = InputEvent::KEY;
+ ev.ID = ++last_event_id;
+ ev.key.echo = false;
+ ev.key.pressed = p_pressed;
+ ev.key.scancode = p_key;
+ ev.key.unicode = p_key;
+ queue_event(ev);
+};
+
+void OSIPhone::mouse_button(int p_idx, int p_x, int p_y, bool p_pressed, bool p_doubleclick, bool p_use_as_mouse) {
+
+ InputEvent ev;
+ ev.type = InputEvent::SCREEN_TOUCH;
+ ev.ID = ++last_event_id;
+ ev.screen_touch.index=p_idx;
+ ev.screen_touch.pressed=p_pressed;
+ ev.screen_touch.x=p_x;
+ ev.screen_touch.y=p_y;
+ queue_event(ev);
+
+ if (p_use_as_mouse) {
+
+ InputEvent ev;
+ ev.type = InputEvent::MOUSE_BUTTON;
+ ev.device = 0;
+ ev.mouse_button.pointer_index = p_idx;
+ ev.ID = ++last_event_id;
+
+ // swaped it for tilted screen
+ //ev.mouse_button.x = ev.mouse_button.global_x = video_mode.height - p_y;
+ //ev.mouse_button.y = ev.mouse_button.global_y = p_x;
+ ev.mouse_button.x = ev.mouse_button.global_x = p_x;
+ ev.mouse_button.y = ev.mouse_button.global_y = p_y;
+
+ ev.mouse_button.button_index = BUTTON_LEFT;
+ ev.mouse_button.doubleclick = p_doubleclick;
+ ev.mouse_button.pressed = p_pressed;
+
+ mouse_list.pressed[p_idx] = p_pressed;
+
+ queue_event(ev);
+ };
+};
+
+void OSIPhone::mouse_move(int p_idx, int p_prev_x, int p_prev_y, int p_x, int p_y, bool p_use_as_mouse) {
+
+ InputEvent ev;
+ ev.type=InputEvent::SCREEN_DRAG;
+ ev.ID = ++last_event_id;
+ ev.screen_drag.index=p_idx;
+ ev.screen_drag.x=p_x;
+ ev.screen_drag.y=p_y;
+ ev.screen_drag.relative_x = p_x - p_prev_x;
+ ev.screen_drag.relative_y = p_y - p_prev_y;
+ queue_event(ev);
+
+ if (p_use_as_mouse) {
+ InputEvent ev;
+ ev.type = InputEvent::MOUSE_MOTION;
+ ev.device = 0;
+ ev.mouse_motion.pointer_index = p_idx;
+ ev.ID = ++last_event_id;
+
+ if (true) { // vertical
+
+ ev.mouse_motion.x = ev.mouse_button.global_x = p_x;
+ ev.mouse_motion.y = ev.mouse_button.global_y = p_y;
+ ev.mouse_motion.relative_x = ev.mouse_motion.x - p_prev_x;
+ ev.mouse_motion.relative_y = ev.mouse_motion.y - p_prev_y;
+
+ } else { // horizontal?
+ ev.mouse_motion.x = ev.mouse_button.global_x = video_mode.height - p_y;
+ ev.mouse_motion.y = ev.mouse_button.global_y = p_x;
+ ev.mouse_motion.relative_x = ev.mouse_motion.x - (video_mode.height - p_prev_x);
+ ev.mouse_motion.relative_y = ev.mouse_motion.y - p_prev_x;
+ };
+
+ input->set_mouse_pos(Point2(ev.mouse_motion.x,ev.mouse_motion.y));
+ ev.mouse_motion.speed_x=input->get_mouse_speed().x;
+ ev.mouse_motion.speed_y=input->get_mouse_speed().y;
+ ev.mouse_motion.button_mask = 1; // pressed
+
+ queue_event(ev);
+ };
+};
+
+void OSIPhone::queue_event(const InputEvent& p_event) {
+
+ ERR_FAIL_INDEX( event_count, MAX_EVENTS );
+
+ event_queue[event_count++] = p_event;
+};
+
+void OSIPhone::touches_cancelled() {
+
+ for (int i=0; i<MAX_MOUSE_COUNT; i++) {
+
+ if (mouse_list.pressed[i]) {
+
+ // send a mouse_up outside the screen
+ mouse_button(i, -1, -1, false, false, false);
+ };
+ };
+};
+
+static const float ACCEL_RANGE = 1;
+
+void OSIPhone::update_accelerometer(float p_x, float p_y, float p_z) {
+
+ input->set_accelerometer(Vector3(p_x / (float)ACCEL_RANGE, p_y / (float)ACCEL_RANGE, -p_z / (float)ACCEL_RANGE));
+
+ /*
+ if (p_x != last_accel.x) {
+ //printf("updating accel x %f\n", p_x);
+ InputEvent ev;
+ ev.type = InputEvent::JOYSTICK_MOTION;
+ ev.device = 0;
+ ev.joy_motion.axis = JOY_ANALOG_0_X;
+ ev.joy_motion.axis_value = (p_x / (float)ACCEL_RANGE);
+ ev.ID = ++last_event_id;
+ last_accel.x = p_x;
+ queue_event(ev);
+ };
+ if (p_y != last_accel.y) {
+ //printf("updating accel y %f\n", p_y);
+ InputEvent ev;
+ ev.type = InputEvent::JOYSTICK_MOTION;
+ ev.device = 0;
+ ev.joy_motion.axis = JOY_ANALOG_0_Y;
+ ev.joy_motion.axis_value = (p_y / (float)ACCEL_RANGE);
+ ev.ID = ++last_event_id;
+ last_accel.y = p_y;
+ queue_event(ev);
+ };
+ if (p_z != last_accel.z) {
+ //printf("updating accel z %f\n", p_z);
+ InputEvent ev;
+ ev.type = InputEvent::JOYSTICK_MOTION;
+ ev.device = 0;
+ ev.joy_motion.axis = JOY_ANALOG_1_X;
+ ev.joy_motion.axis_value = ( (1.0 - p_z) / (float)ACCEL_RANGE);
+ ev.ID = ++last_event_id;
+ last_accel.z = p_z;
+ queue_event(ev);
+ };
+ */
+};
+
+
+
+void OSIPhone::delete_main_loop() {
+
+ if (main_loop) {
+ main_loop->finish();
+ memdelete(main_loop);
+ };
+
+ main_loop = NULL;
+};
+
+void OSIPhone::finalize() {
+
+ if(main_loop) // should not happen?
+ memdelete(main_loop);
+
+ visual_server->finish();
+ memdelete(visual_server);
+ memdelete(rasterizer);
+
+ physics_server->finish();
+ memdelete(physics_server);
+
+ physics_2d_server->finish();
+ memdelete(physics_2d_server);
+
+ spatial_sound_server->finish();
+ memdelete(spatial_sound_server);
+
+ memdelete(input);
+
+ spatial_sound_2d_server->finish();
+ memdelete(spatial_sound_2d_server);
+
+};
+
+void OSIPhone::set_mouse_show(bool p_show) { };
+void OSIPhone::set_mouse_grab(bool p_grab) { };
+
+bool OSIPhone::is_mouse_grab_enabled() const {
+
+ return true;
+};
+
+Point2 OSIPhone::get_mouse_pos() const {
+
+ return Point2();
+};
+
+int OSIPhone::get_mouse_button_state() const {
+
+ return mouse_list.pressed[0];
+};
+
+void OSIPhone::set_window_title(const String& p_title) { };
+
+void OSIPhone::set_video_mode(const VideoMode& p_video_mode, int p_screen) {
+
+ video_mode = p_video_mode;
+};
+
+OS::VideoMode OSIPhone::get_video_mode(int p_screen) const {
+
+ return video_mode;
+};
+
+void OSIPhone::get_fullscreen_mode_list(List<VideoMode> *p_list, int p_screen) const {
+
+ p_list->push_back(video_mode);
+};
+
+bool OSIPhone::can_draw() const {
+
+ return true;
+};
+
+int OSIPhone::set_base_framebuffer(int p_fb) {
+
+ if (rasterizer_gles22) {
+ rasterizer_gles22->set_base_framebuffer(p_fb);
+ };
+ return 0;
+};
+
+bool OSIPhone::has_virtual_keyboard() const {
+ return true;
+};
+
+extern void _show_keyboard(String p_existing);
+extern void _hide_keyboard();
+extern Error _shell_open(String p_uri);
+
+void OSIPhone::show_virtual_keyboard(const String& p_existing_text,const Rect2& p_screen_rect) {
+ _show_keyboard(p_existing_text);
+};
+
+void OSIPhone::hide_virtual_keyboard() {
+ _hide_keyboard();
+};
+
+Error OSIPhone::shell_open(String p_uri) {
+ return _shell_open(p_uri);
+};
+
+
+void OSIPhone::set_cursor_shape(CursorShape p_shape) {
+
+
+};
+
+String OSIPhone::get_data_dir() const {
+
+ return data_dir;
+};
+
+String OSIPhone::get_name() {
+
+ return "iOS";
+};
+
+bool OSIPhone::has_touchscreen_ui_hint() const {
+
+ return true;
+}
+
+void OSIPhone::set_locale(String p_locale)
+{
+ locale_code = p_locale;
+}
+
+String OSIPhone::get_locale() const {
+ return locale_code;
+}
+
+OSIPhone::OSIPhone(int width, int height) {
+
+ rasterizer_gles22 = NULL;
+ main_loop = NULL;
+ visual_server = NULL;
+ rasterizer = NULL;
+
+ VideoMode vm;
+ vm.fullscreen = true;
+ vm.width = width;
+ vm.height = height;
+ vm.resizable = false;
+ set_video_mode(vm);
+ event_count = 0;
+ last_event_id = 0;
+};
+
+OSIPhone::~OSIPhone() {
+
+}
+
+#endif
diff --git a/platform/iphone/os_iphone.h b/platform/iphone/os_iphone.h
new file mode 100644
index 0000000000..a8ccba02b5
--- /dev/null
+++ b/platform/iphone/os_iphone.h
@@ -0,0 +1,193 @@
+/*************************************************************************/
+/* os_iphone.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* http://www.godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+#ifdef IPHONE_ENABLED
+
+#ifndef OS_IPHONE_H
+#define OS_IPHONE_H
+
+#include "os/input.h"
+#include "drivers/unix/os_unix.h"
+
+#include "servers/visual_server.h"
+#include "servers/visual/rasterizer.h"
+#include "servers/physics/physics_server_sw.h"
+#include "servers/physics_2d/physics_2d_server_sw.h"
+#include "servers/audio/audio_server_sw.h"
+#include "servers/audio/sample_manager_sw.h"
+#include "servers/spatial_sound/spatial_sound_server_sw.h"
+#include "servers/spatial_sound_2d/spatial_sound_2d_server_sw.h"
+#include "game_center.h"
+#include "in_app_store.h"
+
+class AudioDriverIphone;
+class RasterizerGLES2;
+
+class OSIPhone : public OS_Unix {
+
+public:
+
+ enum Orientations {
+ PortraitDown,
+ PortraitUp,
+ LandscapeLeft,
+ LandscapeRight,
+ };
+private:
+
+ enum {
+ MAX_MOUSE_COUNT = 8,
+ MAX_EVENTS = 64,
+ };
+
+ uint8_t supported_orientations;
+
+ Rasterizer *rasterizer;
+
+ RasterizerGLES2* rasterizer_gles22;
+
+ VisualServer *visual_server;
+ PhysicsServer* physics_server;
+ Physics2DServer *physics_2d_server;
+
+ AudioServerSW *audio_server;
+ SampleManagerMallocSW *sample_manager;
+ SpatialSoundServerSW *spatial_sound_server;
+ SpatialSound2DServerSW *spatial_sound_2d_server;
+ AudioDriverIphone* audio_driver;
+
+#ifdef GAME_CENTER_ENABLED
+ GameCenter* game_center;
+#endif
+#ifdef STOREKIT_ENABLED
+ InAppStore* store_kit;
+#endif
+
+ MainLoop *main_loop;
+
+ VideoMode video_mode;
+
+
+ virtual int get_video_driver_count() const;
+ virtual const char * get_video_driver_name(int p_driver) const;
+
+ virtual VideoMode get_default_video_mode() const;
+
+ virtual void initialize_core();
+ virtual void initialize(const VideoMode& p_desired,int p_video_driver,int p_audio_driver);
+
+ virtual void set_main_loop( MainLoop * p_main_loop );
+ virtual MainLoop *get_main_loop() const;
+
+ virtual void delete_main_loop();
+
+ virtual void finalize();
+
+ struct MouseList {
+
+ bool pressed[MAX_MOUSE_COUNT];
+ MouseList() {
+ for (int i=0; i<MAX_MOUSE_COUNT; i++)
+ pressed[i] = false;
+ };
+ };
+
+ MouseList mouse_list;
+
+ Vector3 last_accel;
+
+ InputEvent event_queue[MAX_EVENTS];
+ int event_count;
+ int last_event_id;
+ void queue_event(const InputEvent& p_event);
+
+ String data_dir;
+ String unique_ID;
+ String locale_code;
+
+ InputDefault *input;
+
+public:
+
+ bool iterate();
+
+ uint8_t get_orientations() const;
+
+ void mouse_button(int p_idx, int p_x, int p_y, bool p_pressed, bool p_doubleclick, bool p_use_as_mouse);
+ void mouse_move(int p_idx, int p_prev_x, int p_prev_y, int p_x, int p_y, bool p_use_as_mouse);
+ void touches_cancelled();
+ void key(uint32_t p_key, bool p_pressed);
+
+ int set_base_framebuffer(int p_fb);
+
+ void update_accelerometer(float p_x, float p_y, float p_z);
+
+ static OSIPhone* get_singleton();
+
+ virtual void set_mouse_show(bool p_show);
+ virtual void set_mouse_grab(bool p_grab);
+ virtual bool is_mouse_grab_enabled() const;
+ virtual Point2 get_mouse_pos() const;
+ virtual int get_mouse_button_state() const;
+ virtual void set_window_title(const String& p_title);
+
+ virtual void set_video_mode(const VideoMode& p_video_mode,int p_screen=0);
+ virtual VideoMode get_video_mode(int p_screen=0) const;
+ virtual void get_fullscreen_mode_list(List<VideoMode> *p_list,int p_screen=0) const;
+
+ virtual bool can_draw() const;
+
+ virtual bool has_virtual_keyboard() const;
+ virtual void show_virtual_keyboard(const String& p_existing_text,const Rect2& p_screen_rect=Rect2());
+ virtual void hide_virtual_keyboard();
+
+ virtual void set_cursor_shape(CursorShape p_shape);
+
+ virtual bool has_touchscreen_ui_hint() const;
+
+ void set_data_dir(String p_dir);
+
+ virtual String get_name();
+
+ Error shell_open(String p_uri);
+
+ String get_data_dir() const;
+
+ void set_locale(String p_locale);
+ String get_locale() const;
+
+ void set_unique_ID(String p_ID);
+ String get_unique_ID() const;
+
+ OSIPhone(int width, int height);
+ ~OSIPhone();
+};
+
+#endif // OS_IPHONE_H
+
+#endif
diff --git a/platform/iphone/platform_config.h b/platform/iphone/platform_config.h
new file mode 100644
index 0000000000..df50d30f40
--- /dev/null
+++ b/platform/iphone/platform_config.h
@@ -0,0 +1,32 @@
+/*************************************************************************/
+/* platform_config.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* http://www.godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+#include <alloca.h>
+#define GLES2_INCLUDE_H <ES2/gl.h>
+#define GLES1_INCLUDE_H <ES1/gl.h>
+
diff --git a/platform/iphone/rasterizer_iphone.cpp b/platform/iphone/rasterizer_iphone.cpp
new file mode 100644
index 0000000000..4674a5143c
--- /dev/null
+++ b/platform/iphone/rasterizer_iphone.cpp
@@ -0,0 +1,2762 @@
+/*************************************************************************/
+/* rasterizer_iphone.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* http://www.godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+#ifdef IPHONE_ENABLED
+
+#include "rasterizer_iphone.h"
+#include "os/os.h"
+#include "globals.h"
+#include <stdio.h>
+
+_FORCE_INLINE_ static void _gl_load_transform(const Transform& tr) {
+
+ GLfloat matrix[16]={ /* build a 16x16 matrix */
+ tr.basis.elements[0][0],
+ tr.basis.elements[1][0],
+ tr.basis.elements[2][0],
+ 0,
+ tr.basis.elements[0][1],
+ tr.basis.elements[1][1],
+ tr.basis.elements[2][1],
+ 0,
+ tr.basis.elements[0][2],
+ tr.basis.elements[1][2],
+ tr.basis.elements[2][2],
+ 0,
+ tr.origin.x,
+ tr.origin.y,
+ tr.origin.z,
+ 1
+ };
+
+ glLoadMatrixf(matrix);
+};
+
+_FORCE_INLINE_ static void _gl_mult_transform(const Transform& tr) {
+
+ GLfloat matrix[16]={ /* build a 16x16 matrix */
+ tr.basis.elements[0][0],
+ tr.basis.elements[1][0],
+ tr.basis.elements[2][0],
+ 0,
+ tr.basis.elements[0][1],
+ tr.basis.elements[1][1],
+ tr.basis.elements[2][1],
+ 0,
+ tr.basis.elements[0][2],
+ tr.basis.elements[1][2],
+ tr.basis.elements[2][2],
+ 0,
+ tr.origin.x,
+ tr.origin.y,
+ tr.origin.z,
+ 1
+ };
+
+ glMultMatrixf(matrix);
+};
+
+static const GLenum prim_type[]={GL_POINTS,GL_LINES,GL_TRIANGLES,GL_TRIANGLE_FAN};
+
+static void _draw_primitive(int p_points, const float *p_vertices, const float *p_normals, const float* p_colors, const float *p_uvs,const Plane *p_tangents=NULL,int p_instanced=1) {
+
+ ERR_FAIL_COND(!p_vertices);
+ ERR_FAIL_COND(p_points <1 || p_points>4);
+
+ GLenum type = prim_type[p_points - 1];
+
+
+ if (!p_colors) {
+ glColor4f(1, 1, 1, 1);
+ };
+
+ glEnableClientState(GL_VERTEX_ARRAY);
+ glVertexPointer(3, GL_FLOAT, 0, (GLvoid*)p_vertices);
+
+ if (p_normals) {
+
+ glEnableClientState(GL_NORMAL_ARRAY);
+ glNormalPointer(GL_FLOAT, 0, (GLvoid*)p_normals);
+ };
+
+ if (p_colors) {
+ glEnableClientState(GL_COLOR_ARRAY);
+ glColorPointer(4,GL_FLOAT, 0, p_colors);
+ };
+
+ if (p_uvs) {
+
+ glClientActiveTexture(GL_TEXTURE0);
+ glEnableClientState(GL_TEXTURE_COORD_ARRAY);
+ glTexCoordPointer(2, GL_FLOAT, 0, p_uvs);
+ };
+
+ glDrawArrays( type, 0, p_points);
+
+ glDisableClientState(GL_VERTEX_ARRAY);
+ glDisableClientState(GL_NORMAL_ARRAY);
+ glDisableClientState(GL_COLOR_ARRAY);
+ glDisableClientState(GL_TEXTURE_COORD_ARRAY);
+};
+
+
+/* TEXTURE API */
+
+static Image _get_gl_image_and_format(const Image& p_image, Image::Format p_format, uint32_t p_flags,GLenum& r_gl_format,int &r_gl_components,bool &r_has_alpha_cache) {
+
+ r_has_alpha_cache=false;
+ Image image=p_image;
+
+ switch(p_format) {
+
+ case Image::FORMAT_GRAYSCALE: {
+ r_gl_components=1;
+ r_gl_format=GL_LUMINANCE;
+
+ } break;
+ case Image::FORMAT_INTENSITY: {
+
+ image.convert(Image::FORMAT_RGBA);
+ r_gl_components=4;
+ r_gl_format=GL_RGBA;
+ r_has_alpha_cache=true;
+ } break;
+ case Image::FORMAT_GRAYSCALE_ALPHA: {
+
+ image.convert(Image::FORMAT_RGBA);
+ r_gl_components=4;
+ r_gl_format=GL_RGBA;
+ r_has_alpha_cache=true;
+ } break;
+
+ case Image::FORMAT_INDEXED: {
+
+ image.convert(Image::FORMAT_RGB);
+ r_gl_components=3;
+ r_gl_format=GL_RGB;
+
+ } break;
+
+ case Image::FORMAT_INDEXED_ALPHA: {
+
+ image.convert(Image::FORMAT_RGBA);
+ r_gl_components=4;
+ r_gl_format=GL_RGB;
+ r_has_alpha_cache=true;
+
+ } break;
+ case Image::FORMAT_RGB: {
+
+ r_gl_components=3; r_gl_format=GL_RGB;
+ } break;
+ case Image::FORMAT_RGBA: {
+
+ r_gl_components=4;
+ r_gl_format=GL_RGBA;
+ r_has_alpha_cache=true;
+ } break;
+ default: {
+
+ ERR_FAIL_V(Image());
+ }
+ }
+
+ return image;
+}
+
+RID RasterizerIPhone::texture_create() {
+
+ Texture *texture = memnew(Texture);
+ ERR_FAIL_COND_V(!texture,RID());
+ glGenTextures(1, &texture->tex_id);
+ texture->active=false;
+
+ return texture_owner.make_rid( texture );
+
+}
+
+void RasterizerIPhone::texture_allocate(RID p_texture,int p_width, int p_height,Image::Format p_format,uint32_t p_flags) {
+
+ bool has_alpha_cache;
+ int components;
+ GLenum format;
+
+ Texture *texture = texture_owner.get( p_texture );
+ ERR_FAIL_COND(!texture);
+ texture->width=p_width;
+ texture->height=p_height;
+ texture->format=p_format;
+ texture->flags=p_flags;
+ //texture->target = (p_flags & VS::TEXTURE_FLAG_CUBEMAP) ? GL_TEXTURE_CUBE_MAP : GL_TEXTURE_2D;
+ texture->target = GL_TEXTURE_2D;
+
+ _get_gl_image_and_format(Image(),texture->format,texture->flags,format,components,has_alpha_cache);
+
+ texture->gl_components_cache=components;
+ texture->gl_format_cache=format;
+ texture->format_has_alpha=has_alpha_cache;
+ texture->has_alpha=false; //by default it doesn't have alpha unless something with alpha is blitteds
+
+ glBindTexture(texture->target, texture->tex_id);
+
+ if (texture->flags&VS::TEXTURE_FLAG_MIPMAPS) {
+ glTexParameteri( GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE );
+ }
+
+
+ if (texture->target==GL_TEXTURE_2D) {
+ glTexImage2D(texture->target, 0, format, texture->width, texture->height, 0, format, GL_UNSIGNED_BYTE,NULL);
+ }
+
+ /*
+ else {
+ //cubemappor
+ for (int i=0;i<6;i++)
+ glTexImage2D(_cube_side_enum[i], 0, format, texture->width, texture->height, 0, format, GL_UNSIGNED_BYTE,NULL);
+ }
+ */
+
+ glTexParameteri(texture->target,GL_TEXTURE_MIN_FILTER,GL_LINEAR); // Linear Filtering
+
+ if (texture->flags&VS::TEXTURE_FLAG_FILTER) {
+
+ glTexParameteri(texture->target,GL_TEXTURE_MAG_FILTER,GL_LINEAR); // Linear Filtering
+ if (texture->flags&VS::TEXTURE_FLAG_MIPMAPS) {
+ //glTexParameteri(texture->target,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_LINEAR);
+ };
+ }
+
+
+
+ if (texture->flags&VS::TEXTURE_FLAG_REPEAT /* && texture->target != GL_TEXTURE_CUBE_MAP*/) {
+
+ glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );
+ glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );
+ } else {
+
+ //glTexParameterf( texture->target, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE );
+ glTexParameterf( texture->target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
+ glTexParameterf( texture->target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
+ }
+
+ texture->active=true;
+}
+
+void RasterizerIPhone::texture_blit_rect(RID p_texture,int p_x,int p_y, const Image& p_image,VS::CubeMapSide p_cube_side) {
+
+ Texture * texture = texture_owner.get(p_texture);
+
+ ERR_FAIL_COND(!texture);
+ ERR_FAIL_COND(!texture->active);
+ ERR_FAIL_COND(texture->format != p_image.get_format() );
+
+ int components;
+ GLenum format;
+ bool alpha;
+
+ Image img = _get_gl_image_and_format(p_image, p_image.get_format(),texture->flags,format,components,alpha);
+
+ if (img.detect_alpha())
+ texture->has_alpha=true;
+
+ GLenum blit_target = GL_TEXTURE_2D; //(texture->target == GL_TEXTURE_CUBE_MAP)?_cube_side_enum[p_cube_side]:GL_TEXTURE_2D;
+
+ DVector<uint8_t>::Read read = img.get_data().read();
+
+ glBindTexture(texture->target, texture->tex_id);
+ glTexSubImage2D( blit_target, 0, p_x,p_y,img.get_width(),img.get_height(),format,GL_UNSIGNED_BYTE,read.ptr() );
+
+ //glGenerateMipmap( texture->target );
+}
+
+Image RasterizerIPhone::texture_get_rect(RID p_texture,int p_x,int p_y,int p_width, int p_height,VS::CubeMapSide p_cube_side) const {
+
+
+ return Image();
+}
+void RasterizerIPhone::texture_set_flags(RID p_texture,uint32_t p_flags) {
+
+ Texture *texture = texture_owner.get( p_texture );
+ ERR_FAIL_COND(!texture);
+
+ glBindTexture(texture->target, texture->tex_id);
+ uint32_t cube = texture->flags & VS::TEXTURE_FLAG_CUBEMAP;
+ texture->flags=p_flags|cube; // can't remove a cube from being a cube
+
+ if (texture->flags&VS::TEXTURE_FLAG_REPEAT /*&& texture->target != GL_TEXTURE_CUBE_MAP*/) {
+
+ glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );
+ glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );
+ } else {
+ //glTexParameterf( texture->target, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE );
+ glTexParameterf( texture->target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
+ glTexParameterf( texture->target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
+
+ }
+
+
+ if (texture->flags&VS::TEXTURE_FLAG_FILTER) {
+
+ glTexParameteri(texture->target,GL_TEXTURE_MAG_FILTER,GL_LINEAR); // Linear Filtering
+ if (texture->flags&VS::TEXTURE_FLAG_MIPMAPS)
+ glTexParameteri(texture->target,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_LINEAR);
+
+ } else {
+
+ glTexParameteri(texture->target,GL_TEXTURE_MAG_FILTER,GL_NEAREST); // nearest
+ }
+}
+uint32_t RasterizerIPhone::texture_get_flags(RID p_texture) const {
+
+ Texture * texture = texture_owner.get(p_texture);
+
+ ERR_FAIL_COND_V(!texture,0);
+
+ return texture->flags;
+
+}
+Image::Format RasterizerIPhone::texture_get_format(RID p_texture) const {
+
+ Texture * texture = texture_owner.get(p_texture);
+
+ ERR_FAIL_COND_V(!texture,Image::FORMAT_GRAYSCALE);
+
+ return texture->format;
+}
+uint32_t RasterizerIPhone::texture_get_width(RID p_texture) const {
+
+ Texture * texture = texture_owner.get(p_texture);
+
+ ERR_FAIL_COND_V(!texture,0);
+
+ return texture->width;
+}
+uint32_t RasterizerIPhone::texture_get_height(RID p_texture) const {
+
+ Texture * texture = texture_owner.get(p_texture);
+
+ ERR_FAIL_COND_V(!texture,0);
+
+ return texture->height;
+}
+
+bool RasterizerIPhone::texture_has_alpha(RID p_texture) const {
+
+ Texture * texture = texture_owner.get(p_texture);
+
+ ERR_FAIL_COND_V(!texture,0);
+
+ return texture->has_alpha;
+
+}
+
+/* SHADER API */
+
+RID RasterizerIPhone::shader_create() {
+
+ return RID();
+}
+
+void RasterizerIPhone::shader_node_add(RID p_shader,VS::ShaderNodeType p_type,int p_id) {
+
+
+}
+void RasterizerIPhone::shader_node_remove(RID p_shader,int p_id) {
+
+
+}
+void RasterizerIPhone::shader_node_change_type(RID p_shader, int p_id, VS::ShaderNodeType p_type) {
+
+
+}
+void RasterizerIPhone::shader_node_set_param(RID p_shader, int p_id, const Variant& p_value) {
+
+
+}
+
+void RasterizerIPhone::shader_get_node_list(RID p_shader,List<int> *p_node_list) const {
+
+
+}
+VS::ShaderNodeType RasterizerIPhone::shader_node_get_type(RID p_shader,int p_id) const {
+
+
+ return VS::NODE_ADD;
+}
+Variant RasterizerIPhone::shader_node_get_param(RID p_shader,int p_id) const {
+
+ return Variant();
+}
+
+void RasterizerIPhone::shader_connect(RID p_shader,int p_src_id,int p_src_slot, int p_dst_id,int p_dst_slot) {
+
+
+}
+bool RasterizerIPhone::shader_is_connected(RID p_shader,int p_src_id,int p_src_slot, int p_dst_id,int p_dst_slot) const {
+
+ return false;
+}
+
+void RasterizerIPhone::shader_disconnect(RID p_shader,int p_src_id,int p_src_slot, int p_dst_id,int p_dst_slot) {
+
+
+}
+
+void RasterizerIPhone::shader_get_connections(RID p_shader,List<VS::ShaderConnection> *p_connections) const {
+
+
+}
+
+void RasterizerIPhone::shader_clear(RID p_shader) {
+
+
+}
+
+/* COMMON MATERIAL API */
+
+void RasterizerIPhone::material_set_param(RID p_material, const StringName& p_param, const Variant& p_value) {
+
+
+}
+Variant RasterizerIPhone::material_get_param(RID p_material, const StringName& p_param) const {
+
+ return Variant();
+}
+void RasterizerIPhone::material_get_param_list(RID p_material, List<String> *p_param_list) const {
+
+
+}
+
+void RasterizerIPhone::material_set_flag(RID p_material, VS::MaterialFlag p_flag,bool p_enabled) {
+
+
+}
+bool RasterizerIPhone::material_get_flag(RID p_material,VS::MaterialFlag p_flag) const {
+
+ return false;
+}
+
+void RasterizerIPhone::material_set_blend_mode(RID p_material,VS::MaterialBlendMode p_mode) {
+
+
+}
+VS::MaterialBlendMode RasterizerIPhone::material_get_blend_mode(RID p_material) const {
+
+ return VS::MATERIAL_BLEND_MODE_ADD;
+}
+
+void RasterizerIPhone::material_set_line_width(RID p_material,float p_line_width) {
+
+
+}
+float RasterizerIPhone::material_get_line_width(RID p_material) const {
+
+ return 0;
+}
+
+/* FIXED MATERIAL */
+
+RID RasterizerIPhone::material_create() {
+
+ return material_owner.make_rid( memnew( Material ) );
+}
+
+void RasterizerIPhone::fixed_material_set_parameter(RID p_material, VS::FixedMaterialParam p_parameter, const Variant& p_value) {
+
+ Material *m=material_owner.get( p_material );
+ ERR_FAIL_COND(!m);
+ ERR_FAIL_INDEX(p_parameter, VisualServer::FIXED_MATERIAL_PARAM_MAX);
+
+ m->parameters[p_parameter] = p_value;
+}
+Variant RasterizerIPhone::fixed_material_get_parameter(RID p_material,VS::FixedMaterialParam p_parameter) const {
+
+ Material *m=material_owner.get( p_material );
+ ERR_FAIL_COND_V(!m, Variant());
+ ERR_FAIL_INDEX_V(p_parameter, VisualServer::FIXED_MATERIAL_PARAM_MAX, Variant());
+
+ return m->parameters[p_parameter];
+}
+
+void RasterizerIPhone::fixed_material_set_texture(RID p_material,VS::FixedMaterialParam p_parameter, RID p_texture) {
+
+ Material *m=material_owner.get( p_material );
+ ERR_FAIL_COND(!m);
+ ERR_FAIL_INDEX(p_parameter, VisualServer::FIXED_MATERIAL_PARAM_MAX);
+
+ m->textures[p_parameter] = p_texture;
+}
+RID RasterizerIPhone::fixed_material_get_texture(RID p_material,VS::FixedMaterialParam p_parameter) const {
+
+ Material *m=material_owner.get( p_material );
+ ERR_FAIL_COND_V(!m, RID());
+ ERR_FAIL_INDEX_V(p_parameter, VisualServer::FIXED_MATERIAL_PARAM_MAX, Variant());
+
+ return m->textures[p_parameter];
+}
+
+void RasterizerIPhone::fixed_material_set_detail_blend_mode(RID p_material,VS::MaterialBlendMode p_mode) {
+
+ Material *m=material_owner.get( p_material );
+ ERR_FAIL_COND(!m);
+
+ m->detail_blend_mode = p_mode;
+}
+VS::MaterialBlendMode RasterizerIPhone::fixed_material_get_detail_blend_mode(RID p_material) const {
+
+ Material *m=material_owner.get( p_material );
+ ERR_FAIL_COND_V(!m, VS::MATERIAL_BLEND_MODE_MIX);
+
+ return m->detail_blend_mode;
+}
+
+void RasterizerIPhone::fixed_material_set_texcoord_mode(RID p_material,VS::FixedMaterialParam p_parameter, VS::FixedMaterialTexCoordMode p_mode) {
+
+ Material *m=material_owner.get( p_material );
+ ERR_FAIL_COND(!m);
+ ERR_FAIL_INDEX(p_parameter, VisualServer::FIXED_MATERIAL_PARAM_MAX);
+
+ m->texcoord_mode[p_parameter] = p_mode;
+}
+VS::FixedMaterialTexCoordMode RasterizerIPhone::fixed_material_get_texcoord_mode(RID p_material,VS::FixedMaterialParam p_parameter) const {
+
+ Material *m=material_owner.get( p_material );
+ ERR_FAIL_COND_V(!m, VS::FIXED_MATERIAL_TEXCOORD_TEXGEN);
+ ERR_FAIL_INDEX_V(p_parameter, VisualServer::FIXED_MATERIAL_PARAM_MAX, VS::FIXED_MATERIAL_TEXCOORD_UV);
+
+ return m->texcoord_mode[p_parameter]; // for now
+}
+
+void RasterizerIPhone::fixed_material_set_texgen_mode(RID p_material,VS::FixedMaterialTexGenMode p_mode) {
+
+ Material *m=material_owner.get( p_material );
+ ERR_FAIL_COND(!m);
+
+ m->texgen_mode = p_mode;
+};
+
+VS::FixedMaterialTexGenMode RasterizerIPhone::fixed_material_get_texgen_mode(RID p_material) const {
+
+ Material *m=material_owner.get( p_material );
+ ERR_FAIL_COND_V(!m, VS::FIXED_MATERIAL_TEXGEN_SPHERE);
+
+ return m->texgen_mode;
+};
+
+
+void RasterizerIPhone::fixed_material_set_uv_transform(RID p_material,const Transform& p_transform) {
+
+ Material *m=material_owner.get( p_material );
+ ERR_FAIL_COND(!m);
+
+ m->uv_transform = p_transform;
+}
+Transform RasterizerIPhone::fixed_material_get_uv_transform(RID p_material) const {
+
+ Material *m=material_owner.get( p_material );
+ ERR_FAIL_COND_V(!m, Transform());
+
+ return m->uv_transform;
+}
+
+/* SHADER MATERIAL */
+
+RID RasterizerIPhone::shader_material_create() const {
+
+ return RID();
+}
+
+void RasterizerIPhone::shader_material_set_vertex_shader(RID p_material,RID p_shader,bool p_owned) {
+
+
+}
+RID RasterizerIPhone::shader_material_get_vertex_shader(RID p_material) const {
+
+ return RID();
+}
+
+void RasterizerIPhone::shader_material_set_fragment_shader(RID p_material,RID p_shader,bool p_owned) {
+
+
+}
+RID RasterizerIPhone::shader_material_get_fragment_shader(RID p_material) const {
+
+ return RID();
+}
+
+
+/* MESH API */
+
+RID RasterizerIPhone::mesh_create() {
+
+
+ return mesh_owner.make_rid( memnew( Mesh ) );
+}
+
+void RasterizerIPhone::mesh_add_surface(RID p_mesh,VS::PrimitiveType p_primitive,uint32_t p_format,int p_array_len,int p_index_array_len) {
+
+ Mesh *mesh = mesh_owner.get( p_mesh );
+ ERR_FAIL_COND(!mesh);
+
+ ERR_FAIL_COND((p_format&VS::ARRAY_FORMAT_VERTEX)==0); // mandatory
+ ERR_FAIL_COND( p_array_len<=0 );
+ ERR_FAIL_COND( p_index_array_len==0 );
+ ERR_FAIL_INDEX( p_primitive, VS::PRIMITIVE_MAX );
+
+ Surface *surface = memnew( Surface );
+ ERR_FAIL_COND( !surface );
+
+ int total_elem_size=0;
+
+ bool use_VBO=true; //glGenBuffersARB!=NULL; // TODO detect if it's in there
+ if (p_format&VS::ARRAY_FORMAT_WEIGHTS) {
+
+ use_VBO=false;
+ }
+
+
+ for (int i=0;i<VS::ARRAY_MAX;i++) {
+
+
+ Surface::ArrayData&ad=surface->array[i];
+ ad.size=0;
+ ad.configured=false;
+ ad.ofs=0;
+ int elem_size=0;
+ int elem_count=0;
+
+ if (!(p_format&(1<<i))) // no array
+ continue;
+
+
+ switch(i) {
+
+ case VS::ARRAY_VERTEX:
+ case VS::ARRAY_NORMAL: {
+
+ elem_size=3*sizeof(GLfloat); // vertex
+ elem_count=3;
+ } break;
+ case VS::ARRAY_TANGENT: {
+ elem_size=4*sizeof(GLfloat); // vertex
+ elem_count=4;
+
+ } break;
+ case VS::ARRAY_COLOR: {
+
+ elem_size=4; /* RGBA */
+ elem_count=4;
+ } break;
+ case VS::ARRAY_TEX_UV: {
+ elem_size=2*sizeof(GLfloat);
+ elem_count=2;
+
+ } break;
+ case VS::ARRAY_WEIGHTS:
+ case VS::ARRAY_BONES: {
+
+ elem_size=VS::ARRAY_WEIGHTS_SIZE*sizeof(GLfloat);
+ elem_count=VS::ARRAY_WEIGHTS_SIZE;
+
+ } break;
+ case VS::ARRAY_INDEX: {
+
+ if (p_index_array_len<=0) {
+ ERR_PRINT("p_index_array_len==NO_INDEX_ARRAY");
+ break;
+ }
+ /* determine wether using 8 or 16 bits indices */
+ if (p_index_array_len>(1<<8)) {
+
+ elem_size=2;
+ } else {
+ elem_size=1;
+ }
+
+ if (use_VBO) {
+
+ glGenBuffers(1,&surface->index_id);
+ ERR_FAIL_COND(surface->index_id==0);
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,surface->index_id);
+ glBufferData(GL_ELEMENT_ARRAY_BUFFER,p_index_array_len*elem_size,NULL,GL_STATIC_DRAW);
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,0); //unbind
+ } else {
+ surface->index_array_local = (uint8_t*)memalloc(p_index_array_len*elem_size);
+ };
+
+ surface->index_array_len=p_index_array_len; // only way it can exist
+ ad.ofs=0;
+ ad.size=elem_size;
+ ad.configured=false;
+ ad.components=1;
+
+ continue;
+ } break;
+ default: {
+ ERR_FAIL( );
+ }
+ }
+
+ ad.ofs=total_elem_size;
+ ad.size=elem_size;
+ ad.components=elem_count;
+ total_elem_size+=elem_size;
+ ad.configured=false;
+ }
+
+ surface->stride=total_elem_size;
+ surface->array_len=p_array_len;
+ surface->format=p_format;
+ surface->primitive=p_primitive;
+
+
+ /* bind the bigass buffers */
+ if (use_VBO) {
+
+ glGenBuffers(1,&surface->vertex_id);
+ ERR_FAIL_COND(surface->vertex_id==0);
+ glBindBuffer(GL_ARRAY_BUFFER,surface->vertex_id);
+ glBufferData(GL_ARRAY_BUFFER,surface->array_len*surface->stride,NULL,GL_STATIC_DRAW);
+ glBindBuffer(GL_ARRAY_BUFFER,0); //unbind
+ } else {
+ surface->array_local = (uint8_t*)memalloc(surface->array_len*surface->stride);
+ };
+
+ mesh->surfaces.push_back(surface);
+}
+
+Error RasterizerIPhone::mesh_surface_set_array(RID p_mesh, int p_surface,VS::ArrayType p_type,const Variant& p_array) {
+
+ ERR_FAIL_INDEX_V(p_type, VS::ARRAY_MAX, ERR_INVALID_PARAMETER );
+
+ Mesh *mesh = mesh_owner.get( p_mesh );
+ ERR_FAIL_COND_V(!mesh,ERR_INVALID_PARAMETER);
+ ERR_FAIL_INDEX_V(p_surface, mesh->surfaces.size(), ERR_INVALID_PARAMETER );
+ Surface *surface = mesh->surfaces[p_surface];
+ ERR_FAIL_COND_V( !surface, ERR_INVALID_PARAMETER );
+
+ ERR_FAIL_COND_V( surface->array[p_type].size==0, ERR_INVALID_PARAMETER );
+
+ Surface::ArrayData &a=surface->array[p_type];
+
+ switch(p_type) {
+
+ case VS::ARRAY_INDEX: {
+ ERR_FAIL_COND_V( surface->index_array_len<=0, ERR_INVALID_DATA );
+ ERR_FAIL_COND_V( p_array.get_type() != Variant::INT_ARRAY, ERR_INVALID_PARAMETER );
+
+ DVector<int> indices = p_array;
+ ERR_FAIL_COND_V( indices.size() == 0, ERR_INVALID_PARAMETER );
+ ERR_FAIL_COND_V( indices.size() != surface->index_array_len, ERR_INVALID_PARAMETER );
+
+ /* determine wether using 16 or 32 bits indices */
+
+ if (surface->index_array_local == 0) {
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,surface->index_id);
+ };
+
+ DVector<int>::Read read = indices.read();
+ const int *src=read.ptr();
+
+ for (int i=0;i<surface->index_array_len;i++) {
+
+ if (surface->index_array_local) {
+
+ if (a.size<=(1<<8)) {
+ uint8_t v=src[i];
+
+ copymem(&surface->array_local[i*a.size], &v, a.size);
+ } else {
+ uint16_t v=src[i];
+
+ copymem(&surface->array_local[i*a.size], &v, a.size);
+ }
+
+ } else {
+ if (a.size<=(1<<8)) {
+ uint8_t v=src[i];
+
+ glBufferSubData( GL_ELEMENT_ARRAY_BUFFER, i*a.size, a.size, &v );
+ } else {
+ uint16_t v=src[i];
+
+ glBufferSubData( GL_ELEMENT_ARRAY_BUFFER, i*a.size, a.size, &v );
+
+ }
+ };
+ }
+ if (surface->index_array_local == 0) {
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,0);
+ };
+ a.configured=true;
+ return OK;
+ } break;
+ case VS::ARRAY_VERTEX:
+ case VS::ARRAY_NORMAL: {
+
+ ERR_FAIL_COND_V( p_array.get_type() != Variant::VECTOR3_ARRAY, ERR_INVALID_PARAMETER );
+
+
+ DVector<Vector3> array = p_array;
+ ERR_FAIL_COND_V( array.size() != surface->array_len, ERR_INVALID_PARAMETER );
+
+ if (surface->array_local == 0) {
+ glBindBuffer(GL_ARRAY_BUFFER,surface->vertex_id);
+ };
+
+ DVector<Vector3>::Read read = array.read();
+ const Vector3* src=read.ptr();
+
+ // setting vertices means regenerating the AABB
+ if (p_type==VS::ARRAY_VERTEX)
+ surface->aabb=AABB();
+
+ for (int i=0;i<surface->array_len;i++) {
+
+
+ GLfloat vector[3]={ src[i].x, src[i].y, src[i].z };
+
+ if (surface->array_local == 0) {
+ glBufferSubData( GL_ARRAY_BUFFER, a.ofs+i*surface->stride, a.size , vector );
+ } else {
+ copymem(&surface->array_local[a.ofs+i*surface->stride], vector, a.size);
+ }
+
+ if (p_type==VS::ARRAY_VERTEX) {
+
+ if (i==0) {
+
+ surface->aabb=AABB(src[i],Vector3());
+ } else {
+
+ surface->aabb.expand_to( src[i] );
+ }
+ }
+ }
+
+ if (surface->array_local == 0) {
+ glBindBuffer(GL_ARRAY_BUFFER,0);
+ };
+
+ } break;
+ case VS::ARRAY_TANGENT: {
+
+ ERR_FAIL_COND_V( p_array.get_type() != Variant::REAL_ARRAY, ERR_INVALID_PARAMETER );
+
+ DVector<real_t> array = p_array;
+
+ ERR_FAIL_COND_V( array.size() != surface->array_len*4, ERR_INVALID_PARAMETER );
+
+ if (surface->array_local == 0) {
+ glBindBuffer(GL_ARRAY_BUFFER,surface->vertex_id);
+ };
+
+
+ DVector<real_t>::Read read = array.read();
+ const real_t* src = read.ptr();
+
+ for (int i=0;i<surface->array_len;i++) {
+
+ GLfloat xyzw[4]={
+ src[i*4+0],
+ src[i*4+1],
+ src[i*4+2],
+ src[i*4+3]
+ };
+
+ if (surface->array_local == 0) {
+
+ glBufferSubData( GL_ARRAY_BUFFER, a.ofs+i*surface->stride, a.size , xyzw );
+ } else {
+
+ copymem(&surface->array_local[a.ofs+i*surface->stride], xyzw, a.size);
+ };
+
+ }
+
+ if (surface->array_local == 0) {
+ glBindBuffer(GL_ARRAY_BUFFER,0);
+ };
+ } break;
+ case VS::ARRAY_COLOR: {
+
+ ERR_FAIL_COND_V( p_array.get_type() != Variant::COLOR_ARRAY, ERR_INVALID_PARAMETER );
+
+
+ DVector<Color> array = p_array;
+
+ ERR_FAIL_COND_V( array.size() != surface->array_len, ERR_INVALID_PARAMETER );
+
+ if (surface->array_local == 0)
+ glBindBuffer(GL_ARRAY_BUFFER,surface->vertex_id);
+
+
+ DVector<Color>::Read read = array.read();
+ const Color* src = read.ptr();
+ surface->has_alpha_cache=false;
+
+ for (int i=0;i<surface->array_len;i++) {
+
+ if (src[i].a<0.98) // tolerate alpha a bit, for crappy exporters
+ surface->has_alpha_cache=true;
+ uint8_t colors[4]={ src[i].r * 255.0 , src[i].g * 255.0, src[i].b * 255.0, src[i].a * 255.0 };
+ // I'm not sure if this is correct, endianness-wise, i should re-check the GL spec
+
+ if (surface->array_local == 0)
+ glBufferSubData( GL_ARRAY_BUFFER, a.ofs+i*surface->stride, a.size , colors );
+ else
+ copymem(&surface->array_local[a.ofs+i*surface->stride], colors, a.size);
+
+ }
+
+ if (surface->array_local == 0)
+ glBindBuffer(GL_ARRAY_BUFFER,0);
+
+
+ } break;
+ case VS::ARRAY_TEX_UV: {
+
+ ERR_FAIL_COND_V( p_array.get_type() != Variant::VECTOR3_ARRAY, ERR_INVALID_PARAMETER );
+
+ DVector<Vector3> array = p_array;
+
+ ERR_FAIL_COND_V( array.size() != surface->array_len , ERR_INVALID_PARAMETER);
+
+ if (surface->array_local == 0)
+ glBindBuffer(GL_ARRAY_BUFFER,surface->vertex_id);
+
+ DVector<Vector3>::Read read = array.read();
+
+ const Vector3 * src=read.ptr();
+
+ for (int i=0;i<surface->array_len;i++) {
+
+ GLfloat uv[2]={ src[i].x , src[i].y };
+
+ if (surface->array_local == 0)
+ glBufferSubData( GL_ARRAY_BUFFER, a.ofs+i*surface->stride, a.size , uv );
+ else
+ copymem(&surface->array_local[a.ofs+i*surface->stride], uv, a.size);
+
+ }
+
+ if (surface->array_local == 0)
+ glBindBuffer(GL_ARRAY_BUFFER,0);
+
+ } break;
+ case VS::ARRAY_BONES:
+ case VS::ARRAY_WEIGHTS: {
+
+
+ ERR_FAIL_COND_V( p_array.get_type() != Variant::REAL_ARRAY, ERR_INVALID_PARAMETER );
+
+ DVector<real_t> array = p_array;
+
+ ERR_FAIL_COND_V( array.size() != surface->array_len*VS::ARRAY_WEIGHTS_SIZE, ERR_INVALID_PARAMETER );
+
+ if (surface->array_local == 0)
+ glBindBuffer(GL_ARRAY_BUFFER,surface->vertex_id);
+
+ DVector<real_t>::Read read = array.read();
+
+ const real_t * src = read.ptr();
+
+ for (int i=0;i<surface->array_len;i++) {
+
+ GLfloat data[VS::ARRAY_WEIGHTS_SIZE];
+ for (int j=0;j<VS::ARRAY_WEIGHTS_SIZE;j++)
+ data[j]=src[i*VS::ARRAY_WEIGHTS_SIZE+j];
+
+ if (surface->array_local == 0)
+ glBufferSubData( GL_ARRAY_BUFFER, a.ofs+i*surface->stride, a.size , data );
+ else
+ copymem(&surface->array_local[a.ofs+i*surface->stride], data, a.size);
+
+
+ }
+
+ if (surface->array_local == 0)
+ glBindBuffer(GL_ARRAY_BUFFER,0);
+ } break;
+ default: { ERR_FAIL_V(ERR_INVALID_PARAMETER);}
+ }
+
+ a.configured=true;
+
+ return OK;
+}
+Variant RasterizerIPhone::mesh_surface_get_array(RID p_mesh, int p_surface,VS::ArrayType p_type) const {
+
+ return Variant();
+}
+
+void RasterizerIPhone::mesh_surface_set_material(RID p_mesh, int p_surface, RID p_material,bool p_owned) {
+
+ Mesh *mesh = mesh_owner.get( p_mesh );
+ ERR_FAIL_COND(!mesh);
+ ERR_FAIL_INDEX(p_surface, mesh->surfaces.size() );
+ Surface *surface = mesh->surfaces[p_surface];
+ ERR_FAIL_COND( !surface);
+
+ if (surface->material_owned && surface->material.is_valid())
+ free(surface->material);
+
+ surface->material_owned=p_owned;
+
+ surface->material=p_material;
+}
+
+RID RasterizerIPhone::mesh_surface_get_material(RID p_mesh, int p_surface) const {
+
+ Mesh *mesh = mesh_owner.get( p_mesh );
+ ERR_FAIL_COND_V(!mesh,RID());
+ ERR_FAIL_INDEX_V(p_surface, mesh->surfaces.size(), RID() );
+ Surface *surface = mesh->surfaces[p_surface];
+ ERR_FAIL_COND_V( !surface, RID() );
+
+ return surface->material;
+}
+
+int RasterizerIPhone::mesh_surface_get_array_len(RID p_mesh, int p_surface) const {
+
+ Mesh *mesh = mesh_owner.get( p_mesh );
+ ERR_FAIL_COND_V(!mesh,-1);
+ ERR_FAIL_INDEX_V(p_surface, mesh->surfaces.size(), -1 );
+ Surface *surface = mesh->surfaces[p_surface];
+ ERR_FAIL_COND_V( !surface, -1 );
+
+ return surface->array_len;
+}
+int RasterizerIPhone::mesh_surface_get_array_index_len(RID p_mesh, int p_surface) const {
+
+ Mesh *mesh = mesh_owner.get( p_mesh );
+ ERR_FAIL_COND_V(!mesh,-1);
+ ERR_FAIL_INDEX_V(p_surface, mesh->surfaces.size(), -1 );
+ Surface *surface = mesh->surfaces[p_surface];
+ ERR_FAIL_COND_V( !surface, -1 );
+
+ return surface->index_array_len;
+}
+uint32_t RasterizerIPhone::mesh_surface_get_format(RID p_mesh, int p_surface) const {
+
+ Mesh *mesh = mesh_owner.get( p_mesh );
+ ERR_FAIL_COND_V(!mesh,0);
+ ERR_FAIL_INDEX_V(p_surface, mesh->surfaces.size(), 0 );
+ Surface *surface = mesh->surfaces[p_surface];
+ ERR_FAIL_COND_V( !surface, 0 );
+
+ return surface->format;
+}
+VS::PrimitiveType RasterizerIPhone::mesh_surface_get_primitive_type(RID p_mesh, int p_surface) const {
+
+ Mesh *mesh = mesh_owner.get( p_mesh );
+ ERR_FAIL_COND_V(!mesh,VS::PRIMITIVE_POINTS);
+ ERR_FAIL_INDEX_V(p_surface, mesh->surfaces.size(), VS::PRIMITIVE_POINTS );
+ Surface *surface = mesh->surfaces[p_surface];
+ ERR_FAIL_COND_V( !surface, VS::PRIMITIVE_POINTS );
+
+ return surface->primitive;
+}
+
+void RasterizerIPhone::mesh_erase_surface(RID p_mesh,int p_index) {
+
+ Mesh *mesh = mesh_owner.get( p_mesh );
+ ERR_FAIL_COND(!mesh);
+ ERR_FAIL_INDEX(p_index, mesh->surfaces.size() );
+ Surface *surface = mesh->surfaces[p_index];
+ ERR_FAIL_COND( !surface);
+
+ memdelete( mesh->surfaces[p_index] );
+ mesh->surfaces.remove(p_index);
+
+}
+int RasterizerIPhone::mesh_get_surface_count(RID p_mesh) const {
+
+ Mesh *mesh = mesh_owner.get( p_mesh );
+ ERR_FAIL_COND_V(!mesh,-1);
+
+ return mesh->surfaces.size();
+}
+
+AABB RasterizerIPhone::mesh_get_aabb(RID p_mesh) const {
+
+ Mesh *mesh = mesh_owner.get( p_mesh );
+ ERR_FAIL_COND_V(!mesh,AABB());
+
+ AABB aabb;
+
+ for (int i=0;i<mesh->surfaces.size();i++) {
+
+ if (i==0)
+ aabb=mesh->surfaces[i]->aabb;
+ else
+ aabb.merge_with(mesh->surfaces[i]->aabb);
+ }
+
+ return aabb;
+}
+
+/* MULTIMESH API */
+
+RID RasterizerIPhone::multimesh_create() {
+
+ return RID();
+}
+
+void RasterizerIPhone::multimesh_set_instance_count(RID p_multimesh,int p_count) {
+
+
+}
+int RasterizerIPhone::multimesh_get_instance_count(RID p_multimesh) const {
+
+ return 0;
+}
+
+void RasterizerIPhone::multimesh_set_mesh(RID p_multimesh,RID p_mesh) {
+
+
+}
+void RasterizerIPhone::multimesh_set_aabb(RID p_multimesh,const AABB& p_aabb) {
+
+
+}
+void RasterizerIPhone::multimesh_instance_set_transform(RID p_multimesh,int p_index,const Transform& p_transform) {
+
+
+}
+void RasterizerIPhone::multimesh_instance_set_color(RID p_multimesh,int p_index,const Color& p_color) {
+
+
+}
+
+RID RasterizerIPhone::multimesh_get_mesh(RID p_multimesh) const {
+
+ return RID();
+}
+AABB RasterizerIPhone::multimesh_get_aabb(RID p_multimesh) const {
+
+ return AABB();
+}
+
+Transform RasterizerIPhone::multimesh_instance_get_transform(RID p_multimesh,int p_index) const {
+
+ return Transform();
+}
+Color RasterizerIPhone::multimesh_instance_get_color(RID p_multimesh,int p_index) const {
+
+ return Color();
+}
+
+/* POLY API */
+
+RID RasterizerIPhone::poly_create() {
+
+ return RID();
+}
+void RasterizerIPhone::poly_set_material(RID p_poly, RID p_material,bool p_owned) {
+
+
+}
+void RasterizerIPhone::poly_add_primitive(RID p_poly, const Vector<Vector3>& p_points,const Vector<Vector3>& p_normals,const Vector<Color>& p_colors,const Vector<Vector3>& p_uvs) {
+
+
+}
+void RasterizerIPhone::poly_clear(RID p_poly) {
+
+
+}
+
+AABB RasterizerIPhone::poly_get_aabb(RID p_poly) const {
+
+ return AABB();
+}
+
+
+/* PARTICLES API */
+
+RID RasterizerIPhone::particles_create() {
+
+ return RID();
+}
+
+void RasterizerIPhone::particles_set_amount(RID p_particles, int p_amount) {
+
+
+}
+int RasterizerIPhone::particles_get_amount(RID p_particles) const {
+
+ return 0;
+}
+
+void RasterizerIPhone::particles_set_emitting(RID p_particles, bool p_emitting) {
+
+
+}
+
+bool RasterizerIPhone::particles_is_emitting(RID p_particles) const {
+
+ return false;
+}
+
+void RasterizerIPhone::particles_set_visibility_aabb(RID p_particles, const AABB& p_visibility) {
+
+
+}
+AABB RasterizerIPhone::particles_get_visibility_aabb(RID p_particles) const {
+
+ return AABB();
+}
+
+void RasterizerIPhone::particles_set_emission_half_extents(RID p_particles, const Vector3& p_half_extents) {
+
+
+}
+Vector3 RasterizerIPhone::particles_get_emission_half_extents(RID p_particles) const {
+
+ return Vector3();
+}
+
+void RasterizerIPhone::particles_set_gravity_normal(RID p_particles, const Vector3& p_normal) {
+
+
+}
+Vector3 RasterizerIPhone::particles_get_gravity_normal(RID p_particles) const {
+
+ return Vector3();
+}
+
+void RasterizerIPhone::particles_set_variable(RID p_particles, VS::ParticleVariable p_variable,float p_value) {
+
+
+}
+float RasterizerIPhone::particles_get_variable(RID p_particles, VS::ParticleVariable p_variable) const {
+
+ return 0;
+}
+
+void RasterizerIPhone::particles_set_randomness(RID p_particles, VS::ParticleVariable p_variable,float p_randomness) {
+
+
+}
+float RasterizerIPhone::particles_get_randomness(RID p_particles, VS::ParticleVariable p_variable) const {
+
+ return 0;
+}
+
+void RasterizerIPhone::particles_set_color_phase_pos(RID p_particles, int p_phase, float p_pos) {
+
+
+}
+float RasterizerIPhone::particles_get_color_phase_pos(RID p_particles, int p_phase) const {
+
+ return 0;
+}
+
+void RasterizerIPhone::particles_set_color_phases(RID p_particles, int p_phases) {
+
+
+}
+int RasterizerIPhone::particles_get_color_phases(RID p_particles) const {
+
+ return 0;
+}
+
+void RasterizerIPhone::particles_set_color_phase_color(RID p_particles, int p_phase, const Color& p_color) {
+
+
+}
+Color RasterizerIPhone::particles_get_color_phase_color(RID p_particles, int p_phase) const {
+
+ return Color();
+}
+
+void RasterizerIPhone::particles_set_attractors(RID p_particles, int p_attractors) {
+
+
+}
+int RasterizerIPhone::particles_get_attractors(RID p_particles) const {
+
+ return 0;
+}
+
+void RasterizerIPhone::particles_set_attractor_pos(RID p_particles, int p_attractor, const Vector3& p_pos) {
+
+
+}
+Vector3 RasterizerIPhone::particles_get_attractor_pos(RID p_particles,int p_attractor) const {
+
+ return Vector3();
+}
+
+void RasterizerIPhone::particles_set_attractor_strength(RID p_particles, int p_attractor, float p_force) {
+
+
+}
+float RasterizerIPhone::particles_get_attractor_strength(RID p_particles,int p_attractor) const {
+
+ return 0;
+}
+
+void RasterizerIPhone::particles_set_material(RID p_particles, RID p_material,bool p_owned) {
+
+
+}
+
+RID RasterizerIPhone::particles_get_material(RID p_particles) const {
+
+ return RID();
+}
+
+AABB RasterizerIPhone::particles_get_aabb(RID p_particles) const {
+
+ return AABB();
+}
+/* BEAM API */
+
+RID RasterizerIPhone::beam_create() {
+
+ return RID();
+}
+
+void RasterizerIPhone::beam_set_point_count(RID p_beam, int p_count) {
+
+
+}
+int RasterizerIPhone::beam_get_point_count(RID p_beam) const {
+
+ return 0;
+}
+void RasterizerIPhone::beam_clear(RID p_beam) {
+
+
+}
+
+void RasterizerIPhone::beam_set_point(RID p_beam,int p_point,Vector3& p_pos) {
+
+
+}
+Vector3 RasterizerIPhone::beam_get_point(RID p_beam,int p_point) const {
+
+ return Vector3();
+}
+
+void RasterizerIPhone::beam_set_primitive(RID p_beam,VS::BeamPrimitive p_primitive) {
+
+
+}
+
+VS::BeamPrimitive RasterizerIPhone::beam_get_primitive(RID p_beam) const {
+
+ return VS::BEAM_CUBIC;
+}
+
+void RasterizerIPhone::beam_set_material(RID p_beam, RID p_material) {
+
+
+}
+RID RasterizerIPhone::beam_get_material(RID p_beam) const {
+
+ return RID();
+}
+
+AABB RasterizerIPhone::beam_get_aabb(RID p_particles) const {
+
+ return AABB();
+}
+/* SKELETON API */
+
+RID RasterizerIPhone::skeleton_create() {
+
+ Skeleton *skeleton = memnew( Skeleton );
+ ERR_FAIL_COND_V(!skeleton,RID());
+ return skeleton_owner.make_rid( skeleton );
+}
+void RasterizerIPhone::skeleton_resize(RID p_skeleton,int p_bones) {
+
+ Skeleton *skeleton = skeleton_owner.get( p_skeleton );
+ ERR_FAIL_COND(!skeleton);
+ if (p_bones == skeleton->bones.size()) {
+ return;
+ };
+ ERR_FAIL_COND( p_bones<0 || p_bones>256);
+
+ skeleton->bones.resize(p_bones);
+
+}
+int RasterizerIPhone::skeleton_get_bone_count(RID p_skeleton) const {
+
+ Skeleton *skeleton = skeleton_owner.get( p_skeleton );
+ ERR_FAIL_COND_V(!skeleton, -1);
+ return skeleton->bones.size();
+}
+void RasterizerIPhone::skeleton_bone_set_transform(RID p_skeleton,int p_bone, const Transform& p_transform) {
+
+ Skeleton *skeleton = skeleton_owner.get( p_skeleton );
+ ERR_FAIL_COND(!skeleton);
+ ERR_FAIL_INDEX( p_bone, skeleton->bones.size() );
+
+ skeleton->bones[p_bone] = p_transform;
+}
+Transform RasterizerIPhone::skeleton_bone_get_transform(RID p_skeleton,int p_bone) {
+
+ Skeleton *skeleton = skeleton_owner.get( p_skeleton );
+ ERR_FAIL_COND_V(!skeleton, Transform());
+ ERR_FAIL_INDEX_V( p_bone, skeleton->bones.size(), Transform() );
+
+ // something
+ return skeleton->bones[p_bone];
+}
+
+
+/* LIGHT API */
+
+RID RasterizerIPhone::light_create(VS::LightType p_type) {
+
+ Light *light = memnew( Light );
+ light->type=p_type;
+ return light_owner.make_rid(light);
+}
+
+VS::LightType RasterizerIPhone::light_get_type(RID p_light) const {
+
+ Light *light = light_owner.get(p_light);
+ ERR_FAIL_COND_V(!light,VS::LIGHT_OMNI);
+ return light->type;
+}
+
+void RasterizerIPhone::light_set_color(RID p_light,VS::LightColor p_type, const Color& p_color) {
+
+ Light *light = light_owner.get(p_light);
+ ERR_FAIL_COND(!light);
+ ERR_FAIL_INDEX( p_type, 3 );
+ light->colors[p_type]=p_color;
+}
+Color RasterizerIPhone::light_get_color(RID p_light,VS::LightColor p_type) const {
+
+ Light *light = light_owner.get(p_light);
+ ERR_FAIL_COND_V(!light, Color());
+ ERR_FAIL_INDEX_V( p_type, 3, Color() );
+ return light->colors[p_type];
+}
+
+void RasterizerIPhone::light_set_shadow(RID p_light,bool p_enabled) {
+
+ Light *light = light_owner.get(p_light);
+ ERR_FAIL_COND(!light);
+ light->shadow_enabled=p_enabled;
+}
+
+bool RasterizerIPhone::light_has_shadow(RID p_light) const {
+
+ Light *light = light_owner.get(p_light);
+ ERR_FAIL_COND_V(!light,false);
+ return light->shadow_enabled;
+}
+
+void RasterizerIPhone::light_set_volumetric(RID p_light,bool p_enabled) {
+
+ Light *light = light_owner.get(p_light);
+ ERR_FAIL_COND(!light);
+ light->volumetric_enabled=p_enabled;
+
+}
+bool RasterizerIPhone::light_is_volumetric(RID p_light) const {
+
+ Light *light = light_owner.get(p_light);
+ ERR_FAIL_COND_V(!light,false);
+ return light->volumetric_enabled;
+}
+
+void RasterizerIPhone::light_set_projector(RID p_light,RID p_texture) {
+
+ Light *light = light_owner.get(p_light);
+ ERR_FAIL_COND(!light);
+ light->projector=p_texture;
+}
+RID RasterizerIPhone::light_get_projector(RID p_light) const {
+
+ Light *light = light_owner.get(p_light);
+ ERR_FAIL_COND_V(!light,RID());
+ return light->projector;
+}
+
+void RasterizerIPhone::light_set_var(RID p_light, VS::LightParam p_var, float p_value) {
+
+ Light * light = light_owner.get( p_light );
+ ERR_FAIL_COND(!light);
+ ERR_FAIL_INDEX( p_var, VS::LIGHT_PARAM_MAX );
+
+ light->vars[p_var]=p_value;
+}
+float RasterizerIPhone::light_get_var(RID p_light, VS::LightParam p_var) const {
+
+ Light * light = light_owner.get( p_light );
+ ERR_FAIL_COND_V(!light,0);
+
+ ERR_FAIL_INDEX_V( p_var, VS::LIGHT_PARAM_MAX,0 );
+
+ return light->vars[p_var];
+}
+
+AABB RasterizerIPhone::light_get_aabb(RID p_light) const {
+
+ Light *light = light_owner.get( p_light );
+ ERR_FAIL_COND_V(!light,AABB());
+
+ switch( light->type ) {
+
+ case VS::LIGHT_SPOT: {
+
+ float len=light->vars[VS::LIGHT_PARAM_RADIUS];
+ float size=Math::tan(Math::deg2rad(light->vars[VS::LIGHT_PARAM_SPOT_ANGLE]))*len;
+ return AABB( Vector3( -size,-size,-len ), Vector3( size*2, size*2, len ) );
+ } break;
+ case VS::LIGHT_OMNI: {
+
+ float r = light->vars[VS::LIGHT_PARAM_RADIUS];
+ return AABB( -Vector3(r,r,r), Vector3(r,r,r)*2 );
+ } break;
+ case VS::LIGHT_DIRECTIONAL: {
+
+ return AABB();
+ } break;
+ default: {}
+ }
+
+ ERR_FAIL_V( AABB() );
+}
+
+
+RID RasterizerIPhone::light_instance_create(RID p_light) {
+
+ Light *light = light_owner.get( p_light );
+ ERR_FAIL_COND_V(!light, RID());
+
+ LightInstance *light_instance = memnew( LightInstance );
+
+ light_instance->light=p_light;
+ light_instance->base=light;
+ light_instance->last_pass=0;
+
+ return light_instance_owner.make_rid( light_instance );
+}
+void RasterizerIPhone::light_instance_set_transform(RID p_light_instance,const Transform& p_transform) {
+
+ LightInstance *lighti = light_instance_owner.get( p_light_instance );
+ ERR_FAIL_COND(!lighti);
+ lighti->transform=p_transform;
+
+}
+
+void RasterizerIPhone::light_instance_set_active_hint(RID p_light_instance) {
+
+ LightInstance *lighti = light_instance_owner.get( p_light_instance );
+ ERR_FAIL_COND(!lighti);
+ lighti->last_pass=frame;
+
+}
+bool RasterizerIPhone::light_instance_has_shadow(RID p_light_instance) const {
+
+ return false;
+}
+bool RasterizerIPhone::light_instance_assign_shadow(RID p_light_instance) {
+
+ return false;
+}
+Rasterizer::ShadowType RasterizerIPhone::light_instance_get_shadow_type(RID p_light_instance) const {
+
+ return Rasterizer::SHADOW_CUBE;
+}
+int RasterizerIPhone::light_instance_get_shadow_passes(RID p_light_instance) const {
+
+ return 0;
+}
+void RasterizerIPhone::light_instance_set_pssm_split_info(RID p_light_instance, int p_split, float p_near,float p_far, const CameraMatrix& p_camera, const Transform& p_transform) {
+
+
+}
+
+/* PARTICLES INSTANCE */
+
+RID RasterizerIPhone::particles_instance_create(RID p_particles) {
+
+ return RID();
+}
+void RasterizerIPhone::particles_instance_set_transform(RID p_particles_instance,const Transform& p_transform) {
+
+
+}
+
+/* RENDER API */
+/* all calls (inside begin/end shadow) are always warranted to be in the following order: */
+
+static GLfloat rtri; // Angle For The Triangle ( NEW )
+static GLfloat rquad; // Angle For The Quad ( NEW )
+
+void RasterizerIPhone::begin_frame() {
+
+ window_size = Size2( OS::get_singleton()->get_video_mode().width, OS::get_singleton()->get_video_mode().height );
+
+ double time = (OS::get_singleton()->get_ticks_usec()/1000); // get msec
+ time/=1000.0; // make secs
+ time_delta=time-last_time;
+ last_time=time;
+ frame++;
+ glClearColor(0,0,1,1);
+ glClear(GL_COLOR_BUFFER_BIT);
+
+ /* nehe ?*/
+
+ #if 0
+ glViewport(0,0,window_size.width,window_size.height); // Reset The Current Viewport
+
+ glMatrixMode(GL_PROJECTION); // Select The Projection Matrix
+ glLoadIdentity(); // Reset The Projection Matrix
+
+ // Calculate The Aspect Ratio Of The Window
+ gluPerspective(45.0f,(GLfloat)window_size.width/(GLfloat)window_size.height,0.1f,100.0f);
+
+ glMatrixMode(GL_MODELVIEW); // Select The Modelview Matrix
+ glLoadIdentity(); // Reset The Modelview Matrix
+
+
+
+ glShadeModel(GL_SMOOTH); // Enable Smooth Shading
+ glClearColor(0.0f, 0.0f, 0.0f, 0.5f); // Black Background
+ glClearDepth(1.0f); // Depth Buffer Setup
+ glEnable(GL_DEPTH_TEST); // Enables Depth Testing
+ glDepthFunc(GL_LEQUAL); // The Type Of Depth Testing To Do
+ glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // Really Nice Perspective Calculations
+
+ glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear Screen And Depth Buffer
+ glLoadIdentity(); // Reset The Current Modelview Matrix
+ glTranslatef(-1.5f,0.0f,-6.0f); // Move Left 1.5 Units And Into The Screen 6.0
+ glRotatef(rtri,0.0f,1.0f,0.0f); // Rotate The Triangle On The Y axis ( NEW )
+ glBegin(GL_TRIANGLES); // Start Drawing A Triangle
+ glColor3f(1.0f,0.0f,0.0f); // Red
+ glVertex3f( 0.0f, 1.0f, 0.0f); // Top Of Triangle (Front)
+ glColor3f(0.0f,1.0f,0.0f); // Green
+ glVertex3f(-1.0f,-1.0f, 1.0f); // Left Of Triangle (Front)
+ glColor3f(0.0f,0.0f,1.0f); // Blue
+ glVertex3f( 1.0f,-1.0f, 1.0f); // Right Of Triangle (Front)
+ glColor3f(1.0f,0.0f,0.0f); // Red
+ glVertex3f( 0.0f, 1.0f, 0.0f); // Top Of Triangle (Right)
+ glColor3f(0.0f,0.0f,1.0f); // Blue
+ glVertex3f( 1.0f,-1.0f, 1.0f); // Left Of Triangle (Right)
+ glColor3f(0.0f,1.0f,0.0f); // Green
+ glVertex3f( 1.0f,-1.0f, -1.0f); // Right Of Triangle (Right)
+ glColor3f(1.0f,0.0f,0.0f); // Red
+ glVertex3f( 0.0f, 1.0f, 0.0f); // Top Of Triangle (Back)
+ glColor3f(0.0f,1.0f,0.0f); // Green
+ glVertex3f( 1.0f,-1.0f, -1.0f); // Left Of Triangle (Back)
+ glColor3f(0.0f,0.0f,1.0f); // Blue
+ glVertex3f(-1.0f,-1.0f, -1.0f); // Right Of Triangle (Back)
+ glColor3f(1.0f,0.0f,0.0f); // Red
+ glVertex3f( 0.0f, 1.0f, 0.0f); // Top Of Triangle (Left)
+ glColor3f(0.0f,0.0f,1.0f); // Blue
+ glVertex3f(-1.0f,-1.0f,-1.0f); // Left Of Triangle (Left)
+ glColor3f(0.0f,1.0f,0.0f); // Green
+ glVertex3f(-1.0f,-1.0f, 1.0f); // Right Of Triangle (Left)
+ glEnd(); // Done Drawing The Pyramid
+
+ glLoadIdentity(); // Reset The Current Modelview Matrix
+ glTranslatef(1.5f,0.0f,-7.0f); // Move Right 1.5 Units And Into The Screen 7.0
+ glRotatef(rquad,1.0f,1.0f,1.0f); // Rotate The Quad On The X axis ( NEW )
+ glBegin(GL_QUADS); // Draw A Quad
+ glColor3f(0.0f,1.0f,0.0f); // Set The Color To Green
+ glVertex3f( 1.0f, 1.0f,-1.0f); // Top Right Of The Quad (Top)
+ glVertex3f(-1.0f, 1.0f,-1.0f); // Top Left Of The Quad (Top)
+ glVertex3f(-1.0f, 1.0f, 1.0f); // Bottom Left Of The Quad (Top)
+ glVertex3f( 1.0f, 1.0f, 1.0f); // Bottom Right Of The Quad (Top)
+ glColor3f(1.0f,0.5f,0.0f); // Set The Color To Orange
+ glVertex3f( 1.0f,-1.0f, 1.0f); // Top Right Of The Quad (Bottom)
+ glVertex3f(-1.0f,-1.0f, 1.0f); // Top Left Of The Quad (Bottom)
+ glVertex3f(-1.0f,-1.0f,-1.0f); // Bottom Left Of The Quad (Bottom)
+ glVertex3f( 1.0f,-1.0f,-1.0f); // Bottom Right Of The Quad (Bottom)
+ glColor3f(1.0f,0.0f,0.0f); // Set The Color To Red
+ glVertex3f( 1.0f, 1.0f, 1.0f); // Top Right Of The Quad (Front)
+ glVertex3f(-1.0f, 1.0f, 1.0f); // Top Left Of The Quad (Front)
+ glVertex3f(-1.0f,-1.0f, 1.0f); // Bottom Left Of The Quad (Front)
+ glVertex3f( 1.0f,-1.0f, 1.0f); // Bottom Right Of The Quad (Front)
+ glColor3f(1.0f,1.0f,0.0f); // Set The Color To Yellow
+ glVertex3f( 1.0f,-1.0f,-1.0f); // Top Right Of The Quad (Back)
+ glVertex3f(-1.0f,-1.0f,-1.0f); // Top Left Of The Quad (Back)
+ glVertex3f(-1.0f, 1.0f,-1.0f); // Bottom Left Of The Quad (Back)
+ glVertex3f( 1.0f, 1.0f,-1.0f); // Bottom Right Of The Quad (Back)
+ glColor3f(0.0f,0.0f,1.0f); // Set The Color To Blue
+ glVertex3f(-1.0f, 1.0f, 1.0f); // Top Right Of The Quad (Left)
+ glVertex3f(-1.0f, 1.0f,-1.0f); // Top Left Of The Quad (Left)
+ glVertex3f(-1.0f,-1.0f,-1.0f); // Bottom Left Of The Quad (Left)
+ glVertex3f(-1.0f,-1.0f, 1.0f); // Bottom Right Of The Quad (Left)
+ glColor3f(1.0f,0.0f,1.0f); // Set The Color To Violet
+ glVertex3f( 1.0f, 1.0f,-1.0f); // Top Right Of The Quad (Right)
+ glVertex3f( 1.0f, 1.0f, 1.0f); // Top Left Of The Quad (Right)
+ glVertex3f( 1.0f,-1.0f, 1.0f); // Bottom Left Of The Quad (Right)
+ glVertex3f( 1.0f,-1.0f,-1.0f); // Bottom Right Of The Quad (Right)
+ glEnd(); // Done Drawing The Quad
+
+ rtri+=0.2f; // Increase The Rotation Variable For The Triangle ( NEW )
+ rquad-=0.15f; // Decrease The Rotation Variable For The Quad ( NEW )
+
+ #endif
+
+}
+
+void RasterizerIPhone::set_viewport(const VS::ViewportRect& p_viewport) {
+
+
+ viewport=p_viewport;
+ canvas_transform=Transform();
+ canvas_transform.translate(-(viewport.width / 2.0f), -(viewport.height / 2.0f), 0.0f);
+ canvas_transform.scale( Vector3( 2.0f / viewport.width, -2.0f / viewport.height, 1.0f ) );
+
+ glViewport( viewport.x, window_size.height-(viewport.height+viewport.y), viewport.width,viewport.height );
+}
+
+void RasterizerIPhone::begin_scene(RID p_fx,VS::ScenarioDebugMode p_debug) {
+
+ opaque_render_list.clear();
+ alpha_render_list.clear();
+ light_instance_count=0;
+ scene_fx = p_fx.is_valid() ? fx_owner.get(p_fx) : NULL;
+};
+
+void RasterizerIPhone::begin_shadow_map( RID p_light_instance, int p_shadow_pass ) {
+
+
+}
+
+void RasterizerIPhone::set_camera(const Transform& p_world,const CameraMatrix& p_projection) {
+
+ camera_transform=p_world;
+ camera_transform_inverse=camera_transform.inverse();
+ camera_projection=p_projection;
+ camera_plane = Plane( camera_transform.origin, camera_transform.basis.get_axis(2) );
+ camera_z_near=camera_projection.get_z_near();
+camera_z_far=camera_projection.get_z_far();
+ camera_projection.get_viewport_size(camera_vp_size.x,camera_vp_size.y);
+}
+
+void RasterizerIPhone::add_light( RID p_light_instance ) {
+
+#define LIGHT_FADE_TRESHOLD 0.05
+
+ ERR_FAIL_COND( light_instance_count >= MAX_LIGHTS );
+
+ LightInstance *li = light_instance_owner.get(p_light_instance);
+ ERR_FAIL_COND(!li);
+
+ /* make light hash */
+
+ // actually, not really a hash, but helps to sort the lights
+ // and avoid recompiling redudant shader versions
+
+ li->hash_aux=li->base->type;
+
+ if (li->base->shadow_enabled)
+ li->hash_aux|=(1<<3);
+
+ if (li->base->projector.is_valid())
+ li->hash_aux|=(1<<4);
+
+ if (li->base->shadow_enabled && li->base->volumetric_enabled)
+ li->hash_aux|=(1<<5);
+
+ switch(li->base->type) {
+
+ case VisualServer::LIGHT_DIRECTIONAL: {
+
+ Vector3 dir = li->transform.basis.get_axis(2);
+ li->light_vector.x=dir.x;
+ li->light_vector.y=dir.y;
+ li->light_vector.z=dir.z;
+
+ } break;
+ case VisualServer::LIGHT_OMNI: {
+
+ float radius = li->base->vars[VisualServer::LIGHT_PARAM_RADIUS];
+ if (radius==0)
+ radius=0.0001;
+ li->linear_att=(1/LIGHT_FADE_TRESHOLD)/radius;
+ li->light_vector.x=li->transform.origin.x;
+ li->light_vector.y=li->transform.origin.y;
+ li->light_vector.z=li->transform.origin.z;
+
+ } break;
+ case VisualServer::LIGHT_SPOT: {
+
+ float radius = li->base->vars[VisualServer::LIGHT_PARAM_RADIUS];
+ if (radius==0)
+ radius=0.0001;
+ li->linear_att=(1/LIGHT_FADE_TRESHOLD)/radius;
+ li->light_vector.x=li->transform.origin.x;
+ li->light_vector.y=li->transform.origin.y;
+ li->light_vector.z=li->transform.origin.z;
+ Vector3 dir = -li->transform.basis.get_axis(2);
+ li->spot_vector.x=dir.x;
+ li->spot_vector.y=dir.y;
+ li->spot_vector.z=dir.z;
+
+ } break;
+ }
+
+ light_instances[light_instance_count++]=li;
+}
+
+void RasterizerIPhone::_add_geometry( const Geometry* p_geometry, const Transform& p_world, uint32_t p_vertex_format, const RID* p_light_instances, int p_light_count, const ParamOverrideMap* p_material_overrides,const Skeleton* p_skeleton, GeometryOwner *p_owner) {
+
+ Material *m=NULL;
+
+ if (p_geometry->material.is_valid())
+ m=material_owner.get( p_geometry->material );
+
+ if (!m) {
+ m=material_owner.get( default_material );
+ }
+
+ ERR_FAIL_COND(!m);
+
+ LightInstance *lights[RenderList::MAX_LIGHTS];
+ int light_count=0;
+
+ RenderList *render_list=&opaque_render_list;
+ if (p_geometry->has_alpha || m->detail_blend_mode!=VS::MATERIAL_BLEND_MODE_MIX) {
+ render_list = &alpha_render_list;
+ };
+
+ if (!m->flags[VS::MATERIAL_FLAG_UNSHADED]) {
+
+ light_count=p_light_count;
+ for(int i=0;i<light_count;i++) {
+ lights[i]=light_instance_owner.get( p_light_instances[i] );
+ }
+ }
+
+ render_list->add_element( p_geometry, m, p_world, lights, light_count, p_material_overrides,p_skeleton, camera_plane.distance(p_world.origin), p_owner );
+}
+
+void RasterizerIPhone::add_mesh( RID p_mesh, const Transform* p_world, const RID* p_light_instances, int p_light_count, const ParamOverrideMap* p_material_overrides, RID p_skeleton) {
+
+ Mesh *mesh = mesh_owner.get(p_mesh);
+
+ int ssize = mesh->surfaces.size();
+
+ for (int i=0;i<ssize;i++) {
+
+ Surface *s = mesh->surfaces[i];
+ Skeleton *sk = p_skeleton.is_valid()?skeleton_owner.get(p_skeleton):NULL;
+
+ _add_geometry(s,*p_world,s->format,p_light_instances,p_light_count,p_material_overrides,sk,NULL);
+ }
+
+ mesh->last_pass=frame;
+}
+
+void RasterizerIPhone::add_multimesh( RID p_multimesh, const Transform* p_world, const RID* p_light_instances, int p_light_count, const ParamOverrideMap* p_material_overrides) {
+
+
+}
+
+void RasterizerIPhone::add_poly( RID p_poly, const Transform* p_world, const RID* p_light_instances, int p_light_count, const ParamOverrideMap* p_material_overrides) {
+
+ Poly *p = poly_owner.get(p_poly);
+ if (!p->primitives.empty()) {
+ const Poly::Primitive *pp = &p->primitives[0];
+
+ uint32_t format=VisualServer::ARRAY_FORMAT_VERTEX;
+
+ if (!pp->normals.empty())
+ format|=VisualServer::ARRAY_FORMAT_NORMAL;
+ if (!pp->colors.empty())
+ format|=VisualServer::ARRAY_FORMAT_COLOR;
+ if (!pp->uvs.empty())
+ format|=VisualServer::ARRAY_TEX_UV;
+
+ _add_geometry(p,*p_world,format,p_light_instances,p_light_count,p_material_overrides,NULL, NULL);
+ }
+}
+
+void RasterizerIPhone::add_beam( RID p_beam, const Transform* p_world, const RID* p_light_instances, int p_light_count, const ParamOverrideMap* p_material_overrides) {
+
+
+}
+
+void RasterizerIPhone::add_particles( RID p_particle_instance, const RID* p_light_instances, int p_light_count, const ParamOverrideMap* p_material_overrides) {
+
+
+}
+
+void RasterizerIPhone::_setup_material(const Geometry *p_geometry,const Material *p_material) {
+
+ if (p_material->flags[VS::MATERIAL_FLAG_DOUBLE_SIDED])
+ glDisable(GL_CULL_FACE);
+ else {
+ glEnable(GL_CULL_FACE);
+ glCullFace( (p_material->flags[VS::MATERIAL_FLAG_INVERT_FACES])?GL_FRONT:GL_BACK);
+ }
+
+ glEnable(GL_COLOR_MATERIAL); /* unused, unless color array */
+ //glColorMaterial( GL_FRONT_AND_BACK, GL_DIFFUSE );
+ glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
+
+
+ ///ambient @TODO offer global ambient group option
+ float ambient_rgba[4]={
+ 1,
+ 1,
+ 1,
+ 1.0
+ };
+ glMaterialfv(GL_FRONT_AND_BACK,GL_AMBIENT,ambient_rgba);
+
+ ///diffuse
+ const Color &diffuse_color=p_material->parameters[VS::FIXED_MATERIAL_PARAM_DIFFUSE];
+ float diffuse_rgba[4]={
+ (float)diffuse_color.r,
+ (float)diffuse_color.g,
+ (float)diffuse_color.b,
+ (float)diffuse_color.a
+ };
+
+ glColor4f( diffuse_rgba[0],diffuse_rgba[1],diffuse_rgba[2],diffuse_rgba[3]);
+
+ glMaterialfv(GL_FRONT_AND_BACK,GL_DIFFUSE,diffuse_rgba);
+
+ //specular
+
+ const Color &specular_color=p_material->parameters[VS::FIXED_MATERIAL_PARAM_SPECULAR];
+ float specular_rgba[4]={
+ (float)specular_color.r,
+ (float)specular_color.g,
+ (float)specular_color.b,
+ 1.0
+ };
+
+ glMaterialfv(GL_FRONT_AND_BACK,GL_SPECULAR,specular_rgba);
+
+ const Color &emission_color=p_material->parameters[VS::FIXED_MATERIAL_PARAM_EMISSION];
+ float emission_rgba[4]={
+ (float)emission_color.r,
+ (float)emission_color.g,
+ (float)emission_color.b,
+ 1.0
+ };
+
+ glMaterialfv(GL_FRONT_AND_BACK,GL_EMISSION,emission_rgba);
+
+ glMaterialf(GL_FRONT_AND_BACK,GL_SHININESS,p_material->parameters[VS::FIXED_MATERIAL_PARAM_SPECULAR_EXP]);
+
+ if (p_material->flags[VS::MATERIAL_FLAG_UNSHADED]) {
+ glDisable(GL_LIGHTING);
+ } else {
+ glEnable(GL_LIGHTING);
+ glDisable(GL_LIGHTING);
+ }
+
+ //depth test?
+ /*
+ if (p_material->flags[VS::MATERIAL_FLAG_WIREFRAME])
+ glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
+ else
+ glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
+ */
+ if (p_material->textures[VS::FIXED_MATERIAL_PARAM_DIFFUSE]) {
+
+ Texture *texture = texture_owner.get( p_material->textures[VS::FIXED_MATERIAL_PARAM_DIFFUSE] );
+ ERR_FAIL_COND(!texture);
+ glActiveTexture(GL_TEXTURE0);
+ glEnable(GL_TEXTURE_2D);
+ glBindTexture( GL_TEXTURE_2D,texture->tex_id );
+ };
+};
+
+void RasterizerIPhone::_setup_light(LightInstance* p_instance, int p_idx) {
+
+ Light* ld = p_instance->base;
+
+ int glid = GL_LIGHT0 + p_idx;
+ glLightfv(glid , GL_AMBIENT, ld->colors[VS::LIGHT_COLOR_AMBIENT].components );
+ glLightfv(glid, GL_DIFFUSE, ld->colors[VS::LIGHT_COLOR_DIFFUSE].components );
+ glLightfv(glid, GL_SPECULAR, ld->colors[VS::LIGHT_COLOR_SPECULAR].components );
+
+
+
+ switch(ld->type) {
+
+ case VS::LIGHT_DIRECTIONAL: {
+ /* This doesnt have attenuation */
+
+ glMatrixMode(GL_MODELVIEW);
+ glPushMatrix();
+ glLoadIdentity();
+ Vector3 v(0.0,0.0,-1.0); // directional lights point up by default
+ v = p_instance->transform.get_basis().xform( v );
+ v = camera_transform_inverse.get_basis().xform( v );
+ v.normalize(); // this sucks, so it will be optimized at some point
+ v = -v;
+ float lightpos[4]={v.x,v.y,v.z,0.0};
+
+ glLightfv(glid,GL_POSITION,lightpos); //at modelview
+
+ glPopMatrix();
+
+ } break;
+ case VS::LIGHT_OMNI: {
+
+ glLightf(glid,GL_SPOT_CUTOFF,180.0);
+ glLightf(glid,GL_CONSTANT_ATTENUATION, ld->vars[VS::LIGHT_PARAM_ATTENUATION]);
+ glLightf(glid,GL_LINEAR_ATTENUATION, ld->vars[VS::LIGHT_PARAM_RADIUS]);
+ glLightf(glid,GL_QUADRATIC_ATTENUATION, ld->vars[VS::LIGHT_PARAM_ENERGY]); // wut?
+
+ glMatrixMode(GL_MODELVIEW);
+ glPushMatrix();
+ glLoadIdentity();
+ Vector3 pos = p_instance->transform.get_origin();
+ pos = camera_transform_inverse.xform(pos);
+ float lightpos[4]={pos.x,pos.y,pos.z,1.0};
+ glLightfv(glid,GL_POSITION,lightpos); //at modelview
+
+ glPopMatrix();
+
+ } break;
+ case VS::LIGHT_SPOT: {
+
+ glLightf(glid,GL_SPOT_CUTOFF, ld->vars[VS::LIGHT_PARAM_SPOT_ANGLE]);
+ glLightf(glid,GL_SPOT_EXPONENT, ld->vars[VS::LIGHT_PARAM_SPOT_ATTENUATION]);
+ glLightf(glid,GL_CONSTANT_ATTENUATION, ld->vars[VS::LIGHT_PARAM_ATTENUATION]);
+ glLightf(glid,GL_LINEAR_ATTENUATION, ld->vars[VS::LIGHT_PARAM_RADIUS]);
+ glLightf(glid,GL_QUADRATIC_ATTENUATION, ld->vars[VS::LIGHT_PARAM_ENERGY]); // wut?
+
+
+ glMatrixMode(GL_MODELVIEW);
+ glPushMatrix();
+ glLoadIdentity();
+
+ Vector3 v(0.0,0.0,-1.0); // directional lights point up by default
+ v = p_instance->transform.get_basis().xform( v );
+ v = camera_transform_inverse.get_basis().xform( v );
+ v.normalize(); // this sucks, so it will be optimized at some point
+ float lightdir[4]={v.x, v.y, v.z, 1.0};
+ glLightfv(glid,GL_SPOT_DIRECTION,lightdir); //at modelview
+
+ v = p_instance->transform.get_origin();
+ v = camera_transform_inverse.xform(v);
+ float lightpos[4]={v.x,v.y,v.z,1.0};
+ glLightfv(glid,GL_POSITION,lightpos); //at modelview
+
+
+ glPopMatrix();
+
+
+ } break;
+ default: break;
+ }
+};
+
+void RasterizerIPhone::_setup_lights(LightInstance **p_lights,int p_light_count) {
+
+ for (int i=0; i<MAX_LIGHTS; i++) {
+
+ if (i<p_light_count) {
+ glEnable(GL_LIGHT0 + i);
+ _setup_light(p_lights[i], i);
+ } else {
+ glDisable(GL_LIGHT0 + i);
+ }
+ }
+}
+
+static const int gl_client_states[] = {
+
+ GL_VERTEX_ARRAY,
+ GL_NORMAL_ARRAY,
+ -1, // ARRAY_TANGENT
+ GL_COLOR_ARRAY,
+ GL_TEXTURE_COORD_ARRAY, // ARRAY_TEX_UV
+ GL_TEXTURE_COORD_ARRAY, // ARRAY_TEX_UV2
+ -1, // ARRAY_BONES
+ -1, // ARRAY_WEIGHTS
+ -1, // ARRAY_INDEX
+};
+
+void RasterizerIPhone::_setup_geometry(const Geometry *p_geometry, const Material* p_material) {
+
+
+ switch(p_geometry->type) {
+
+ case Geometry::GEOMETRY_SURFACE: {
+
+ Surface *surf = (Surface*)p_geometry;
+ uint8_t *base=0;
+ bool use_VBO = (surf->array_local==0);
+
+ if (!use_VBO) {
+
+ base = surf->array_local;
+ glBindBuffer(GL_ARRAY_BUFFER, 0);
+
+ } else {
+
+ glBindBuffer(GL_ARRAY_BUFFER, surf->vertex_id);
+ };
+
+ const Surface::ArrayData* a=surf->array;
+ for (int i=0;i<VS::ARRAY_MAX;i++) {
+
+ const Surface::ArrayData& ad=surf->array[i];
+ if (ad.size==0) {
+ if (gl_client_states[i] != -1) {
+ glDisableClientState(gl_client_states[i]);
+ };
+ continue; // this one is disabled.
+ }
+ ERR_CONTINUE( !ad.configured );
+
+ if (gl_client_states[i] != -1) {
+ glEnableClientState(gl_client_states[i]);
+ };
+
+ switch (i) {
+
+ case VS::ARRAY_VERTEX:
+ if (!use_VBO)
+ glVertexPointer(3,GL_FLOAT,surf->stride,(GLvoid*)&base[a->ofs]);
+ else
+ if (surf->array[VS::ARRAY_BONES].size)
+ glVertexPointer(3, GL_FLOAT, 0, skinned_buffer);
+ else
+ glVertexPointer(3,GL_FLOAT,surf->stride,(GLvoid*)a->ofs);
+ break;
+
+ case VS::ARRAY_NORMAL:
+ if (use_VBO)
+ glNormalPointer(GL_FLOAT,surf->stride,(GLvoid*)a->ofs);
+ else
+ glNormalPointer(GL_FLOAT,surf->stride,(GLvoid*)&base[a->ofs]);
+ break;
+ case VS::ARRAY_TANGENT:
+ break;
+ case VS::ARRAY_COLOR:
+ if (use_VBO)
+ glColorPointer(4,GL_UNSIGNED_BYTE,surf->stride,(GLvoid*)a->ofs);
+ else
+ glColorPointer(4,GL_UNSIGNED_BYTE,surf->stride,(GLvoid*)&base[a->ofs]);
+ break;
+ case VS::ARRAY_TEX_UV:
+ case VS::ARRAY_TEX_UV2:
+ if (use_VBO)
+ glTexCoordPointer(2,GL_FLOAT,surf->stride,(GLvoid*)a->ofs);
+ else
+ glTexCoordPointer(2,GL_FLOAT,surf->stride,&base[a->ofs]);
+ break;
+ case VS::ARRAY_BONES:
+ case VS::ARRAY_WEIGHTS:
+ case VS::ARRAY_INDEX:
+ break;
+ };
+ }
+
+
+ // process skeleton here
+
+ } break;
+
+ default: break;
+
+ };
+};
+
+static const GLenum gl_primitive[]={
+ GL_POINTS,
+ GL_LINES,
+ GL_LINE_STRIP,
+ GL_LINE_LOOP,
+ GL_TRIANGLES,
+ GL_TRIANGLE_STRIP,
+ GL_TRIANGLE_FAN
+};
+
+void RasterizerIPhone::_render(const Geometry *p_geometry,const Material *p_material, const Skeleton* p_skeleton) {
+
+
+ switch(p_geometry->type) {
+
+ case Geometry::GEOMETRY_SURFACE: {
+
+
+ Surface *s = (Surface*)p_geometry;
+
+ if (s->index_array_len>0) {
+
+ if (s->index_array_local) {
+
+ glDrawElements(gl_primitive[s->primitive], s->index_array_len, (s->index_array_len>(1<<8))?GL_UNSIGNED_SHORT:GL_UNSIGNED_BYTE, s->index_array_local);
+
+ } else {
+
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,s->index_id);
+ glDrawElements(gl_primitive[s->primitive],s->index_array_len, (s->index_array_len>(1<<8))?GL_UNSIGNED_SHORT:GL_UNSIGNED_BYTE,0);
+ }
+
+
+ } else {
+
+ glDrawArrays(gl_primitive[s->primitive],0,s->array_len);
+
+ };
+ } break;
+
+ default: break;
+ };
+};
+
+void RasterizerIPhone::_render_list_forward(RenderList *p_render_list) {
+
+ const Material *prev_material=NULL;
+ uint64_t prev_light_hash=0;
+ const Skeleton *prev_skeleton=NULL;
+ const Geometry *prev_geometry=NULL;
+ const ParamOverrideMap* prev_overrides=NULL; // make it diferent than NULL
+
+ Geometry::Type prev_geometry_type=Geometry::GEOMETRY_INVALID;
+
+ glMatrixMode(GL_PROJECTION);
+ glLoadMatrixf(&camera_projection.matrix[0][0]);
+
+ for (int i=0;i<p_render_list->element_count;i++) {
+
+ RenderList::Element *e = p_render_list->elements[i];
+ const Material *material = e->material;
+ uint64_t light_hash = e->light_hash;
+ const Skeleton *skeleton = e->skeleton;
+ const Geometry *geometry = e->geometry;
+ const ParamOverrideMap* material_overrides=e->material_overrides;
+
+ if (material!=prev_material || geometry->type!=prev_geometry_type) {
+ _setup_material(e->geometry,material);
+ //_setup_material_overrides(e->material,NULL,material_overrides);
+ //_setup_material_skeleton(material,skeleton);
+ } else {
+
+ if (material_overrides != prev_overrides) {
+
+ //_setup_material_overrides(e->material,prev_overrides,material_overrides);
+ }
+
+ if (prev_skeleton!=skeleton) {
+ //_setup_material_skeleton(material,skeleton);
+ };
+ }
+
+ if (geometry!=prev_geometry || geometry->type!=prev_geometry_type) {
+
+ _setup_geometry(geometry, material);
+ };
+
+ if (i==0 || light_hash!=prev_light_hash)
+ _setup_lights(e->lights,e->light_count);
+
+ glMatrixMode(GL_MODELVIEW);
+ _gl_load_transform(camera_transform_inverse);
+ _gl_mult_transform(e->transform);
+
+ _render(geometry, material, skeleton);
+
+ prev_material=material;
+ prev_skeleton=skeleton;
+ prev_geometry=geometry;
+ prev_light_hash=e->light_hash;
+ prev_geometry_type=geometry->type;
+ prev_overrides=material_overrides;
+ }
+};
+
+void RasterizerIPhone::end_scene() {
+
+ glEnable(GL_BLEND);
+ glDepthMask(GL_FALSE);
+
+ opaque_render_list.sort_mat_light();
+ _render_list_forward(&opaque_render_list);
+
+ glDisable(GL_BLEND);
+ glDepthMask(GL_TRUE);
+
+ alpha_render_list.sort_z();
+ _render_list_forward(&alpha_render_list);
+
+
+}
+void RasterizerIPhone::end_shadow_map() {
+
+
+}
+
+void RasterizerIPhone::end_frame() {
+
+ //ContextGL::get_singleton()->swap_buffers();
+}
+
+/* CANVAS API */
+
+void RasterizerIPhone::canvas_begin() {
+
+ glDisable(GL_CULL_FACE);
+ glDisable(GL_DEPTH_TEST);
+ glEnable(GL_BLEND);
+ glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
+ glLineWidth(1.0);
+ glDisable(GL_LIGHTING);
+
+ glMatrixMode(GL_PROJECTION);
+ glLoadIdentity();
+}
+void RasterizerIPhone::canvas_set_transparency(float p_transparency) {
+
+
+}
+
+void RasterizerIPhone::canvas_set_rect(const Rect2& p_rect, bool p_clip) {
+
+ glMatrixMode(GL_MODELVIEW);
+ glLoadIdentity();
+ glScalef(2.0 / window_size.x, -2.0 / window_size.y, 0);
+ glTranslatef((-(window_size.x / 2.0)) + p_rect.pos.x, (-(window_size.y / 2.0)) + p_rect.pos.y, 0);
+
+ if (p_clip) {
+
+ glEnable(GL_SCISSOR_TEST);
+ glScissor(viewport.x+p_rect.pos.x,viewport.y+ (viewport.height-(p_rect.pos.y+p_rect.size.height)),
+ p_rect.size.width,p_rect.size.height);
+ } else {
+
+ glDisable(GL_SCISSOR_TEST);
+ }
+
+
+}
+void RasterizerIPhone::canvas_draw_line(const Point2& p_from, const Point2& p_to,const Color& p_color,float p_width) {
+
+ glColor4f(1, 1, 1, 1);
+
+ float verts[6]={
+ p_from.x,p_from.y,0,
+ p_to.x,p_to.y,0
+ };
+
+ float colors[]={
+ p_color.r, p_color.g, p_color.b, p_color.a,
+ p_color.r, p_color.g, p_color.b, p_color.a,
+ };
+ glLineWidth(p_width);
+ _draw_primitive(2,verts,0,colors,0);
+}
+
+static void _draw_textured_quad(const Rect2& p_rect, const Rect2& p_src_region, const Size2& p_tex_size ) {
+
+ float texcoords[]= {
+ p_src_region.pos.x/p_tex_size.width,
+ p_src_region.pos.y/p_tex_size.height,
+
+ (p_src_region.pos.x+p_src_region.size.width)/p_tex_size.width,
+ p_src_region.pos.y/p_tex_size.height,
+
+ (p_src_region.pos.x+p_src_region.size.width)/p_tex_size.width,
+ (p_src_region.pos.y+p_src_region.size.height)/p_tex_size.height,
+
+ p_src_region.pos.x/p_tex_size.width,
+ (p_src_region.pos.y+p_src_region.size.height)/p_tex_size.height,
+ };
+
+ float coords[]= {
+ p_rect.pos.x, p_rect.pos.y, 0,
+ p_rect.pos.x+p_rect.size.width, p_rect.pos.y, 0,
+ p_rect.pos.x+p_rect.size.width, p_rect.pos.y+p_rect.size.height, 0,
+ p_rect.pos.x,p_rect.pos.y+p_rect.size.height, 0
+ };
+
+ _draw_primitive(4,coords,0,0,texcoords);
+}
+
+static void _draw_quad(const Rect2& p_rect) {
+
+ float coords[]= {
+ p_rect.pos.x,p_rect.pos.y, 0,
+ p_rect.pos.x+p_rect.size.width,p_rect.pos.y, 0,
+ p_rect.pos.x+p_rect.size.width,p_rect.pos.y+p_rect.size.height, 0,
+ p_rect.pos.x,p_rect.pos.y+p_rect.size.height, 0
+ };
+
+ _draw_primitive(4,coords,0,0,0);
+
+}
+
+void RasterizerIPhone::canvas_draw_rect(const Rect2& p_rect, bool p_region, const Rect2& p_source,bool p_tile,RID p_texture,const Color& p_modulate) {
+
+ glColor4f(p_modulate.r, p_modulate.g, p_modulate.b, p_modulate.a);
+
+ if ( p_texture.is_valid() ) {
+
+ glEnable(GL_TEXTURE_2D);
+ Texture *texture = texture_owner.get( p_texture );
+ ERR_FAIL_COND(!texture);
+ glActiveTexture(GL_TEXTURE0);
+ glBindTexture( GL_TEXTURE_2D,texture->tex_id );
+
+ if (!p_region) {
+
+ Rect2 region = Rect2(0,0,texture->width,texture->height);
+ _draw_textured_quad(p_rect,region,region.size);
+
+ } else {
+
+ _draw_textured_quad(p_rect, p_source, Size2(texture->width,texture->height) );
+
+ }
+ } else {
+
+ _draw_quad( p_rect );
+
+ }
+
+
+}
+void RasterizerIPhone::canvas_draw_style_box(const Rect2& p_rect, RID p_texture,const float *p_margin, bool p_draw_center) {
+
+ glColor4f(1, 1, 1, 1);
+
+ Texture *texture = texture_owner.get( p_texture );
+ ERR_FAIL_COND(!texture);
+
+ glEnable(GL_TEXTURE_2D);
+ glActiveTexture(GL_TEXTURE0);
+ glBindTexture( GL_TEXTURE_2D,texture->tex_id );
+
+
+ /* CORNERS */
+
+ _draw_textured_quad( // top left
+ Rect2( p_rect.pos, Size2(p_margin[MARGIN_LEFT],p_margin[MARGIN_TOP])),
+ Rect2( Point2(), Size2(p_margin[MARGIN_LEFT],p_margin[MARGIN_TOP])),
+ Size2( texture->width, texture->height ) );
+
+ _draw_textured_quad( // top right
+ Rect2( Point2( p_rect.pos.x + p_rect.size.width - p_margin[MARGIN_RIGHT], p_rect.pos.y), Size2(p_margin[MARGIN_RIGHT],p_margin[MARGIN_TOP])),
+ Rect2( Point2(texture->width-p_margin[MARGIN_RIGHT],0), Size2(p_margin[MARGIN_RIGHT],p_margin[MARGIN_TOP])),
+ Size2( texture->width, texture->height ) );
+
+
+ _draw_textured_quad( // bottom left
+ Rect2( Point2(p_rect.pos.x,p_rect.pos.y + p_rect.size.height - p_margin[MARGIN_BOTTOM]), Size2(p_margin[MARGIN_LEFT],p_margin[MARGIN_BOTTOM])),
+ Rect2( Point2(0,texture->height-p_margin[MARGIN_BOTTOM]), Size2(p_margin[MARGIN_LEFT],p_margin[MARGIN_BOTTOM])),
+ Size2( texture->width, texture->height ) );
+
+ _draw_textured_quad( // bottom right
+ Rect2( Point2( p_rect.pos.x + p_rect.size.width - p_margin[MARGIN_RIGHT], p_rect.pos.y + p_rect.size.height - p_margin[MARGIN_BOTTOM]), Size2(p_margin[MARGIN_RIGHT],p_margin[MARGIN_BOTTOM])),
+ Rect2( Point2(texture->width-p_margin[MARGIN_RIGHT],texture->height-p_margin[MARGIN_BOTTOM]), Size2(p_margin[MARGIN_RIGHT],p_margin[MARGIN_BOTTOM])),
+ Size2( texture->width, texture->height ) );
+
+ Rect2 rect_center( p_rect.pos+Point2( p_margin[MARGIN_LEFT], p_margin[MARGIN_TOP]), Size2( p_rect.size.width - p_margin[MARGIN_LEFT] - p_margin[MARGIN_RIGHT], p_rect.size.height - p_margin[MARGIN_TOP] - p_margin[MARGIN_BOTTOM] ));
+
+ Rect2 src_center( Point2( p_margin[MARGIN_LEFT], p_margin[MARGIN_TOP]), Size2( texture->width - p_margin[MARGIN_LEFT] - p_margin[MARGIN_RIGHT], texture->height - p_margin[MARGIN_TOP] - p_margin[MARGIN_BOTTOM] ));
+
+
+ _draw_textured_quad( // top
+ Rect2( Point2(rect_center.pos.x,p_rect.pos.y),Size2(rect_center.size.width,p_margin[MARGIN_TOP])),
+ Rect2( Point2(p_margin[MARGIN_LEFT],0), Size2(src_center.size.width,p_margin[MARGIN_TOP])),
+ Size2( texture->width, texture->height ) );
+
+ _draw_textured_quad( // bottom
+ Rect2( Point2(rect_center.pos.x,rect_center.pos.y+rect_center.size.height),Size2(rect_center.size.width,p_margin[MARGIN_BOTTOM])),
+ Rect2( Point2(p_margin[MARGIN_LEFT],src_center.pos.y+src_center.size.height), Size2(src_center.size.width,p_margin[MARGIN_BOTTOM])),
+ Size2( texture->width, texture->height ) );
+
+ _draw_textured_quad( // left
+ Rect2( Point2(p_rect.pos.x,rect_center.pos.y),Size2(p_margin[MARGIN_LEFT],rect_center.size.height)),
+ Rect2( Point2(0,p_margin[MARGIN_TOP]), Size2(p_margin[MARGIN_LEFT],src_center.size.height)),
+ Size2( texture->width, texture->height ) );
+
+ _draw_textured_quad( // right
+ Rect2( Point2(rect_center.pos.x+rect_center.size.width,rect_center.pos.y),Size2(p_margin[MARGIN_RIGHT],rect_center.size.height)),
+ Rect2( Point2(src_center.pos.x+src_center.size.width,p_margin[MARGIN_TOP]), Size2(p_margin[MARGIN_RIGHT],src_center.size.height)),
+ Size2( texture->width, texture->height ) );
+
+ if (p_draw_center) {
+
+ _draw_textured_quad(
+ rect_center,
+ src_center,
+ Size2( texture->width, texture->height ));
+ }
+
+}
+void RasterizerIPhone::canvas_draw_primitive(const Vector<Point2>& p_points, const Vector<Color>& p_colors,const Vector<Point2>& p_uvs, RID p_texture) {
+
+ ERR_FAIL_COND(p_points.size()<1);
+ float verts[12];
+ float uvs[8];
+ float colors[16];
+
+ glColor4f(1, 1, 1, 1);
+
+ int idx = 0;
+ for(int i=0;i<p_points.size();i++) {
+
+ verts[idx++]=p_points[i].x;
+ verts[idx++]=p_points[i].y;
+ verts[idx++]=0;
+ }
+
+ idx = 0;
+ for(int i=0;i<p_uvs.size();i++) {
+
+ uvs[idx++] = p_uvs[i].x;
+ uvs[idx++] = p_uvs[i].y;
+ }
+
+ idx = 0;
+ for (int i=0; i<p_colors.size(); i++) {
+
+ colors[idx++] = p_colors[i].r;
+ colors[idx++] = p_colors[i].g;
+ colors[idx++] = p_colors[i].b;
+ colors[idx++] = p_colors[i].a;
+ };
+
+ if (p_texture.is_valid()) {
+ glEnable(GL_TEXTURE_2D);
+ Texture *texture = texture_owner.get( p_texture );
+ if (texture) {
+ glActiveTexture(GL_TEXTURE0);
+ glBindTexture( GL_TEXTURE_2D,texture->tex_id );
+ }
+ }
+
+ _draw_primitive(p_points.size(),&verts[0],NULL,p_colors.size()?&colors[0]:NULL,p_uvs.size()?uvs:NULL);
+
+}
+
+/* FX */
+
+RID RasterizerIPhone::fx_create() {
+
+ return RID();
+}
+void RasterizerIPhone::fx_get_effects(RID p_fx,List<String> *p_effects) const {
+
+
+}
+void RasterizerIPhone::fx_set_active(RID p_fx,const String& p_effect, bool p_active) {
+
+
+}
+bool RasterizerIPhone::fx_is_active(RID p_fx,const String& p_effect) const {
+
+ return false;
+}
+void RasterizerIPhone::fx_get_effect_params(RID p_fx,const String& p_effect,List<PropertyInfo> *p_params) const {
+
+
+}
+Variant RasterizerIPhone::fx_get_effect_param(RID p_fx,const String& p_effect,const String& p_param) const {
+
+ return Variant();
+}
+void RasterizerIPhone::fx_set_effect_param(RID p_fx,const String& p_effect, const String& p_param, const Variant& p_pvalue) {
+
+
+}
+
+/*MISC*/
+
+bool RasterizerIPhone::is_texture(const RID& p_rid) const {
+
+ return texture_owner.owns(p_rid);
+}
+bool RasterizerIPhone::is_material(const RID& p_rid) const {
+
+ return material_owner.owns(p_rid);
+}
+bool RasterizerIPhone::is_mesh(const RID& p_rid) const {
+
+ return mesh_owner.owns(p_rid);
+}
+bool RasterizerIPhone::is_multimesh(const RID& p_rid) const {
+
+ return false;
+}
+bool RasterizerIPhone::is_poly(const RID& p_rid) const {
+
+ return poly_owner.owns(p_rid);
+}
+bool RasterizerIPhone::is_particles(const RID &p_beam) const {
+
+ return false;
+}
+
+bool RasterizerIPhone::is_beam(const RID &p_beam) const {
+
+ return false;
+}
+
+bool RasterizerIPhone::is_light(const RID& p_rid) const {
+
+ return light_owner.owns(p_rid);
+}
+bool RasterizerIPhone::is_light_instance(const RID& p_rid) const {
+
+ return light_instance_owner.owns(p_rid);
+}
+bool RasterizerIPhone::is_particles_instance(const RID& p_rid) const {
+
+ return false;
+}
+bool RasterizerIPhone::is_skeleton(const RID& p_rid) const {
+
+ return skeleton_owner.owns(p_rid);
+}
+bool RasterizerIPhone::is_fx(const RID& p_rid) const {
+
+ return fx_owner.owns(p_rid);
+}
+bool RasterizerIPhone::is_shader(const RID& p_rid) const {
+
+ return false;
+}
+
+void RasterizerIPhone::free(const RID& p_rid) const {
+
+ if (texture_owner.owns(p_rid)) {
+
+ // delete the texture
+ Texture *texture = texture_owner.get(p_rid);
+
+ glDeleteTextures( 1,&texture->tex_id );
+
+ texture_owner.free(p_rid);
+ memdelete(texture);
+
+ } else if (material_owner.owns(p_rid)) {
+
+ Material *material = material_owner.get( p_rid );
+ ERR_FAIL_COND(!material);
+
+ material_owner.free(p_rid);
+ memdelete(material);
+
+ } else if (mesh_owner.owns(p_rid)) {
+
+ Mesh *mesh = mesh_owner.get(p_rid);
+ ERR_FAIL_COND(!mesh);
+ for (int i=0;i<mesh->surfaces.size();i++) {
+
+ Surface *surface = mesh->surfaces[i];
+ if (surface->array_local != 0) {
+ memfree(surface->array_local);
+ };
+ if (surface->index_array_local != 0) {
+ memfree(surface->index_array_local);
+ };
+
+ if (surface->vertex_id)
+ glDeleteBuffers(1,&surface->vertex_id);
+ if (surface->index_id)
+ glDeleteBuffers(1,&surface->index_id);
+
+ memdelete( surface );
+ };
+
+ mesh->surfaces.clear();
+
+ mesh_owner.free(p_rid);
+ memdelete(mesh);
+
+ } else if (skeleton_owner.owns(p_rid)) {
+
+ Skeleton *skeleton = skeleton_owner.get( p_rid );
+ ERR_FAIL_COND(!skeleton)
+
+ skeleton_owner.free(p_rid);
+ memdelete(skeleton);
+
+ } else if (light_owner.owns(p_rid)) {
+
+ Light *light = light_owner.get( p_rid );
+ ERR_FAIL_COND(!light)
+
+ light_owner.free(p_rid);
+ memdelete(light);
+
+ } else if (light_instance_owner.owns(p_rid)) {
+
+ LightInstance *light_instance = light_instance_owner.get( p_rid );
+ ERR_FAIL_COND(!light_instance);
+
+ light_instance_owner.free(p_rid);
+ memdelete( light_instance );
+
+ } else if (fx_owner.owns(p_rid)) {
+
+ FX *fx = fx_owner.get( p_rid );
+ ERR_FAIL_COND(!fx);
+
+ fx_owner.free(p_rid);
+ memdelete( fx );
+
+ };
+}
+
+void RasterizerIPhone::init() {
+
+ glEnable(GL_DEPTH_TEST);
+ glDepthFunc(GL_LEQUAL);
+ glFrontFace(GL_CW);
+
+ glEnable(GL_TEXTURE_2D);
+}
+
+void RasterizerIPhone::finish() {
+
+}
+
+ int RasterizerIPhone::get_render_info(VS::RenderInfo p_info) {
+
+ return false;
+}
+
+RasterizerIPhone::RasterizerIPhone() {
+
+ frame = 0;
+};
+
+RasterizerIPhone::~RasterizerIPhone() {
+
+};
+
+
+#endif
diff --git a/platform/iphone/rasterizer_iphone.h b/platform/iphone/rasterizer_iphone.h
new file mode 100644
index 0000000000..41dbbdaa5a
--- /dev/null
+++ b/platform/iphone/rasterizer_iphone.h
@@ -0,0 +1,894 @@
+/*************************************************************************/
+/* rasterizer_iphone.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* http://www.godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+#ifdef IPHONE_ENABLED
+
+#ifndef RASTERIZER_IPHONE_H
+#define RASTERIZER_IPHONE_H
+
+#include "servers/visual/rasterizer.h"
+
+#include "image.h"
+#include "rid.h"
+#include "servers/visual_server.h"
+#include "list.h"
+#include "map.h"
+#include "camera_matrix.h"
+#include "sort.h"
+#include <ES1/gl.h>
+
+/**
+ @author Juan Linietsky <reduzio@gmail.com>
+*/
+class RasterizerIPhone : public Rasterizer {
+
+ enum {
+ SKINNED_BUFFER_SIZE = 1024 * 128, // 10k vertices
+ MAX_LIGHTS = 8,
+ };
+
+ uint8_t skinned_buffer[SKINNED_BUFFER_SIZE];
+
+ struct Texture {
+
+ uint32_t flags;
+ int width,height;
+ Image::Format format;
+
+ GLenum target;
+ GLenum gl_format_cache;
+ int gl_components_cache;
+ bool has_alpha;
+ bool format_has_alpha;
+
+ bool active;
+ GLuint tex_id;
+ bool mipmap_dirty;
+
+ Texture() {
+
+ flags=width=height=0;
+ tex_id=0;
+ format=Image::FORMAT_GRAYSCALE;
+ gl_components_cache=0;
+ format_has_alpha=false;
+ has_alpha=false;
+ active=false;
+ mipmap_dirty=true;
+ }
+
+ ~Texture() {
+
+ if (tex_id!=0) {
+
+ glDeleteTextures(1,&tex_id);
+ }
+ }
+ };
+
+ mutable RID_Owner<Texture> texture_owner;
+
+ struct Material {
+
+ bool flags[VS::MATERIAL_FLAG_MAX];
+ Variant parameters[VisualServer::FIXED_MATERIAL_PARAM_MAX];
+ RID textures[VisualServer::FIXED_MATERIAL_PARAM_MAX];
+
+ Transform uv_transform;
+ VS::FixedMaterialTexCoordMode texcoord_mode[VisualServer::FIXED_MATERIAL_PARAM_MAX];
+
+ VS::MaterialBlendMode detail_blend_mode;
+
+ VS::FixedMaterialTexGenMode texgen_mode;
+
+ Material() {
+
+ flags[VS::MATERIAL_FLAG_VISIBLE]=true;
+ flags[VS::MATERIAL_FLAG_DOUBLE_SIDED]=false;
+ flags[VS::MATERIAL_FLAG_INVERT_FACES]=false;
+ flags[VS::MATERIAL_FLAG_UNSHADED]=false;
+ flags[VS::MATERIAL_FLAG_WIREFRAME]=false;
+
+ parameters[VS::FIXED_MATERIAL_PARAM_DIFFUSE] = Color(0.8, 0.8, 0.8);
+ parameters[VS::FIXED_MATERIAL_PARAM_SPECULAR_EXP] = 12;
+
+ for (int i=0; i<VisualServer::FIXED_MATERIAL_PARAM_MAX; i++) {
+ texcoord_mode[i] = VS::FIXED_MATERIAL_TEXCOORD_UV;
+ };
+ detail_blend_mode = VS::MATERIAL_BLEND_MODE_MIX;
+ texgen_mode = VS::FIXED_MATERIAL_TEXGEN_SPHERE;
+ }
+ };
+ mutable RID_Owner<Material> material_owner;
+
+
+ struct Geometry {
+
+ enum Type {
+ GEOMETRY_INVALID,
+ GEOMETRY_SURFACE,
+ GEOMETRY_POLY,
+ GEOMETRY_PARTICLES,
+ GEOMETRY_BEAM,
+ GEOMETRY_DETAILER,
+ };
+
+ Type type;
+ RID material;
+ bool has_alpha;
+ bool material_owned;
+
+ Vector3 scale;
+ Vector3 uv_scale;
+
+ Geometry() : scale(1, 1, 1) { has_alpha=false; material_owned = false; }
+ virtual ~Geometry() {};
+ };
+
+ struct GeometryOwner {
+
+ virtual ~GeometryOwner() {}
+ };
+
+
+ struct Surface : public Geometry {
+
+ struct ArrayData {
+
+ uint32_t ofs,size;
+ bool configured;
+ int components;
+ ArrayData() { ofs=0; size=0; configured=false; }
+ };
+
+ ArrayData array[VS::ARRAY_MAX];
+ // support for vertex array objects
+ GLuint array_object_id;
+ // support for vertex buffer object
+ GLuint vertex_id; // 0 means, unconfigured
+ GLuint index_id; // 0 means, unconfigured
+ // no support for the above, array in localmem.
+ uint8_t *array_local;
+ uint8_t *index_array_local;
+
+ AABB aabb;
+
+ int array_len;
+ int index_array_len;
+
+ VS::PrimitiveType primitive;
+
+ uint32_t format;
+
+ int stride;
+
+ bool active;
+
+ Point2 uv_min;
+ Point2 uv_max;
+
+ bool has_alpha_cache;
+
+ Surface() {
+
+ array_len=0;
+ type=GEOMETRY_SURFACE;
+ primitive=VS::PRIMITIVE_POINTS;
+ index_array_len=VS::NO_INDEX_ARRAY;
+ format=0;
+ stride=0;
+
+ array_local = index_array_local = 0;
+ vertex_id = index_id = 0;
+
+ active=false;
+ }
+
+ ~Surface() {
+
+ }
+ };
+
+
+ struct Mesh {
+
+ bool active;
+ Vector<Surface*> surfaces;
+
+ mutable uint64_t last_pass;
+ Mesh() {
+ last_pass=0;
+ active=false;
+ }
+ };
+ mutable RID_Owner<Mesh> mesh_owner;
+
+ struct Poly : public Geometry {
+
+ struct Primitive {
+
+ Vector<Vector3> vertices;
+ Vector<Vector3> normals;
+ Vector<Vector3> uvs;
+ Vector<Color> colors;
+
+ };
+
+ AABB aabb;
+ List<Primitive> primitives;
+ Poly() {
+
+ type=GEOMETRY_POLY;
+ }
+ };
+
+ mutable RID_Owner<Poly> poly_owner;
+
+
+ struct Skeleton {
+
+ Vector<Transform> bones;
+
+ };
+
+ mutable RID_Owner<Skeleton> skeleton_owner;
+
+
+ struct Light {
+
+ VS::LightType type;
+ float vars[VS::LIGHT_PARAM_MAX];
+ Color colors[3];
+ bool shadow_enabled;
+ RID projector;
+ bool volumetric_enabled;
+ Color volumetric_color;
+
+
+ Light() {
+
+ vars[VS::LIGHT_PARAM_SPOT_ATTENUATION]=1;
+ vars[VS::LIGHT_PARAM_SPOT_ANGLE]=45;
+ vars[VS::LIGHT_PARAM_ATTENUATION]=1.0;
+ vars[VS::LIGHT_PARAM_ENERGY]=1.0;
+ vars[VS::LIGHT_PARAM_RADIUS]=1.0;
+ colors[VS::LIGHT_COLOR_AMBIENT]=Color(0,0,0);
+ colors[VS::LIGHT_COLOR_DIFFUSE]=Color(1,1,1);
+ colors[VS::LIGHT_COLOR_SPECULAR]=Color(1,1,1);
+ shadow_enabled=false;
+ volumetric_enabled=false;
+ }
+ };
+
+ struct ShadowBuffer;
+
+ struct LightInstance {
+
+ struct SplitInfo {
+
+ CameraMatrix camera;
+ Transform transform;
+ float near;
+ float far;
+ };
+
+ RID light;
+ Light *base;
+ uint64_t last_pass;
+ Transform transform;
+
+
+ CameraMatrix projection;
+ Vector<SplitInfo> splits;
+
+ Vector3 light_vector;
+ Vector3 spot_vector;
+ float linear_att;
+
+ uint64_t hash_aux;
+ };
+ mutable RID_Owner<Light> light_owner;
+ mutable RID_Owner<LightInstance> light_instance_owner;
+
+ LightInstance *light_instances[MAX_LIGHTS];
+ int light_instance_count;
+
+ struct RenderList {
+
+ enum {
+ MAX_ELEMENTS=4096,
+ MAX_LIGHTS=4
+ };
+
+ struct Element {
+
+ float depth;
+ const Skeleton *skeleton;
+ Transform transform;
+ LightInstance* lights[MAX_LIGHTS];
+ int light_count;
+ const Geometry *geometry;
+ const Material *material;
+ uint64_t light_hash;
+ GeometryOwner *owner;
+ const ParamOverrideMap* material_overrides;
+ };
+
+
+ Element _elements[MAX_ELEMENTS];
+ Element *elements[MAX_ELEMENTS];
+ int element_count;
+
+ void clear() {
+
+ element_count=0;
+ }
+
+ struct SortZ {
+
+ _FORCE_INLINE_ bool operator()(const Element* A, const Element* B ) const {
+
+ return A->depth > B->depth;
+ }
+ };
+
+ void sort_z() {
+
+ SortArray<Element*,SortZ> sorter;
+ sorter.sort(elements,element_count);
+ }
+
+ struct SortSkel {
+
+ _FORCE_INLINE_ bool operator()(const Element* A, const Element* B ) const {
+
+ if (A->geometry < B->geometry)
+ return true;
+ else if (A->geometry > B->geometry)
+ return false;
+ else return (!A->skeleton && B->skeleton);
+ }
+ };
+
+ void sort_skel() {
+
+ SortArray<Element*,SortSkel> sorter;
+ sorter.sort(elements,element_count);
+ }
+
+ struct SortMat {
+
+ _FORCE_INLINE_ bool operator()(const Element* A, const Element* B ) const {
+
+ if (A->geometry == B->geometry) {
+
+ if (A->material == B->material) {
+
+
+ return (A->material_overrides < B->material_overrides);
+ } else {
+
+ return (A->material < B->material);
+ }
+ } else {
+
+ return (A->geometry < B->geometry);
+ }
+ }
+ };
+
+ void sort_mat() {
+
+ SortArray<Element*,SortMat> sorter;
+ sorter.sort(elements,element_count);
+ }
+
+ struct SortMatLight {
+
+ _FORCE_INLINE_ bool operator()(const Element* A, const Element* B ) const {
+
+ if (A->geometry == B->geometry) {
+
+ if (A->material == B->material) {
+
+ if (A->light_hash == B->light_hash)
+ return (A->material_overrides < B->material_overrides);
+ else
+ return A->light_hash<B->light_hash;
+ } else {
+
+ return (A->material < B->material);
+ }
+ } else {
+
+ return (A->geometry < B->geometry);
+ }
+ }
+ };
+
+ void sort_mat_light() {
+
+ SortArray<Element*,SortMatLight> sorter;
+ sorter.sort(elements,element_count);
+ }
+
+ struct LISort {
+
+ _FORCE_INLINE_ bool operator ()(const LightInstance *A, const LightInstance *B) const {
+
+ return (A->hash_aux < B->hash_aux);
+ }
+ };
+
+ _FORCE_INLINE_ void add_element( const Geometry *p_geometry, const Material* p_material,const Transform& p_transform, LightInstance **p_light_instances, int p_light_count, const ParamOverrideMap* p_material_overrides, const Skeleton *p_skeleton, float p_depth, GeometryOwner *p_owner=NULL) {
+
+
+ ERR_FAIL_COND( element_count >= MAX_ELEMENTS );
+ Element *e = elements[element_count++];
+
+ e->geometry=p_geometry;
+ e->material=p_material;
+ e->transform=p_transform;
+ e->skeleton=p_skeleton;
+ e->light_hash=0;
+ e->light_count=p_light_count;
+ e->owner=p_owner;
+ e->material_overrides=p_material_overrides;
+
+ if (e->light_count>0) {
+
+ SortArray<LightInstance*,LISort> light_sort;
+ light_sort.sort(p_light_instances,p_light_count);
+ //@TODO OPTIOMIZE
+
+ for (int i=0;i<p_light_count;i++) {
+
+ e->lights[i]=p_light_instances[i];
+
+ if (i==0)
+ e->light_hash=hash_djb2_one_64( make_uint64_t(e->lights[i]) );
+ else
+ e->light_hash=hash_djb2_one_64( make_uint64_t(e->lights[i]),e->light_hash);
+ }
+
+ }
+
+ }
+
+ RenderList() {
+
+ for (int i=0;i<MAX_ELEMENTS;i++)
+ elements[i]=&_elements[i]; // assign elements
+ }
+ };
+
+ RenderList opaque_render_list;
+ RenderList alpha_render_list;
+
+ RID default_material;
+
+ struct FX {
+
+ bool bgcolor_active;
+ Color bgcolor;
+
+ bool skybox_active;
+ RID skybox_cubemap;
+
+ bool antialias_active;
+ float antialias_tolerance;
+
+ bool glow_active;
+ int glow_passes;
+ float glow_attenuation;
+ float glow_bloom;
+
+ bool ssao_active;
+ float ssao_attenuation;
+ float ssao_radius;
+ float ssao_max_distance;
+ float ssao_range_max;
+ float ssao_range_min;
+ bool ssao_only;
+
+ bool fog_active;
+ float fog_distance;
+ float fog_attenuation;
+ Color fog_color_near;
+ Color fog_color_far;
+ bool fog_bg;
+
+ bool toon_active;
+ float toon_treshold;
+ float toon_soft;
+
+ bool edge_active;
+ Color edge_color;
+ float edge_size;
+
+ FX();
+
+ };
+ mutable RID_Owner<FX> fx_owner;
+
+
+ FX *scene_fx;
+ CameraMatrix camera_projection;
+ Transform camera_transform;
+ Transform camera_transform_inverse;
+ float camera_z_near;
+ float camera_z_far;
+ Size2 camera_vp_size;
+
+ Plane camera_plane;
+
+ void _add_geometry( const Geometry* p_geometry, const Transform& p_world, uint32_t p_vertex_format, const RID* p_light_instances, int p_light_count, const ParamOverrideMap* p_material_overrides,const Skeleton* p_skeleton,GeometryOwner *p_owner);
+ void _render_list_forward(RenderList *p_render_list);
+
+ void _setup_light(LightInstance* p_instance, int p_idx);
+ void _setup_lights(LightInstance **p_lights,int p_light_count);
+ void _setup_material(const Geometry *p_geometry,const Material *p_material);
+
+ void _setup_geometry(const Geometry *p_geometry, const Material* p_material);
+ void _render(const Geometry *p_geometry,const Material *p_material, const Skeleton* p_skeleton);
+
+
+ /*********/
+ /* FRAME */
+ /*********/
+
+ Size2 window_size;
+ VS::ViewportRect viewport;
+ Transform canvas_transform;
+ double last_time;
+ double time_delta;
+ uint64_t frame;
+
+public:
+
+ /* TEXTURE API */
+
+ virtual RID texture_create();
+ virtual void texture_allocate(RID p_texture,int p_width, int p_height,Image::Format p_format,uint32_t p_flags=VS::TEXTURE_FLAGS_DEFAULT);
+ virtual void texture_blit_rect(RID p_texture,int p_x,int p_y, const Image& p_image,VS::CubeMapSide p_cube_side=VS::CUBEMAP_LEFT);
+ virtual Image texture_get_rect(RID p_texture,int p_x,int p_y,int p_width, int p_height,VS::CubeMapSide p_cube_side=VS::CUBEMAP_LEFT) const;
+ virtual void texture_set_flags(RID p_texture,uint32_t p_flags);
+ virtual uint32_t texture_get_flags(RID p_texture) const;
+ virtual Image::Format texture_get_format(RID p_texture) const;
+ virtual uint32_t texture_get_width(RID p_texture) const;
+ virtual uint32_t texture_get_height(RID p_texture) const;
+ virtual bool texture_has_alpha(RID p_texture) const;
+
+ /* SHADER API */
+
+ virtual RID shader_create();
+
+ virtual void shader_node_add(RID p_shader,VS::ShaderNodeType p_type,int p_id);
+ virtual void shader_node_remove(RID p_shader,int p_id);
+ virtual void shader_node_change_type(RID p_shader, int p_id, VS::ShaderNodeType p_type);
+ virtual void shader_node_set_param(RID p_shader, int p_id, const Variant& p_value);
+
+ virtual void shader_get_node_list(RID p_shader,List<int> *p_node_list) const;
+ virtual VS::ShaderNodeType shader_node_get_type(RID p_shader,int p_id) const;
+ virtual Variant shader_node_get_param(RID p_shader,int p_id) const;
+
+ virtual void shader_connect(RID p_shader,int p_src_id,int p_src_slot, int p_dst_id,int p_dst_slot);
+ virtual bool shader_is_connected(RID p_shader,int p_src_id,int p_src_slot, int p_dst_id,int p_dst_slot) const;
+ virtual void shader_disconnect(RID p_shader,int p_src_id,int p_src_slot, int p_dst_id,int p_dst_slot);
+
+ virtual void shader_get_connections(RID p_shader,List<VS::ShaderConnection> *p_connections) const;
+
+ virtual void shader_clear(RID p_shader);
+
+ /* COMMON MATERIAL API */
+
+ virtual void material_set_param(RID p_material, const StringName& p_param, const Variant& p_value);
+ virtual Variant material_get_param(RID p_material, const StringName& p_param) const;
+ virtual void material_get_param_list(RID p_material, List<String> *p_param_list) const;
+
+ virtual void material_set_flag(RID p_material, VS::MaterialFlag p_flag,bool p_enabled);
+ virtual bool material_get_flag(RID p_material,VS::MaterialFlag p_flag) const;
+
+ virtual void material_set_blend_mode(RID p_material,VS::MaterialBlendMode p_mode);
+ virtual VS::MaterialBlendMode material_get_blend_mode(RID p_material) const;
+
+ virtual void material_set_line_width(RID p_material,float p_line_width);
+ virtual float material_get_line_width(RID p_material) const;
+
+ /* FIXED MATERIAL */
+
+ virtual RID material_create();
+
+ virtual void fixed_material_set_parameter(RID p_material, VS::FixedMaterialParam p_parameter, const Variant& p_value);
+ virtual Variant fixed_material_get_parameter(RID p_material,VS::FixedMaterialParam p_parameter) const;
+
+ virtual void fixed_material_set_texture(RID p_material,VS::FixedMaterialParam p_parameter, RID p_texture);
+ virtual RID fixed_material_get_texture(RID p_material,VS::FixedMaterialParam p_parameter) const;
+
+ virtual void fixed_material_set_detail_blend_mode(RID p_material,VS::MaterialBlendMode p_mode);
+ virtual VS::MaterialBlendMode fixed_material_get_detail_blend_mode(RID p_material) const;
+
+ virtual void fixed_material_set_texgen_mode(RID p_material,VS::FixedMaterialTexGenMode p_mode);
+ virtual VS::FixedMaterialTexGenMode fixed_material_get_texgen_mode(RID p_material) const;
+
+ virtual void fixed_material_set_texcoord_mode(RID p_material,VS::FixedMaterialParam p_parameter, VS::FixedMaterialTexCoordMode p_mode);
+ virtual VS::FixedMaterialTexCoordMode fixed_material_get_texcoord_mode(RID p_material,VS::FixedMaterialParam p_parameter) const;
+
+ virtual void fixed_material_set_uv_transform(RID p_material,const Transform& p_transform);
+ virtual Transform fixed_material_get_uv_transform(RID p_material) const;
+
+ /* SHADER MATERIAL */
+
+ virtual RID shader_material_create() const;
+
+ virtual void shader_material_set_vertex_shader(RID p_material,RID p_shader,bool p_owned=false);
+ virtual RID shader_material_get_vertex_shader(RID p_material) const;
+
+ virtual void shader_material_set_fragment_shader(RID p_material,RID p_shader,bool p_owned=false);
+ virtual RID shader_material_get_fragment_shader(RID p_material) const;
+
+
+ /* MESH API */
+
+ virtual RID mesh_create();
+
+ virtual void mesh_add_surface(RID p_mesh,VS::PrimitiveType p_primitive,uint32_t p_format,int p_array_len,int p_index_array_len=VS::NO_INDEX_ARRAY);
+
+ virtual Error mesh_surface_set_array(RID p_mesh, int p_surface,VS::ArrayType p_type,const Variant& p_array) ;
+ virtual Variant mesh_surface_get_array(RID p_mesh, int p_surface,VS::ArrayType p_type) const;
+
+ virtual void mesh_surface_set_material(RID p_mesh, int p_surface, RID p_material,bool p_owned=false);
+ virtual RID mesh_surface_get_material(RID p_mesh, int p_surface) const;
+
+ virtual int mesh_surface_get_array_len(RID p_mesh, int p_surface) const;
+ virtual int mesh_surface_get_array_index_len(RID p_mesh, int p_surface) const;
+ virtual uint32_t mesh_surface_get_format(RID p_mesh, int p_surface) const;
+ virtual VS::PrimitiveType mesh_surface_get_primitive_type(RID p_mesh, int p_surface) const;
+
+ virtual void mesh_erase_surface(RID p_mesh,int p_index);
+ virtual int mesh_get_surface_count(RID p_mesh) const;
+
+ virtual AABB mesh_get_aabb(RID p_mesh) const;
+
+ /* MULTIMESH API */
+
+ virtual RID multimesh_create();
+
+ virtual void multimesh_set_instance_count(RID p_multimesh,int p_count);
+ virtual int multimesh_get_instance_count(RID p_multimesh) const;
+
+ virtual void multimesh_set_mesh(RID p_multimesh,RID p_mesh);
+ virtual void multimesh_set_aabb(RID p_multimesh,const AABB& p_aabb);
+ virtual void multimesh_instance_set_transform(RID p_multimesh,int p_index,const Transform& p_transform);
+ virtual void multimesh_instance_set_color(RID p_multimesh,int p_index,const Color& p_color);
+
+ virtual RID multimesh_get_mesh(RID p_multimesh) const;
+ virtual AABB multimesh_get_aabb(RID p_multimesh) const;;
+
+ virtual Transform multimesh_instance_get_transform(RID p_multimesh,int p_index) const;
+ virtual Color multimesh_instance_get_color(RID p_multimesh,int p_index) const;
+
+ /* POLY API */
+
+ virtual RID poly_create();
+ virtual void poly_set_material(RID p_poly, RID p_material,bool p_owned=false);
+ virtual void poly_add_primitive(RID p_poly, const Vector<Vector3>& p_points,const Vector<Vector3>& p_normals,const Vector<Color>& p_colors,const Vector<Vector3>& p_uvs);
+ virtual void poly_clear(RID p_poly);
+
+ virtual AABB poly_get_aabb(RID p_poly) const;
+
+
+ /* PARTICLES API */
+
+ virtual RID particles_create();
+
+ virtual void particles_set_amount(RID p_particles, int p_amount);
+ virtual int particles_get_amount(RID p_particles) const;
+
+ virtual void particles_set_emitting(RID p_particles, bool p_emitting);
+ virtual bool particles_is_emitting(RID p_particles) const;
+
+ virtual void particles_set_visibility_aabb(RID p_particles, const AABB& p_visibility);
+ virtual AABB particles_get_visibility_aabb(RID p_particles) const;
+
+ virtual void particles_set_emission_half_extents(RID p_particles, const Vector3& p_half_extents);
+ virtual Vector3 particles_get_emission_half_extents(RID p_particles) const;
+
+ virtual void particles_set_gravity_normal(RID p_particles, const Vector3& p_normal);
+ virtual Vector3 particles_get_gravity_normal(RID p_particles) const;
+
+ virtual void particles_set_variable(RID p_particles, VS::ParticleVariable p_variable,float p_value);
+ virtual float particles_get_variable(RID p_particles, VS::ParticleVariable p_variable) const;
+
+ virtual void particles_set_randomness(RID p_particles, VS::ParticleVariable p_variable,float p_randomness);
+ virtual float particles_get_randomness(RID p_particles, VS::ParticleVariable p_variable) const;
+
+ virtual void particles_set_color_phase_pos(RID p_particles, int p_phase, float p_pos);
+ virtual float particles_get_color_phase_pos(RID p_particles, int p_phase) const;
+
+ virtual void particles_set_color_phases(RID p_particles, int p_phases);
+ virtual int particles_get_color_phases(RID p_particles) const;
+
+ virtual void particles_set_color_phase_color(RID p_particles, int p_phase, const Color& p_color);
+ virtual Color particles_get_color_phase_color(RID p_particles, int p_phase) const;
+
+ virtual void particles_set_attractors(RID p_particles, int p_attractors);
+ virtual int particles_get_attractors(RID p_particles) const;
+
+ virtual void particles_set_attractor_pos(RID p_particles, int p_attractor, const Vector3& p_pos);
+ virtual Vector3 particles_get_attractor_pos(RID p_particles,int p_attractor) const;
+
+ virtual void particles_set_attractor_strength(RID p_particles, int p_attractor, float p_force);
+ virtual float particles_get_attractor_strength(RID p_particles,int p_attractor) const;
+
+ virtual void particles_set_material(RID p_particles, RID p_material,bool p_owned=false);
+ virtual RID particles_get_material(RID p_particles) const;
+
+ virtual AABB particles_get_aabb(RID p_particles) const;
+ /* BEAM API */
+
+ virtual RID beam_create();
+
+ virtual void beam_set_point_count(RID p_beam, int p_count);
+ virtual int beam_get_point_count(RID p_beam) const;
+ virtual void beam_clear(RID p_beam);
+
+ virtual void beam_set_point(RID p_beam,int p_point,Vector3& p_pos);
+ virtual Vector3 beam_get_point(RID p_beam,int p_point) const;
+
+ virtual void beam_set_primitive(RID p_beam,VS::BeamPrimitive p_primitive);
+ virtual VS::BeamPrimitive beam_get_primitive(RID p_beam) const;
+
+ virtual void beam_set_material(RID p_beam, RID p_material);
+ virtual RID beam_get_material(RID p_beam) const;
+
+ virtual AABB beam_get_aabb(RID p_particles) const;
+ /* SKELETON API */
+
+ virtual RID skeleton_create();
+ virtual void skeleton_resize(RID p_skeleton,int p_bones);
+ virtual int skeleton_get_bone_count(RID p_skeleton) const;
+ virtual void skeleton_bone_set_transform(RID p_skeleton,int p_bone, const Transform& p_transform);
+ virtual Transform skeleton_bone_get_transform(RID p_skeleton,int p_bone);
+
+
+ /* LIGHT API */
+
+ virtual RID light_create(VS::LightType p_type);
+ virtual VS::LightType light_get_type(RID p_light) const;
+
+ virtual void light_set_color(RID p_light,VS::LightColor p_type, const Color& p_color);
+ virtual Color light_get_color(RID p_light,VS::LightColor p_type) const;
+
+ virtual void light_set_shadow(RID p_light,bool p_enabled);
+ virtual bool light_has_shadow(RID p_light) const;
+
+ virtual void light_set_volumetric(RID p_light,bool p_enabled);
+ virtual bool light_is_volumetric(RID p_light) const;
+
+ virtual void light_set_projector(RID p_light,RID p_texture);
+ virtual RID light_get_projector(RID p_light) const;
+
+ virtual void light_set_var(RID p_light, VS::LightParam p_var, float p_value);
+ virtual float light_get_var(RID p_light, VS::LightParam p_var) const;
+
+ virtual AABB light_get_aabb(RID p_poly) const;
+
+
+ virtual RID light_instance_create(RID p_light);
+ virtual void light_instance_set_transform(RID p_light_instance,const Transform& p_transform);
+
+ virtual void light_instance_set_active_hint(RID p_light_instance);
+ virtual bool light_instance_has_shadow(RID p_light_instance) const;
+ virtual bool light_instance_assign_shadow(RID p_light_instance);
+ virtual ShadowType light_instance_get_shadow_type(RID p_light_instance) const;
+ virtual int light_instance_get_shadow_passes(RID p_light_instance) const;
+ virtual void light_instance_set_pssm_split_info(RID p_light_instance, int p_split, float p_near,float p_far, const CameraMatrix& p_camera, const Transform& p_transform);
+
+ /* PARTICLES INSTANCE */
+
+ virtual RID particles_instance_create(RID p_particles);
+ virtual void particles_instance_set_transform(RID p_particles_instance,const Transform& p_transform);
+
+ /* RENDER API */
+ /* all calls (inside begin/end shadow) are always warranted to be in the following order: */
+
+ virtual void begin_frame();
+
+ virtual void set_viewport(const VS::ViewportRect& p_viewport);
+
+ virtual void begin_scene(RID p_fx=RID(),VS::ScenarioDebugMode p_debug=VS::SCENARIO_DEBUG_DISABLED);
+ virtual void begin_shadow_map( RID p_light_instance, int p_shadow_pass );
+
+ virtual void set_camera(const Transform& p_world,const CameraMatrix& p_projection);
+
+ virtual void add_light( RID p_light_instance ); ///< all "add_light" calls happen before add_geometry calls
+
+ typedef Map<StringName,Variant> ParamOverrideMap;
+
+ virtual void add_mesh( RID p_mesh, const Transform* p_world, const RID* p_light_instances, int p_light_count, const ParamOverrideMap* p_material_overrides = NULL, RID p_skeleton=RID());
+ virtual void add_multimesh( RID p_multimesh, const Transform* p_world, const RID* p_light_instances, int p_light_count, const ParamOverrideMap* p_material_overrides = NULL);
+ virtual void add_poly( RID p_poly, const Transform* p_world, const RID* p_light_instances, int p_light_count, const ParamOverrideMap* p_material_overrides = NULL);
+ virtual void add_beam( RID p_beam, const Transform* p_world, const RID* p_light_instances, int p_light_count, const ParamOverrideMap* p_material_overrides = NULL);
+ virtual void add_particles( RID p_particle_instance, const RID* p_light_instances, int p_light_count, const ParamOverrideMap* p_material_overrides = NULL);
+
+ virtual void end_scene();
+ virtual void end_shadow_map();
+
+ virtual void end_frame();
+
+ /* CANVAS API */
+
+ virtual void canvas_begin();
+ virtual void canvas_set_transparency(float p_transparency);
+ virtual void canvas_set_rect(const Rect2& p_rect, bool p_clip);;
+ virtual void canvas_draw_line(const Point2& p_from, const Point2& p_to,const Color& p_color,float p_width);
+ virtual void canvas_draw_rect(const Rect2& p_rect, bool p_region, const Rect2& p_source,bool p_tile,RID p_texture,const Color& p_modulate);
+ virtual void canvas_draw_style_box(const Rect2& p_rect, RID p_texture,const float *p_margins, bool p_draw_center=true);
+ virtual void canvas_draw_primitive(const Vector<Point2>& p_points, const Vector<Color>& p_colors,const Vector<Point2>& p_uvs, RID p_texture);
+
+ /* FX */
+
+ virtual RID fx_create();
+ virtual void fx_get_effects(RID p_fx,List<String> *p_effects) const;
+ virtual void fx_set_active(RID p_fx,const String& p_effect, bool p_active);
+ virtual bool fx_is_active(RID p_fx,const String& p_effect) const;
+ virtual void fx_get_effect_params(RID p_fx,const String& p_effect,List<PropertyInfo> *p_params) const;
+ virtual Variant fx_get_effect_param(RID p_fx,const String& p_effect,const String& p_param) const;
+ virtual void fx_set_effect_param(RID p_fx,const String& p_effect, const String& p_param, const Variant& p_pvalue);
+
+ /*MISC*/
+
+ virtual bool is_texture(const RID& p_rid) const;
+ virtual bool is_material(const RID& p_rid) const;
+ virtual bool is_mesh(const RID& p_rid) const;
+ virtual bool is_multimesh(const RID& p_rid) const;
+ virtual bool is_poly(const RID& p_rid) const;
+ virtual bool is_particles(const RID &p_beam) const;
+ virtual bool is_beam(const RID &p_beam) const;
+
+ virtual bool is_light(const RID& p_rid) const;
+ virtual bool is_light_instance(const RID& p_rid) const;
+ virtual bool is_particles_instance(const RID& p_rid) const;
+ virtual bool is_skeleton(const RID& p_rid) const;
+ virtual bool is_fx(const RID& p_rid) const;
+ virtual bool is_shader(const RID& p_rid) const;
+
+ virtual void free(const RID& p_rid) const;
+
+ virtual void init();
+ virtual void finish();
+
+ virtual int get_render_info(VS::RenderInfo p_info);
+
+ RasterizerIPhone();
+ virtual ~RasterizerIPhone();
+};
+
+#endif
+#endif
diff --git a/platform/iphone/sem_iphone.cpp b/platform/iphone/sem_iphone.cpp
new file mode 100644
index 0000000000..5afaa7b308
--- /dev/null
+++ b/platform/iphone/sem_iphone.cpp
@@ -0,0 +1,115 @@
+/*************************************************************************/
+/* sem_iphone.cpp */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* http://www.godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+#include "sem_iphone.h"
+
+#include <unistd.h>
+#include <fcntl.h>
+
+void cgsem_init(cgsem_t *cgsem)
+{
+ int flags, fd, i;
+
+ pipe(cgsem->pipefd);
+
+ /* Make the pipes FD_CLOEXEC to allow them to close should we call
+ * execv on restart. */
+ for (i = 0; i < 2; i++) {
+ fd = cgsem->pipefd[i];
+ flags = fcntl(fd, F_GETFD, 0);
+ flags |= FD_CLOEXEC;
+ fcntl(fd, F_SETFD, flags);
+ }
+}
+
+void cgsem_post(cgsem_t *cgsem)
+{
+ const char buf = 1;
+
+ write(cgsem->pipefd[1], &buf, 1);
+}
+
+void cgsem_wait(cgsem_t *cgsem)
+{
+ char buf;
+
+ read(cgsem->pipefd[0], &buf, 1);
+}
+
+void cgsem_destroy(cgsem_t *cgsem)
+{
+ close(cgsem->pipefd[1]);
+ close(cgsem->pipefd[0]);
+}
+
+
+#include "os/memory.h"
+#include <errno.h>
+
+
+Error SemaphoreIphone::wait() {
+
+ cgsem_wait(&sem);
+ return OK;
+}
+
+Error SemaphoreIphone::post() {
+
+ cgsem_post(&sem);
+
+ return OK;
+}
+int SemaphoreIphone::get() const {
+
+ return 0;
+}
+
+
+Semaphore *SemaphoreIphone::create_semaphore_iphone() {
+
+ return memnew( SemaphoreIphone );
+}
+
+void SemaphoreIphone::make_default() {
+
+ create_func=create_semaphore_iphone;
+}
+
+SemaphoreIphone::SemaphoreIphone() {
+
+ cgsem_init(&sem);
+}
+
+
+SemaphoreIphone::~SemaphoreIphone() {
+
+ cgsem_destroy(&sem);
+}
+
+
+
diff --git a/platform/iphone/sem_iphone.h b/platform/iphone/sem_iphone.h
new file mode 100644
index 0000000000..7a57b5dd99
--- /dev/null
+++ b/platform/iphone/sem_iphone.h
@@ -0,0 +1,60 @@
+/*************************************************************************/
+/* sem_iphone.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* http://www.godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+#ifndef SEM_IPHONE_H
+#define SEM_IPHONE_H
+
+struct cgsem {
+ int pipefd[2];
+};
+
+typedef struct cgsem cgsem_t;
+
+#include "os/semaphore.h"
+
+class SemaphoreIphone : public Semaphore {
+
+ mutable cgsem_t sem;
+
+ static Semaphore *create_semaphore_iphone();
+
+public:
+
+ virtual Error wait();
+ virtual Error post();
+ virtual int get() const;
+
+ static void make_default();
+ SemaphoreIphone();
+
+ ~SemaphoreIphone();
+
+};
+
+
+#endif
diff --git a/platform/iphone/view_controller.h b/platform/iphone/view_controller.h
new file mode 100644
index 0000000000..ac94d7ed3a
--- /dev/null
+++ b/platform/iphone/view_controller.h
@@ -0,0 +1,40 @@
+/*************************************************************************/
+/* view_controller.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* http://www.godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+#import <UIKit/UIKit.h>
+
+@interface ViewController : UIViewController {
+
+};
+
+- (BOOL)shouldAutorotateToInterfaceOrientation:
+ (UIInterfaceOrientation)p_orientation;
+
+- (void)didReceiveMemoryWarning;
+
+@end
diff --git a/platform/iphone/view_controller.mm b/platform/iphone/view_controller.mm
new file mode 100644
index 0000000000..8af20358b9
--- /dev/null
+++ b/platform/iphone/view_controller.mm
@@ -0,0 +1,107 @@
+/*************************************************************************/
+/* view_controller.mm */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* http://www.godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+#import "view_controller.h"
+
+#include "os_iphone.h"
+
+extern "C" {
+
+int add_path(int p_argc, char** p_args) {
+
+ NSString* str = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"godot_path"];
+ if (!str)
+ return p_argc;
+
+ p_args[p_argc++] = "-path";
+ [str retain]; // memory leak lol (maybe make it static here and delete it in ViewController destructor? @todo
+ p_args[p_argc++] = (char*)[str cString];
+ p_args[p_argc] = NULL;
+
+ return p_argc;
+};
+
+};
+
+@interface ViewController ()
+
+@end
+
+@implementation ViewController
+
+- (void)didReceiveMemoryWarning {
+
+ printf("*********** did receive memory warning!\n");
+};
+
+- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)p_orientation {
+
+ if (/*OSIPhone::get_singleton() == NULL*/TRUE) {
+
+ printf("checking on info.plist\n");
+ NSArray* arr = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"UISupportedInterfaceOrientations"];
+ switch(p_orientation) {
+
+ case UIInterfaceOrientationLandscapeLeft:
+ return [arr indexOfObject:@"UIInterfaceOrientationLandscapeLeft"] != NSNotFound ? YES : NO;
+
+ case UIInterfaceOrientationLandscapeRight:
+ return [arr indexOfObject:@"UIInterfaceOrientationLandscapeRight"] != NSNotFound ? YES : NO;
+
+ case UIInterfaceOrientationPortrait:
+ return [arr indexOfObject:@"UIInterfaceOrientationPortrait"] != NSNotFound ? YES : NO;
+
+ case UIInterfaceOrientationPortraitUpsideDown:
+ return [arr indexOfObject:@"UIInterfaceOrientationPortraitUpsideDown"] != NSNotFound ? YES : NO;
+
+ default:
+ return NO;
+ }
+ };
+
+ uint8_t supported = OSIPhone::get_singleton()->get_orientations();
+ switch(p_orientation) {
+
+ case UIInterfaceOrientationLandscapeLeft:
+ return supported & (1<<OSIPhone::LandscapeLeft) ? YES : NO;
+
+ case UIInterfaceOrientationLandscapeRight:
+ return supported & (1<<OSIPhone::LandscapeRight) ? YES : NO;
+
+ case UIInterfaceOrientationPortrait:
+ return supported & (1<<OSIPhone::PortraitDown) ? YES : NO;
+
+ case UIInterfaceOrientationPortraitUpsideDown:
+ return supported & (1<<OSIPhone::PortraitUp) ? YES : NO;
+
+ default:
+ return NO;
+ }
+};
+
+@end