Esempio n. 1
0
/*
 * given a controller button name and a joystick name update our mapping structure with it
 */
void SDL_PrivateGameControllerParseButton(const char *szGameButton, const char *szJoystickButton, struct _SDL_ControllerMapping *pMapping)
{
    int iSDLButton = 0;
    SDL_GameControllerButton button;
    SDL_GameControllerAxis axis;
    button = SDL_GameControllerGetButtonFromString(szGameButton);
    axis = SDL_GameControllerGetAxisFromString(szGameButton);
    iSDLButton = SDL_atoi(&szJoystickButton[1]);

    if (szJoystickButton[0] == 'a') {
        if (iSDLButton >= k_nMaxReverseEntries) {
            SDL_SetError("Axis index too large: %d", iSDLButton);
            return;
        }
        if (axis != SDL_CONTROLLER_AXIS_INVALID) {
            pMapping->axes[ axis ] = iSDLButton;
            pMapping->raxes[ iSDLButton ] = axis;
        } else if (button != SDL_CONTROLLER_BUTTON_INVALID) {
            pMapping->axesasbutton[ button ] = iSDLButton;
            pMapping->raxesasbutton[ iSDLButton ] = button;
        } else {
            SDL_assert(!"How did we get here?");
        }

    } else if (szJoystickButton[0] == 'b') {
        if (iSDLButton >= k_nMaxReverseEntries) {
            SDL_SetError("Button index too large: %d", iSDLButton);
            return;
        }
        if (button != SDL_CONTROLLER_BUTTON_INVALID) {
            pMapping->buttons[ button ] = iSDLButton;
            pMapping->rbuttons[ iSDLButton ] = button;
        } else if (axis != SDL_CONTROLLER_AXIS_INVALID) {
            pMapping->buttonasaxis[ axis ] = iSDLButton;
            pMapping->rbuttonasaxis[ iSDLButton ] = axis;
        } else {
            SDL_assert(!"How did we get here?");
        }
    } else if (szJoystickButton[0] == 'h') {
        int hat = SDL_atoi(&szJoystickButton[1]);
        int mask = SDL_atoi(&szJoystickButton[3]);
        if (hat >= 4) {
            SDL_SetError("Hat index too large: %d", iSDLButton);
        }

        if (button != SDL_CONTROLLER_BUTTON_INVALID) {
            int ridx;
            pMapping->hatasbutton[ button ].hat = hat;
            pMapping->hatasbutton[ button ].mask = mask;
            ridx = (hat << 4) | mask;
            pMapping->rhatasbutton[ ridx ] = button;
        } else if (axis != SDL_CONTROLLER_AXIS_INVALID) {
            SDL_assert(!"Support hat as axis");
        } else {
            SDL_assert(!"How did we get here?");
        }
    }
}
Esempio n. 2
0
static SDL_AudioDevice *DISKAUD_CreateDevice(int devindex)
{
	SDL_AudioDevice *this;
	const char *envr;

	/* Initialize all variables that we clean on shutdown */
	this = (SDL_AudioDevice *)SDL_malloc(sizeof(SDL_AudioDevice));
	if ( this ) {
		SDL_memset(this, 0, (sizeof *this));
		this->hidden = (struct SDL_PrivateAudioData *)
				SDL_malloc((sizeof *this->hidden));
	}
	if ( (this == NULL) || (this->hidden == NULL) ) {
		SDL_OutOfMemory();
		if ( this ) {
			SDL_free(this);
		}
		return(0);
	}
	SDL_memset(this->hidden, 0, (sizeof *this->hidden));

	envr = SDL_getenv(DISKENVR_WRITEDELAY);
	this->hidden->write_delay = (envr) ? SDL_atoi(envr) : DISKDEFAULT_WRITEDELAY;

	/* Set the function pointers */
	this->OpenAudio = DISKAUD_OpenAudio;
	this->WaitAudio = DISKAUD_WaitAudio;
	this->PlayAudio = DISKAUD_PlayAudio;
	this->GetAudioBuf = DISKAUD_GetAudioBuf;
	this->CloseAudio = DISKAUD_CloseAudio;

	this->free = DISKAUD_DeleteDevice;

	return this;
}
Esempio n. 3
0
SDL_Overlay *SDL_CreateYUVOverlay(int w, int h, Uint32 format,
                                  SDL_Surface *display)
{
	SDL_VideoDevice *video = current_video;
	SDL_VideoDevice *this  = current_video;
	const char *yuv_hwaccel;
	SDL_Overlay *overlay;

	if ( (display->flags & SDL_OPENGL) == SDL_OPENGL ) {
		SDL_SetError("YUV overlays are not supported in OpenGL mode");
		return NULL;
	}

	/* Display directly on video surface, if possible */
	if ( SDL_getenv("SDL_VIDEO_YUV_DIRECT") ) {
		if ( (display == SDL_PublicSurface) &&
		     ((SDL_VideoSurface->format->BytesPerPixel == 2) ||
		      (SDL_VideoSurface->format->BytesPerPixel == 4)) ) {
			display = SDL_VideoSurface;
		}
	}
	overlay = NULL;
        yuv_hwaccel = SDL_getenv("SDL_VIDEO_YUV_HWACCEL");
	if ( ((display == SDL_VideoSurface) && video->CreateYUVOverlay) &&
	     (!yuv_hwaccel || (SDL_atoi(yuv_hwaccel) > 0)) ) {
		overlay = video->CreateYUVOverlay(this, w, h, format, display);
	}
	/* If hardware YUV overlay failed ... */
	if ( overlay == NULL ) {
		overlay = SDL_CreateYUV_SW(this, w, h, format, display);
	}
	return overlay;
}
Esempio n. 4
0
static int GetVideoDisplay()
{
	const char *variable = SDL_getenv("SDL_VIDEO_FULLSCREEN_DISPLAY");
	if (!variable)
		variable = SDL_getenv("SDL_VIDEO_FULLSCREEN_HEAD");

	if (variable)
		return SDL_atoi(variable);
	else
		return 0;
}
Esempio n. 5
0
static void SDLCALL
SDL_MouseDoubleClickRadiusChanged(void *userdata, const char *name, const char *oldValue, const char *hint)
{
    SDL_Mouse *mouse = (SDL_Mouse *)userdata;

    if (hint && *hint) {
        mouse->double_click_radius = SDL_atoi(hint);
    } else {
        mouse->double_click_radius = 32;    /* 32 pixels seems about right for touch interfaces */
    }
}
static void
SelectVideoDisplay()
{
    const char *variable = SDL_getenv("SDL_VIDEO_FULLSCREEN_DISPLAY");
    if ( !variable ) {
        variable = SDL_getenv("SDL_VIDEO_FULLSCREEN_HEAD");
    }
    if ( variable ) {
        SDL_SelectVideoDisplay(SDL_atoi(variable));
    }
}
Esempio n. 7
0
int
SDL_XINPUT_JoystickInit(void)
{
    const char *env = SDL_GetHint(SDL_HINT_XINPUT_ENABLED);
    if (env && !SDL_atoi(env)) {
        s_bXInputEnabled = SDL_FALSE;
    }

    if (s_bXInputEnabled && WIN_LoadXInputDLL() < 0) {
        s_bXInputEnabled = SDL_FALSE;  /* oh well. */
    }
    return 0;
}
Esempio n. 8
0
static void SDLCALL
SDL_MouseDoubleClickTimeChanged(void *userdata, const char *name, const char *oldValue, const char *hint)
{
    SDL_Mouse *mouse = (SDL_Mouse *)userdata;

    if (hint && *hint) {
        mouse->double_click_time = SDL_atoi(hint);
    } else {
#ifdef __WIN32__
        mouse->double_click_time = GetDoubleClickTime();
#else
        mouse->double_click_time = 500;
#endif
    }
}
Esempio n. 9
0
int
SDL_SYS_JoystickInit(void)
{
    const char *hint;
    SDL_SYS_JoystickDetect();
    
    hint = SDL_GetHint(SDL_HINT_ACCELEROMETER_AS_JOYSTICK);
    if (!hint || SDL_atoi(hint)) {
        /* Default behavior, accelerometer as joystick */
        Android_AddJoystick(ANDROID_ACCELEROMETER_DEVICE_ID, ANDROID_ACCELEROMETER_NAME, SDL_TRUE, 0, 3, 0, 0);
    }
   
    return (numjoysticks);

}
Esempio n. 10
0
static void
SDL_TimerResolutionChanged(void *userdata, const char *name, const char *oldValue, const char *hint)
{
    UINT uPeriod;

    /* Unless the hint says otherwise, let's have good sleep precision */
    if (hint && *hint) {
        uPeriod = SDL_atoi(hint);
    } else {
        uPeriod = 1;
    }
    if (uPeriod || oldValue != hint) {
        timeSetPeriod(uPeriod);
    }
}
Esempio n. 11
0
int
SDL_XINPUT_HapticInit(void)
{
    const char *env = SDL_GetHint(SDL_HINT_XINPUT_ENABLED);
    if (!env || SDL_atoi(env)) {
        loaded_xinput = (WIN_LoadXInputDLL() == 0);
    }

    if (loaded_xinput) {
        DWORD i;
        for (i = 0; i < XUSER_MAX_COUNT; i++) {
            SDL_XINPUT_MaybeAddDevice(i);
        }
    }
    return 0;
}
Esempio n. 12
0
void initSDL()
{
    SDL_DisplayMode mode;
    int init_flags = SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER | SDL_INIT_JOYSTICK;
    const char *var = SDL_getenv("SDL_VIDEO_FULLSCREEN_DISPLAY");
    int vm;


#ifdef CUSTOM_SIGNAL_HANDLER
    init_flags |= SDL_INIT_NOPARACHUTE;
#endif

    if(SDL_Init(init_flags) < 0)
    {
        printf("SDL Failed to Init!!!! (%s)\n", SDL_GetError());
        borExit(0);
    }
    SDL_ShowCursor(SDL_DISABLE);
    atexit(SDL_Quit);

    if ( !var )
    {
        var = SDL_getenv("SDL_VIDEO_FULLSCREEN_HEAD");
    }
    if ( var )
    {
        vm = SDL_atoi(var);
    }
    else
    {
        vm = 0;
    }

    // Store the monitor's current resolution before setting the video mode for the first time
    if(SDL_GetDesktopDisplayMode(vm, &mode) == 0)
    {
        nativeWidth = mode.w;
        nativeHeight = mode.h;
    }
    else
    {
        nativeWidth = 640;
        nativeHeight = 480;
    }

    savedata.fullscreen = 1;
}
Esempio n. 13
0
/*
 * Sets the global gain of the device.
 */
int
SDL_HapticSetGain(SDL_Haptic * haptic, int gain)
{
    const char *env;
    int real_gain, max_gain;

    if (!ValidHaptic(haptic)) {
        return -1;
    }

    if ((haptic->supported & SDL_HAPTIC_GAIN) == 0) {
        SDL_SetError("Haptic: Device does not support setting gain.");
        return -1;
    }

    if ((gain < 0) || (gain > 100)) {
        SDL_SetError("Haptic: Gain must be between 0 and 100.");
        return -1;
    }

    /* We use the envvar to get the maximum gain. */
    env = SDL_getenv("SDL_HAPTIC_GAIN_MAX");
    if (env != NULL) {
        max_gain = SDL_atoi(env);

        /* Check for sanity. */
        if (max_gain < 0)
            max_gain = 0;
        else if (max_gain > 100)
            max_gain = 100;

        /* We'll scale it linearly with SDL_HAPTIC_GAIN_MAX */
        real_gain = (gain * max_gain) / 100;
    } else {
        real_gain = gain;
    }

    if (SDL_SYS_HapticSetGain(haptic, real_gain) < 0) {
        return -1;
    }

    return 0;
}
Esempio n. 14
0
int
SDL_SYS_CreateThread(SDL_Thread * thread, void *args)
{
    pthread_attr_t type;
    size_t ss;
    const char *hint = SDL_GetHint(SDL_HINT_THREAD_STACK_SIZE);

    /* do this here before any threads exist, so there's no race condition. */
    #if defined(__MACOSX__) || defined(__IPHONEOS__) || defined(__LINUX__)
    if (!checked_setname) {
        void *fn = dlsym(RTLD_DEFAULT, "pthread_setname_np");
        #if defined(__MACOSX__) || defined(__IPHONEOS__)
        ppthread_setname_np = (int(*)(const char*)) fn;
        #elif defined(__LINUX__)
        ppthread_setname_np = (int(*)(pthread_t, const char*)) fn;
        #endif
        checked_setname = SDL_TRUE;
    }
    #endif

    /* Set the thread attributes */
    if (pthread_attr_init(&type) != 0) {
        return SDL_SetError("Couldn't initialize pthread attributes");
    }
    pthread_attr_setdetachstate(&type, PTHREAD_CREATE_JOINABLE);
    
    /* If the SDL_HINT_THREAD_STACK_SIZE exists and it seems to be a positive number, use it */
    if (hint && hint[0] >= '0' && hint[0] <= '9') {
        const size_t stacksize = (size_t) SDL_atoi(hint);
        if (stacksize > 0) {
            pthread_attr_setstacksize(&type, stacksize);
        }
    }
    
    pthread_attr_getstacksize(&type, &ss);

    /* Create the thread and go! */
    if (pthread_create(&thread->handle, &type, RunThread, args) != 0) {
        return SDL_SetError("Not enough resources to create thread");
    }

    return 0;
}
Esempio n. 15
0
static int
DISKAUD_OpenDevice(_THIS, const char *devname, int iscapture)
{
    const char *envr = SDL_getenv(DISKENVR_WRITEDELAY);
    const char *fname = DISKAUD_GetOutputFilename(devname);

    this->hidden = (struct SDL_PrivateAudioData *)
        SDL_malloc(sizeof(*this->hidden));
    if (this->hidden == NULL) {
        SDL_OutOfMemory();
        return 0;
    }
    SDL_memset(this->hidden, 0, sizeof(*this->hidden));

    /* Open the audio device */
    this->hidden->output = SDL_RWFromFile(fname, "wb");
    if (this->hidden->output == NULL) {
        DISKAUD_CloseDevice(this);
        return 0;
    }

    /* Allocate mixing buffer */
    this->hidden->mixbuf = (Uint8 *) SDL_AllocAudioMem(this->hidden->mixlen);
    if (this->hidden->mixbuf == NULL) {
        DISKAUD_CloseDevice(this);
        return 0;
    }
    SDL_memset(this->hidden->mixbuf, this->spec.silence, this->spec.size);

    this->hidden->mixlen = this->spec.size;
    this->hidden->write_delay =
        (envr) ? SDL_atoi(envr) : DISKDEFAULT_WRITEDELAY;

#if HAVE_STDIO_H
    fprintf(stderr,
            "WARNING: You are using the SDL disk writer audio driver!\n"
            " Writing to file [%s].\n", fname);
#endif

    /* We're ready to rock and roll. :-) */
    return 1;
}
Esempio n. 16
0
static void
SetupScreenSaver(int flags)
{
    const char *env;
    SDL_bool allow_screensaver;

    /* Allow environment override of screensaver disable */
    env = SDL_getenv("SDL_VIDEO_ALLOW_SCREENSAVER");
    if (env) {
        allow_screensaver = SDL_atoi(env) ? SDL_TRUE : SDL_FALSE;
    } else if (flags & SDL_FULLSCREEN) {
        allow_screensaver = SDL_FALSE;
    } else {
        allow_screensaver = SDL_TRUE;
    }
    if (allow_screensaver) {
        SDL_EnableScreenSaver();
    } else {
        SDL_DisableScreenSaver();
    }
}
Esempio n. 17
0
/**
 * @brief The entry point of this force feedback demo.
 * @param[in] argc Number of arguments.
 * @param[in] argv Array of argc arguments.
 */
