Commit c6ac35a2 authored by Sam Lantinga's avatar Sam Lantinga

Final merge of Google Summer of Code 2008 work...

Bring SDL to iPhone and iPod Touch
by Holmes Futrell, mentored by Sam Lantinga

--HG--
extra : convert_revision : svn%3Ac70aab31-4412-0410-b14c-859654838e24/trunk%403222
parent 338ff54f
==============================================================================
Building the Simple DirectMedia Layer for iPhone OS 2.0
==============================================================================
Requirements: Mac OS X v10.5 or later and the iPhone SDK.
Instructions:
1. Open SDLiPhoneOS.xcodeproj (located in XCodeiPhoneOS/SDL) in XCode.
2. Set Project->Set Active SDK to "Use Project Settings"
3. Select your desired target, and hit build.
There are three build targets:
- StaticLibiPhoneOS:
Build SDL as a statically linked (armv6) library for iPhone OS 2.0.
- StaticLibSimulator:
Build SDL as a statically linked (x86) library for the iPhone Simulator
- Template:
Package a project template together with the SDL for iPhone static libraries and copies of the SDL headers. The template includes proper references to the SDL library and headers, skeleton code for a basic SDL program, and placeholder graphics for the application icon and startup screen.
==============================================================================
Using the Simple DirectMedia Layer for iPhone OS 2.0
==============================================================================
Here is the easiest method:
1. Build the SDL libraries (libSDLiPhoneOS.a and libSDLSimulator.a) and the iPhone SDL Application template.
1. Install the iPhone SDL Application template by copying it to one of XCode's template directories. I recommend creating a directory called "SDL" in "/Developer/Platforms/iPhoneOS.platform/Developer/Library/XCode/Project Templates/" and placing it there.
2. Start a new project using the template. The project should be immediately ready for use with SDL.
Here is a more manual method:
1. Create a new iPhone view based application.
2. Build the SDL static libraries (libSDLiPhoneOS.a and libSDLSimulator.a) for iPhone and include them in your project. XCode will ignore the library that is not currently of the correct architecture, hence your app will work both on iPhone and in the iPhone Simulator.
3. Include the SDL header files in your project.
4. Remove the ApplicationDelegate.h and ApplicationDelegate.m files -- SDL for iPhone provides its own UIApplicationDelegate. Remove MainWindow.xib -- SDL for iPhone produces its user interface programmatically.
5. Delete the contents of main.m and program your app as a regular SDL program instead. You may replace main.m with your own main.c, but you must tell XCode not to use the project prefix file, as it includes Objective-C code.
==============================================================================
Notes -- Touch Input
==============================================================================
Touch input in SDL for iPhone OS is presently exposed through SDL's mouse input API. Multi-touch input is reported as multiple mice, with each touch associated with a specific mouse. This association stays coherent from the time the touch starts to the time a touch ends.
By default, multi-touch is turned ON. This requires some care, because if you simply respond to mouse events without checking which mouse caused the event, you may end up fetching data from the wrong mouse, ie, from an incorrect or invalid touch. To turn multi-touch OFF, you can recompile SDL for iPhone with the macro SDL_IPHONE_MULTIPLE_MICE (found in SDL_config_iphoneos.h) set to 0.
==============================================================================
Notes -- Accelerometer as Joystick
==============================================================================
SDL for iPhone supports polling the built in accelerometer as a joystick device. For an example on how to do this, see the accelerometer.c in the demos directory.
The main thing to note when using the accelerometer with SDL is that while the iPhone natively reports accelerometer as floating point values in units of g-force, SDL_JoystickGetAxis reports joystick values as signed integers. Hence, in order to convert between the two, some clamping and scaling is necessary on the part of the iPhone SDL joystick driver. To convert SDL_JoystickGetAxis reported values BACK to units of g-force, simply multiply the values by SDL_IPHONE_MAX_GFORCE / 0x7FFF.
==============================================================================
Notes -- OpenGL ES
==============================================================================
Your SDL application for iPhone uses OpenGL ES for video by default.
OpenGL ES for iPhone supports two display pixel formats, RGBA8 and RGB565, which provide a 32 bit and 16 bit color buffer respectively. By default, the implementation uses RGB565, but you may use RGBA8 by setting each color component to 8 bits in SDL_GL_SetAttribute.
If your application doesn't use OpenGL's depth buffer, you may find significant performance improvement by setting SDL_GL_DEPTH_SIZE to 0.
Finally, if your application completely redraws the screen each frame, you may find significant performance improvement by setting the attribute SDL_GL_RETAINED_BACKING to 1.
==============================================================================
Notes -- Keyboard
==============================================================================
SDL for iPhone contains several additional functions related to keyboard visibility. These functions are not part of the SDL standard API, but are necessary for revealing and hiding the iPhone's virtual onscreen keyboard. You can use them in your own applications by including a copy of the SDL_uikitkeyboard.h header (located in src/video/uikit) in your project.
int SDL_iPhoneKeyboardShow(SDL_WindowID windowID)
-- reveals the onscreen keyboard. Returns 0 on success and -1 on error.
int SDL_iPhoneKeyboardHide(SDL_WindowID windowID)
-- hides the onscreen keyboard. Returns 0 on success and -1 on error.
SDL_bool SDL_iPhoneKeyboardIsShown(SDL_WindowID windowID)
-- returns whether or not the onscreen keyboard is currently visible.
int SDL_iPhoneKeyboardToggle(SDL_WindowID windowID)
-- toggles the visibility of the onscreen keyboard. Returns 0 on success and -1 on error.
==============================================================================
Notes -- Reading and Writing files
==============================================================================
Each application installed on iPhone resides in a sandbox which includes its own Application Home directory. Your application may not access files outside this directory.
Once your application is installed its directory tree looks like:
MySDLApp Home/
MySDLApp.app
Documents/
Library/
Preferences/
tmp/
When your SDL based iPhone application starts up, it sets the working directory to the main bundle (MySDLApp Home/MySDLApp.app), where your application resources are stored. You cannot write to this directory. Instead, I advise you to write document files to "../Documents/" and preferences to "../Library/Preferences".
More information on this subject is available here:
http://developer.apple.com/iphone/library/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/ApplicationEnvironment/chapter_6_section_3.html#//apple_ref/doc/uid/TP40007072-CH7-SW21
==============================================================================
Notes -- iPhone SDL limitations
==============================================================================
Windows:
Full-size, single window applications only. You cannot create multi-window SDL applications for iPhone OS. The application window will fill the display, though you have the option of turning on or off the menu-bar (pass SDL_CreateWindow the flag SDL_WINDOW_BORDERLESS). Presently, landscape mode is not supported.
Video:
For real time frame-rates, you are advised to use strictly SDL 1.3 video calls. Using compatibility video calls uploads an OpenGL texture for each frame drawn, and this operation is excruciatingly slow.
Textures:
SDL for iPhone Textures supports only SDL_PIXELFORMAT_ABGR8888 and SDL_PIXELFORMAT_RGB24 pixel formats. This is because texture support in SDL for iPhone is done through OpenGL ES, which supports fewer pixel formats than OpenGL, will not re-order pixel data for you, and has no support for color-paletted formats (without extensions).
Audio:
SDL for iPhone does not yet support audio input.
Loading Shared Objects:
This is disabled by default since it seems to break the terms of the iPhone SDK agreement. It can be re-enabled in SDL_config_iphoneos.h.
XCodeiPhoneOS/Demos/Default.png

