Unreal Engine 3 on iOS devices

Today I got to try Epic Games ‘Epic Citadel’ free app from Apple’s AppStore which demonstrates the capabilities of Unreal Engine 3 and I must say I’m impressed. This is by far the best 3D environment I’ve seen for mobile devices and also a good sign that the games on iOS devices have a bright future. I took several screenshots posted below so you can enjoy the colors.

The engine features [via Epic Games]:

  • Amazing visuals. “Epic Citadel” pushes the envelope for stunning visuals on iOS devices. Through the latest advances in Unreal Engine 3 technology, the application delivers unrivaled graphics and special effects that immerse players in the kingdom’s grounds.
  • Bump offset mapping. Also known as parallax mapping or relief mapping, bump offset mapping enhances the visual appearance of stone walls and rocks providing intricate textures.
  • Normal mapped architecture. Brings stunning detail to bricks and ground surfaces within the environment.
  • Texture blending with painted weight maps. Refines nuances on roads and terrain, making them rich and lifelike.
  • Global illumination. Unreal Engine 3’s built-in global illumination system, Unreal Lightmass, provides realistic lighting and shadows with minimal development resources.
  • Dynamic specular lighting with texture masks. Helps create authentic cobblestone roads and vivid reflective marble surfaces, while lens flares and light coronas add dramatic emphasis when panning across light sources.
  • Real-time reflections and animation. Environment mapping enables real-time reflections on objects such as the statue inside the cathedral. Dynamic movements of trees and banners are made possible through the use of vertex deformation and skeletal animation.
  • Free tools. Epic’s Unreal Development Kit (UDK), available for free download at http://www.udk.com/download, ships with the same tools and technologies used to create Epic Citadel.

iPhone 4: Unboxing & First Impressions

I know it’s a bit late but got my iPhone 4 today and I’ll share my impressions in this post. There are plenty of posts covering iPhone 4 unboxing, reviews, first impressions, hands-on etc.. These are my own impressions and thoughts probably completely random and not so deep but might be useful as it’s a different perspective.

What’s in the box?

Usual stuff inside, a charger with USB cable, headphones, sim tray pin and obviously the shiny iPhone 4 device. I immediately noticed that I didn’t get the cleaning cloth so that was a disappointment. The cleaning cloth wasn’t in the box with iPhone 3GS too but still I kind of hoped…

iPhone 4 box content

iPhone 4 box content

First impression

Retina display wins big time. Period. I was truly amazed with the display quality and I simply don’t believe the difference between iPhone 4 retina display and older models display. I expected to see the improvement with the screen but I didn’t believe it would be as much better as this. You can see the difference in simple text (mail app for example), the fonts are so crisp and clear and smooth. I’m trying to find some ‘amazing’ words to describe this and risk sounding like Steve, but retina display is just – wow! And yes, I should probably mention that the apps not optimized for it don’t look so good.

Speed, speed, speed and even more speed

This tiny beast powered with Apple’s A4 chip provides as much speed as one would want from a small computer let alone a smartphone. Multitasking is smooth, I haven’t seen a single hickup from the device even when I had more than a dozen apps running in background. The only problems I noticed so far were related to some buggy apps (which I won’t name but, FYI, they are popular) which lag and crash but that’s due to the apps not the iPhone.

As a small test I ran 20+ apps at the same time. Some of them had background multitasking, some didn’t but I was still able to access my huge address book and scroll the list without noticing ANY problems.

Camera(s), 5MP photos, HD videos

Camera is something the community complained about since the very first iPhone 2G. Equipped with 2MP camera, both iPhone 2G and 3G had not so good image quality although daylight photos were pretty much satisfactory for my own taste. iPhone 3GS had the same camera but improved with auto and manual focus. Users wanted more and Steve listened, it was a long wait indeed but we got 5MP camera with LED flash on the back and a front facing VGA camera.

Photo quality is now really awesome and finally you can take beautiful photos with descent resolution. Dark environment photos are also cool now with flash on the back. Front facing camera on iPhone 4 is VGA which is 0.4 megapixels which is not so good but I think good enough for a 2nd camera on the device.

Here are a few pics as a demo taken with iPhone 4.

Conclusion

I haven’t mention FaceTime and some other stuff because I haven’t yet tried it – I was so anxious to put my impressions in here. And yes, my biggest impressions are retina display and speed followed by the camera(s) and then everything else. I think this phone has everything I need as opposed to my previous 3G(s) which lacked features in a few critical areas. Should you get the iPhone 4? Yes. If you have the 3GS you might want to give it a little thought first but if you’re still on iPhone 3G like me – than definitely go for it!