int
main(int argc, char **argv)
{
    int i;
    char *name;
    int index;

    /* Enable standard application logging */
    SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);

    name = NULL;
    index = -1;
    if (argc > 1) {
        size_t l;
        name = argv[1];
        if ((strcmp(name, "--help") == 0) || (strcmp(name, "-h") == 0)) {
            SDL_Log("USAGE: %s [device]\n"
                   "If device is a two-digit number it'll use it as an index, otherwise\n"
                   "it'll use it as if it were part of the device's name.\n",
                   argv[0]);
            return 0;
        }

        l = SDL_strlen(name);
        if ((l < 3) && SDL_isdigit(name[0]) && ((l == 1) || SDL_isdigit(name[1]))) {
            index = SDL_atoi(name);
            name = NULL;
        }
    }

    /* Initialize the force feedbackness */
    SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_JOYSTICK |
             SDL_INIT_HAPTIC);
    SDL_Log("%d Haptic devices detected.\n", SDL_NumHaptics());
    if (SDL_NumHaptics() > 0) {
        /* We'll just use index or the first force feedback device found */
        if (name == NULL) {
            i = (index != -1) ? index : 0;
        }
        /* Try to find matching device */
        else {
            for (i = 0; i < SDL_NumHaptics(); i++) {
                if (strstr(SDL_HapticName(i), name) != NULL)
                    break;
            }

            if (i >= SDL_NumHaptics()) {
                SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Unable to find device matching '%s', aborting.\n",
                       name);
                return 1;
            }
        }

        haptic = SDL_HapticOpen(i);
        if (haptic == NULL) {
            SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Unable to create the haptic device: %s\n",
                   SDL_GetError());
            return 1;
        }
        SDL_Log("Device: %s\n", SDL_HapticName(i));
    } else {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "No Haptic devices found!\n");
        return 1;
    }

    /* We only want force feedback errors. */
    SDL_ClearError();

    if (SDL_HapticRumbleSupported(haptic) == SDL_FALSE) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Rumble not supported!\n");
        return 1;
    }
    if (SDL_HapticRumbleInit(haptic) != 0) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to initialize rumble: %s\n", SDL_GetError());
        return 1;
    }
    SDL_Log("Playing 2 second rumble at 0.5 magnitude.\n");
    if (SDL_HapticRumblePlay(haptic, 0.5, 5000) != 0) {
       SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to play rumble: %s\n", SDL_GetError() );
       return 1;
    }
    SDL_Delay(2000);
    SDL_Log("Stopping rumble.\n");
    SDL_HapticRumbleStop(haptic);
    SDL_Delay(2000);
    SDL_Log("Playing 2 second rumble at 0.3 magnitude.\n");
    if (SDL_HapticRumblePlay(haptic, 0.3f, 5000) != 0) {
       SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to play rumble: %s\n", SDL_GetError() );
       return 1;
    }
    SDL_Delay(2000);

    /* Quit */
    if (haptic != NULL)
        SDL_HapticClose(haptic);
    SDL_Quit();

    return 0;
}
Esempio n. 18
0
int
main(int argc, char *argv[])
{
    int i;
    Uint32 then, now, frames;

	/* Enable standard application logging */
	SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);

    /* Initialize parameters */
    num_objects = NUM_OBJECTS;

    /* Initialize test framework */
    state = SDLTest_CommonCreateState(argv, SDL_INIT_VIDEO);
    if (!state) {
        return 1;
    }
    for (i = 1; i < argc;) {
        int consumed;

        consumed = SDLTest_CommonArg(state, i);
        if (consumed == 0) {
            consumed = -1;
            if (SDL_strcasecmp(argv[i], "--blend") == 0) {
                if (argv[i + 1]) {
                    if (SDL_strcasecmp(argv[i + 1], "none") == 0) {
                        blendMode = SDL_BLENDMODE_NONE;
                        consumed = 2;
                    } else if (SDL_strcasecmp(argv[i + 1], "blend") == 0) {
                        blendMode = SDL_BLENDMODE_BLEND;
                        consumed = 2;
                    } else if (SDL_strcasecmp(argv[i + 1], "add") == 0) {
                        blendMode = SDL_BLENDMODE_ADD;
                        consumed = 2;
                    } else if (SDL_strcasecmp(argv[i + 1], "mod") == 0) {
                        blendMode = SDL_BLENDMODE_MOD;
                        consumed = 2;
                    }
                }
            } else if (SDL_strcasecmp(argv[i], "--cyclecolor") == 0) {
                cycle_color = SDL_TRUE;
                consumed = 1;
            } else if (SDL_strcasecmp(argv[i], "--cyclealpha") == 0) {
                cycle_alpha = SDL_TRUE;
                consumed = 1;
            } else if (SDL_isdigit(*argv[i])) {
                num_objects = SDL_atoi(argv[i]);
                consumed = 1;
            }
        }
        if (consumed < 0) {
            SDL_Log("Usage: %s %s [--blend none|blend|add|mod] [--cyclecolor] [--cyclealpha]\n",
                    argv[0], SDLTest_CommonUsage(state));
            return 1;
        }
        i += consumed;
    }
    if (!SDLTest_CommonInit(state)) {
        return 2;
    }

    /* Create the windows and initialize the renderers */
    for (i = 0; i < state->num_windows; ++i) {
        SDL_Renderer *renderer = state->renderers[i];
        SDL_SetRenderDrawBlendMode(renderer, blendMode);
        SDL_SetRenderDrawColor(renderer, 0xA0, 0xA0, 0xA0, 0xFF);
        SDL_RenderClear(renderer);
    }

    srand((unsigned int)time(NULL));

    /* Main render loop */
    frames = 0;
    then = SDL_GetTicks();
    done = 0;

#ifdef __EMSCRIPTEN__
    emscripten_set_main_loop(loop, 0, 1);
#else
    while (!done) {
        ++frames;
        loop();
        }
#endif


    SDLTest_CommonQuit(state);

    /* Print out some timing information */
    now = SDL_GetTicks();
    if (now > then) {
        double fps = ((double) frames * 1000) / (now - then);
        SDL_Log("%2.2f frames per second\n", fps);
    }
    return 0;
}
Esempio n. 19
0
int
main(int argc, char *argv[])
{
    int fsaa, accel;
    int value;
    int i;
    SDL_DisplayMode mode;
    Uint32 then, now;
    int status;
    shader_data *data;

    /* Initialize parameters */
    fsaa = 0;
    accel = 0;

    /* Initialize test framework */
    state = SDLTest_CommonCreateState(argv, SDL_INIT_VIDEO);
    if (!state) {
        return 1;
    }
    for (i = 1; i < argc;) {
        int consumed;

        consumed = SDLTest_CommonArg(state, i);
        if (consumed == 0) {
            if (SDL_strcasecmp(argv[i], "--fsaa") == 0) {
                ++fsaa;
                consumed = 1;
            } else if (SDL_strcasecmp(argv[i], "--accel") == 0) {
                ++accel;
                consumed = 1;
            } else if (SDL_strcasecmp(argv[i], "--zdepth") == 0) {
                i++;
                if (!argv[i]) {
                    consumed = -1;
                } else {
                    depth = SDL_atoi(argv[i]);
                    consumed = 1;
                }
            } else {
                consumed = -1;
            }
        }
        if (consumed < 0) {
            SDL_Log ("Usage: %s %s [--fsaa] [--accel] [--zdepth %%d]\n", argv[0],
                    SDLTest_CommonUsage(state));
            quit(1);
        }
        i += consumed;
    }

    /* Set OpenGL parameters */
    state->window_flags |= SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_BORDERLESS;
    state->gl_red_size = 5;
    state->gl_green_size = 5;
    state->gl_blue_size = 5;
    state->gl_depth_size = depth;
    state->gl_major_version = 2;
    state->gl_minor_version = 0;
    state->gl_profile_mask = SDL_GL_CONTEXT_PROFILE_ES;

    if (fsaa) {
        state->gl_multisamplebuffers=1;
        state->gl_multisamplesamples=fsaa;
    }
    if (accel) {
        state->gl_accelerated=1;
    }
    if (!SDLTest_CommonInit(state)) {
        quit(2);
        return 0;
    }

    context = (SDL_GLContext *)SDL_calloc(state->num_windows, sizeof(context));
    if (context == NULL) {
        SDL_Log("Out of memory!\n");
        quit(2);
    }
    
    /* Create OpenGL ES contexts */
    for (i = 0; i < state->num_windows; i++) {
        context[i] = SDL_GL_CreateContext(state->windows[i]);
        if (!context[i]) {
            SDL_Log("SDL_GL_CreateContext(): %s\n", SDL_GetError());
            quit(2);
        }
    }

    /* Important: call this *after* creating the context */
    if (LoadContext(&ctx) < 0) {
        SDL_Log("Could not load GLES2 functions\n");
        quit(2);
        return 0;
    }

    /* from here on out, it should be ok to call gles 2.0 routines */

    if (state->render_flags & SDL_RENDERER_PRESENTVSYNC) {
        SDL_GL_SetSwapInterval(1);
    } else {
        SDL_GL_SetSwapInterval(0);
    }
    SDL_Log("first call address is %llx data is %lx\n",(long long)(&glGetString),GL_VENDOR);
        
    const char *test = ctx.glGetString(GL_VENDOR);
    if (test) {
      SDL_Log("we got %s\n",test);
      }
    else {
      SDL_Log("we got a null.\n");
      quit(2);
      }
    
    SDL_Log("try again call address is %lx\n",(long long)(&glGetString));
    SDL_Log("first ctx address is %llx data is %lx ind %llx\n",(long long)(ctx.glGetString),GL_VENDOR,((long long *)(ctx.glGetString))[0] );
    {const char *test = glGetString(GL_VENDOR);
    if (test) {
      SDL_Log("we got %s\n",test);
      }
    else {
      SDL_Log("we got a null.\n");
      quit(2);
      }
    }

    SDL_GetCurrentDisplayMode(0, &mode);
    SDL_Log("Screen bpp: %d\n", SDL_BITSPERPIXEL(mode.format));
    SDL_Log("\n");
    SDL_Log("Vendor     : %s\n", glGetString(GL_VENDOR));
    SDL_Log("Renderer   : %s\n", glGetString(GL_RENDERER));
    SDL_Log("Version    : %s\n", glGetString(GL_VERSION));
    SDL_Log("Extensions : %s\n", glGetString(GL_EXTENSIONS));
    SDL_Log("\n");

    status = SDL_GL_GetAttribute(SDL_GL_RED_SIZE, &value);
    if (!status) {
        SDL_Log("SDL_GL_RED_SIZE: requested %d, got %d\n", 5, value);
    } else {
        SDL_Log( "Failed to get SDL_GL_RED_SIZE: %s\n",
                SDL_GetError());
    }
    status = SDL_GL_GetAttribute(SDL_GL_GREEN_SIZE, &value);
    if (!status) {
        SDL_Log("SDL_GL_GREEN_SIZE: requested %d, got %d\n", 5, value);
    } else {
        SDL_Log( "Failed to get SDL_GL_GREEN_SIZE: %s\n",
                SDL_GetError());
    }
    status = SDL_GL_GetAttribute(SDL_GL_BLUE_SIZE, &value);
    if (!status) {
        SDL_Log("SDL_GL_BLUE_SIZE: requested %d, got %d\n", 5, value);
    } else {
        SDL_Log( "Failed to get SDL_GL_BLUE_SIZE: %s\n",
                SDL_GetError());
    }
    status = SDL_GL_GetAttribute(SDL_GL_DEPTH_SIZE, &value);
    if (!status) {
        SDL_Log("SDL_GL_DEPTH_SIZE: requested %d, got %d\n", depth, value);
    } else {
        SDL_Log( "Failed to get SDL_GL_DEPTH_SIZE: %s\n",
                SDL_GetError());
    }
    if (fsaa) {
        status = SDL_GL_GetAttribute(SDL_GL_MULTISAMPLEBUFFERS, &value);
        if (!status) {
            SDL_Log("SDL_GL_MULTISAMPLEBUFFERS: requested 1, got %d\n", value);
        } else {
            SDL_Log( "Failed to get SDL_GL_MULTISAMPLEBUFFERS: %s\n",
                    SDL_GetError());
        }
        status = SDL_GL_GetAttribute(SDL_GL_MULTISAMPLESAMPLES, &value);
        if (!status) {
            SDL_Log("SDL_GL_MULTISAMPLESAMPLES: requested %d, got %d\n", fsaa,
                   value);
        } else {
            SDL_Log( "Failed to get SDL_GL_MULTISAMPLESAMPLES: %s\n",
                    SDL_GetError());
        }
    }
    if (accel) {
        status = SDL_GL_GetAttribute(SDL_GL_ACCELERATED_VISUAL, &value);
        if (!status) {
            SDL_Log("SDL_GL_ACCELERATED_VISUAL: requested 1, got %d\n", value);
        } else {
            SDL_Log( "Failed to get SDL_GL_ACCELERATED_VISUAL: %s\n",
                    SDL_GetError());
        }
    }

    datas = (shader_data *)SDL_calloc(state->num_windows, sizeof(shader_data));

    /* Set rendering settings for each context */
    for (i = 0; i < state->num_windows; ++i) {

        int w, h;
        status = SDL_GL_MakeCurrent(state->windows[i], context[i]);
        if (status) {
            SDL_Log("SDL_GL_MakeCurrent(): %s\n", SDL_GetError());

            /* Continue for next window */
            continue;
        }
        SDL_GL_GetDrawableSize(state->windows[i], &w, &h);
        glViewport(0, 0, w, h);

        data = &datas[i];
        data->angle_x = 0; data->angle_y = 0; data->angle_z = 0;

        /* Shader Initialization */
        process_shader(&data->shader_vert, _shader_vert_src, GL_VERTEX_SHADER);
        process_shader(&data->shader_frag, _shader_frag_src, GL_FRAGMENT_SHADER);

        /* Create shader_program (ready to attach shaders) */
        data->shader_program = GL_CHECK(glCreateProgram());

        /* Attach shaders and link shader_program */
        GL_CHECK(glAttachShader(data->shader_program, data->shader_vert));
        GL_CHECK(glAttachShader(data->shader_program, data->shader_frag));
        GL_CHECK(glLinkProgram(data->shader_program));

        /* Get attribute locations of non-fixed attributes like color and texture coordinates. */
        data->attr_position = GL_CHECK(glGetAttribLocation(data->shader_program, "av4position"));
        data->attr_color = GL_CHECK(glGetAttribLocation(data->shader_program, "av3color"));

        /* Get uniform locations */
        data->attr_mvp = GL_CHECK(glGetUniformLocation(data->shader_program, "mvp"));

        GL_CHECK(glUseProgram(data->shader_program));

        /* Enable attributes for position, color and texture coordinates etc. */
        GL_CHECK(glEnableVertexAttribArray(data->attr_position));
        GL_CHECK(glEnableVertexAttribArray(data->attr_color));

        /* Populate attributes for position, color and texture coordinates etc. */
        GL_CHECK(glVertexAttribPointer(data->attr_position, 3, GL_FLOAT, GL_FALSE, 0, _vertices));
        GL_CHECK(glVertexAttribPointer(data->attr_color, 3, GL_FLOAT, GL_FALSE, 0, _colors));

        GL_CHECK(glEnable(GL_CULL_FACE));
        GL_CHECK(glEnable(GL_DEPTH_TEST));
    }

    /* Main render loop */
    frames = 0;
    then = SDL_GetTicks();
    done = 0;

#ifdef __EMSCRIPTEN__
    emscripten_set_main_loop(loop, 0, 1);
#else
    while (!done) {
        loop();
    }
#endif

    /* Print out some timing information */
    now = SDL_GetTicks();
    if (now > then) {
        SDL_Log("%2.2f frames per second\n",
               ((double) frames * 1000) / (now - then));
    }
#if !defined(__ANDROID__) && !defined(__NACL__)  
    quit(0);
#endif    
    return 0;
}
Esempio n. 20
0
int
SDLTest_CommonArg(SDLTest_CommonState * state, int index)
{
    char **argv = state->argv;

    if (SDL_strcasecmp(argv[index], "--video") == 0) {
        ++index;
        if (!argv[index]) {
            return -1;
        }
        state->videodriver = argv[index];
        return 2;
    }
    if (SDL_strcasecmp(argv[index], "--renderer") == 0) {
        ++index;
        if (!argv[index]) {
            return -1;
        }
        state->renderdriver = argv[index];
        return 2;
    }
    if (SDL_strcasecmp(argv[index], "--gldebug") == 0) {
        state->gl_debug = 1;
        return 1;
    }
    if (SDL_strcasecmp(argv[index], "--info") == 0) {
        ++index;
        if (!argv[index]) {
            return -1;
        }
        if (SDL_strcasecmp(argv[index], "all") == 0) {
            state->verbose |=
                (VERBOSE_VIDEO | VERBOSE_MODES | VERBOSE_RENDER |
                 VERBOSE_EVENT);
            return 2;
        }
        if (SDL_strcasecmp(argv[index], "video") == 0) {
            state->verbose |= VERBOSE_VIDEO;
            return 2;
        }
        if (SDL_strcasecmp(argv[index], "modes") == 0) {
            state->verbose |= VERBOSE_MODES;
            return 2;
        }
        if (SDL_strcasecmp(argv[index], "render") == 0) {
            state->verbose |= VERBOSE_RENDER;
            return 2;
        }
        if (SDL_strcasecmp(argv[index], "event") == 0) {
            state->verbose |= VERBOSE_EVENT;
            return 2;
        }
        return -1;
    }
    if (SDL_strcasecmp(argv[index], "--log") == 0) {
        ++index;
        if (!argv[index]) {
            return -1;
        }
        if (SDL_strcasecmp(argv[index], "all") == 0) {
            SDL_LogSetAllPriority(SDL_LOG_PRIORITY_VERBOSE);
            return 2;
        }
        if (SDL_strcasecmp(argv[index], "error") == 0) {
            SDL_LogSetPriority(SDL_LOG_CATEGORY_ERROR, SDL_LOG_PRIORITY_VERBOSE);
            return 2;
        }
        if (SDL_strcasecmp(argv[index], "system") == 0) {
            SDL_LogSetPriority(SDL_LOG_CATEGORY_SYSTEM, SDL_LOG_PRIORITY_VERBOSE);
            return 2;
        }
        if (SDL_strcasecmp(argv[index], "audio") == 0) {
            SDL_LogSetPriority(SDL_LOG_CATEGORY_AUDIO, SDL_LOG_PRIORITY_VERBOSE);
            return 2;
        }
        if (SDL_strcasecmp(argv[index], "video") == 0) {
            SDL_LogSetPriority(SDL_LOG_CATEGORY_VIDEO, SDL_LOG_PRIORITY_VERBOSE);
            return 2;
        }
        if (SDL_strcasecmp(argv[index], "render") == 0) {
            SDL_LogSetPriority(SDL_LOG_CATEGORY_RENDER, SDL_LOG_PRIORITY_VERBOSE);
            return 2;
        }
        if (SDL_strcasecmp(argv[index], "input") == 0) {
            SDL_LogSetPriority(SDL_LOG_CATEGORY_INPUT, SDL_LOG_PRIORITY_VERBOSE);
            return 2;
        }
        return -1;
    }
    if (SDL_strcasecmp(argv[index], "--display") == 0) {
        ++index;
        if (!argv[index]) {
            return -1;
        }
        state->display = SDL_atoi(argv[index]);
        if (SDL_WINDOWPOS_ISUNDEFINED(state->window_x)) {
            state->window_x = SDL_WINDOWPOS_UNDEFINED_DISPLAY(state->display);
            state->window_y = SDL_WINDOWPOS_UNDEFINED_DISPLAY(state->display);
        }
        if (SDL_WINDOWPOS_ISCENTERED(state->window_x)) {
            state->window_x = SDL_WINDOWPOS_CENTERED_DISPLAY(state->display);
            state->window_y = SDL_WINDOWPOS_CENTERED_DISPLAY(state->display);
        }
        return 2;
    }
    if (SDL_strcasecmp(argv[index], "--fullscreen") == 0) {
        state->window_flags |= SDL_WINDOW_FULLSCREEN;
        state->num_windows = 1;
        return 1;
    }
    if (SDL_strcasecmp(argv[index], "--fullscreen-desktop") == 0) {
        state->window_flags |= SDL_WINDOW_FULLSCREEN_DESKTOP;
        state->num_windows = 1;
        return 1;
    }
    if (SDL_strcasecmp(argv[index], "--windows") == 0) {
        ++index;
        if (!argv[index] || !SDL_isdigit(*argv[index])) {
            return -1;
        }
        if (!(state->window_flags & SDL_WINDOW_FULLSCREEN)) {
            state->num_windows = SDL_atoi(argv[index]);
        }
        return 2;
    }
    if (SDL_strcasecmp(argv[index], "--title") == 0) {
        ++index;
        if (!argv[index]) {
            return -1;
        }
        state->window_title = argv[index];
        return 2;
    }
    if (SDL_strcasecmp(argv[index], "--icon") == 0) {
        ++index;
        if (!argv[index]) {
            return -1;
        }
        state->window_icon = argv[index];
        return 2;
    }
    if (SDL_strcasecmp(argv[index], "--center") == 0) {
        state->window_x = SDL_WINDOWPOS_CENTERED;
        state->window_y = SDL_WINDOWPOS_CENTERED;
        return 1;
    }
    if (SDL_strcasecmp(argv[index], "--position") == 0) {
        char *x, *y;
        ++index;
        if (!argv[index]) {
            return -1;
        }
        x = argv[index];
        y = argv[index];
        while (*y && *y != ',') {
            ++y;
        }
        if (!*y) {
            return -1;
        }
        *y++ = '\0';
        state->window_x = SDL_atoi(x);
        state->window_y = SDL_atoi(y);
        return 2;
    }
    if (SDL_strcasecmp(argv[index], "--geometry") == 0) {
        char *w, *h;
        ++index;
        if (!argv[index]) {
            return -1;
        }
        w = argv[index];
        h = argv[index];
        while (*h && *h != 'x') {
            ++h;
        }
        if (!*h) {
            return -1;
        }
        *h++ = '\0';
        state->window_w = SDL_atoi(w);
        state->window_h = SDL_atoi(h);
        return 2;
    }
    if (SDL_strcasecmp(argv[index], "--min-geometry") == 0) {
        char *w, *h;
        ++index;
        if (!argv[index]) {
            return -1;
        }
        w = argv[index];
        h = argv[index];
        while (*h && *h != 'x') {
            ++h;
        }
        if (!*h) {
            return -1;
        }
        *h++ = '\0';
        state->window_minW = SDL_atoi(w);
        state->window_minH = SDL_atoi(h);
        return 2;
    }
    if (SDL_strcasecmp(argv[index], "--max-geometry") == 0) {
        char *w, *h;
        ++index;
        if (!argv[index]) {
            return -1;
        }
        w = argv[index];
        h = argv[index];
        while (*h && *h != 'x') {
            ++h;
        }
        if (!*h) {
            return -1;
        }
        *h++ = '\0';
        state->window_maxW = SDL_atoi(w);
        state->window_maxH = SDL_atoi(h);
        return 2;
    }
    if (SDL_strcasecmp(argv[index], "--logical") == 0) {
        char *w, *h;
        ++index;
        if (!argv[index]) {
            return -1;
        }
        w = argv[index];
        h = argv[index];
        while (*h && *h != 'x') {
            ++h;
        }
        if (!*h) {
            return -1;
        }
        *h++ = '\0';
        state->logical_w = SDL_atoi(w);
        state->logical_h = SDL_atoi(h);
        return 2;
    }
    if (SDL_strcasecmp(argv[index], "--scale") == 0) {
        ++index;
        if (!argv[index]) {
            return -1;
        }
        state->scale = (float)SDL_atof(argv[index]);
        return 2;
    }
    if (SDL_strcasecmp(argv[index], "--depth") == 0) {
        ++index;
        if (!argv[index]) {
            return -1;
        }
        state->depth = SDL_atoi(argv[index]);
        return 2;
    }
    if (SDL_strcasecmp(argv[index], "--refresh") == 0) {
        ++index;
        if (!argv[index]) {
            return -1;
        }
        state->refresh_rate = SDL_atoi(argv[index]);
        return 2;
    }
    if (SDL_strcasecmp(argv[index], "--vsync") == 0) {
        state->render_flags |= SDL_RENDERER_PRESENTVSYNC;
        return 1;
    }
    if (SDL_strcasecmp(argv[index], "--noframe") == 0) {
        state->window_flags |= SDL_WINDOW_BORDERLESS;
        return 1;
    }
    if (SDL_strcasecmp(argv[index], "--resize") == 0) {
        state->window_flags |= SDL_WINDOW_RESIZABLE;
        return 1;
    }
    if (SDL_strcasecmp(argv[index], "--minimize") == 0) {
        state->window_flags |= SDL_WINDOW_MINIMIZED;
        return 1;
    }
    if (SDL_strcasecmp(argv[index], "--maximize") == 0) {
        state->window_flags |= SDL_WINDOW_MAXIMIZED;
        return 1;
    }
    if (SDL_strcasecmp(argv[index], "--grab") == 0) {
        state->window_flags |= SDL_WINDOW_INPUT_GRABBED;
        return 1;
    }
    if (SDL_strcasecmp(argv[index], "--rate") == 0) {
        ++index;
        if (!argv[index]) {
            return -1;
        }
        state->audiospec.freq = SDL_atoi(argv[index]);
        return 2;
    }
    if (SDL_strcasecmp(argv[index], "--format") == 0) {
        ++index;
        if (!argv[index]) {
            return -1;
        }
        if (SDL_strcasecmp(argv[index], "U8") == 0) {
            state->audiospec.format = AUDIO_U8;
            return 2;
        }
        if (SDL_strcasecmp(argv[index], "S8") == 0) {
            state->audiospec.format = AUDIO_S8;
            return 2;
        }
        if (SDL_strcasecmp(argv[index], "U16") == 0) {
            state->audiospec.format = AUDIO_U16;
            return 2;
        }
        if (SDL_strcasecmp(argv[index], "U16LE") == 0) {
            state->audiospec.format = AUDIO_U16LSB;
            return 2;
        }
        if (SDL_strcasecmp(argv[index], "U16BE") == 0) {
            state->audiospec.format = AUDIO_U16MSB;
            return 2;
        }
        if (SDL_strcasecmp(argv[index], "S16") == 0) {
            state->audiospec.format = AUDIO_S16;
            return 2;
        }
        if (SDL_strcasecmp(argv[index], "S16LE") == 0) {
            state->audiospec.format = AUDIO_S16LSB;
            return 2;
        }
        if (SDL_strcasecmp(argv[index], "S16BE") == 0) {
            state->audiospec.format = AUDIO_S16MSB;
            return 2;
        }
        return -1;
    }
    if (SDL_strcasecmp(argv[index], "--channels") == 0) {
        ++index;
        if (!argv[index]) {
            return -1;
        }
        state->audiospec.channels = (Uint8) SDL_atoi(argv[index]);
        return 2;
    }
    if (SDL_strcasecmp(argv[index], "--samples") == 0) {
        ++index;
        if (!argv[index]) {
            return -1;
        }
        state->audiospec.samples = (Uint16) SDL_atoi(argv[index]);
        return 2;
    }
    if ((SDL_strcasecmp(argv[index], "-h") == 0)
        || (SDL_strcasecmp(argv[index], "--help") == 0)) {
        /* Print the usage message */
        return -1;
    }
    if (SDL_strcmp(argv[index], "-NSDocumentRevisionsDebugMode") == 0) {
    /* Debug flag sent by Xcode */
        return 2;
    }
    return 0;
}
Esempio n. 21
0
int
main(int argc, char **argv)
{
    SDL_AudioSpec spec;
    SDL_AudioCVT cvt;
    Uint32 len = 0;
    Uint8 *data = NULL;
    int cvtfreq = 0;
    int bitsize = 0;
    int blockalign = 0;
    int avgbytes = 0;
    SDL_RWops *io = NULL;

    if (argc != 4) {
        fprintf(stderr, "USAGE: %s in.wav out.wav newfreq\n", argv[0]);
        return 1;
    }

    cvtfreq = SDL_atoi(argv[3]);

    if (SDL_Init(SDL_INIT_AUDIO) == -1) {
        fprintf(stderr, "SDL_Init() failed: %s\n", SDL_GetError());
        return 2;
    }

    if (SDL_LoadWAV(argv[1], &spec, &data, &len) == NULL) {
        fprintf(stderr, "failed to load %s: %s\n", argv[1], SDL_GetError());
        SDL_Quit();
        return 3;
    }

    if (SDL_BuildAudioCVT(&cvt, spec.format, spec.channels, spec.freq,
                          spec.format, spec.channels, cvtfreq) == -1) {
        fprintf(stderr, "failed to build CVT: %s\n", SDL_GetError());
        SDL_FreeWAV(data);
        SDL_Quit();
        return 4;
    }

    cvt.len = len;
    cvt.buf = (Uint8 *) SDL_malloc(len * cvt.len_mult);
    if (cvt.buf == NULL) {
        fprintf(stderr, "Out of memory.\n");
        SDL_FreeWAV(data);
        SDL_Quit();
        return 5;
    }
    SDL_memcpy(cvt.buf, data, len);

    if (SDL_ConvertAudio(&cvt) == -1) {
        fprintf(stderr, "Conversion failed: %s\n", SDL_GetError());
        SDL_free(cvt.buf);
        SDL_FreeWAV(data);
        SDL_Quit();
        return 6;
    }

    /* write out a WAV header... */
    io = SDL_RWFromFile(argv[2], "wb");
    if (io == NULL) {
        fprintf(stderr, "fopen('%s') failed: %s\n", argv[2], SDL_GetError());
        SDL_free(cvt.buf);
        SDL_FreeWAV(data);
        SDL_Quit();
        return 7;
    }

    bitsize = SDL_AUDIO_BITSIZE(spec.format);
    blockalign = (bitsize / 8) * spec.channels;
    avgbytes = cvtfreq * blockalign;

    SDL_WriteLE32(io, 0x46464952);      /* RIFF */
    SDL_WriteLE32(io, len * cvt.len_mult + 36);
    SDL_WriteLE32(io, 0x45564157);      /* WAVE */
    SDL_WriteLE32(io, 0x20746D66);      /* fmt */
    SDL_WriteLE32(io, 16);      /* chunk size */
    SDL_WriteLE16(io, 1);       /* uncompressed */
    SDL_WriteLE16(io, spec.channels);   /* channels */
    SDL_WriteLE32(io, cvtfreq); /* sample rate */
    SDL_WriteLE32(io, avgbytes);        /* average bytes per second */
    SDL_WriteLE16(io, blockalign);      /* block align */
    SDL_WriteLE16(io, bitsize); /* significant bits per sample */
    SDL_WriteLE32(io, 0x61746164);      /* data */
    SDL_WriteLE32(io, cvt.len_cvt);     /* size */
    SDL_RWwrite(io, cvt.buf, cvt.len_cvt, 1);

    if (SDL_RWclose(io) == -1) {
        fprintf(stderr, "fclose('%s') failed: %s\n", argv[2], SDL_GetError());
        SDL_free(cvt.buf);
        SDL_FreeWAV(data);
        SDL_Quit();
        return 8;
    }                           // if

    SDL_free(cvt.buf);
    SDL_FreeWAV(data);
    SDL_Quit();
    return 0;
}                               // main
Esempio n. 22
0
/* Public functions */
int SDL_KeyboardInit(void)
{
	const char* env;
	SDL_VideoDevice *video = current_video;
	SDL_VideoDevice *this  = current_video;

	/* Set default mode of UNICODE translation */
	SDL_EnableUNICODE(DEFAULT_UNICODE_TRANSLATION);

	/* Initialize the tables */
	SDL_ModState = KMOD_NONE;
	SDL_memset((void*)keynames, 0, sizeof(keynames));
	SDL_memset(SDL_KeyState, 0, sizeof(SDL_KeyState));
	video->InitOSKeymap(this);

	SDL_EnableKeyRepeat(0, 0);

	/* Allow environment override to disable special lock-key behavior */
	SDL_NoLockKeys = 0;
	env = SDL_getenv("SDL_DISABLE_LOCK_KEYS");
	if (env) {
		switch (SDL_atoi(env)) {
			case 1:
				SDL_NoLockKeys = SDL_NLK_CAPS | SDL_NLK_NUM;
				break;
			case 2:
				SDL_NoLockKeys = SDL_NLK_CAPS;
				break;
			case 3:
				SDL_NoLockKeys = SDL_NLK_NUM;
				break;
			default:
				break;
		}
	}

	/* Fill in the blanks in keynames */
	keynames[SDLK_BACKSPACE] = "backspace";
	keynames[SDLK_TAB] = "tab";
	keynames[SDLK_CLEAR] = "clear";
	keynames[SDLK_RETURN] = "return";
	keynames[SDLK_PAUSE] = "pause";
	keynames[SDLK_ESCAPE] = "escape";
	keynames[SDLK_SPACE] = "space";
	keynames[SDLK_EXCLAIM]  = "!";
	keynames[SDLK_QUOTEDBL]  = "\"";
	keynames[SDLK_HASH]  = "#";
	keynames[SDLK_DOLLAR]  = "$";
	keynames[SDLK_AMPERSAND]  = "&";
	keynames[SDLK_QUOTE] = "'";
	keynames[SDLK_LEFTPAREN] = "(";
	keynames[SDLK_RIGHTPAREN] = ")";
	keynames[SDLK_ASTERISK] = "*";
	keynames[SDLK_PLUS] = "+";
	keynames[SDLK_COMMA] = ",";
	keynames[SDLK_MINUS] = "-";
	keynames[SDLK_PERIOD] = ".";
	keynames[SDLK_SLASH] = "/";
	keynames[SDLK_0] = "0";
	keynames[SDLK_1] = "1";
	keynames[SDLK_2] = "2";
	keynames[SDLK_3] = "3";
	keynames[SDLK_4] = "4";
	keynames[SDLK_5] = "5";
	keynames[SDLK_6] = "6";
	keynames[SDLK_7] = "7";
	keynames[SDLK_8] = "8";
	keynames[SDLK_9] = "9";
	keynames[SDLK_COLON] = ":";
	keynames[SDLK_SEMICOLON] = ";";
	keynames[SDLK_LESS] = "<";
	keynames[SDLK_EQUALS] = "=";
	keynames[SDLK_GREATER] = ">";
	keynames[SDLK_QUESTION] = "?";
	keynames[SDLK_AT] = "@";
	keynames[SDLK_LEFTBRACKET] = "[";
	keynames[SDLK_BACKSLASH] = "\\";
	keynames[SDLK_RIGHTBRACKET] = "]";
	keynames[SDLK_CARET] = "^";
	keynames[SDLK_UNDERSCORE] = "_";
	keynames[SDLK_BACKQUOTE] = "`";
	keynames[SDLK_a] = "a";
	keynames[SDLK_b] = "b";
	keynames[SDLK_c] = "c";
	keynames[SDLK_d] = "d";
	keynames[SDLK_e] = "e";
	keynames[SDLK_f] = "f";
	keynames[SDLK_g] = "g";
	keynames[SDLK_h] = "h";
	keynames[SDLK_i] = "i";
	keynames[SDLK_j] = "j";
	keynames[SDLK_k] = "k";
	keynames[SDLK_l] = "l";
	keynames[SDLK_m] = "m";
	keynames[SDLK_n] = "n";
	keynames[SDLK_o] = "o";
	keynames[SDLK_p] = "p";
	keynames[SDLK_q] = "q";
	keynames[SDLK_r] = "r";
	keynames[SDLK_s] = "s";
	keynames[SDLK_t] = "t";
	keynames[SDLK_u] = "u";
	keynames[SDLK_v] = "v";
	keynames[SDLK_w] = "w";
	keynames[SDLK_x] = "x";
	keynames[SDLK_y] = "y";
	keynames[SDLK_z] = "z";
	keynames[SDLK_DELETE] = "delete";

	keynames[SDLK_WORLD_0] = "world 0";
	keynames[SDLK_WORLD_1] = "world 1";
	keynames[SDLK_WORLD_2] = "world 2";
	keynames[SDLK_WORLD_3] = "world 3";
	keynames[SDLK_WORLD_4] = "world 4";
	keynames[SDLK_WORLD_5] = "world 5";
	keynames[SDLK_WORLD_6] = "world 6";
	keynames[SDLK_WORLD_7] = "world 7";
	keynames[SDLK_WORLD_8] = "world 8";
	keynames[SDLK_WORLD_9] = "world 9";
	keynames[SDLK_WORLD_10] = "world 10";
	keynames[SDLK_WORLD_11] = "world 11";
	keynames[SDLK_WORLD_12] = "world 12";
	keynames[SDLK_WORLD_13] = "world 13";
	keynames[SDLK_WORLD_14] = "world 14";
	keynames[SDLK_WORLD_15] = "world 15";
	keynames[SDLK_WORLD_16] = "world 16";
	keynames[SDLK_WORLD_17] = "world 17";
	keynames[SDLK_WORLD_18] = "world 18";
	keynames[SDLK_WORLD_19] = "world 19";
	keynames[SDLK_WORLD_20] = "world 20";
	keynames[SDLK_WORLD_21] = "world 21";
	keynames[SDLK_WORLD_22] = "world 22";
	keynames[SDLK_WORLD_23] = "world 23";
	keynames[SDLK_WORLD_24] = "world 24";
	keynames[SDLK_WORLD_25] = "world 25";
	keynames[SDLK_WORLD_26] = "world 26";
	keynames[SDLK_WORLD_27] = "world 27";
	keynames[SDLK_WORLD_28] = "world 28";
	keynames[SDLK_WORLD_29] = "world 29";
	keynames[SDLK_WORLD_30] = "world 30";
	keynames[SDLK_WORLD_31] = "world 31";
	keynames[SDLK_WORLD_32] = "world 32";
	keynames[SDLK_WORLD_33] = "world 33";
	keynames[SDLK_WORLD_34] = "world 34";
	keynames[SDLK_WORLD_35] = "world 35";
	keynames[SDLK_WORLD_36] = "world 36";
	keynames[SDLK_WORLD_37] = "world 37";
	keynames[SDLK_WORLD_38] = "world 38";
	keynames[SDLK_WORLD_39] = "world 39";
	keynames[SDLK_WORLD_40] = "world 40";
	keynames[SDLK_WORLD_41] = "world 41";
	keynames[SDLK_WORLD_42] = "world 42";
	keynames[SDLK_WORLD_43] = "world 43";
	keynames[SDLK_WORLD_44] = "world 44";
	keynames[SDLK_WORLD_45] = "world 45";
	keynames[SDLK_WORLD_46] = "world 46";
	keynames[SDLK_WORLD_47] = "world 47";
	keynames[SDLK_WORLD_48] = "world 48";
	keynames[SDLK_WORLD_49] = "world 49";
	keynames[SDLK_WORLD_50] = "world 50";
	keynames[SDLK_WORLD_51] = "world 51";
	keynames[SDLK_WORLD_52] = "world 52";
	keynames[SDLK_WORLD_53] = "world 53";
	keynames[SDLK_WORLD_54] = "world 54";
	keynames[SDLK_WORLD_55] = "world 55";
	keynames[SDLK_WORLD_56] = "world 56";
	keynames[SDLK_WORLD_57] = "world 57";
	keynames[SDLK_WORLD_58] = "world 58";
	keynames[SDLK_WORLD_59] = "world 59";
	keynames[SDLK_WORLD_60] = "world 60";
	keynames[SDLK_WORLD_61] = "world 61";
	keynames[SDLK_WORLD_62] = "world 62";
	keynames[SDLK_WORLD_63] = "world 63";
	keynames[SDLK_WORLD_64] = "world 64";
	keynames[SDLK_WORLD_65] = "world 65";
	keynames[SDLK_WORLD_66] = "world 66";
	keynames[SDLK_WORLD_67] = "world 67";
	keynames[SDLK_WORLD_68] = "world 68";
	keynames[SDLK_WORLD_69] = "world 69";
	keynames[SDLK_WORLD_70] = "world 70";
	keynames[SDLK_WORLD_71] = "world 71";
	keynames[SDLK_WORLD_72] = "world 72";
	keynames[SDLK_WORLD_73] = "world 73";
	keynames[SDLK_WORLD_74] = "world 74";
	keynames[SDLK_WORLD_75] = "world 75";
	keynames[SDLK_WORLD_76] = "world 76";
	keynames[SDLK_WORLD_77] = "world 77";
	keynames[SDLK_WORLD_78] = "world 78";
	keynames[SDLK_WORLD_79] = "world 79";
	keynames[SDLK_WORLD_80] = "world 80";
	keynames[SDLK_WORLD_81] = "world 81";
	keynames[SDLK_WORLD_82] = "world 82";
	keynames[SDLK_WORLD_83] = "world 83";
	keynames[SDLK_WORLD_84] = "world 84";
	keynames[SDLK_WORLD_85] = "world 85";
	keynames[SDLK_WORLD_86] = "world 86";
	keynames[SDLK_WORLD_87] = "world 87";
	keynames[SDLK_WORLD_88] = "world 88";
	keynames[SDLK_WORLD_89] = "world 89";
	keynames[SDLK_WORLD_90] = "world 90";
	keynames[SDLK_WORLD_91] = "world 91";
	keynames[SDLK_WORLD_92] = "world 92";
	keynames[SDLK_WORLD_93] = "world 93";
	keynames[SDLK_WORLD_94] = "world 94";
	keynames[SDLK_WORLD_95] = "world 95";

	keynames[SDLK_KP0] = "[0]";
	keynames[SDLK_KP1] = "[1]";
	keynames[SDLK_KP2] = "[2]";
	keynames[SDLK_KP3] = "[3]";
	keynames[SDLK_KP4] = "[4]";
	keynames[SDLK_KP5] = "[5]";
	keynames[SDLK_KP6] = "[6]";
	keynames[SDLK_KP7] = "[7]";
	keynames[SDLK_KP8] = "[8]";
	keynames[SDLK_KP9] = "[9]";
	keynames[SDLK_KP_PERIOD] = "[.]";
	keynames[SDLK_KP_DIVIDE] = "[/]";
	keynames[SDLK_KP_MULTIPLY] = "[*]";
	keynames[SDLK_KP_MINUS] = "[-]";
	keynames[SDLK_KP_PLUS] = "[+]";
	keynames[SDLK_KP_ENTER] = "enter";
	keynames[SDLK_KP_EQUALS] = "equals";

	keynames[SDLK_UP] = "up";
	keynames[SDLK_DOWN] = "down";
	keynames[SDLK_RIGHT] = "right";
	keynames[SDLK_LEFT] = "left";
	keynames[SDLK_DOWN] = "down";
	keynames[SDLK_INSERT] = "insert";
	keynames[SDLK_HOME] = "home";
	keynames[SDLK_END] = "end";
	keynames[SDLK_PAGEUP] = "page up";
	keynames[SDLK_PAGEDOWN] = "page down";

	keynames[SDLK_F1] = "f1";
	keynames[SDLK_F2] = "f2";
	keynames[SDLK_F3] = "f3";
	keynames[SDLK_F4] = "f4";
	keynames[SDLK_F5] = "f5";
	keynames[SDLK_F6] = "f6";
	keynames[SDLK_F7] = "f7";
	keynames[SDLK_F8] = "f8";
	keynames[SDLK_F9] = "f9";
	keynames[SDLK_F10] = "f10";
	keynames[SDLK_F11] = "f11";
	keynames[SDLK_F12] = "f12";
	keynames[SDLK_F13] = "f13";
	keynames[SDLK_F14] = "f14";
	keynames[SDLK_F15] = "f15";

	keynames[SDLK_NUMLOCK] = "numlock";
	keynames[SDLK_CAPSLOCK] = "caps lock";
	keynames[SDLK_SCROLLOCK] = "scroll lock";
	keynames[SDLK_RSHIFT] = "right shift";
	keynames[SDLK_LSHIFT] = "left shift";
	keynames[SDLK_RCTRL] = "right ctrl";
	keynames[SDLK_LCTRL] = "left ctrl";
	keynames[SDLK_RALT] = "right alt";
	keynames[SDLK_LALT] = "left alt";
	keynames[SDLK_RMETA] = "right meta";
	keynames[SDLK_LMETA] = "left meta";
	keynames[SDLK_LSUPER] = "left super";	/* "Windows" keys */
	keynames[SDLK_RSUPER] = "right super";	
	keynames[SDLK_MODE] = "alt gr";
	keynames[SDLK_COMPOSE] = "compose";

	keynames[SDLK_HELP] = "help";
	keynames[SDLK_PRINT] = "print screen";
	keynames[SDLK_SYSREQ] = "sys req";
	keynames[SDLK_BREAK] = "break";
	keynames[SDLK_MENU] = "menu";
	keynames[SDLK_POWER] = "power";
	keynames[SDLK_EURO] = "euro";
	keynames[SDLK_UNDO] = "undo";

	/* Done.  Whew. */
	return(0);
}
Esempio n. 23
0
// opens the file, returns NULL if it fails.
void* cfg_OpenFile( const char* fileName )
{
	if( SDL_strlen( fileName ) >= ( FILE_PATH_LEN - 1 ) ) {
		llog( LOG_ERROR, "Configuration file path too long" );
		return NULL;
	}

	CFGFile* newFile = (CFGFile*)mem_Allocate( sizeof( CFGFile ) );
	if( newFile == NULL ) {
		llog( LOG_INFO, "Unable to open configuration file." );
		return NULL;
	}
	newFile->sbAttributes = NULL;
	SDL_strlcpy( newFile->filePath, fileName, FILE_PATH_LEN - 1 );
	newFile->filePath[FILE_PATH_LEN-1] = 0;

	SDL_RWops* rwopsFile = SDL_RWFromFile( fileName, "r" );
	if( rwopsFile == NULL ) {
		// file doesn't exist, just create a new empty configuration file to use
		return newFile;
	}

	// TODO: change this so everything is happening in place and there are no allocations
	// parse what this configuration file currently has in it
	char buffer[READ_BUFFER_SIZE];
	size_t numRead;
	char* fileText = NULL;
	llog( LOG_INFO, "Stream size: %i", (int)SDL_RWsize( rwopsFile ) );
	while( ( numRead = SDL_RWread( rwopsFile, (void*)buffer, sizeof( char ), sizeof( buffer ) ) ) != 0 ) {
		char* c = sb_Add( fileText, (int)numRead );
		for( size_t i = 0; i < numRead; ++i ) {
			*c++ = buffer[i];
		}
	}
	sb_Push( fileText, 0 ); // make this c-string compatible

	// got the entire file text, now tokenize and parse
	//  only tokens we're worried about are '=' and '/r/n'
	//  everything before the '=' is the attribute name, everything
	//  after is the attribute value, all white space should be cut
	//  off of each end
	int gettingAttrName = 1;
	const char* delimiters = "\f\v\t =\r\n";
	char* token = strtok( fileText, delimiters );
	CFGAttribute attr;

	while( token != NULL ) {

		// cut off white space, don't care about preserving memory
		if( gettingAttrName ) {
			SDL_strlcpy( attr.fileName, token, sizeof( attr.fileName ) - 1 );
			attr.fileName[sizeof( attr.fileName ) - 1] = 0;
			gettingAttrName = 0;
		} else {
			attr.value = SDL_atoi( token );
			sb_Push( newFile->sbAttributes, attr );
			llog( LOG_INFO, "New attribute: %s  %i", attr.fileName, attr.value );
			gettingAttrName = 1;
		}

		token = strtok( NULL, delimiters );
	}

	sb_Release( fileText );
	SDL_RWclose( rwopsFile );

	return newFile;
}
Esempio n. 24
0
int main(int argc, char *argv[])
{
	int i;
	SDL_Event event;
	Uint32 then, now, frames;
	FPSmanager fpsm;

	/* Initialize test framework */
	state = SDLTest_CommonCreateState(argv, SDL_INIT_VIDEO);
	if (!state) {
		return 1;
	}

    SDL_Log("SDL2_gfx %i.%i.%i: testframerate", SDL2_GFXPRIMITIVES_MAJOR, SDL2_GFXPRIMITIVES_MINOR, SDL2_GFXPRIMITIVES_MICRO);
    SDL_Log("Platform: %s", SDL_GetPlatform());

	for (i = 1; i < argc;) {
		int consumed;

		consumed = SDLTest_CommonArg(state, i);
		if (consumed == 0) {
                   consumed = -1;
                   if (SDL_strcasecmp(argv[i], "--x") == 0) {
                      if (argv[i + 1]) {
						  x = SDL_atoi(argv[i + 1]);
                         if (x < 0) x = 0;
                         if (x >= WIDTH) x = WIDTH - 1;
                         consumed = 2;
                      }
				   }
                   else if (SDL_strcasecmp(argv[i], "--y") == 0) {
                      if (argv[i + 1]) {
                         y = SDL_atoi(argv[i + 1]);
                         if (y < 0) y = 0;
                         if (y >= HEIGHT) y = HEIGHT - 1;
                         consumed = 2;
                      }
                   }
                }
                
		if (consumed < 0) {
			SDL_Log("Usage: %s %s [--x #] [--y #]\n",
				argv[0], SDLTest_CommonUsage(state));
			return 1;
		}
		i += consumed;
	}
	if (!SDLTest_CommonInit(state)) {
		return 2;
	}

	/* Create the windows and initialize the renderers */
	for (i = 0; i < state->num_windows; ++i) {
		SDL_Renderer *renderer = state->renderers[i];
                SDL_RendererInfo info;
                SDL_GetRendererInfo(state->renderers[i], &info);		                
                SDL_Log("Renderer %i: %s %s", i, info.name, (info.flags | SDL_RENDERER_ACCELERATED) ? "(Accelerated)" : "");		
		SDL_SetRenderDrawColor(renderer, 0xA0, 0xA0, 0xA0, 0xFF);
		SDL_RenderClear(renderer);
	}

	/* Initialize random number generator */
	srand((unsigned int)time(NULL));

	/* Create common message buffer */
	messageText = (char *)SDL_malloc(1024);
	if (messageText == NULL) {
		return -1;
	}

	/* Initialize framerate manager */
	SDL_initFramerate(&fpsm);

	/* Main render loop */
	frames = 0;
	then = SDL_GetTicks();
	done = 0;
	while (!done) {
		/* Check for events */
		++frames;
		while (SDL_PollEvent(&event) && !done) {
			SDLTest_CommonEvent(state, &event, &done);
		}

        /* Do all the drawing work */
		Draw(state->renderers[0], &fpsm);
	}

	/* Print out some timing information */
	now = SDL_GetTicks();
	if (now > then) {
		double fps = ((double) frames * 1000) / (now - then);
		SDL_Log("%2.2f frames per second\n", fps);
	}

	/* Free common message buffer */
	if (messageText) {
		free(messageText);
	}

	/* Shutdown SDL */
	SDLTest_CommonQuit(state);

	return 0;
}
Esempio n. 25
0
int
main(int argc, char *argv[])
{
    int fsaa, accel;
    int value;
    int i, done;
    SDL_DisplayMode mode;
    SDL_Event event;
    Uint32 then, now, frames;
    int status;

    /* Initialize parameters */
    fsaa = 0;
    accel = 0;

    /* Initialize test framework */
    state = CommonCreateState(argv, SDL_INIT_VIDEO);
    if (!state) {
        return 1;
    }
    for (i = 1; i < argc;) {
        int consumed;

        consumed = CommonArg(state, i);
        if (consumed == 0) {
            if (SDL_strcasecmp(argv[i], "--fsaa") == 0) {
                ++fsaa;
                consumed = 1;
            } else if (SDL_strcasecmp(argv[i], "--accel") == 0) {
                ++accel;
                consumed = 1;
            } else if (SDL_strcasecmp(argv[i], "--zdepth") == 0) {
                i++;
                if (!argv[i]) {
                    consumed = -1;
                } else {
                    depth = SDL_atoi(argv[i]);
                    consumed = 1;
                }
            } else {
                consumed = -1;
            }
        }
        if (consumed < 0) {
            fprintf(stderr, "Usage: %s %s [--fsaa] [--accel] [--zdepth %%d]\n", argv[0],
                    CommonUsage(state));
            quit(1);
        }
        i += consumed;
    }

    /* Set OpenGL parameters */
    state->window_flags |= SDL_WINDOW_OPENGL;
    state->gl_red_size = 5;
    state->gl_green_size = 5;
    state->gl_blue_size = 5;
    state->gl_depth_size = depth;
    if (fsaa) {
        state->gl_multisamplebuffers=1;
        state->gl_multisamplesamples=fsaa;
    }
    if (accel) {
        state->gl_accelerated=1;
    }
    if (!CommonInit(state)) {
        quit(2);
    }

    context = SDL_calloc(state->num_windows, sizeof(context));
    if (context == NULL) {
        fprintf(stderr, "Out of memory!\n");
        quit(2);
    }

    /* Create OpenGL ES contexts */
    for (i = 0; i < state->num_windows; i++) {
        context[i] = SDL_GL_CreateContext(state->windows[i]);
        if (!context[i]) {
            fprintf(stderr, "SDL_GL_CreateContext(): %s\n", SDL_GetError());
            quit(2);
        }
    }

    if (state->render_flags & SDL_RENDERER_PRESENTVSYNC) {
        SDL_GL_SetSwapInterval(1);
    } else {
        SDL_GL_SetSwapInterval(0);
    }

    SDL_GetCurrentDisplayMode(&mode);
    printf("Screen bpp: %d\n", SDL_BITSPERPIXEL(mode.format));
    printf("\n");
    printf("Vendor     : %s\n", glGetString(GL_VENDOR));
    printf("Renderer   : %s\n", glGetString(GL_RENDERER));
    printf("Version    : %s\n", glGetString(GL_VERSION));
    printf("Extensions : %s\n", glGetString(GL_EXTENSIONS));
    printf("\n");

    status = SDL_GL_GetAttribute(SDL_GL_RED_SIZE, &value);
    if (!status) {
        printf("SDL_GL_RED_SIZE: requested %d, got %d\n", 5, value);
    } else {
        fprintf(stderr, "Failed to get SDL_GL_RED_SIZE: %s\n",
                SDL_GetError());
    }
    status = SDL_GL_GetAttribute(SDL_GL_GREEN_SIZE, &value);
    if (!status) {
        printf("SDL_GL_GREEN_SIZE: requested %d, got %d\n", 5, value);
    } else {
        fprintf(stderr, "Failed to get SDL_GL_GREEN_SIZE: %s\n",
                SDL_GetError());
    }
    status = SDL_GL_GetAttribute(SDL_GL_BLUE_SIZE, &value);
    if (!status) {
        printf("SDL_GL_BLUE_SIZE: requested %d, got %d\n", 5, value);
    } else {
        fprintf(stderr, "Failed to get SDL_GL_BLUE_SIZE: %s\n",
                SDL_GetError());
    }
    status = SDL_GL_GetAttribute(SDL_GL_DEPTH_SIZE, &value);
    if (!status) {
        printf("SDL_GL_DEPTH_SIZE: requested %d, got %d\n", depth, value);
    } else {
        fprintf(stderr, "Failed to get SDL_GL_DEPTH_SIZE: %s\n",
                SDL_GetError());
    }
    if (fsaa) {
        status = SDL_GL_GetAttribute(SDL_GL_MULTISAMPLEBUFFERS, &value);
        if (!status) {
            printf("SDL_GL_MULTISAMPLEBUFFERS: requested 1, got %d\n", value);
        } else {
            fprintf(stderr, "Failed to get SDL_GL_MULTISAMPLEBUFFERS: %s\n",
                    SDL_GetError());
        }
        status = SDL_GL_GetAttribute(SDL_GL_MULTISAMPLESAMPLES, &value);
        if (!status) {
            printf("SDL_GL_MULTISAMPLESAMPLES: requested %d, got %d\n", fsaa,
                   value);
        } else {
            fprintf(stderr, "Failed to get SDL_GL_MULTISAMPLESAMPLES: %s\n",
                    SDL_GetError());
        }
    }
    if (accel) {
        status = SDL_GL_GetAttribute(SDL_GL_ACCELERATED_VISUAL, &value);
        if (!status) {
            printf("SDL_GL_ACCELERATED_VISUAL: requested 1, got %d\n", value);
        } else {
            fprintf(stderr, "Failed to get SDL_GL_ACCELERATED_VISUAL: %s\n",
                    SDL_GetError());
        }
    }

    /* Set rendering settings for each context */
    for (i = 0; i < state->num_windows; ++i) {
        status = SDL_GL_MakeCurrent(state->windows[i], context[i]);
        if (status) {
            printf("SDL_GL_MakeCurrent(): %s\n", SDL_GetError());

            /* Continue for next window */
            continue;
        }

        glViewport(0, 0, state->window_w, state->window_h);
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        glOrthof(-2.0, 2.0, -2.0, 2.0, -20.0, 20.0);
        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();
        glEnable(GL_DEPTH_TEST);
        glDepthFunc(GL_LESS);
        glShadeModel(GL_SMOOTH);
    }

    /* Main render loop */
    frames = 0;
    then = SDL_GetTicks();
    done = 0;
    while (!done) {
        /* Check for events */
        ++frames;
        while (SDL_PollEvent(&event)) {
            switch (event.type) {
            case SDL_WINDOWEVENT:
                switch (event.window.event) {
                    case SDL_WINDOWEVENT_RESIZED:
                        for (i = 0; i < state->num_windows; ++i) {
                            if (event.window.windowID == state->windows[i]) {
                                status = SDL_GL_MakeCurrent(state->windows[i], context[i]);
                                if (status) {
                                    printf("SDL_GL_MakeCurrent(): %s\n", SDL_GetError());
                                    break;
                                }
                                /* Change view port to the new window dimensions */
                                glViewport(0, 0, event.window.data1, event.window.data2);
                                /* Update window content */
                                Render();
                                SDL_GL_SwapWindow(state->windows[i]);
                                break;
                            }
                        }
                        break;
                }
            }
            CommonEvent(state, &event, &done);
        }
        for (i = 0; i < state->num_windows; ++i) {
            status = SDL_GL_MakeCurrent(state->windows[i], context[i]);
            if (status) {
                printf("SDL_GL_MakeCurrent(): %s\n", SDL_GetError());

                /* Continue for next window */
                continue;
            }
            Render();
            SDL_GL_SwapWindow(state->windows[i]);
        }
    }

    /* Print out some timing information */
    now = SDL_GetTicks();
    if (now > then) {
        printf("%2.2f frames per second\n",
               ((double) frames * 1000) / (now - then));
    }
    quit(0);
    return 0;
}
Esempio n. 26
0
/*
 * Initializes the haptic subsystem.
 */
int
SDL_SYS_HapticInit(void)
{
    const char *env = SDL_GetHint(SDL_HINT_XINPUT_ENABLED);
    HRESULT ret;
    HINSTANCE instance;

    if (dinput != NULL) {       /* Already open. */
        return SDL_SetError("Haptic: SubSystem already open.");
    }

    /* Clear all the memory. */
    SDL_memset(SDL_hapticlist, 0, sizeof(SDL_hapticlist));

    SDL_numhaptics = 0;

    ret = WIN_CoInitialize();
    if (FAILED(ret)) {
        return DI_SetError("Coinitialize", ret);
    }

    coinitialized = SDL_TRUE;

    ret = CoCreateInstance(&CLSID_DirectInput8, NULL, CLSCTX_INPROC_SERVER,
                           &IID_IDirectInput8, (LPVOID) & dinput);
    if (FAILED(ret)) {
        SDL_SYS_HapticQuit();
        return DI_SetError("CoCreateInstance", ret);
    }

    /* Because we used CoCreateInstance, we need to Initialize it, first. */
    instance = GetModuleHandle(NULL);
    if (instance == NULL) {
        SDL_SYS_HapticQuit();
        return SDL_SetError("GetModuleHandle() failed with error code %d.",
                            GetLastError());
    }
    ret = IDirectInput8_Initialize(dinput, instance, DIRECTINPUT_VERSION);
    if (FAILED(ret)) {
        SDL_SYS_HapticQuit();
        return DI_SetError("Initializing DirectInput device", ret);
    }

    /* Look for haptic devices. */
    ret = IDirectInput8_EnumDevices(dinput,
                                   0,
                                   EnumHapticsCallback,
                                   NULL,
                                   DIEDFL_FORCEFEEDBACK |
                                   DIEDFL_ATTACHEDONLY);
    if (FAILED(ret)) {
        SDL_SYS_HapticQuit();
        return DI_SetError("Enumerating DirectInput devices", ret);
    }

    if (!env || SDL_atoi(env)) {
        loaded_xinput = (WIN_LoadXInputDLL() == 0);
    }

    if (loaded_xinput) {
        DWORD i;
        const SDL_bool bIs14OrLater = (SDL_XInputVersion >= ((1<<16)|4));

        for (i = 0; (i < SDL_XINPUT_MAX_DEVICES) && (SDL_numhaptics < MAX_HAPTICS); i++) {
            XINPUT_CAPABILITIES caps;
            if (XINPUTGETCAPABILITIES(i, XINPUT_FLAG_GAMEPAD, &caps) == ERROR_SUCCESS) {
                if ((!bIs14OrLater) || (caps.Flags & XINPUT_CAPS_FFB_SUPPORTED)) {
                    /* !!! FIXME: I'm not bothering to query for a real name right now. */
                    char buf[64];
                    SDL_snprintf(buf, sizeof (buf), "XInput Controller #%u", i+1);
                    SDL_hapticlist[SDL_numhaptics].name = SDL_strdup(buf);
                    SDL_hapticlist[SDL_numhaptics].bXInputHaptic = 1;
                    SDL_hapticlist[SDL_numhaptics].userid = (Uint8) i;
                    SDL_numhaptics++;
                }
            }
        }
    }

    return SDL_numhaptics;
}
Esempio n. 27
0
int main(int argc, char *argv[])
{
    std::vector<std::string> args;
    for(int i = 0; i < argc; i++)
        args.emplace_back(argv[i]);

    #ifdef __EMSCRIPTEN__
    args.emplace_back(PGE_RUN_SINGLE_LEVEL);
    #endif

    // Parse --version or --install low args
    if(!PGEEngineApp::parseLowArgs(args))
        return 0;

    // RAII for loaded/initialized libraries and modules
    PGEEngineApp  app;
    //Initialize Qt's subsystem
    AppPathManager::initAppPath();
    //Load settings
    app.loadSettings();
    //Init log writer
    app.loadLogger();
    //Initialize translation sub-system
    app.loadTr();
    // Parse high arguments
    app.parseHighArgs(args);

    // Initializing SDL
    if(app.initSDL())
    {
        //% "Unable to init SDL!"
        PGE_Window::printSDLError(qtTrId("SDL_INIT_ERROR"));
        pLogDebug("<Application closed with failure>");
        return 1;
    }

    if(g_flags.audioEnabled && app.initAudio(g_flags.audioEnabled))
    {
        std::string msg = "Unable to load audio sub-system!\n";
        msg += app.errorAudio();
        msg += "\n\nContinuing without sound...";
        pLogWarning(msg.c_str());
        SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_WARNING,
                                 "Audio subsystem Error",
                                 msg.c_str(),
                                 nullptr);
        g_flags.audioEnabled = false;
    }

    if(app.initWindow(INITIAL_WINDOW_TITLE, g_flags.rendererType))
    {
        pLogDebug("<Application closed with failure>");
        return 1;
    }

    app.loadJoysticks();
    SDL_PumpEvents();

    if(g_AppSettings.fullScreen)
        pLogDebug("Toggle fullscreen...");

    #ifdef __APPLE__
    macosReceiveOpenFile();
    #endif

    PGE_Window::setFullScreen(g_AppSettings.fullScreen);
    GlRenderer::resetViewport();
    //Init font manager
    app.initFontBasics();
    pLogDebug("Showing window...");
    SDL_ShowWindow(PGE_Window::window);
    pLogDebug("Clear screen...");
    GlRenderer::clearScreen();
    GlRenderer::flush();
    GlRenderer::repaint();
    SDL_PumpEvents();
    /************************************************
     *      Check & ask for configuration pack      *
     ************************************************/
    //Process config manager screen
    {
        // Create configs folder if not exists
        app.createConfigsDir();
        // Initialize config selection screen
        ConfigSelectScene GOScene;

        // Are any config packs exists?
        if(!GOScene.hasConfigPacks())
        {
            pLogCritical("Config packs not found");
            SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR,
                                     //% "Config packs not found"
                                     qtTrId("ERROR_NO_CONFIG_PACKS_TTL").c_str(),
                                     /*% "Can't start game, because available\n"
                                         "configuration packages are not found!" */
                                     qtTrId("ERROR_NO_CONFIG_PACKS_TEXT").c_str(),
                                     PGE_Window::window);
            return 2;
        }

        std::string configPath_manager = GOScene.isPreLoaded();

        if(!g_fileToOpen.empty())
        {
            //% "Choose a game to test:"
            GOScene.setLabel(qtTrId("CONFIG_SELECT_TEST"));
        }

        //If application have ran a first time or target configuration is not exist
        if(configPath_manager.empty() && g_configPackPath.empty())
        {
            //Ask for configuration
            if(GOScene.exec() == 1)
                g_configPackPath = GOScene.currentConfigPath;
            else
                return 2;
        }
        else if(!configPath_manager.empty() && g_configPackPath.empty())
            g_configPackPath = GOScene.currentConfigPath;

        pLogDebug("Opening of the configuration package...");
        ConfigManager::setConfigPath(g_configPackPath);

        pLogDebug("Initialization of basic properties...");

        if(!ConfigManager::loadBasics())
        {
            pLogDebug("<Application closed with failure>");
            return 1;
        }

        app.enableConfigManager();

        if(!ConfigManager::config_name.empty())
            PGE_Window::setWindowTitle(ConfigManager::config_name);

        pLogDebug("Current scene resolution: %d x %d", PGE_Window::Width, PGE_Window::Height);
        pLogDebug("Config pack scene resolution: %d x %d", ConfigManager::viewport_width, ConfigManager::viewport_height);

        if(ConfigManager::viewport_width != static_cast<unsigned int>(PGE_Window::Width) ||
           ConfigManager::viewport_height != static_cast<unsigned int>(PGE_Window::Height))
        {
            PGE_Window::changeViewportResolution(ConfigManager::viewport_width, ConfigManager::viewport_height);
            pLogDebug("Using scene resolution: %d x %d", ConfigManager::viewport_width, ConfigManager::viewport_height);
        }

        pLogDebug("Configuration package successfully loaded!");

        if(g_flags.audioEnabled)
        {
            PGE_MusPlayer::setVolume(g_AppSettings.volume_music);
            pLogDebug("Build SFX index cache...");
            ConfigManager::buildSoundIndex(); //Load all sound effects into memory
        }

        //Init font manager
        app.initFontFull();
    }

    if(!g_fileToOpen.empty())
    {
        g_GameState.reset();
        //Apply custom game parameters from command line
        g_flags.applyTestSettings(g_GameState);

        if(Files::hasSuffix(g_fileToOpen, ".lvl") || Files::hasSuffix(g_fileToOpen, ".lvlx"))
        {
            g_GameState.LevelFile = g_fileToOpen;
            g_GameState.isEpisode = false;
            g_GameState.isTestingModeL = true;
            g_GameState.isTestingModeW = false;
            g_flags.testLevel = true;
            g_flags.testWorld = false;
            goto PlayLevel;
        }
        else if(Files::hasSuffix(g_fileToOpen, ".wld") || Files::hasSuffix(g_fileToOpen, ".wldx"))
        {
            g_Episode.character = 1;
            g_Episode.savefile = "save1.savx";
            g_Episode.worldfile = g_fileToOpen;
            g_GameState._episodePath = DirMan(Files::dirname(g_fileToOpen)).absolutePath() + "/";
            g_GameState.saveFileName = g_Episode.savefile;
            g_GameState.isEpisode = true;
            g_GameState.WorldFile = g_fileToOpen;
            g_GameState.isTestingModeL = false;
            g_GameState.isTestingModeW = true;
            g_flags.testLevel = false;
            g_flags.testWorld = true;
            goto PlayWorldMap;
        }
    }

    if(g_AppSettings.interprocessing)
    {
        //Apply custom game parameters from command line
        g_flags.applyTestSettings(g_GameState);
        goto PlayLevel;
    }

LoadingScreen:
    {
        LoadingScene ttl;
        ttl.setWaitTime(15000);
        ttl.init();
        ttl.m_fader.setFade(10, 0.0, 0.01);
        int ret = ttl.exec();

        if(ttl.doShutDown())
            ret = -1;

        if(ret == -1)
            goto ExitFromApplication;

        goto MainMenu;
    }
CreditsScreen:
    {
        CreditsScene ttl;
        ttl.setWaitTime(30000);
        ttl.init();
        ttl.m_fader.setFade(10, 0.0, 0.01);
        int ret = ttl.exec();

        if(ttl.doShutDown())
            ret = -1;

        if(ret == -1) goto ExitFromApplication;

        if(g_flags.testWorld)
            goto ExitFromApplication;

        goto MainMenu;
    }
GameOverScreen:
    {
        GameOverScene GOScene;
        int result = GOScene.exec();

        if(result == GameOverSceneResult::CONTINUE)
        {
            if(g_GameState.isHubLevel)
                goto PlayLevel;
            else
                goto PlayWorldMap;
        }

        if(g_flags.testWorld)
            goto ExitFromApplication;

        goto MainMenu;
    }
MainMenu:
    {
        g_GameState.reset();
        std::shared_ptr<TitleScene> iScene(new TitleScene());
        iScene->init();
        iScene->m_fader.setFade(10, 0.0, 0.02);
        int answer = iScene->exec();
        PlayLevelResult   res_level   = iScene->m_result_level;
        PlayEpisodeResult res_episode = iScene->m_result_episode;

        if(iScene->doShutDown())
            answer = TitleScene::ANSWER_EXIT;

        switch(answer)
        {
        case TitleScene::ANSWER_EXIT:
            goto ExitFromApplication;

        case TitleScene::ANSWER_CREDITS:
            goto CreditsScreen;

        case TitleScene::ANSWER_LOADING:
            goto LoadingScreen;

        case TitleScene::ANSWER_GAMEOVER:
            goto GameOverScreen;

        case TitleScene::ANSWER_PLAYLEVEL:
        {
            g_jumpOnLevelEndTo = RETURN_TO_MAIN_MENU;
            g_GameState.isEpisode = false;
            g_GameState.numOfPlayers = 1;
            g_GameState.LevelFile = res_level.levelfile;
            g_GameState._episodePath.clear();
            g_GameState.saveFileName.clear();
            g_GameState.isTestingModeL = true;
            goto PlayLevel;
        }

        case TitleScene::ANSWER_PLAYEPISODE:
        case TitleScene::ANSWER_PLAYEPISODE_2P:
        {
            g_jumpOnLevelEndTo = RETURN_TO_WORLDMAP;
            g_GameState.numOfPlayers = (answer == TitleScene::ANSWER_PLAYEPISODE_2P) ? 2 : 1;
            PlayerState plr;
            plr._chsetup = FileFormats::CreateSavCharacterState();
            plr.characterID = 1;
            plr.stateID = 1;
            plr._chsetup.id = 1;
            plr._chsetup.state = 1;
            g_GameState.setPlayerState(1, plr);
            plr.characterID = 2;
            plr.stateID = 1;
            plr._chsetup.id = 2;
            plr._chsetup.state = 1;
            g_GameState.setPlayerState(2, plr);
            g_GameState.isEpisode = true;
            g_Episode = res_episode;
            g_GameState._episodePath = DirMan(Files::dirname(g_Episode.worldfile)).absolutePath() + "/";
            g_GameState.saveFileName = g_Episode.savefile;
            g_GameState.load();
            goto PlayWorldMap;
        }

        default:
            goto PlayWorldMap;
        }

        //goto PlayLevel;
    }