18 KB

This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
XCodeiPhoneOS/Demos/Icon.png

2.35 KB

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleDisplayName</key>
<string>${PRODUCT_NAME}</string>
<key>CFBundleExecutable</key>
<string>${EXECUTABLE_NAME}</string>
<key>CFBundleIconFile</key>
<string></string>
<key>CFBundleIdentifier</key>
<string>com.yourcompany.${PRODUCT_NAME:identifier}</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>${PRODUCT_NAME}</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1.0</string>
<key>NSMainNibFile</key>
<string></string>
</dict>
</plist>
==============================================================================
About the iPhone OS Demo Applications
==============================================================================
DemosiPhoneOS.xcodeproj contains several targets for iPhone oriented SDL demos. These demos are written strictly using SDL 1.3 calls. All the demos except for Fireworks (which requires OpenGL ES) should work on platforms other than iPhone OS, though you'll need to write your own compile script. To run them on your favorite platform, you may wish to set the macros SCREEN_WIDTH and SCREEN_HEIGHT, located in common.h.
Common files:
common.c and common.h contain code common to all demo applications. This includes macros about the screen dimensions (in pixels), simple error handling, and functions for generating random numbers.
Rectangles (rectangles.c):
Draws randomly sized and colored rectangles all over the screen by using SDL_RenderFill. This is the simplest of all the demos.
Happy (happy.c):
Loads the classic happy-face bitmap and draws a large number of happy faces bouncing around the screen. Shows how you can load a bitmap into an SDL_Texture.
Accelerometer (accelerometer.c):
Uses the iPhone's accelerometer as a joystick device to move a spaceship around the screen. Note the use of the macro SDL_IPHONE_MAX_GFORCE (normally defined in SDL_config_iphoneos.h) which converts between the Sint16 number returned by SDL_JoystickGetAxis, and the floating point units of g-force reported natively by the iPhone.
Touch (touch.c):
Acts as a finger-paint type program. Demonstrates how you can use SDL mouse input to accept touch input from the iPhone. If SDL for iPhone is compiled with multitouch as multiple mouse emulation (SDL_IPHONE_MULTIPLE_MICE in SDL_config_iphoneos.h) then the program will accept multiple finger inputs simultaneously.
Mixer (mixer.c):
Displays several rectangular buttons which can be used as a virtual drumkit. Demonstrates how you can play .wav sounds in SDL and how you can use SDL_MixAudioFormat to build a software mixer that can play multiple sounds at once.
Keyboard (keyboard.c):
Loads a bitmap font and let's the user type words, numbers, and symbols using the iPhone's virtual keyboard. The iPhone's onscreen keyboard visibility is toggled when the user taps the screen. If the user types ':)' a happy face is displayed. Demonstrates how to use functions added to the iPhone implementation of SDL to toggle keyboard onscreen visibility.
Fireworks (fireworks.c):
Displays a fireworks show. When you tap the iPhone's screen, fireworks fly from the bottom of the screen and explode at the point that you tapped. Demonstrates how you can use SDL on iPhone to build an OpenGL ES based application. Shows you how you can use SDL_LoadBMP to load a bmp image and convert it to an OpenGL ES texture. Of lesser importance, shows how you can use OpenGL ES point sprites to build an efficient particle system.
==============================================================================
Building and Running the demos
==============================================================================
Before building the demos you must first build SDL as a static library for BOTH the iPhone Simulator and the iPhone itself. See the iPhone SDL main README file for directions on how to do this. Once this is done, simply launch XCode, select the target you'd like to build, select the active SDK (simulator or device), and then build and go.
XCodeiPhoneOS/Demos/data/bitmapfont/kromasky_16x16.bmp