iOS 4.1 due September 8th, solves iPhone 3G performance problems

iOS 4.1 was announced last week with promises to fix incredibly slow UI for iPhone 3G amongst other goodies and fixes. The official release is due September 8th 2010 but the developers have access to GM release for a week now. I have an iPhone 3G so I installed this GM right away to see if it fixes the problems for me and it did. At least a bit.

With 4.0 entering text was slow and painful process, also interacting with the most GUI elements sometimes took a second or even more. Installing 4.1 made UI responsive again, I’m actually able to type SMS and emails without so much frustration. Now the thing I’m worried about is that after almost a week of 4.1, I’m starting to notice some lagging. It’s not nearly as much as I used to have with 4.0 but still, the phone doesn’t appear as fast as it was 5 days ago. It’s probably due to a bunch of stuff I sync’ed with it or at least I hope so.

If you’re an iPhone 3G owner with iOS 4.0 you should most definitely upgrade. And not to forget, Lifehacker uploaded this great video of comparison if you still have doubts whether or not you should upgrade.

6 Useful Objective C & Cocoa macros

Here are a few useful cocoa & cocoa touch macros that I’ve come across and thought I share here. Some of those I use regularly and some I just know about but you may find them useful.

Hex (HTML) color to UIColor macro

I found this macro a long time ago somewhere and I’m not sure what’s the original source, yet the Google search returned this blog so I’m going to give him the credit.

#define HEXCOLOR(c) [UIColor colorWithRed:((c>>24)&0xFF)/255.0
                                  green:((c>>16)&0xFF)/255.0
                                     blue:((c>>8)&0xFF)/255.0 \
                                    alpha:((c)&0xFF)/255.0]
//usage
UIColor* color = HEXCOLOR(0xff00ff00);

Enumerating collections macros

The following macro helps you with fast enumeration over collections, credit goes to Wincent.

#define WOEnumerate(collection, object)                                     \
for (id enumerator = [collection objectEnumerator],                         \
     selector = (id)@selector(nextObject),                                  \
     method = (id)[enumerator methodForSelector:(SEL)selector],             \
     object = enumerator ? ((IMP)method)(enumerator, (SEL)selector) : nil;  \
     object != nil;                                                         \
     object = ((IMP)method)(enumerator, (SEL)selector))
 
#define WOKeyEnumerate(collection, object)                                  \
for (id enumerator = [collection keyEnumerator],                            \
     selector = (id)@selector(nextObject),                                  \
     method = (id)[enumerator methodForSelector:(SEL)selector],             \
     object = enumerator ? ((IMP)method)(enumerator, (SEL)selector) : nil;  \
     object != nil;                                                         \
     object = ((IMP)method)(enumerator, (SEL)selector))

Logging macros

CMLog - use to extend NSLog functionality.

#define CMLog(format, ...) NSLog(@"%s:%@", __PRETTY_FUNCTION__,[NSString stringWithFormat:format, ## __VA_ARGS__]);
 
//usage
CMLog(@"My iPhone is an %@, v %@", [[UIDevice currentDevice] model], [[UIDevice currentDevice] systemVersion]);

MARK - method stamp macro, use to output class and method name.

#define MARK	CMLog(@"%s", __PRETTY_FUNCTION__);

Benchmarking macros

Use START_TIMER and END_TIMER to get the timing between these two calls.

#define START_TIMER NSTimeInterval start = [NSDate timeIntervalSinceReferenceDate];
#define END_TIMER(msg) 	NSTimeInterval stop = [NSDate timeIntervalSinceReferenceDate]; CMLog([NSString stringWithFormat:@"%@ Time = %f", msg, stop-start]);
 
//usage example
- (NSData *)loadDataFromURL:(NSString *)dataURL
{
  START_TIMER;
  NSData *data = [self doSomeStuff:dataURL];
  END_TIMER(@"loadDataFromURL");
  return data;
}

Logging and benchmarking macros, courtesy of Stephan Burlot.

UIView frame (CGRect) macros

And for the end, here’s my own modest addition to the list. When developing an iPhone or iPad apps, you probably found yourself lots of times working with UIView frames, changing them etc… Often times I just change the UIView size or I just need to move it around the screen, reposition the view and each time I need to do CGRectMake etc… The following macros have helped me and saved me some typing.

#define width(a) a.frame.size.width
#define height(a) a.frame.size.height
#define top(a) a.frame.origin.y
#define left(a) a.frame.origin.x
#define FrameReposition(a,x,y) a.frame = CGRectMake(x, y, width(a), height(a))
#define FrameResize(a,w,h) a.frame = CGRectMake(left(a), top(a), w, h)

Obviously you can do the same for UIView ‘bounds’ instead of ‘frame’.

Getting started: Windows Phone 7, getting location, reverse geocoding & weather

Having signed up for Microsoft’s Windows Phone 7 developer program and awaiting for Phone 7 launch this fall, I’m actually pretty much late with the development of 5 apps I need to have ready yesterday. This afternoon was perfect for giving myself a crash course of Microsoft Windows Phone 7 app development. I have to mention that I didn’t have a clue about Phone 7 except that I knew it’s XAML and C# .NET so I wanted to try a simple Hello World application but soon realized it’s way to simple for that so I went just a bit further.

I ended up creating an app which uses Phone 7 geo-location services to obtain GPS position, I used Bing’s geo location services to do reverse geocoding and get the ZIP code of the device’s current location and finally I used a public SOAP weather web service to get current weather conditions and display them. Besides a short guide in this blog I also attached the complete Visual Studio 2010 solution and source code, you can find it at the end of this post.

Installing Windows Phone 7 tools

I already had Visual Studio 2010 along with other tools installed on my box so I just headed to msdn and downloaded the Phone 7 tools. To make sure everything was OK, opened up VS and created a Windows Phone 7 application.

Visual Studio New Windows Phone 7 application dialog

Create Windows Phone 7 app

My first Windows Phone 7 application (a.k.a. Hello World)

After creating a new WP7 app project you get something like this on your screen.

Windows Phone 7 Visual Studio project

Windows Phone 7 Visual Studio project

So far so good, I see a familiar XAML UI interface designer and XAML code editor. I changed the label to “Weather” and started Windows Phone 7 emulator for the first time. It took a while before it loaded up but eventually I got this:

Hello World WP7

Hello World, Windows Phone 7

Getting geo location on Phone 7

Geolocation API (dll) was not referenced in WP7 app project by default so I needed to add the reference manually. The DLL file I was looking for was System.Device.dll.

Add reference to System.Device.dll

Add reference to System.Device.dll for location services

Now creating location aware app is pretty easy and it’s just instancing GeoCoordinateWatcher and assigning a callback for its event PositionChanged.

GeoCoordinateWatcher watcher = null;
watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.Default);
			watcher.PositionChanged += new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(watcher_PositionChanged);
			watcher.Start();

Callback is triggered once the application gets location coordinates and its EventArgs hold the result we need. I just need current location and I don’t want to be notified when the position changes so that’s why I’m stopping location acquiring the moment I first get it.

void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)

{
//stop & clean up, we don’t need it anymore
watcher.Stop();
watcher.Dispose();
watcher = null;

location = e.Position.Location;
}

Pretty easy. Now that I have the GPS coordinates, I want to use reverse geocoding to get the information of my whereabouts that actually make sense for humans (not that GPS latitude and longitude don’t).

Reverse geocoding using Bing geo location services

First thing I needed is Bing maps API key in order to be able to query its SOAP web service. You get one (for free) at https://www.bingmapsportal.com/. Now we add a web (service) reference to the Bing geo location WCF service. I called it BingMaps and I only used GeoLocation service.

ReverseGeocodeRequest reverseGeocodeRequest = new ReverseGeocodeRequest();

// Set the credentials using a valid Bing Maps key
reverseGeocodeRequest.Credentials = new BingMaps.Credentials();

reverseGeocodeRequest.Credentials.ApplicationId = "ENTER YOUR BING MAPS KEY HERE";

// Set the point to use to find a matching address

BingMaps.Location point = new BingMaps.Location();
point.Latitude = location.Latitude;
point.Longitude = location.Longitude;

reverseGeocodeRequest.Location = point;

// Make the reverse geocode request
GeocodeServiceClient geocodeService = new GeocodeServiceClient("BasicHttpBinding_IGeocodeService");

geocodeService.ReverseGeocodeCompleted += new EventHandler<ReverseGeocodeCompletedEventArgs>(geocodeService_ReverseGeocodeCompleted);

geocodeService.ReverseGeocodeAsync(reverseGeocodeRequest);

Once Bing finishes with reverse geocoding, geocodeService_ReverseGeocodeCompleted callback is triggered with the results in EventArgs. So now I got my address, town, country, ZIP code etc… I was shooting for ZIP code cause that’s what the weather service wants as an argument.

Getting weather conditions for current location

I used a public free weather SOAP web service found here. It does current weather as well as weather forecast but for the sake of this example I just wanted and used current weather method. After adding web reference to this weather service WSDL, the code was rather simple.

private void GetWeather()

{
WeatherWsc.WeatherSoapClient wsc = new WeatherWsc.WeatherSoapClient();
wsc.GetCityWeatherByZIPCompleted += new EventHandler<WeatherWsc.GetCityWeatherByZIPCompletedEventArgs>(wsc_GetCityWeatherByZIPCompleted);

wsc.GetCityWeatherByZIPAsync(zip);
}

void wsc_GetCityWeatherByZIPCompleted(object sender, WeatherWsc.GetCityWeatherByZIPCompletedEventArgs e)

{
txtStatus.Text = "Finished";
prgProgress.IsEnabled = false;
prgProgress.Visibility = System.Windows.Visibility.Collapsed;

txtLoc.Text = e.Result.City;
txtTemp.Text = e.Result.Temperature + "F";
txtRest.Text = string.Format("Pressure: {0}{1}{2}", e.Result.Pressure, System.Environment.NewLine, e.Result.Description);

}

Putting it all together: an example location aware weather Windows Phone 7 app

Surprisingly enough this was pretty easy task for me even if I didn’t know anything about Phone 7 programming. Yes, I am proficient in C# .NET development but still, I also code Java and Android apps don’t look so simple to me. It took only 30 mins to do this. So kudos to Microsoft from an Apple fanboy!

Demo WP7 app progress

Demo WP7 weather app progress

WP7 Weather app

WP7 Weather app

Pretty nice, huh? Complete Visual Studio 2010 source code is available for Hello Windows Phone 7. You can use this example however you want but please note that I don’t provide any guarantees for this code nor I’m responsible for what you do with it in any way. And you are also encouraged to check it for bugs and add exception handling which has been totally omitted for the sake of demonstration.

Handling layout on UIInterfaceOrientation change

In iOS version >= 3.0, it’s very simple to support interface orientation changes and layout your GUI elements accordingly. Support for landscape and portrait mode are very important for user experience and I think even essential on iPad. In this short text, we’ll cover several UIViewController instance methods that help dealing with UIInterfaceOrientation on iOS devices.

As an example, we can use the YouTube app that comes installed with iOS operating system. This great app shows how simple GUI provides perfect user experience in both landscape and portrait mode. Rotating your iPad makes it remove not needed GUI elements, at the same time unclutter the screen and resize visible controls to fit new layout.

YouTube iPad app

YouTube iPad app

In order to support a certain interface orientation, first you need to override the following method:

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
	//we want to support all orientations
    return YES;
}

Now that you enabled the interface rotation, you would want to implement the methods that inform you when the rotation (and rotation animation) starts and finishes. Those are:

  • willRotateToInterfaceOrientation:duration:
  • willAnimateRotationToInterfaceOrientation:duration:
  • didRotateFromInterfaceOrientation:

Simple enough – willRotateToInterfaceOrientation will be called just before the the device layout rotates, willAnimateRotationToInterfaceOrientation gets called inside animation block just before the animation of the rotation starts and finally didRotateFromInterfaceOrientation gets called once everything is finished and the rotation ended.

With these descriptions alone it’s easy to understand that your logic would be to:

  • Create views/controllers inside willRotateToInterfaceOrientation and add them to the layout
  • Modify view’s attributes (position, size etc…) inside willAnimateRotationToInterfaceOrientation
  • Clean up & remove not needed views inside didRotateFromInterfaceOrientation

Important thing to mention is that willAnimateRotationToInterfaceOrientation method is called inside an animation block so every animatable properties of your views you modify inside this method will be automatically animated. This is very neat, for example, if you just need to reposition and resize your views. You would just change pass desired CGRect as view’s frame and the change would be automatically animated for you when the device changes it’s orientation. to either portrait or landscape.

 - (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
	if (UIInterfaceOrientationIsLandscape(interfaceOrientation)) {
		previewLayout.frame = CGRectMake(695, 13, previewLayout.frame.size.width, previewLayout.frame.size.height);
	} else {
		previewLayout.frame = CGRectMake(413, 575, previewLayout.frame.size.width, previewLayout.frame.size.height);
	}
}

This example demonstrates view reposition only and as you can see the coordinates are hardcoded. I also used a macro UIInterfaceOrientationIsLandscape() which totally simplifies how you determine whether the interface orientation is portrait or landscape.

Besides mentioned methods for responding to view rotation events, there are another 3 that I’m just going to mention now and possibly cover in a future post. Basically they are triggered during animation and inform you about the first half of animation start/finish and the second half animation start. They are also called during animation block just like willAnimateRotationToInterfaceOrientation.

  • willAnimateFirstHalfOfRotationToInterfaceOrientation:duration:
  • didAnimateFirstHalfOfRotationToInterfaceOrientation:
  • willAnimateSecondHalfOfRotationFromInterfaceOrientation:duration:

Check out the Apple’s developer docs for more info.

To sum up – by responding to view rotation events using above mentioned methods, you can create rich user experience and make you app accessible in all orientations. Transitions from one orientation to another can also be enriched with nice animations in few lines of code so make sure you take advantage of that.

Apple Rejects an app: a method name collides with Apple’s private API

Few days ago I got an interesting app rejection email from Apple. Apparently, their ‘grep’ method for checking my app against the use of undocumented API’s is working just fine as it found that I use one. Actually I don’t but they think I do because I named one of my methods the same as one of their private API’s. To quote the email:

The non-public API that is included in your application is httpMethod.

If you have defined a method in your source code with the same name as the above mentioned API, we suggest altering your method name so that it no longer collides with Apple’s private API to avoid your application being flagged with future submissions.

So apparently you have to be very careful when selecting a method name in your code as it can turn out to be already used by Apple. If only they would provide a list of these methods so we don’t make these mistakes again ::evil::

I had 2 options – one was to resubmit the same binary and email Apple’s review team explaining the situation or refactor my code and resubmit a new binary and I decided to go with the latter. I’m just not sure I’ll be able to get the review team to their senses and I can’t risk another 2 weeks of review. I’ll update the post when I hear from them again.

Showing network activity indicator in status bar

Showing network activity indicator in iOS device’s status bar is fairly simple job and can be done in 1 line of code. However, I’ve seen lots of apps with bugs in this area and moreover I see them every day. Reason for this is because few people actually pays attention to coordinate network activity indicator showing and hiding. Let’s see how do you show and hide the indicator.

	UIApplication* app = [UIApplication sharedApplication];
 
	//to show it, set it to YES
	app.networkActivityIndicatorVisible = YES;
 
	...
 
	//to hide it, set it to NO
	app.networkActivityIndicatorVisible = NO;
iPhone Status Bar

iPhone Status Bar w/ network activity indicator on

So, just this 1 line to either show or hide it. It’s that simple. But the problems may show up if you have multiple requests that release the indicator at different times so you get yourself a race condition. This problem can surely be fixed by using some of the concurrency techniques but I use a simpler method which includes request/release counter and updates the indicator accordingly.

First you need to find a suitable place for sending requests/releases to. I use app delegate as it’s singleton and can be accessed from any class but you can decide to use something else. You declare one integer ivar e.g. netActivityReqs and assign a property to it (optional). Now all you need is just these two methods and you’re done.

-(void) requestNetworkActivityIndicator {
	UIApplication* app = [UIApplication sharedApplication];
	app.networkActivityIndicatorVisible = YES;
 
	self.netActivityReqs++;
}
 
-(void) releaseNetworkActivityIndicator {
 
	self.netActivityReqs--;
	if(self.netActivityReqs &lt;= 0)
	{
		UIApplication* app = [UIApplication sharedApplication];
		app.networkActivityIndicatorVisible = NO;
	}
 
	//failsafe
	if(self.netActivityReqs &lt; 0)
		self.netActivityReqs = 0;
}

As you can see it’s extremely simple and straight-forward, you just need to pay attention to these details that may hurt user experience. You still, however, need to be careful to match your request and release calls as this idea only helps with preventing race conditions from multiple activity request calls but it can’t even your calls so you might end up with activity indicator spinning forever if you’re not careful.

iTunesConnect new Payments and Financial reports module

Apple rolled out revamped Payments and Financial reports module today. The interface looks much prettier, there are few major changes and some of them are great. I especially love how they changed monthly payment from multiple stores to a single payment. It saves a lot of trouble. Officially, Apple says:

  • A consolidated single monthly payment for all your proceeds worldwide, reducing bank fees and costs*.
  • Clearer presentation of amounts earned, amounts owed, and a reconciliation between the reported sales and the amounts paid.
  • A Dashboard view of financial information including last payment, amount owed, and latest monthly earnings.
  • Rolling transaction history showing the cumulative balance of amounts earned, taxes, and payments by reporting currency.
  • Graphical views of unit sales and payment trends.
  • Consistent scheduling and timing of reports and payments each month.
  • Improved messaging if your bank returns payments we’ve issued.

*This assumes you have a single bank account setup for all payments worldwide.

Surprisingly enough, most of data is missing on my account from “Owed” and “Payments” tabs and those 2 tabs I was most interested in :)

Additionally, I love this:

In addition, we’ve reduced the thresholds required for you to be paid, increasing the likelihood you’ll receive proceeds each month.

Check it out, maybe you can find out how much exactly Apple owes you from all those stores worldwide ;)