PlayWorldMap:
    {
        WldExit::ExitWorldCodes wldExitCode = WldExit::EXIT_close;
        std::shared_ptr<WorldScene> wScene;
        wScene.reset(new WorldScene());
        bool sceneResult = true;

        if(g_Episode.worldfile.empty())
        {
            sceneResult = false;
            //% "No opened files"
            PGE_MsgBox::warn(qtTrId("ERROR_NO_OPEN_FILES_MSG"));

            if(g_AppSettings.debugMode || g_flags.testWorld)
                goto ExitFromApplication;
            else
                goto MainMenu;
        }
        else
        {
            sceneResult = wScene->loadFile(g_Episode.worldfile);
            wScene->setGameState(&g_GameState); //Load game state to the world map

            if(!sceneResult)
            {
                //% "ERROR:\nFail to start world map\n\n%1"
                PGE_MsgBox::error( fmt::qformat(qtTrId("ERROR_FAIL_START_WLD"), wScene->getLastError()) );
                wldExitCode = WldExit::EXIT_error;
            }
        }

        if(sceneResult)
            sceneResult = wScene->init();

        if(sceneResult)
            wScene->m_fader.setFade(10, 0.0, 0.02);

        if(sceneResult)
            wldExitCode = (WldExit::ExitWorldCodes)wScene->exec();

        if(!sceneResult)
        {
            wldExitCode = WldExit::EXIT_error;
            //% "World map was closed with error.\n%1"
            PGE_MsgBox::error( fmt::qformat(qtTrId("WLD_ERROR_LVLCLOSED"), wScene->errorString()) );
        }

        g_GameState._recent_ExitCode_world = (int)wldExitCode;

        if(wScene->doShutDown())
        {
            wScene.reset();
            goto ExitFromApplication;
        }

        if(g_AppSettings.debugMode)
        {
            if(wldExitCode == WldExit::EXIT_beginLevel)
            {
                std::string msg;
                //% "Start level\n%1"
                msg += fmt::qformat(qtTrId("MSG_START_LEVEL"), g_GameState.LevelFile) + "\n\n";
                //% "Type an exit code (signed integer)"
                msg += qtTrId("MSG_WLDTEST_EXIT_CODE");
                PGE_TextInputBox text(nullptr, msg, PGE_BoxBase::msg_info_light,
                                      PGE_Point(-1, -1),
                                      ConfigManager::setup_message_box.box_padding,
                                      ConfigManager::setup_message_box.sprite);
                text.exec();
                g_GameState._recent_ExitCode_level  = LvlExit::EXIT_Neutral;

                if(PGEFile::IsIntS(text.inputText()))
                    g_GameState._recent_ExitCode_level = SDL_atoi(text.inputText().c_str());

                if(g_GameState.isHubLevel)
                    goto ExitFromApplication;

                goto PlayWorldMap;
            }
            else
                goto ExitFromApplication;
        }

        switch(wldExitCode)
        {
        case WldExit::EXIT_beginLevel:
            goto PlayLevel;

        case WldExit::EXIT_close:
            break;

        case WldExit::EXIT_error:
            break;

        case WldExit::EXIT_exitNoSave:
            break;

        case WldExit::EXIT_exitWithSave:
            break;

        default:
            break;
        }

        if(g_flags.testWorld)
            goto ExitFromApplication;

        goto MainMenu;
    }
PlayLevel:
    {
        bool playAgain = true;
        unsigned long entranceID = 0;
        std::shared_ptr<LevelScene> lScene(nullptr);

        while(playAgain)
        {
            entranceID = g_GameState.LevelTargetWarp;

            if(g_GameState.LevelFile_hub == g_GameState.LevelFile)
            {
                g_GameState.isHubLevel = true;
                entranceID = g_GameState.game_state.last_hub_warp;
            }

            int levelExitCode = 0;
            lScene.reset(new LevelScene());

            if(g_AppSettings.interprocessing)
                g_GameState.isTestingModeL = true;

            lScene->setGameState(&g_GameState);
            bool sceneResult = true;

            if(g_GameState.LevelFile.empty())
            {
                if(g_AppSettings.interprocessing && IntProc::isEnabled())
                {
                    sceneResult = lScene->loadFileIP();

                    if((!sceneResult) && (!lScene->isExiting()))
                    {
                        //SDL_Delay(50);
                        levelExitCode = LvlExit::EXIT_Error;
                        PGE_MsgBox msgBox(nullptr, fmt::format_ne("ERROR:\nFail to start level\n\n{0}",
                                                lScene->getLastError()),
                                                PGE_MsgBox::msg_error);
                        msgBox.exec();
                    }
                }
                else
                {
                    sceneResult = false;
                    levelExitCode = LvlExit::EXIT_Error;
                    //% "No opened files"
                    PGE_MsgBox::warn(qtTrId("ERROR_NO_OPEN_FILES_MSG"));
                }
            }
            else
            {
                sceneResult = lScene->loadFile(g_GameState.LevelFile);

                if(!sceneResult)
                {
                    SDL_Delay(50);
                    PGE_MsgBox msgBox(nullptr,
                                      fmt::format_ne("ERROR:\nFail to start level\n\n"
                                                     "{0}", lScene->getLastError()),
                                      PGE_MsgBox::msg_error);
                    msgBox.exec();
                }
            }

            if(sceneResult)
                sceneResult = lScene->setEntrance(entranceID);

            if(sceneResult)
                sceneResult = lScene->init();

            if(sceneResult)
            {
                lScene->m_fader.setFade(10, 0.0, 0.02);
                levelExitCode = lScene->exec();
                g_GameState._recent_ExitCode_level = levelExitCode;
            }

            if(!sceneResult)
                levelExitCode = LvlExit::EXIT_Error;

            switch(levelExitCode)
            {
            case LvlExit::EXIT_Warp:
            {
                if(lScene->m_warpToWorld)
                {
                    g_GameState.game_state.worldPosX = lScene->toWorldXY().x();
                    g_GameState.game_state.worldPosY = lScene->toWorldXY().y();
                    g_GameState.LevelFile.clear();
                    entranceID = 0;
                    g_jumpOnLevelEndTo = g_GameState.isEpisode ? RETURN_TO_WORLDMAP : RETURN_TO_MAIN_MENU;
                }
                else
                {
                    g_GameState.LevelFile = lScene->toAnotherLevel();
                    g_GameState.LevelTargetWarp = lScene->toAnotherEntrance();
                    entranceID = g_GameState.LevelTargetWarp;

                    if(g_GameState.isHubLevel)
                    {
                        g_GameState.isHubLevel = false;
                        g_GameState.game_state.last_hub_warp = lScene->m_lastWarpID;
                    }
                }

                if(g_GameState.LevelFile.empty())
                    playAgain = false;

                if(g_AppSettings.debugMode)
                {
                    std::string target;

                    if(lScene->m_warpToWorld)
                    {
                        target = fmt::format_ne("X={0}, Y={1}",
                                 g_GameState.game_state.worldPosX,
                                 g_GameState.game_state.worldPosY);
                    }
                    else
                        target = g_GameState.LevelFile;

                    if(!target.empty())
                    {
                        //% "Warp exit\n\nExit into:\n%1\n\nEntrance point: %2"
                        PGE_MsgBox::warn( fmt::qformat(qtTrId("LVL_EXIT_WARP_INFO"), target, entranceID) );
                    }

                    playAgain = false;
                }
            }
            break;

            case LvlExit::EXIT_Closed:
            {
                g_jumpOnLevelEndTo = RETURN_TO_EXIT;
                playAgain = false;
            }
            break;

            case LvlExit::EXIT_ReplayRequest:
            {
                playAgain = true;
            }
            break;

            case LvlExit::EXIT_MenuExit:
            {
                g_jumpOnLevelEndTo = g_GameState.isEpisode ? RETURN_TO_WORLDMAP : RETURN_TO_MAIN_MENU;

                if(g_GameState.isHubLevel)
                    g_jumpOnLevelEndTo = g_flags.testLevel ? RETURN_TO_EXIT : RETURN_TO_MAIN_MENU;

                playAgain = false;
            }
            break;

            case LvlExit::EXIT_PlayerDeath:
            {
                playAgain = g_GameState.isEpisode ? g_GameState.replay_on_fail : true;
                g_jumpOnLevelEndTo = g_GameState.isEpisode ? RETURN_TO_WORLDMAP : RETURN_TO_MAIN_MENU;

                //check the number of player lives here and decided to return worldmap or gameover
                if(g_GameState.isEpisode)
                {
                    g_GameState.game_state.lives--;

                    if(g_GameState.game_state.lives < 0)
                    {
                        playAgain = false;
                        g_GameState.game_state.coins = 0;
                        g_GameState.game_state.points = 0;
                        g_GameState.game_state.lives = 3;
                        g_jumpOnLevelEndTo = RETURN_TO_GAMEOVER_SCREEN;
                    }
                }
            }
            break;

            case LvlExit::EXIT_Error:
            {
                g_jumpOnLevelEndTo = (g_GameState.isEpisode) ? RETURN_TO_WORLDMAP : RETURN_TO_MAIN_MENU;
                playAgain = false;
                //% "Level was closed with error.\n%1"
                PGE_MsgBox::error( fmt::qformat(qtTrId("LVL_ERROR_LVLCLOSED"), lScene->errorString()) );
            }
            break;

            default:
                g_jumpOnLevelEndTo = g_GameState.isEpisode ? RETURN_TO_WORLDMAP : RETURN_TO_MAIN_MENU;
                playAgain = false;
            }

            if(g_flags.testLevel || g_AppSettings.debugMode)
                g_jumpOnLevelEndTo = RETURN_TO_EXIT;

            ConfigManager::unloadLevelConfigs();
            lScene.reset();
        }

        if(g_AppSettings.interprocessing)
            goto ExitFromApplication;

        switch(g_jumpOnLevelEndTo)
        {
        case RETURN_TO_WORLDMAP:
            goto PlayWorldMap;

        case RETURN_TO_MAIN_MENU:
            goto MainMenu;

        case RETURN_TO_EXIT:
            goto ExitFromApplication;

        case RETURN_TO_GAMEOVER_SCREEN:
            goto GameOverScreen;

        case RETURN_TO_CREDITS_SCREEN:
            goto CreditsScreen;
        }
    }
ExitFromApplication:
    return 0;
}
Esempio n. 28
0
int
main(int argc, char *argv[])
{
    int i;
    Uint32 then, now, frames;
    Uint64 seed;
    const char *icon = "icon.bmp";

    /* Initialize parameters */
    num_sprites = NUM_SPRITES;

    /* Initialize test framework */
    state = SDLTest_CommonCreateState(argv, SDL_INIT_VIDEO);
    if (!state) {
        return 1;
    }

    for (i = 1; i < argc;) {
        int consumed;

        consumed = SDLTest_CommonArg(state, i);
        if (consumed == 0) {
            consumed = -1;
            if (SDL_strcasecmp(argv[i], "--blend") == 0) {
                if (argv[i + 1]) {
                    if (SDL_strcasecmp(argv[i + 1], "none") == 0) {
                        blendMode = SDL_BLENDMODE_NONE;
                        consumed = 2;
                    } else if (SDL_strcasecmp(argv[i + 1], "blend") == 0) {
                        blendMode = SDL_BLENDMODE_BLEND;
                        consumed = 2;
                    } else if (SDL_strcasecmp(argv[i + 1], "add") == 0) {
                        blendMode = SDL_BLENDMODE_ADD;
                        consumed = 2;
                    } else if (SDL_strcasecmp(argv[i + 1], "mod") == 0) {
                        blendMode = SDL_BLENDMODE_MOD;
                        consumed = 2;
                    }
                }
            } else if (SDL_strcasecmp(argv[i], "--iterations") == 0) {
                if (argv[i + 1]) {
                    iterations = SDL_atoi(argv[i + 1]);
                    if (iterations < -1) iterations = -1;
                    consumed = 2;
                }
            } else if (SDL_strcasecmp(argv[i], "--cyclecolor") == 0) {
                cycle_color = SDL_TRUE;
                consumed = 1;
            } else if (SDL_strcasecmp(argv[i], "--cyclealpha") == 0) {
                cycle_alpha = SDL_TRUE;
                consumed = 1;
            } else if (SDL_isdigit(*argv[i])) {
                num_sprites = SDL_atoi(argv[i]);
                consumed = 1;
            } else if (argv[i][0] != '-') {
                icon = argv[i];
                consumed = 1;
            }
        }
        if (consumed < 0) {
            SDL_Log("Usage: %s %s [--blend none|blend|add|mod] [--cyclecolor] [--cyclealpha] [--iterations N] [num_sprites] [icon.bmp]\n",
                    argv[0], SDLTest_CommonUsage(state));
            quit(1);
        }
        i += consumed;
    }
    if (!SDLTest_CommonInit(state)) {
        quit(2);
    }

    /* Create the windows, initialize the renderers, and load the textures */
    sprites =
        (SDL_Texture **) SDL_malloc(state->num_windows * sizeof(*sprites));
    if (!sprites) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Out of memory!\n");
        quit(2);
    }
    for (i = 0; i < state->num_windows; ++i) {
        SDL_Renderer *renderer = state->renderers[i];
        SDL_SetRenderDrawColor(renderer, 0xA0, 0xA0, 0xA0, 0xFF);
        SDL_RenderClear(renderer);
    }
    if (LoadSprite(icon) < 0) {
        quit(2);
    }

    /* Allocate memory for the sprite info */
    positions = (SDL_Rect *) SDL_malloc(num_sprites * sizeof(SDL_Rect));
    velocities = (SDL_Rect *) SDL_malloc(num_sprites * sizeof(SDL_Rect));
    if (!positions || !velocities) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Out of memory!\n");
        quit(2);
    }

    /* Position sprites and set their velocities using the fuzzer */ 
    if (iterations >= 0) {
        /* Deterministic seed - used for visual tests */
        seed = (Uint64)iterations;
    } else {
        /* Pseudo-random seed generated from the time */
        seed = (Uint64)time(NULL);
    }
    SDLTest_FuzzerInit(seed);
    for (i = 0; i < num_sprites; ++i) {
        positions[i].x = SDLTest_RandomIntegerInRange(0, state->window_w - sprite_w);
        positions[i].y = SDLTest_RandomIntegerInRange(0, state->window_h - sprite_h);
        positions[i].w = sprite_w;
        positions[i].h = sprite_h;
        velocities[i].x = 0;
        velocities[i].y = 0;
        while (!velocities[i].x && !velocities[i].y) {
            velocities[i].x = SDLTest_RandomIntegerInRange(-MAX_SPEED, MAX_SPEED);
            velocities[i].y = SDLTest_RandomIntegerInRange(-MAX_SPEED, MAX_SPEED);
        }
    }

    /* Main render loop */
    frames = 0;
    then = SDL_GetTicks();
    done = 0;

#ifdef __EMSCRIPTEN__
    emscripten_set_main_loop(loop, 0, 1);
#else
    while (!done) {
        ++frames;
        loop();
    }
#endif

    /* Print out some timing information */
    now = SDL_GetTicks();
    if (now > then) {
        double fps = ((double) frames * 1000) / (now - then);
        SDL_Log("%2.2f frames per second\n", fps);
    }
    quit(0);
    return 0;
}
Esempio n. 29
0
SDL_bool
SDL_GetPowerInfo_Linux_sys_class_power_supply(SDL_PowerState *state, int *seconds, int *percent)
{
    const char *base = sys_class_power_supply_path;
    struct dirent *dent;
    DIR *dirp;

    dirp = opendir(base);
    if (!dirp) {
        return SDL_FALSE;
    }

    *state = SDL_POWERSTATE_NO_BATTERY;  /* assume we're just plugged in. */
    *seconds = -1;
    *percent = -1;

    while ((dent = readdir(dirp)) != NULL) {
        const char *name = dent->d_name;
        SDL_bool choose = SDL_FALSE;
        char str[64];
        SDL_PowerState st;
        int secs;
        int pct;

        if ((SDL_strcmp(name, ".") == 0) || (SDL_strcmp(name, "..") == 0)) {
            continue;  /* skip these, of course. */
        } else if (!read_power_file(base, name, "type", str, sizeof (str))) {
            continue;  /* Don't know _what_ we're looking at. Give up on it. */
        } else if (SDL_strcmp(str, "Battery\n") != 0) {
            continue;  /* we don't care about UPS and such. */
        }

        /* some drivers don't offer this, so if it's not explicitly reported assume it's present. */
        if (read_power_file(base, name, "present", str, sizeof (str)) && (SDL_strcmp(str, "0\n") == 0)) {
            st = SDL_POWERSTATE_NO_BATTERY;
        } else if (!read_power_file(base, name, "status", str, sizeof (str))) {
            st = SDL_POWERSTATE_UNKNOWN;  /* uh oh */
        } else if (SDL_strcmp(str, "Charging\n") == 0) {
            st = SDL_POWERSTATE_CHARGING;
        } else if (SDL_strcmp(str, "Discharging\n") == 0) {
            st = SDL_POWERSTATE_ON_BATTERY;
        } else if ((SDL_strcmp(str, "Full\n") == 0) || (SDL_strcmp(str, "Not charging\n") == 0)) {
            st = SDL_POWERSTATE_CHARGED;
        } else {
            st = SDL_POWERSTATE_UNKNOWN;  /* uh oh */
        }

        if (!read_power_file(base, name, "capacity", str, sizeof (str))) {
            pct = -1;
        } else {
            pct = SDL_atoi(str);
            pct = (pct > 100) ? 100 : pct; /* clamp between 0%, 100% */
        }

        if (!read_power_file(base, name, "time_to_empty_now", str, sizeof (str))) {
            secs = -1;
        } else {
            secs = SDL_atoi(str);
            secs = (secs <= 0) ? -1 : secs;  /* 0 == unknown */
        }

        /*
         * We pick the battery that claims to have the most minutes left.
         *  (failing a report of minutes, we'll take the highest percent.)
         */
        if ((secs < 0) && (*seconds < 0)) {
            if ((pct < 0) && (*percent < 0)) {
                choose = SDL_TRUE;  /* at least we know there's a battery. */
            } else if (pct > *percent) {
                choose = SDL_TRUE;
            }
        } else if (secs > *seconds) {
            choose = SDL_TRUE;
        }

        if (choose) {
            *seconds = secs;
            *percent = pct;
            *state = st;
        }
    }

    closedir(dirp);
    return SDL_TRUE;  /* don't look any further. */
}
Esempio n. 30
0
int
CommonArg(CommonState * state, int index)
{
    char **argv = state->argv;

    if (SDL_strcasecmp(argv[index], "--video") == 0) {
        ++index;
        if (!argv[index]) {
            return -1;
        }
        state->videodriver = argv[index];
        return 2;
    }
    if (SDL_strcasecmp(argv[index], "--renderer") == 0) {
        ++index;
        if (!argv[index]) {
            return -1;
        }
        state->renderdriver = argv[index];
        return 2;
    }
    if (SDL_strcasecmp(argv[index], "--info") == 0) {
        ++index;
        if (!argv[index]) {
            return -1;
        }
        if (SDL_strcasecmp(argv[index], "all") == 0) {
            state->verbose |=
                (VERBOSE_VIDEO | VERBOSE_MODES | VERBOSE_RENDER |
                 VERBOSE_EVENT);
            return 2;
        }
        if (SDL_strcasecmp(argv[index], "video") == 0) {
            state->verbose |= VERBOSE_VIDEO;
            return 2;
        }
        if (SDL_strcasecmp(argv[index], "modes") == 0) {
            state->verbose |= VERBOSE_MODES;
            return 2;
        }
        if (SDL_strcasecmp(argv[index], "render") == 0) {
            state->verbose |= VERBOSE_RENDER;
            return 2;
        }
        if (SDL_strcasecmp(argv[index], "event") == 0) {
            state->verbose |= VERBOSE_EVENT;
            return 2;
        }
        return -1;
    }
    if (SDL_strcasecmp(argv[index], "--display") == 0) {
        ++index;
        if (!argv[index]) {
            return -1;
        }
        state->display = SDL_atoi(argv[index]);
        return 2;
    }
    if (SDL_strcasecmp(argv[index], "--fullscreen") == 0) {
        state->window_flags |= SDL_WINDOW_FULLSCREEN;
        state->num_windows = 1;
        return 1;
    }
    if (SDL_strcasecmp(argv[index], "--windows") == 0) {
        ++index;
        if (!argv[index] || !SDL_isdigit(*argv[index])) {
            return -1;
        }
        if (!(state->window_flags & SDL_WINDOW_FULLSCREEN)) {
            state->num_windows = SDL_atoi(argv[index]);
        }
        return 2;
    }
    if (SDL_strcasecmp(argv[index], "--title") == 0) {
        ++index;
        if (!argv[index]) {
            return -1;
        }
        state->window_title = argv[index];
        return 2;
    }
    if (SDL_strcasecmp(argv[index], "--center") == 0) {
        state->window_x = SDL_WINDOWPOS_CENTERED;
        state->window_y = SDL_WINDOWPOS_CENTERED;
        return 1;
    }
    if (SDL_strcasecmp(argv[index], "--position") == 0) {
        char *x, *y;
        ++index;
        if (!argv[index]) {
            return -1;
        }
        x = argv[index];
        y = argv[index];
        while (*y && *y != ',') {
            ++y;
        }
        if (!*y) {
            return -1;
        }
        *y++ = '\0';
        state->window_x = SDL_atoi(x);
        state->window_y = SDL_atoi(y);
        return 2;
    }
    if (SDL_strcasecmp(argv[index], "--geometry") == 0) {
        char *w, *h;
        ++index;
        if (!argv[index]) {
            return -1;
        }
        w = argv[index];
        h = argv[index];
        while (*h && *h != 'x') {
            ++h;
        }
        if (!*h) {
            return -1;
        }
        *h++ = '\0';
        state->window_w = SDL_atoi(w);
        state->window_h = SDL_atoi(h);
        return 2;
    }
    if (SDL_strcasecmp(argv[index], "--depth") == 0) {
        ++index;
        if (!argv[index]) {
            return -1;
        }
        state->depth = SDL_atoi(argv[index]);
        return 2;
    }
    if (SDL_strcasecmp(argv[index], "--refresh") == 0) {
        ++index;
        if (!argv[index]) {
            return -1;
        }
        state->refresh_rate = SDL_atoi(argv[index]);
        return 2;
    }
    if (SDL_strcasecmp(argv[index], "--vsync") == 0) {
        state->render_flags |= SDL_RENDERER_PRESENTVSYNC;
        return 1;
    }
    if (SDL_strcasecmp(argv[index], "--noframe") == 0) {
        state->window_flags |= SDL_WINDOW_BORDERLESS;
        return 1;
    }
    if (SDL_strcasecmp(argv[index], "--resize") == 0) {
        state->window_flags |= SDL_WINDOW_RESIZABLE;
        return 1;
    }
    if (SDL_strcasecmp(argv[index], "--minimize") == 0) {
        state->window_flags |= SDL_WINDOW_MINIMIZED;
        return 1;
    }
    if (SDL_strcasecmp(argv[index], "--maximize") == 0) {
        state->window_flags |= SDL_WINDOW_MAXIMIZED;
        return 1;
    }
    if (SDL_strcasecmp(argv[index], "--grab") == 0) {
        state->window_flags |= SDL_WINDOW_INPUT_GRABBED;
        return 1;
    }
    if (SDL_strcasecmp(argv[index], "--rate") == 0) {
        ++index;
        if (!argv[index]) {
            return -1;
        }
        state->audiospec.freq = SDL_atoi(argv[index]);
        return 2;
    }
    if (SDL_strcasecmp(argv[index], "--format") == 0) {
        ++index;
        if (!argv[index]) {
            return -1;
        }
        if (SDL_strcasecmp(argv[index], "U8") == 0) {
            state->audiospec.format = AUDIO_U8;
            return 2;
        }
        if (SDL_strcasecmp(argv[index], "S8") == 0) {
            state->audiospec.format = AUDIO_S8;
            return 2;
        }
        if (SDL_strcasecmp(argv[index], "U16") == 0) {
            state->audiospec.format = AUDIO_U16;
            return 2;
        }
        if (SDL_strcasecmp(argv[index], "U16LE") == 0) {
            state->audiospec.format = AUDIO_U16LSB;
            return 2;
        }
        if (SDL_strcasecmp(argv[index], "U16BE") == 0) {
            state->audiospec.format = AUDIO_U16MSB;
            return 2;
        }
        if (SDL_strcasecmp(argv[index], "S16") == 0) {
            state->audiospec.format = AUDIO_S16;
            return 2;
        }
        if (SDL_strcasecmp(argv[index], "S16LE") == 0) {
            state->audiospec.format = AUDIO_S16LSB;
            return 2;
        }
        if (SDL_strcasecmp(argv[index], "S16BE") == 0) {
            state->audiospec.format = AUDIO_S16MSB;
            return 2;
        }
        return -1;
    }
    if (SDL_strcasecmp(argv[index], "--channels") == 0) {
        ++index;
        if (!argv[index]) {
            return -1;
        }
        state->audiospec.channels = (Uint8) SDL_atoi(argv[index]);
        return 2;
    }
    if (SDL_strcasecmp(argv[index], "--samples") == 0) {
        ++index;
        if (!argv[index]) {
            return -1;
        }
        state->audiospec.samples = (Uint16) SDL_atoi(argv[index]);
        return 2;
    }
    if ((SDL_strcasecmp(argv[index], "-h") == 0)
        || (SDL_strcasecmp(argv[index], "--help") == 0)) {
        /* Print the usage message */
        return -1;
    }
    return 0;
}