44.3 KB

This diff is collapsed.
File added
File added
File added
File added
XCodeiPhoneOS/Demos/data/icon.bmp

578 Bytes

XCodeiPhoneOS/Demos/data/ship.bmp

12.1 KB

XCodeiPhoneOS/Demos/data/space.bmp

450 KB

XCodeiPhoneOS/Demos/data/stroke.bmp

3.05 KB

/*
* accelerometer.c
* written by Holmes Futrell
* use however you want
*/
#include "SDL.h"
#include "math.h"
#include "common.h"
#define MILLESECONDS_PER_FRAME 16 /* about 60 frames per second */
#define DAMPING 0.5f; /* after bouncing off a wall, damping coefficient determines final speed */
#define FRICTION 0.0008f /* coefficient of acceleration that opposes direction of motion */
#define GRAVITY_CONSTANT 0.004f /* how sensitive the ship is to the accelerometer */
/* If we aren't on an iPhone, then this definition ought to yield reasonable behavior */
#ifndef SDL_IPHONE_MAX_GFORCE
#define SDL_IPHONE_MAX_GFORCE 5.0f
#endif
static SDL_Joystick *accelerometer; /* used for controlling the ship */
static struct
{
float x, y; /* position of ship */
float vx, vy; /* velocity of ship (in pixels per millesecond) */
SDL_Rect rect; /* (drawn) position and size of ship */
} ship;
static SDL_TextureID shipID = 0; /* texture for spaceship */
static SDL_TextureID spaceID = 0; /* texture for space (background */
void
render(void)
{
/* get joystick (accelerometer) axis values and normalize them */
float ax = SDL_JoystickGetAxis(accelerometer, 0);
float ay = -SDL_JoystickGetAxis(accelerometer, 1);
/* ship screen constraints */
Uint32 minx = 0.0f;
Uint32 maxx = SCREEN_WIDTH - ship.rect.w;
Uint32 miny = 0.0f;
Uint32 maxy = SCREEN_HEIGHT - ship.rect.h;
#define SINT16_MAX ((float)(0x7FFF))
/* update velocity from accelerometer
the factor SDL_IPHONE_MAX_G_FORCE / SINT16_MAX converts between
SDL's units reported from the joytick, and units of g-force, as reported by the accelerometer
*/
ship.vx +=
ax * SDL_IPHONE_MAX_GFORCE / SINT16_MAX * GRAVITY_CONSTANT *
MILLESECONDS_PER_FRAME;
ship.vy +=
ay * SDL_IPHONE_MAX_GFORCE / SINT16_MAX * GRAVITY_CONSTANT *
MILLESECONDS_PER_FRAME;
float speed = sqrt(ship.vx * ship.vx + ship.vy * ship.vy);
if (speed > 0) {
/* compensate for friction */
float dirx = ship.vx / speed; /* normalized x velocity */
float diry = ship.vy / speed; /* normalized y velocity */
/* update velocity due to friction */
if (speed - FRICTION * MILLESECONDS_PER_FRAME > 0) {
/* apply friction */
ship.vx -= dirx * FRICTION * MILLESECONDS_PER_FRAME;
ship.vy -= diry * FRICTION * MILLESECONDS_PER_FRAME;
} else {
/* applying friction would MORE than stop the ship, so just stop the ship */
ship.vx = 0.0f;
ship.vy = 0.0f;
}
}
/* update ship location */
ship.x += ship.vx * MILLESECONDS_PER_FRAME;
ship.y += ship.vy * MILLESECONDS_PER_FRAME;
if (ship.x > maxx) {
ship.x = maxx;
ship.vx = -ship.vx * DAMPING;
} else if (ship.x < minx) {
ship.x = minx;
ship.vx = -ship.vx * DAMPING;
}
if (ship.y > maxy) {
ship.y = maxy;
ship.vy = -ship.vy * DAMPING;
} else if (ship.y < miny) {
ship.y = miny;
ship.vy = -ship.vy * DAMPING;
}
/* draw the background */
SDL_RenderCopy(spaceID, NULL, NULL);
/* draw the ship */
ship.rect.x = ship.x;
ship.rect.y = ship.y;
SDL_RenderCopy(shipID, NULL, &ship.rect);
/* update screen */
SDL_RenderPresent();
}
void
initializeTextures()
{
SDL_Surface *bmp_surface;
SDL_Surface *bmp_surface_rgba;
int format = SDL_PIXELFORMAT_ABGR8888; /* desired texture format */
Uint32 Rmask, Gmask, Bmask, Amask; /* masks for desired format */
int bpp; /* bits per pixel for desired format */
/* load the ship */
bmp_surface = SDL_LoadBMP("ship.bmp");
if (bmp_surface == NULL) {
fatalError("could not ship.bmp");
}
/* set blue to transparent on the ship */
SDL_SetColorKey(bmp_surface, 1,
SDL_MapRGB(bmp_surface->format, 0, 0, 255));
SDL_PixelFormatEnumToMasks(format, &bpp, &Rmask, &Gmask, &Bmask, &Amask);
/*
create a new RGBA surface and blit the bmp to it
this is an extra step, but it seems to be necessary for the color key to work
does the fact that this is necessary indicate a bug in SDL?
*/
bmp_surface_rgba =
SDL_CreateRGBSurface(0, bmp_surface->w, bmp_surface->h, bpp, Rmask,
Gmask, Bmask, Amask);
SDL_BlitSurface(bmp_surface, NULL, bmp_surface_rgba, NULL);
/* create ship texture from surface */
shipID = SDL_CreateTextureFromSurface(format, bmp_surface_rgba);
if (shipID == 0) {
fatalError("could not create ship texture");
}
SDL_SetTextureBlendMode(shipID, SDL_TEXTUREBLENDMODE_BLEND);
/* set the width and height of the ship from the surface dimensions */
ship.rect.w = bmp_surface->w;
ship.rect.h = bmp_surface->h;
SDL_FreeSurface(bmp_surface_rgba);
SDL_FreeSurface(bmp_surface);
/* load the space background */
bmp_surface = SDL_LoadBMP("space.bmp");
if (bmp_surface == NULL) {
fatalError("could not load space.bmp");
}
/* create space texture from surface */
spaceID = SDL_CreateTextureFromSurface(format, bmp_surface);
if (spaceID == 0) {
fatalError("could not create space texture");
}
SDL_FreeSurface(bmp_surface);
}
int
main(int argc, char *argv[])
{
SDL_WindowID windowID; /* ID of main window */
Uint32 startFrame; /* time frame began to process */
Uint32 endFrame; /* time frame ended processing */
Uint32 delay; /* time to pause waiting to draw next frame */
int done; /* should we clean up and exit? */
/* initialize SDL */
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0) {
fatalError("Could not initialize SDL");
}
/* create main window and renderer */
windowID = SDL_CreateWindow(NULL, 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT,
SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN |
SDL_WINDOW_BORDERLESS);
SDL_CreateRenderer(windowID, 0, 0);
/* print out some info about joysticks and try to open accelerometer for use */
printf("There are %d joysticks available\n", SDL_NumJoysticks());
printf("Default joystick (index 0) is %s\n", SDL_JoystickName(0));
accelerometer = SDL_JoystickOpen(0);
if (accelerometer == NULL) {
fatalError("Could not open joystick (accelerometer)");
}
printf("joystick number of axis = %d\n",
SDL_JoystickNumAxes(accelerometer));
printf("joystick number of hats = %d\n",
SDL_JoystickNumHats(accelerometer));
printf("joystick number of balls = %d\n",
SDL_JoystickNumBalls(accelerometer));
printf("joystick number of buttons = %d\n",
SDL_JoystickNumButtons(accelerometer));
/* load graphics */
initializeTextures();
/* setup ship */
ship.x = (SCREEN_WIDTH - ship.rect.w) / 2;
ship.y = (SCREEN_HEIGHT - ship.rect.h) / 2;
ship.vx = 0.0f;
ship.vy = 0.0f;
done = 0;
/* enter main loop */
while (!done) {
startFrame = SDL_GetTicks();
SDL_Event event;
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT) {
done = 1;
}
}
render();
endFrame = SDL_GetTicks();
/* figure out how much time we have left, and then sleep */
delay = MILLESECONDS_PER_FRAME - (endFrame - startFrame);
if (delay < 0) {
delay = 0;
} else if (delay > MILLESECONDS_PER_FRAME) {
delay = MILLESECONDS_PER_FRAME;
}
SDL_Delay(delay);
}
/* delete textures */
SDL_DestroyTexture(shipID);
SDL_DestroyTexture(spaceID);
/* shutdown SDL */
SDL_Quit();
return 0;
}
/*
* common.c
* written by Holmes Futrell
* use however you want
*/
#include "common.h"
#include "SDL.h"
#include <stdlib.h>
/*
Produces a random int x, min <= x <= max
following a uniform distribution
*/
int
randomInt(int min, int max)
{
return min + rand() % (max - min + 1);
}
/*
Produces a random float x, min <= x <= max
following a uniform distribution
*/
float
randomFloat(float min, float max)
{
return rand() / (float) RAND_MAX *(max - min) + min;
}
void
fatalError(const char *string)
{
printf("%s: %s\n", string, SDL_GetError());
exit(1);
}
/*
* common.h
* written by Holmes Futrell
* use however you want
*/
#define SCREEN_WIDTH 320
#define SCREEN_HEIGHT 480
extern int randomInt(int min, int max);
extern float randomFloat(float min, float max);
extern void fatalError(const char *string);
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
XCodeiPhoneOS/Template/SDL Application/Default.png

18 KB

XCodeiPhoneOS/Template/SDL Application/Icon.png

2.35 KB

This diff is collapsed.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Description</key>
<string>This project builds an SDL based project for iPhone OS using C or Objective-C. It includes everything you need to get up and running with SDL on iPhone.</string>
<key>CFBundleIconFile</key>
<string>Icon.png</string>
</dict>
</plist>
APPL????
\ No newline at end of file
/Users/hfutrell/iPhoneSource/gsoc2008_iphone/XCodeiPhoneOS/SDLiPhoneOS/template/SDLApplicationTemplate/build/___PROJECTNAME___.build/Debug-iphonesimulator/___PROJECTNAME___.build/Objects-normal/i386/main.o
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment