示例#1
0
    bool SDLPlatform::_initialize()
    {
        m_touchpad = false;

        if( SDL_Init(SDL_INIT_EVERYTHING) < 0 )
        {
            LOGGER_CRITICAL(m_serviceProvider)("SDL initialization failed");
            return false;
        }

        const Char* sdlPlatform = SDL_GetPlatform();
        const int sdlRam = SDL_GetSystemRAM();

        m_platformName = Helper::stringizeString(m_serviceProvider, sdlPlatform);

        LOGGER_WARNING(m_serviceProvider)("Device info:"
            );

        LOGGER_WARNING(m_serviceProvider)("Platform: %s"
            , sdlPlatform
            );

        LOGGER_WARNING(m_serviceProvider)("RAM: %d MB"
            , sdlRam
            );

        m_sdlInput = new SDLInput();
        m_sdlInput->setServiceProvider(m_serviceProvider);
        if( !m_sdlInput->initialize() )
        {
            return false;
        }

        return true;
    }
示例#2
0
文件: trap.c 项目: Protovision/io-lua
int	trap_GetPlatform(lua_State *s)
{
	const char *platform;

	platform = SDL_GetPlatform();
	lua_pushstring(s, platform);
	return 1;
}
示例#3
0
文件: testsdl.c 项目: albertz/sdl
/**
 * @brief Main entry point.
 */
int main( int argc, char *argv[] )
{
   int failed;
   int rev;
   SDL_version ver;

   /* Get options. */
   parse_options( argc, argv );

   /* Defaults. */
   failed = 0;

   /* Print some text if verbose. */
   SDL_GetVersion( &ver );
   rev = SDL_GetRevision();
   SDL_ATprintVerbose( 1, "Running tests with SDL %d.%d.%d revision %d\n",
         ver.major, ver.minor, ver.patch, rev );

   /* Automatic tests. */
   if (run_platform)
      failed += test_platform();
   if (run_rwops)
      failed += test_rwops();
   if (run_rect)
      failed += test_rect();
   if (run_surface)
      failed += test_surface();
   if (run_render)
      failed += test_render();
   if (run_audio)
      failed += test_audio();

   /* Manual tests. */
   if (run_manual) {
   }

   /* Display more information if failed. */
   if (failed > 0) {
      SDL_ATprintErr( "Tests run with SDL %d.%d.%d revision %d\n",
            ver.major, ver.minor, ver.patch, rev );
      SDL_ATprintErr( "System is running %s and is %s endian\n",
            SDL_GetPlatform(),
#if SDL_BYTEORDER == SDL_LIL_ENDIAN
            "little"
#else
            "big"
#endif
            );
   }

   return failed;
}
示例#4
0
static int _SaveMappings()
{
    char bind[2056];
    const char* name;

    if (_this->controller != NULL) {    
        name = SDL_GameControllerName(_this->controller);
    } else {
        name = SDL_JoystickName(_this->joystick);
    }

    SDL_JoystickGUID guid = SDL_JoystickGetGUID(_this->joystick);
    
    char guid_string[33];
    SDL_JoystickGetGUIDString(guid, guid_string, 33);
    guid_string[32] = 0;

    snprintf(bind, 2056, "%s,%s,platform:%s,", guid_string, name, SDL_GetPlatform());

    int index = strlen(bind);
    for (int i = 0; i < NUM_MAPPINGS; ++i) {
        const char* to = NULL;
        if (_this->mappings[i].type == SDL_CONTROLLER_BINDTYPE_AXIS) {
            to = SDL_GameControllerGetStringForAxis(_this->mappings[i].value.axis);
        } else if (_this->mappings[i].type != SDL_CONTROLLER_BINDTYPE_BUTTON){
            to = SDL_GameControllerGetStringForButton(_this->mappings[i].value.button);
        } 

        if (to == NULL) {
            continue;
        }

        char from[10];
        if (_this->mappings[i].bind.bindType == SDL_CONTROLLER_BINDTYPE_AXIS) {
            snprintf(from, 10, "a%d", _this->mappings[i].bind.value.axis);
        } else if (_this->mappings[i].bind.bindType
                   == SDL_CONTROLLER_BINDTYPE_BUTTON) {
            snprintf(from, 10, "b%d", _this->mappings[i].bind.value.button);
        } if (_this->mappings[i].bind.bindType == SDL_CONTROLLER_BINDTYPE_HAT) {
            snprintf(from, 10, "h%d.%d", _this->mappings[i].bind.value.hat.hat,
                    _this->mappings[i].bind.value.hat.hat_mask);
        } else {
            continue;
        }
        snprintf(bind, 2056 - index, "%s:%s,", to, from);
        index += strlen(to) + strlen(from);
    }
    SDL_GameControllerAddMapping(bind);
    // TODO Save to file
    SDL_Log("Mapping: %s\n", bind);
}
示例#5
0
    void QuerySystemInformation()
    {
        num_cpus = SDL_GetCPUCount();
        ram = SDL_GetSystemRAM();
        l1_cache = SDL_GetCPUCacheLineSize();

        const char *_vendor = reinterpret_cast<const char*>(glGetString(GL_VENDOR));
        const char *_renderer = reinterpret_cast<const char*>(glGetString(GL_RENDERER));
        const char *_version = reinterpret_cast<const char*>(glGetString(GL_VERSION));

        strcpy(platform, SDL_GetPlatform());
        strcpy(vendor, _vendor);
        strcpy(renderer, _renderer);
        strcpy(version, _version);
    }
示例#6
0
internal void OutputSystemInfo()
{
	SDL_Log("System Info\n");
	int ram = SDL_GetSystemRAM();
	SDL_Log("Ram: %dMB\n", ram);

	int cpu_count = SDL_GetCPUCount();
	SDL_Log("CPU Count: %d\n", cpu_count);

	const char *platform = SDL_GetPlatform();
	SDL_Log("Platform: %s\n", platform);


	int display_num = SDL_GetNumVideoDisplays();
	SDL_Log("Display Count: %d\n", display_num);

	for (int i = 0; i < display_num; i++)
	{
		SDL_Rect rect;
		SDL_GetDisplayBounds(i, &rect);
		const char *name = SDL_GetDisplayName(i);

		SDL_Log("Display: %s\n", name);
		SDL_Log("-X: %d, ", rect.x);
		SDL_Log("Y: %d, ", rect.y);
		SDL_Log("Width: %d, ", rect.w);
		SDL_Log("Height: %d\n", rect.h);


		for (int j = 0; j < SDL_GetNumDisplayModes(i); j++)
		{
			SDL_DisplayMode mode;
			SDL_GetDisplayMode(i, j, &mode);
			SDL_Log("--Mode: \n");
			SDL_Log("---Width: %d\n", mode.w);
			SDL_Log("---Height: %d\n", mode.h);
			SDL_Log("---Refresh Rate: %d\n", mode.refresh_rate);
		}
	}
}
示例#7
0
文件: system.c 项目: dns/CLove
const char* system_getOS() {
    return SDL_GetPlatform();
}
示例#8
0
void Client::initSDL()
{
    Debug::log(Debug::Area::StartupArea) << "SDL on platform: " << SDL_GetPlatform();

    SDL_version compiled;
    SDL_version linked;
    SDL_VERSION(&compiled);
    SDL_GetVersion(&linked);

    Debug::log(Debug::Area::StartupArea) << "Compiled against SDL version: " << int(compiled.major) << "." << int(compiled.minor) << "-" << int(compiled.patch) <<
                                         " Running (linked) against version: " << int(linked.major) << "." << int(linked.minor) << "-" << int(linked.patch);

    if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER) != 0) {
        std::string error = SDL_GetError();
        Debug::fatal(false, Debug::Area::ImportantArea, "failure to initialize SDL error: " + error);
    }

    m_window = SDL_CreateWindow("Ore Infinium", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
                                Settings::instance()->windowWidth, Settings::instance()->windowHeight, SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL);

    if (!m_window) {
        Debug::checkSDLError();
    }

    int ret = IMG_Init(IMG_INIT_PNG);
    assert(ret != 0);

//    glewExperimental = GL_TRUE;
    SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
    SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
    SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);

    // Request opengl 3.3 context.
    // FIXME: i *want 3.2, but Mesa 9 only has 3.0.. :(
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_COMPATIBILITY);

    /* Turn on double buffering with a 24bit Z buffer.
     * You may need to change this to 16 or 32 for your system */
    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
    SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);

    //TODO: we'll probably need some extension at some point in time..
    //SDL_GL_ExtensionSupported();

    m_GLcontext = SDL_GL_CreateContext(m_window);
    Debug::assertf(m_GLcontext != nullptr, "SDL GL Context creation failure! Context nullptr.");
    Debug::checkGLError();

    //FIXME: doesn't do shit
    SDL_GL_SetSwapInterval(1);

    Debug::checkSDLError();
    Debug::checkGLError();

    SDL_ShowCursor(0);

    Debug::checkSDLError();
    Debug::checkGLError();

    glewExperimental = true;

    int retGLEW = glewInit();

    Debug::log(Debug::Area::StartupArea) << "glewInit return code: " << retGLEW;

    for(int i = 0; i < 100; ++i) {
      Debug::checkGLErrorSafe();
    }

    Debug::checkGLError();


    Debug::assertf(retGLEW == GLEW_OK, "glewInit returned !GLEW_OK. No GL context can be formed..bailing out");

    Debug::checkGLError();

    Debug::log(Debug::Area::StartupArea) << "Platform: Driver Vendor: " << glGetString(GL_VENDOR);
    Debug::log(Debug::Area::StartupArea) << "Platform: Renderer: " << glGetString(GL_RENDERER);
    Debug::log(Debug::Area::StartupArea) << "OpenGL Version: " << glGetString(GL_VERSION);
    Debug::log(Debug::Area::StartupArea) << "GLSL Version: " << glGetString(GL_SHADING_LANGUAGE_VERSION);

    Debug::checkGLError();

    GLint textureSize;
    glGetIntegerv(GL_MAX_TEXTURE_SIZE, &textureSize);
    Debug::log(Debug::Area::StartupArea) << "Maximum OpenGL texture size allowed: " << textureSize << "\n\n\n";

#ifdef GLEW_KHR_debug
    if (GLEW_KHR_debug) {
        glEnable(GL_DEBUG_OUTPUT);
        glDebugMessageCallback(&Debug::glDebugCallback, 0);
        glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, 0, GL_TRUE);
    } else {
        Debug::log(Debug::Area::ImportantArea) << "GLEW_KHR_debug is not available, disabling OpenGL debug reporting facilities. The extension was compiled in but is not available at runtime.";
    }
#endif

    Debug::fatal(enet_initialize() == 0, Debug::Area::ImportantArea, "An error occurred during ENet init (network init failure");

    //glClearColor(0.f, .5f, 0.f, 1.0f);
    glClearColor(1.0f, 1.0f, 1.0f, 1.0f);

    glViewport(0, 0, Settings::instance()->windowWidth, Settings::instance()->windowHeight);

    Debug::checkGLError();
}
static SDL_bool
WatchJoystick(SDL_Joystick * joystick)
{
    SDL_Window *window = NULL;
    SDL_Renderer *screen = NULL;
    SDL_Texture *background, *button, *axis, *marker;
    const char *name = NULL;
    SDL_bool retval = SDL_FALSE;
    SDL_bool done = SDL_FALSE, next=SDL_FALSE;
    SDL_Event event;
    SDL_Rect dst;
    int s, _s;
    Uint8 alpha=200, alpha_step = -1;
    Uint32 alpha_ticks;
    char mapping[4096], temp[4096];
    MappingStep *step;
    MappingStep steps[] = {
        {342, 132,  0.0,  MARKER_BUTTON, "x", -1, -1, -1, -1, ""},
        {387, 167,  0.0,  MARKER_BUTTON, "a", -1, -1, -1, -1, ""},
        {431, 132,  0.0,  MARKER_BUTTON, "b", -1, -1, -1, -1, ""},
        {389, 101,  0.0,  MARKER_BUTTON, "y", -1, -1, -1, -1, ""},
        {174, 132,  0.0,  MARKER_BUTTON, "back", -1, -1, -1, -1, ""},
        {233, 132,  0.0,  MARKER_BUTTON, "guide", -1, -1, -1, -1, ""},
        {289, 132,  0.0,  MARKER_BUTTON, "start", -1, -1, -1, -1, ""},        
        {116, 217,  0.0,  MARKER_BUTTON, "dpleft", -1, -1, -1, -1, ""},
        {154, 249,  0.0,  MARKER_BUTTON, "dpdown", -1, -1, -1, -1, ""},
        {186, 217,  0.0,  MARKER_BUTTON, "dpright", -1, -1, -1, -1, ""},
        {154, 188,  0.0,  MARKER_BUTTON, "dpup", -1, -1, -1, -1, ""},
        {77,  40,   0.0,  MARKER_BUTTON, "leftshoulder", -1, -1, -1, -1, ""},
        {91, 0,    0.0,  MARKER_BUTTON, "lefttrigger", -1, -1, -1, -1, ""},
        {396, 36,   0.0,  MARKER_BUTTON, "rightshoulder", -1, -1, -1, -1, ""},
        {375, 0,    0.0,  MARKER_BUTTON, "righttrigger", -1, -1, -1, -1, ""},
        {75,  154,  0.0,  MARKER_BUTTON, "leftstick", -1, -1, -1, -1, ""},
        {305, 230,  0.0,  MARKER_BUTTON, "rightstick", -1, -1, -1, -1, ""},
        {75,  154,  0.0,  MARKER_AXIS,   "leftx", -1, -1, -1, -1, ""},
        {75,  154,  90.0, MARKER_AXIS,   "lefty", -1, -1, -1, -1, ""},        
        {305, 230,  0.0,  MARKER_AXIS,   "rightx", -1, -1, -1, -1, ""},
        {305, 230,  90.0, MARKER_AXIS,   "righty", -1, -1, -1, -1, ""},
    };

    /* Create a window to display joystick axis position */
    window = SDL_CreateWindow("Game Controller Map", SDL_WINDOWPOS_CENTERED,
                              SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH,
                              SCREEN_HEIGHT, 0);
    if (window == NULL) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create window: %s\n", SDL_GetError());
        return SDL_FALSE;
    }

    screen = SDL_CreateRenderer(window, -1, 0);
    if (screen == NULL) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create renderer: %s\n", SDL_GetError());
        SDL_DestroyWindow(window);
        return SDL_FALSE;
    }
    
    background = LoadTexture(screen, "controllermap.bmp", SDL_FALSE);
    button = LoadTexture(screen, "button.bmp", SDL_TRUE);
    axis = LoadTexture(screen, "axis.bmp", SDL_TRUE);
    SDL_RaiseWindow(window);

    /* scale for platforms that don't give you the window size you asked for. */
    SDL_RenderSetLogicalSize(screen, SCREEN_WIDTH, SCREEN_HEIGHT);

    /* Print info about the joystick we are watching */
    name = SDL_JoystickName(joystick);
    SDL_Log("Watching joystick %d: (%s)\n", SDL_JoystickInstanceID(joystick),
           name ? name : "Unknown Joystick");
    SDL_Log("Joystick has %d axes, %d hats, %d balls, and %d buttons\n",
           SDL_JoystickNumAxes(joystick), SDL_JoystickNumHats(joystick),
           SDL_JoystickNumBalls(joystick), SDL_JoystickNumButtons(joystick));
    
    SDL_Log("\n\n\
    ====================================================================================\n\
    Press the buttons on your controller when indicated\n\
    (Your controller may look different than the picture)\n\
    If you want to correct a mistake, press backspace or the back button on your device\n\
    To skip a button, press SPACE or click/touch the screen\n\
    To exit, press ESC\n\
    ====================================================================================\n");
    
    /* Initialize mapping with GUID and name */
    SDL_JoystickGetGUIDString(SDL_JoystickGetGUID(joystick), temp, SDL_arraysize(temp));
    SDL_snprintf(mapping, SDL_arraysize(mapping), "%s,%s,platform:%s,",
        temp, name ? name : "Unknown Joystick", SDL_GetPlatform());

    /* Loop, getting joystick events! */
    for(s=0; s<SDL_arraysize(steps) && !done;) {
        /* blank screen, set up for drawing this frame. */
        step = &steps[s];
        SDL_strlcpy(step->mapping, mapping, SDL_arraysize(step->mapping));
        step->axis = -1;
        step->button = -1;
        step->hat = -1;
        step->hat_value = -1;
        SDL_SetClipboardText("TESTING TESTING 123");
        
        switch(step->marker) {
            case MARKER_AXIS:
                marker = axis;
                break;
            case MARKER_BUTTON:
                marker = button;
                break;
            default:
                break;
        }
        
        dst.x = step->x;
        dst.y = step->y;
        SDL_QueryTexture(marker, NULL, NULL, &dst.w, &dst.h);
        next=SDL_FALSE;

        SDL_SetRenderDrawColor(screen, 0xFF, 0xFF, 0xFF, SDL_ALPHA_OPAQUE);

        while (!done && !next) {
            if (SDL_GetTicks() - alpha_ticks > 5) {
                alpha_ticks = SDL_GetTicks();
                alpha += alpha_step;
                if (alpha == 255) {
                    alpha_step = -1;
                }
                if (alpha < 128) {
                    alpha_step = 1;
                }
            }
            
            SDL_RenderClear(screen);
            SDL_RenderCopy(screen, background, NULL, NULL);
            SDL_SetTextureAlphaMod(marker, alpha);
            SDL_SetTextureColorMod(marker, 10, 255, 21);
            SDL_RenderCopyEx(screen, marker, NULL, &dst, step->angle, NULL, 0);
            SDL_RenderPresent(screen);
            
            if (SDL_PollEvent(&event)) {
                switch (event.type) {
                case SDL_JOYAXISMOTION:
                    if (event.jaxis.value > 20000 || event.jaxis.value < -20000) {
                        for (_s = 0; _s < s; _s++) {
                            if (steps[_s].axis == event.jaxis.axis) {
                                break;
                            }
                        }
                        if (_s == s) {
                            step->axis = event.jaxis.axis;
                            SDL_strlcat(mapping, step->field, SDL_arraysize(mapping));
                            SDL_snprintf(temp, SDL_arraysize(temp), ":a%u,", event.jaxis.axis);
                            SDL_strlcat(mapping, temp, SDL_arraysize(mapping));
                            s++;
                            next=SDL_TRUE;
                        }
                    }
                    
                    break;
                case SDL_JOYHATMOTION:
                        if (event.jhat.value == SDL_HAT_CENTERED) {
                            break;  /* ignore centering, we're probably just coming back to the center from the previous item we set. */
                        }
                        for (_s = 0; _s < s; _s++) {
                            if (steps[_s].hat == event.jhat.hat && steps[_s].hat_value == event.jhat.value) {
                                break;
                            }
                        }
                        if (_s == s) {
                            step->hat = event.jhat.hat;
                            step->hat_value = event.jhat.value;
                            SDL_strlcat(mapping, step->field, SDL_arraysize(mapping));
                            SDL_snprintf(temp, SDL_arraysize(temp), ":h%u.%u,", event.jhat.hat, event.jhat.value );
                            SDL_strlcat(mapping, temp, SDL_arraysize(mapping));
                            s++;
                            next=SDL_TRUE;
                        }
                    break;
                case SDL_JOYBALLMOTION:
                    break;
                case SDL_JOYBUTTONUP:
                    for (_s = 0; _s < s; _s++) {
                        if (steps[_s].button == event.jbutton.button) {
                            break;
                        }
                    }
                    if (_s == s) {
                        step->button = event.jbutton.button;
                        SDL_strlcat(mapping, step->field, SDL_arraysize(mapping));
                        SDL_snprintf(temp, SDL_arraysize(temp), ":b%u,", event.jbutton.button);
                        SDL_strlcat(mapping, temp, SDL_arraysize(mapping));
                        s++;
                        next=SDL_TRUE;
                    }
                    break;
                case SDL_FINGERDOWN:
                case SDL_MOUSEBUTTONDOWN:
                    /* Skip this step */
                    s++;
                    next=SDL_TRUE;
                    break;
                case SDL_KEYDOWN:
                    if (event.key.keysym.sym == SDLK_BACKSPACE || event.key.keysym.sym == SDLK_AC_BACK) {
                        /* Undo! */
                        if (s > 0) {
                            SDL_strlcpy(mapping, step->mapping, SDL_arraysize(step->mapping));
                            s--;
                            next = SDL_TRUE;
                        }
                        break;
                    }
                    if (event.key.keysym.sym == SDLK_SPACE) {
                        /* Skip this step */
                        s++;
                        next=SDL_TRUE;
                        break;
                    }
                    
                    if ((event.key.keysym.sym != SDLK_ESCAPE)) {
                        break;
                    }
                    /* Fall through to signal quit */
                case SDL_QUIT:
                    done = SDL_TRUE;
                    break;
                default:
                    break;
                }
            }
        }

    }

    if (s == SDL_arraysize(steps) ) {
        SDL_Log("Mapping:\n\n%s\n\n", mapping);
        /* Print to stdout as well so the user can cat the output somewhere */
        printf("%s\n", mapping);
    }
    
    while(SDL_PollEvent(&event)) {};
    
    SDL_DestroyRenderer(screen);
    SDL_DestroyWindow(window);
    return retval;
}
示例#10
0
文件: global.c 项目: csusbdt/441-2016
bool is_osx() {
	return SDL_strcmp(SDL_GetPlatform(), "Mac OS X") == 0;
}
示例#11
0
文件: global.c 项目: csusbdt/441-2016
bool is_windows() {
	return SDL_strcmp(SDL_GetPlatform(), "Windows") == 0;
}
AnsiString CBPlatform::GetPlatformName()
{
	return AnsiString(SDL_GetPlatform());
}
示例#13
0
QString InputDevice::getSDLPlatform()
{
    QString temp = SDL_GetPlatform();
    return temp;
}
示例#14
0
	static int lua_SDL_GetPlatform(lutok::state& state){
		state.push_string(SDL_GetPlatform());
		return 1;
	}
示例#15
0
static void _sys_info_reset(void)
{
    memset(sys_info_buffer,0,sizeof(sys_info_buffer));

    _sys_info_printf("SDL information:\n"
                     "----------------\n"
                     "\n"
                     "SDL_GetPlatform(): %s\n\n"
                     "SDL_GetCPUCount(): %d (Number of logical CPU cores)\n"
#if SDL_VERSION_ATLEAST(2,0,1)
                     "SDL_GetSystemRAM(): %d MB\n"
#endif
                     "SDL_GetCPUCacheLineSize(): %d kB (Cache L1)\n\n",
                     SDL_GetPlatform(), SDL_GetCPUCount(),
#if SDL_VERSION_ATLEAST(2,0,1)
                     SDL_GetSystemRAM(),
#endif
                     SDL_GetCPUCacheLineSize() );

    int total_secs, pct;
    SDL_PowerState st = SDL_GetPowerInfo(&total_secs,&pct);
    char * st_string;
    switch(st)
    {
        default:
        case SDL_POWERSTATE_UNKNOWN:
            st_string = "SDL_POWERSTATE_UNKNOWN (cannot determine power status)";
            break;
        case SDL_POWERSTATE_ON_BATTERY:
            st_string = "SDL_POWERSTATE_ON_BATTERY (not plugged in, running on battery)";
            break;
        case SDL_POWERSTATE_NO_BATTERY:
            st_string = "SDL_POWERSTATE_NO_BATTERY (plugged in, no battery available)";
            break;
        case SDL_POWERSTATE_CHARGING:
            st_string = "SDL_POWERSTATE_CHARGING (plugged in, charging battery)";
            break;
        case SDL_POWERSTATE_CHARGED:
            st_string = "SDL_POWERSTATE_CHARGED (plugged in, battery charged)";
            break;
    }

    unsigned int hours = ((unsigned int)total_secs)/3600;
    unsigned int min = (((unsigned int)total_secs)-(hours*3600))/60;
    unsigned int secs = (((unsigned int)total_secs)-(hours*3600)-(min*60));

    _sys_info_printf("SDL_GetPowerInfo():\n  %s\n  Time left: %d:%02d:%02d\n  Percentage: %3d%%\n\n",
                     st_string,hours,min,secs,pct);
#ifdef ENABLE_OPENGL
    _sys_info_printf("OpenGL information:\n"
                     "-------------------\n"
                     "\n"
                     "GL_RENDERER   = %s\n"
                     "GL_VERSION    = %s\n"
                     "GL_VENDOR     = %s\n"
                     "GL_EXTENSIONS = ",
                     (char*)glGetString(GL_RENDERER),(char*)glGetString(GL_VERSION),
                     (char*)glGetString(GL_VENDOR));
    _sys_info_print((char*)glGetString(GL_EXTENSIONS));
#endif
    _sys_info_printf("\n\nEND LOG\n");
}
示例#16
0
int main(int argc, char *argv[]) {
    // Get path
    char *ip = NULL;
    unsigned short connect_port = 0;
    unsigned short listen_port = 0;
    int net_mode = NET_MODE_NONE;
    int ret = 0;

    // Path manager
    if(pm_init() != 0) {
        err_msgbox(pm_get_errormsg());
        return 1;
    }

    // Check arguments
    if(argc >= 2) {
        if(strcmp(argv[1], "-v") == 0) {
            printf("OpenOMF v%d.%d.%d\n", V_MAJOR, V_MINOR, V_PATCH);
            printf("Source available at https://github.com/omf2097/ under MIT License\n");
            printf("(C) 2097 Tuomas Virtanen, Andrew Thompson, Hunter and others\n");
            goto exit_0;
        } else if(strcmp(argv[1], "-h") == 0) {
            printf("Arguments:\n");
            printf("-h              Prints this help\n");
            printf("-c [ip] [port]  Connect to server\n");
            printf("-l [port]       Start server\n");
            goto exit_0;
        } else if(strcmp(argv[1], "-c") == 0) {
            if(argc >= 3) {
                ip = strcpy(malloc(strlen(argv[2])+1), argv[2]);
            }
            if(argc >= 4) {
                connect_port = atoi(argv[3]);
            }
            net_mode = NET_MODE_CLIENT;
        } else if(strcmp(argv[1], "-l") == 0) {
            if(argc >= 3) {
                listen_port = atoi(argv[2]);
            }
            net_mode = NET_MODE_SERVER;
        }
    }

    // Init log
#if defined(DEBUGMODE) || defined(STANDALONE_SERVER)
    if(log_init(0)) {
        err_msgbox("Error while initializing log!");
        goto exit_0;
    }
#else
    if(log_init(pm_get_local_path(LOG_PATH))) {
        err_msgbox("Error while initializing log '%s'!", pm_get_local_path(LOG_PATH));
        goto exit_0;
    }
#endif

    // Simple header
    INFO("Starting OpenOMF v%d.%d.%d", V_MAJOR, V_MINOR, V_PATCH);

    // Dump pathmanager log
    pm_log();

    // Random seed
    rand_seed(time(NULL));

    // Init stringparser
    sd_stringparser_lib_init();

    // Init config
    if(settings_init(pm_get_local_path(CONFIG_PATH))) {
        err_msgbox("Failed to initialize settings file");
        goto exit_1;
    }
    settings_load();

    // Find plugins and make sure they are valid
    plugins_init();

    // Network game override stuff
    if(ip) {
        DEBUG("Connect IP overridden to %s", ip);
        settings_get()->net.net_connect_ip = ip;
    }
    if(connect_port > 0 && connect_port < 0xFFFF) {
        DEBUG("Connect Port overridden to %u", connect_port&0xFFFF);
        settings_get()->net.net_connect_port = connect_port;
    }
    if(listen_port > 0 && listen_port < 0xFFFF) {
        DEBUG("Listen Port overridden to %u", listen_port&0xFFFF);
        settings_get()->net.net_listen_port = listen_port;
    }

    // Init SDL2
    unsigned int sdl_flags = SDL_INIT_TIMER;
#ifndef STANDALONE_SERVER
    sdl_flags |= SDL_INIT_VIDEO;
#endif
    if(SDL_Init(sdl_flags)) {
        err_msgbox("SDL2 Initialization failed: %s", SDL_GetError());
        goto exit_2;
    }
    SDL_version sdl_linked;
    SDL_GetVersion(&sdl_linked);
    INFO("Found SDL v%d.%d.%d", sdl_linked.major, sdl_linked.minor, sdl_linked.patch);
    INFO("Running on platform: %s", SDL_GetPlatform());

#ifndef STANDALONE_SERVER
    if(SDL_InitSubSystem(SDL_INIT_JOYSTICK|SDL_INIT_GAMECONTROLLER|SDL_INIT_HAPTIC)) {
        err_msgbox("SDL2 Initialization failed: %s", SDL_GetError());
        goto exit_2;
    }

    // Attempt to find gamecontrollerdb.txt, either from resources or from
    // built-in header
    SDL_RWops *rw = SDL_RWFromConstMem(gamecontrollerdb, strlen(gamecontrollerdb));
    SDL_GameControllerAddMappingsFromRW(rw, 1);
    char *gamecontrollerdbpath = malloc(128);
    snprintf(gamecontrollerdbpath, 128, "%s/gamecontrollerdb.txt", pm_get_local_path(RESOURCE_PATH));
    int mappings_loaded = SDL_GameControllerAddMappingsFromFile(gamecontrollerdbpath);
    if (mappings_loaded > 0) {
        DEBUG("loaded %d mappings from %s", mappings_loaded, gamecontrollerdbpath);
    }
    free(gamecontrollerdbpath);

    // Load up joysticks
    INFO("Found %d joysticks attached", SDL_NumJoysticks());
    SDL_Joystick *joy;
    char guidstr[33];
    for (int i = 0; i < SDL_NumJoysticks(); i++) {
        joy = SDL_JoystickOpen(i);
        if (joy) {
            SDL_JoystickGUID guid = SDL_JoystickGetGUID(joy);
            SDL_JoystickGetGUIDString(guid, guidstr, 33);
            INFO("Opened Joystick %d", i);
            INFO(" * Name:              %s", SDL_JoystickNameForIndex(i));
            INFO(" * Number of Axes:    %d", SDL_JoystickNumAxes(joy));
            INFO(" * Number of Buttons: %d", SDL_JoystickNumButtons(joy));
            INFO(" * Number of Balls:   %d", SDL_JoystickNumBalls(joy));
            INFO(" * Number of Hats:    %d", SDL_JoystickNumHats(joy));
            INFO(" * GUID          :    %s", guidstr);
        } else {
            INFO("Joystick %d is unsupported", i);
        }

        if (SDL_JoystickGetAttached(joy)) {
            SDL_JoystickClose(joy);
        }
    }

    // Init libDumb
    dumb_register_stdfiles();
#endif

    // Init enet
    if(enet_initialize() != 0) {
        err_msgbox("Failed to initialize enet");
        goto exit_3;
    }

    // Initialize engine
    if(engine_init()) {
        err_msgbox("Failed to initialize game engine.");
        goto exit_4;
    }

    // Run
    engine_run(net_mode);

    // Close everything
    engine_close();
exit_4:
    enet_deinitialize();
exit_3:
    SDL_Quit();
exit_2:
    dumb_exit();
    settings_save();
    settings_free();
exit_1:
    sd_stringparser_lib_deinit();
    INFO("Exit.");
    log_close();
exit_0:
    if (ip) {
        free(ip);
    }
    plugins_close();
    pm_free();
    return ret;
}
示例#17
0
文件: name.hpp 项目: Rapptz/gum
inline std::string platform() {
    return SDL_GetPlatform();
}
示例#18
0
int main ()
{
	slInit("EasyAudio");
	slSetIcon("app-icon.png");
	opInit();
	//opSetCustomEscapeCallback(EnableOptionsMenu);

	// UI
	PlayToggleButton = slCreateBox(slLoadTexture(PLAY_BUTTON_IMGPATH));
	slSetBoxDims(PlayToggleButton,0.42,0.87,0.06,0.06, 17);
	PlayToggleButton->z = 22;
	PlayToggleButton->onclick = TogglePlaying;
	LoopToggleButton = slCreateBox(slLoadTexture(LOOP_BUTTON_IMGPATH));
	slSetBoxDims(LoopToggleButton,0.52,0.87,0.06,0.06, 17);
	LoopToggleButton->z = 22;
	LoopToggleButton->onclick = ToggleLooping;
	ControlsInfoBox = slCreateBox(slLoadTexture("interface/help-card.png"));
	slSetBoxDims(ControlsInfoBox,0.05,0.05,0.9,0.9, 1);
	ControlsInfoBox->z = 18;
	ControlsInfoBox->texbordercolor = {0,0,0,255};
	ControlsInfoBox->onclick = slDoNothing;
	slBox* ControlsHintBox = slCreateBox(slRenderText("Press C to toggle controls info.",{0,0,0,255}));
	slSetBoxDims(ControlsHintBox,0.01,0,0.2,0.05, 1);
	ControlsHintBox->z = 18;
	slBox* ProgressSliderBack = slCreateBox();
	slBox* ProgressSliderMark = slCreateBox();
	slSlider* ProgressSlider = slCreateSlider(ProgressSliderBack,ProgressSliderMark,false,true,false);
	ProgressSliderBack->backcolor = {159,159,159,255};
	ProgressSliderMark->backcolor = {63,63,63,255};
	ProgressSlider->minvalue = 0;
	ProgressSlider->maxvalue = 1;
	slSetBoxDims(ProgressSliderBack,0,0.97,1,0.03, 16);
	slSetBoxDims(ProgressSliderMark,0,0.97,0,0.03, 15);
	ProgressSliderBack->z = 210;
	ProgressSliderMark->z = 209;
	ProgressSlider->onchange = OnProgressAdjust;
	slBox* TempoSliderBack = slCreateBox();
	slBox* TempoSliderMark = slCreateBox();
	slSetBoxDims(TempoSliderBack,(0.42 - 0.35) / 2,0.87,0.35,0.06, 16);
	slSetBoxDims(TempoSliderMark,0,0.87,0.05,0.06, 15);
	slSlider* TempoSlider = slCreateSlider(TempoSliderBack,TempoSliderMark);
	TempoSliderBack->z = 210;
	TempoSliderMark->z = 209;
	TempoSliderBack->backcolor = {191,191,191,255};
	TempoSliderMark->backcolor = {95,95,95,255};
	TempoSlider->onchange = ChangeTempo;
	TempoSlider->minvalue = 40;
	TempoSlider->maxvalue = 220;
	TempoSlider->curvalue = 120.1;
	ChangeTempo(TempoSlider); // Initialize text on slider mark.
	slBox* TempoInfoBox = slCreateBox(slRenderText("TEMPO",BLACK));
	TempoInfoBox->backcolor = TempoSliderBack->backcolor;
	slSetBoxDims(TempoInfoBox,TempoSliderBack->x,0.84,0.07,0.03, 14);

	// Initialization
	slSetCustomDrawStage_Back(DrawBackground);
	slSetCustomDrawStage_Middle(DrawGrid);
	slOpenAudio();
	slSetCustomMixStage(Mix);
	VolAdjInit();

	// Keybindings
  int delete_key, lctrl_key, rctrl_key;
  if (!strcmp(SDL_GetPlatform(), "Mac OS X"))
  {
    delete_key = SDLK_BACKSPACE;
    lctrl_key = SDLK_LGUI;
    rctrl_key = SDLK_RGUI;
  }
  else
  {
    delete_key = SDLK_DELETE;
    lctrl_key = SDLK_LCTRL;
    rctrl_key = SDLK_RCTRL;
  }

	slGetKeyBind("Show/Hide Controls Info",SDLK_c)->onpress = OnControlsPress;
	slGetKeyBind("Append Measure to End",SDLK_m)->onpress = InsertMeasureAtEnd;
	slGetKeyBind("Chop Measure from End",SDLK_n)->onpress = RemoveMeasureFromEnd;
	slKeyBind* dragbind = slGetKeyBind("Drag Note",0,SDL_BUTTON(SDL_BUTTON_LEFT));
	dragbind->onpress = GrabNote;
	dragbind->onrelease = ReleaseNote;
	slGetKeyBind("Toggle Looping",SDLK_l)->onpress = ToggleLooping;
	slGetKeyBind("Toggle Playing",SDLK_SPACE)->onpress = TogglePlaying;
	CreateNoteLengthBind("Whole Note",SDLK_a,8);
	CreateNoteLengthBind("Half Note",SDLK_s,4);
	CreateNoteLengthBind("Quarter Note",SDLK_d,2);
	CreateNoteLengthBind("Eighth Note",SDLK_f,1);
	CreateNoteLengthBind("Sixteenth Note",SDLK_g,0.5);
	CreateNoteLengthBind("Thirty-Second Note",SDLK_h,0.25);
	slGetKeyBind("I Chord", SDLK_1)->onpress = EditChordKeyBind;
	slGetKeyBind("II Chord", SDLK_2)->onpress = EditChordKeyBind;
	slGetKeyBind("III Chord", SDLK_3)->onpress = EditChordKeyBind;
	slGetKeyBind("IV Chord", SDLK_4)->onpress = EditChordKeyBind;
	slGetKeyBind("V Chord", SDLK_5)->onpress = EditChordKeyBind;
	slGetKeyBind("VI Chord", SDLK_6)->onpress = EditChordKeyBind;
	slGetKeyBind("VII Chord", SDLK_7)->onpress = EditChordKeyBind;
	slGetKeyBind("Remove Chord", SDLK_DELETE)->onpress = RemoveChordKeyBind;

	///CreateInstrumentPanel();

	// Loading
	LoadAllInstruments();
	slxEnableFpsCounter(SDLK_F3);
  InsertMeasureAtEnd();

	// Main Loop
	while (!slGetReqt())
	{
	  if (!opGetVisi())
    {
      RepositionNotes();
      RepositionChords();
      UpdateGrabbedNote();
      VolAdjStep();
      slSetSliderValue(ProgressSlider,SongProgress());
    }
    slxRunHooks();
		slCycle();
	}

	// Cleanup
	VolAdjQuit();
	slDestroyBox(PlayToggleButton);
	slDestroyBox(LoopToggleButton);
	opQuit();
	slQuit();
	return 0;
}
示例#19
0
文件: audio.cpp 项目: djyt/cannonball
void Audio::start_audio()
{
    if (!sound_enabled)
    {
        // Since many GNU/Linux distros are infected with PulseAudio, SDL2 could chose PA as first
	// driver option before ALSA, and PA doesn't obbey our sample number requests, resulting
	// in audio gaps, if we're on a GNU/Linux we force ALSA.
	// Else we accept whatever SDL2 wants to give us or what the user specifies on SDL_AUDIODRIVER
	// enviroment variable.
	std::string platform = SDL_GetPlatform();
	if (platform=="Linux"){

	    if (SDL_InitSubSystem(SDL_INIT_AUDIO)!=0) {

		std::cout << "Error initalizing audio subsystem: " << SDL_GetError() << std::endl;
	    }

	    if (SDL_AudioInit("alsa")!=0) {
		std::cout << "Error initalizing audio using ALSA: " << SDL_GetError() << std::endl;
		return;
	    }

	}
	else {
	    if(SDL_Init(SDL_INIT_AUDIO) == -1) 
	    {
		std::cout << "Error initalizing audio: " << SDL_GetError() << std::endl;
		return;
	    }		
	}

        // SDL Audio Properties
        SDL_AudioSpec desired, obtained;

        desired.freq     = FREQ;
        desired.format   = AUDIO_S16SYS;
        desired.channels = CHANNELS;
        desired.samples  = SAMPLES;
        desired.callback = fill_audio;
        desired.userdata = NULL;
	
	// SDL2 block
	dev = SDL_OpenAudioDevice(NULL, 0, &desired, &obtained, /*SDL_AUDIO_ALLOW_FORMAT_CHANGE*/0);
	if (dev == 0)
	{
            std::cout << "Error opening audio device: " << SDL_GetError() << std::endl;
            return;
        }

        if (desired.samples != obtained.samples) {
            std::cout << "Error initalizing audio: number of samples not supported." << std::endl
                      << "Please compare desired vs obtained. Look at what audio driver SDL2 is using." << std::endl;
	    return;
	}

        bytes_per_sample = CHANNELS * (BITS / 8);

        // Start Audio
        sound_enabled = true;

        // how many fragments in the dsp buffer
        const int DSP_BUFFER_FRAGS = 5;
        int specified_delay_samps = (FREQ * SND_DELAY) / 1000;
        int dsp_buffer_samps = SAMPLES * DSP_BUFFER_FRAGS + specified_delay_samps;
        dsp_buffer_bytes = CHANNELS * dsp_buffer_samps * (BITS / 8);
        dsp_buffer = new uint8_t[dsp_buffer_bytes];

        // Create Buffer For Mixing
        uint16_t buffer_size = (FREQ / config.fps) * CHANNELS;
        mix_buffer = new uint16_t[buffer_size];

        clear_buffers();
        clear_wav();

        SDL_PauseAudioDevice(dev,0);
    }
}
示例#20
0
文件: global.c 项目: csusbdt/441-2016
bool is_linux() {
	return SDL_strcmp(SDL_GetPlatform(), "Linux") == 0;
}
static int ReadMappingsString(const char *s)
{
#define READ_TOKEN(buf, p, end)\
	if (end == NULL)\
	{\
		strcpy(buf, p);\
		p = NULL;\
	}\
	else\
	{\
		strncpy(buf, p, end - p);\
		buf[end - p] = '\0';\
		p = end + 1;\
	}

	// Read compiled string button names into memory
	// Search for a matching GUID + joystickName in the db
	int read = 0;
	for (const char *cur = s; cur;)
	{
		const char *nl = strchr(cur, '\n');
		char line[2048];
		READ_TOKEN(line, cur, nl);

		char buf[256];

		// Check for the platform string
		sprintf(buf, "platform:%s", SDL_GetPlatform());
		if (strstr(line, buf) == NULL) continue;

#define STR_NOT_EQ(expected, actualP, actualEnd)\
	strlen(expected) != (actualEnd) - (actualP) || \
	strncmp(expected, actualP, (actualEnd) - (actualP)) != 0
		const char *curL = line;
		// Ignore hash comments
		if (*curL == '#') continue;

		const char *nextComma;
		JoystickButtonNames j = jDefault;

		// Read GUID
		nextComma = strchr(curL, ',');
		if (nextComma == NULL || cur == nextComma) continue;
		READ_TOKEN(buf, curL, nextComma);
		j.guid = SDL_JoystickGetGUIDFromString(buf);

		// Read joystick name
		nextComma = strchr(curL, ',');
		if (nextComma == NULL || curL == nextComma) continue;
		READ_TOKEN(j.joystickName, curL, nextComma);

		// Check if GUID+joystick name already exists
		bool exists = false;
		for (int i = 0; i < nJBN; i++)
		{
			const JoystickButtonNames *jp = jbn + i;
			if (memcmp(&jp->guid, &j.guid, sizeof j.guid) == 0 &&
				strcmp(jp->joystickName, j.joystickName) == 0)
			{
				exists = true;
				break;
			}
		}
		if (exists) continue;

		// Read name and colors
		for (;; curL = nextComma + 1)
		{
			nextComma = strchr(curL, ',');
			if (nextComma == NULL) break;

			const char *nextColon;

			nextColon = strchr(curL, ':');
			if (nextColon == NULL || curL == nextColon) continue;
			READ_TOKEN(buf, curL, nextColon);
			const SDL_GameControllerButton button =
				SDL_GameControllerGetButtonFromString(buf);
			const SDL_GameControllerAxis axis =
				SDL_GameControllerGetAxisFromString(buf);
			char *name;
			SDL_Color *color;
			if (button != SDL_CONTROLLER_BUTTON_INVALID)
			{
				name = j.buttonNames[(int)button];
				color = &j.buttonColors[(int)button];
			}
			else if (axis != SDL_CONTROLLER_AXIS_INVALID)
			{
				name = j.axisNames[(int)axis];
				color = &j.axisColors[(int)axis];
			}
			else
			{
				continue;
			}
			// Read the real button/axis name
			nextColon = strchr(curL, ':');
			if (nextColon == NULL) continue;
			READ_TOKEN(name, curL, nextColon);
			// R
			nextColon = strchr(curL, ':');
			if (nextColon == NULL) continue;
			READ_TOKEN(buf, curL, nextColon);
			color->r = (Uint8)atoi(buf);
			// G
			nextColon = strchr(curL, ':');
			if (nextColon == NULL) continue;
			READ_TOKEN(buf, curL, nextColon);
			color->g = (Uint8)atoi(buf);
			// B
			READ_TOKEN(buf, curL, nextComma);
			color->b = (Uint8)atoi(buf);

			color->a = 255;
		}
		nJBN++;
		read++;
		jbn = SDL_realloc(jbn, nJBN * sizeof *jbn);
		memcpy(jbn + nJBN - 1, &j, sizeof j);
	}
	return read;
}
示例#22
0
int config_init ( int argc, char **argv )
{
	const char *config_name = DEFAULT_CONFIG_FILE;	// name of the used config file, can be overwritten via CLI
	const struct configOption_st *opt;
	const char *exe = argv[0];
	int default_config = 1;
	int testparsing = 0;
	argc--; argv++;
#ifdef __EMSCRIPTEN__
	exe = strdup("/files/emscripten-virtual-executable");
#endif
#ifdef _WIN32
	console_open_window();
#endif
	SDL_VERSION(&sdlver_compiled);
	SDL_GetVersion(&sdlver_linked);
	if (sdlver_linked.major < 2 || (sdlver_linked.minor == 0 && sdlver_linked.patch < 4)) {
		ERROR_WINDOW("Too old SDL library linked, at least version 2.0.4 is required.");
		return 1;
	}
	/* SDL info on paths */
	if (get_path_info())
		return 1;
	/* ugly hack: pre-parse comand line to find debug statement (to be worse, it does not handle single argument options too well ... */
#ifdef DISABLE_DEBUG
	printf("DEBUG: disabled at compilation time." NL);
#else
	while (testparsing < argc) {
		if (!strcmp(argv[testparsing], "-" DEBUGFILE_OPT) && testparsing != argc - 1 && strcmp(argv[testparsing + 1], "none")) {
			debug_fp = fopen(argv[testparsing + 1], "w");
			DEBUGPRINT("DEBUG: enable logging into file: %s" NL, argv[testparsing + 1]);
			if (debug_fp == NULL)
				fprintf(stderr, "Cannot open debug logging file: %s" NL, argv[testparsing + 1]);
			break;
		}
		testparsing++;
	}
	testparsing = 0;
#endif
	/* end of ugly hack */
	/* let's continue with the info block ... */
	DEBUGPRINT("%s %s v%s %s %s" NL
		"GIT %s compiled by (%s) at (%s) with (%s)-(%s)" NL
		"Platform: (%s) (%d-bit), video: (%s), audio: (%s), "
		"SDL version compiled: (%d.%d.%d) and linked: (%d.%d.%d) rev (%s)" NL NL,
		WINDOW_TITLE, DESCRIPTION, VERSION, COPYRIGHT, PROJECT_PAGE,
		XEMU_BUILDINFO_GIT, XEMU_BUILDINFO_ON, XEMU_BUILDINFO_AT, CC_TYPE, XEMU_BUILDINFO_CC,
		SDL_GetPlatform(), ARCH_BITS, SDL_GetCurrentVideoDriver(), SDL_GetCurrentAudioDriver(),
		sdlver_compiled.major, sdlver_compiled.minor, sdlver_compiled.patch,
		sdlver_linked.major, sdlver_linked.minor, sdlver_linked.patch, SDL_GetRevision()
	);
	DEBUGPRINT("PATH: executable: %s" NL, exe);
	/* SDL path info block printout */
	DEBUGPRINT("PATH: SDL base path: %s" NL, app_base_path);
	DEBUGPRINT("PATH: SDL pref path: %s" NL, app_pref_path);
#ifndef _WIN32
	DEBUGPRINT("PATH: data directory: %s/" NL, DATADIR);
#endif
	DEBUGPRINT("PATH: Current directory: %s" NL NL, current_directory);
	/* Look the very basic command line switches first */
	if (argc && is_help_request_option(argv[0])) {
		opt = configOptions;
		printf("USAGE:" NL NL
			"\t%s -optname optval -optname2 optval2 ..." NL NL "OPTIONS:" NL NL
			"-config" NL "\tUse config file (or do not use the default one, if \"none\" is specified). This must be the first option if used! [default: @config]" NL,
			exe
		);
		while (opt->name) {
			printf("-%s" NL "\t%s [default: %s]" NL, opt->name, opt->help, opt->defval ? opt->defval : "-");
			opt++;
		}
		printf(NL "%s" NL, disclaimer);
#ifdef _WIN32
		if (!console_is_open)
			ERROR_WINDOW("Could not dump help, since console couldn't be allocated.");
#endif
		XEMUEXIT(0);
	}
	DEBUGPRINT("%s" NL NL, disclaimer);
	if (argc && !strcasecmp(argv[0], "-testparsing")) {
		testparsing = 1;
		argc--; argv++;
	}
	if (argc & 1) {
		fprintf(stderr, "FATAL: Bad command line: should be even number of parameters (two for an option as key and its value)" NL);
		return 1;
	}
	if (argc > 1 && !strcmp(argv[0], "-config")) {
		default_config = 0;
		config_name = argv[1];
		argc -= 2;
		argv += 2;
	}
	/* Set default (built-in) values */
	opt = configOptions;
	while (opt->name) {
		if (opt->defval)
			config_set_internal(opt->name, -1, opt->defval);
		opt++;
	}
	config_set_internal("rom", 0, COMBINED_ROM_FN);	// set default "combined" ROM image set (from segment 0, starting with EXOS)
	/* Default values for the keyboard follows ... */
	keymap_preinit_config_internal();
	/* check if we have written sample config file, if there is not, let's create one */
	save_sample_config(DEFAULT_CONFIG_SAMPLE_FILE);
	/* now parse config file (not the sample one!) if there is any */
	if (strcasecmp(config_name, "none")) {
		char path[PATH_MAX + 1];
		FILE *f = open_emu_file(config_name, "r", path);
		DEBUGPRINT("CONFIG: config file: %s (%s)" NL, config_name, f ? path : "*** CANNOT OPEN, NOT USING CONFIG FILE ***");
		if (f) {
			if (load_config_file_stream(f, path)) {
				fclose(f);
				return 1;
			}
			fclose(f);
		} else if (!default_config) {
			fprintf(stderr, "FATAL: Cannot open requested config file: %s" NL, config_name);
			return 1;
		} else
			DEBUGPRINT("CONFIG: Skipping default config file (cannot open), using built-in defaults." NL);
	} else
		DEBUGPRINT("CONFIG: Using config file: DISABLED in command line" NL);
	/* parse command line ... */
	if (parse_command_line(argc, argv))
		return -1;
	/* open debug file, if it was not requested via command line at the beginning ... */
	if (!debug_fp && strcmp(config_getopt_str(DEBUGFILE_OPT), "none")) {
		debug_fp = fopen(config_getopt_str(DEBUGFILE_OPT), "w");
		DEBUGPRINT("DEBUG: enable logging into file: %s" NL, config_getopt_str(DEBUGFILE_OPT));
		if (!debug_fp)
                	ERROR_WINDOW("Cannot open debug messages log file requested: %s", config_getopt_str(DEBUGFILE_OPT));
	}
	if (debug_fp)
		INFO_WINDOW("DEBUG: Debug messages logging is active");
	else
		printf("DEBUG: No debug messages logging is active." NL);
	/* test parsing mode? */
	if (testparsing) {
		printf(NL "--- TEST DUMP OF *PARSED* CONFIGURATION (requested)" NL NL);
		dump_config(stdout);
		printf(NL "--- END OF TEST PARSING MODE (requested)" NL);
		XEMUEXIT(0);
	}
	DEBUG("CONFIG: End of configuration step." NL NL);
	/* Close console, unless user requested it with the -console option */
#ifdef _WIN32
	if (!config_getopt_int("console"))
		console_close_window();
#else
	if (config_getopt_int("console"))
		console_open_window();	// on non-windows, it only will mark console as open for monitor to be used ..
#endif
	return 0;
}
示例#23
0
void Remapper::dataIn( Node::DataType type, QMutex *mutex, void *data, size_t bytes, qint64 timeStamp ) {
    switch( type ) {
        case DataType::Input: {
            // Copy incoming data to our own buffer
            GamepadState gamepad;
            {
                mutex->lock();
                gamepad = *reinterpret_cast<GamepadState *>( data );
                mutex->unlock();
            }

            int instanceID = gamepad.instanceID;
            int joystickID = gamepad.joystickID;
            QString GUID( QByteArray( reinterpret_cast<const char *>( gamepad.GUID.data ), 16 ).toHex() );

            // Do initial calibration if not done yet
            {
                if( deadzoneFlag[ GUID ] ) {
                    deadzoneFlag[ GUID ] = false;

                    // Apply default value
                    for( int i = 0; i < gamepad.joystickNumAxes; i++ ) {
                        deadzones[ GUID ][ i ] = 10000;

                        // Check analog value at this moment. If its magnitude is less than 30000 then it's most likely
                        // an analog stick. Otherwise, it might be a trigger (with a centered value of -32768)
                        deadzoneModes[ GUID ][ i ] = ( qAbs( static_cast<int>( gamepad.joystickAxis[ i ] ) ) < 30000 );
                    }

                    // TODO: Replace with stored value from disk
                }
            }

            // Inject deadzone settings into gamepad
            {
                for( int i = 0; i < gamepad.joystickNumAxes; i++ ) {
                    gamepad.deadzone[ i ] = deadzones[ GUID ][ i ];
                    gamepad.deadzoneMode[ i ] = deadzoneModes[ GUID ][ i ];
                }
            }

            // Send raw joystick data to the model
            // Do this before we apply joystick deadzones so the user sees completely unprocessed data
            {
                // Copy current gamepad into buffer
                this->mutex.lock();
                gamepadBuffer[ gamepadBufferIndex ] = gamepad;
                this->mutex.unlock();

                // Send buffer on its way
                emit rawJoystickData( &( this->mutex ), reinterpret_cast<void *>( &gamepadBuffer[ gamepadBufferIndex ] ) );

                // Increment the index
                gamepadBufferIndex = ( gamepadBufferIndex + 1 ) % 100;
            }

            // Apply deadzones to each stick and both triggers independently
            {
                qreal deadzone = 0.0;
                bool deadzoneMode = false;

                for( int i = 0; i < 4; i++ ) {
                    int xAxis;
                    int yAxis;

                    // For the analog sticks, average the underlying joystick axes together to get the final deadzone value
                    // If either axis has deadzone mode set to true, it'll apply to both
                    // FIXME: If users complain about this, expand the code to handle this case (one axis true and one axis false) and treat axes indepenently
                    switch( i ) {
                        case 0: {
                            xAxis = SDL_CONTROLLER_AXIS_LEFTX;
                            yAxis = SDL_CONTROLLER_AXIS_LEFTY;

                            Val val = gameControllerToJoystick[ GUID ][ Key( AXIS, SDL_CONTROLLER_AXIS_LEFTX ) ];
                            int axisID = val.second.first;

                            if( val.first == AXIS ) {
                                deadzone = deadzones[ GUID ][ axisID ];
                                deadzoneMode = deadzoneModes[ GUID ][ axisID ];
                            }

                            Val val2 = gameControllerToJoystick[ GUID ][ Key( AXIS, SDL_CONTROLLER_AXIS_LEFTY ) ];
                            axisID = val2.second.first;

                            if( val2.first == AXIS ) {
                                deadzone += deadzones[ GUID ][ axisID ];
                                deadzone /= 2.0;
                                deadzoneMode = deadzoneMode || deadzoneModes[ GUID ][ axisID ];
                            }

                            break;
                        }

                        case 1: {
                            xAxis = SDL_CONTROLLER_AXIS_RIGHTX;
                            yAxis = SDL_CONTROLLER_AXIS_RIGHTY;

                            Val val = gameControllerToJoystick[ GUID ][ Key( AXIS, SDL_CONTROLLER_AXIS_RIGHTX ) ];
                            int axisID = val.second.first;

                            if( val.first == AXIS ) {
                                deadzone = deadzones[ GUID ][ axisID ];
                                deadzoneMode = deadzoneModes[ GUID ][ axisID ];
                            }

                            Val val2 = gameControllerToJoystick[ GUID ][ Key( AXIS, SDL_CONTROLLER_AXIS_RIGHTY ) ];
                            axisID = val2.second.first;

                            if( val2.first == AXIS ) {
                                deadzone += deadzones[ GUID ][ axisID ];
                                deadzone /= 2.0;
                                deadzoneMode = deadzoneMode || deadzoneModes[ GUID ][ axisID ];
                            }

                            break;
                        }

                        // For simplicity, just map the triggers to the line y = x
                        case 2: {
                            xAxis = SDL_CONTROLLER_AXIS_TRIGGERLEFT;
                            yAxis = SDL_CONTROLLER_AXIS_TRIGGERLEFT;
                            Val val = gameControllerToJoystick[ GUID ][ Key( AXIS, SDL_CONTROLLER_AXIS_TRIGGERLEFT ) ];
                            int axisID = val.second.first;

                            if( val.first == AXIS ) {
                                deadzone = deadzones[ GUID ][ axisID ];
                                deadzoneMode = deadzoneModes[ GUID ][ axisID ];
                            }

                            break;
                        }

                        case 3: {
                            xAxis = SDL_CONTROLLER_AXIS_TRIGGERRIGHT;
                            yAxis = SDL_CONTROLLER_AXIS_TRIGGERRIGHT;
                            Val val = gameControllerToJoystick[ GUID ][ Key( AXIS, SDL_CONTROLLER_AXIS_TRIGGERRIGHT ) ];
                            int axisID = val.second.first;

                            if( val.first == AXIS ) {
                                deadzone = deadzones[ GUID ][ axisID ];
                                deadzoneMode = deadzoneModes[ GUID ][ axisID ];
                            }

                            break;
                        }
                    }

                    // Map from [-32768, 32767] to [0, 32767]
                    if( !deadzoneMode ) {
                        gamepad.axis[ xAxis ] /= 2;
                        gamepad.axis[ yAxis ] /= 2;
                        gamepad.axis[ xAxis ] += 16384;
                        gamepad.axis[ yAxis ] += 16384;
                    }

                    // Get axis coords in cartesian coords
                    // Bottom right is positive -> top right is positive
                    qreal xCoord = gamepad.axis[ xAxis ];
                    qreal yCoord = -gamepad.axis[ yAxis ];

                    // Get radius from center
                    QVector2D position( static_cast<float>( xCoord ), static_cast<float>( yCoord ) );
                    qreal radius = static_cast<qreal>( position.length() );

                    if( !( radius > deadzone ) ) {
                        gamepad.axis[ xAxis ] = 0;
                        gamepad.axis[ yAxis ] = 0;

                        if( xAxis == SDL_CONTROLLER_AXIS_TRIGGERLEFT ) {
                            gamepad.digitalL2 = false;
                        }

                        if( xAxis == SDL_CONTROLLER_AXIS_TRIGGERRIGHT ) {
                            gamepad.digitalR2 = false;
                        }
                    } else {
                        if( xAxis == SDL_CONTROLLER_AXIS_TRIGGERLEFT ) {
                            gamepad.digitalL2 = true;
                        }

                        if( xAxis == SDL_CONTROLLER_AXIS_TRIGGERRIGHT ) {
                            gamepad.digitalR2 = true;
                        }
                    }
                }
            }

            // Apply deadzones to all joystick axes
            // Used only when detecting input for remapping
            {
                for( int i = 0; i < 16; i++ ) {
                    qreal deadzoneRadius = deadzones[ GUID ][ i ];
                    qreal coord = gamepad.joystickAxis[ i ];

                    if( !deadzoneModes[ GUID ][ i ] ) {
                        coord += 32768;
                    }

                    if( !( qAbs( coord ) > deadzoneRadius ) ) {
                        gamepad.joystickAxis[ i ] = 0;
                    }
                }
            }

            // If ignoreMode is set, the user hasn't let go of the button they were remapping to
            // Do not let the button go through until they let go
            {
                if( ignoreMode && ignoreModeGUID == GUID && ignoreModeInstanceID == gamepad.instanceID ) {
                    if( ignoreModeVal.first == BUTTON ) {
                        if( gamepad.joystickButton[ ignoreModeVal.second.first ] == SDL_PRESSED ) {
                            gamepad.joystickButton[ ignoreModeVal.second.first ] = SDL_RELEASED;
                        } else {
                            ignoreMode = false;
                        }
                    } else if( ignoreModeVal.first == HAT ) {
                        if( gamepad.joystickHat[ ignoreModeVal.second.first ] != SDL_HAT_CENTERED ) {
                            gamepad.joystickHat[ ignoreModeVal.second.first ] = SDL_HAT_CENTERED;
                        } else {
                            ignoreMode = false;
                        }
                    } else if( ignoreModeVal.first == AXIS ) {
                        if( gamepad.joystickAxis[ ignoreModeVal.second.first ] != 0 ) {
                            gamepad.joystickAxis[ ignoreModeVal.second.first ] = 0;
                        } else {
                            ignoreMode = false;
                        }
                    }
                }
            }

            // If we opened an SDL2 Game controller handle from this class, keep it and inject it into all gamepads we send out
            {
                if( gameControllerHandles[ instanceID ] ) {
                    gamepad.gamecontrollerHandle = gameControllerHandles[ instanceID ];
                }
            }

            // If we are in remap mode, check for a button press from the stored GUID, and remap the stored button to that button
            // All game controller states are cleared past this point if in remap mode
            {
                if( remapMode && GUID == remapModeGUID ) {
                    // Find a button press, the first one we encounter will be the new remapping
                    bool foundInput = false;
                    Key key = remapModeKey;
                    Val value = Val( INVALID, VHat( -1, -1 ) );

                    // Prioritize buttons and hats over analog sticks
                    for( int joystickButton = 0; joystickButton < 256; joystickButton++ ) {
                        if( gamepad.joystickButton[ joystickButton ] == SDL_PRESSED ) {
                            qCDebug( phxInput ).nospace() << "Button b" << joystickButton
                                                          << " from GUID " << GUID << " now activates " << keyToMappingString( key );

                            foundInput = true;
                            value.first = BUTTON;
                            value.second = VHat( joystickButton, -1 );
                            break;
                        }
                    }

                    for( int joystickHat = 0; joystickHat < 16; joystickHat++ ) {
                        if( gamepad.joystickHat[ joystickHat ] != SDL_HAT_CENTERED ) {
                            qCDebug( phxInput ).nospace() << "Hat h" << joystickHat << "." << gamepad.joystickHat[ joystickHat ]
                                                          << " from GUID " << GUID << " now activates " << keyToMappingString( key );
                            foundInput = true;
                            value.first = HAT;
                            value.second = VHat( joystickHat, gamepad.joystickHat[ joystickHat ] );
                            break;
                        }
                    }

                    for( int joystickAxis = 0; joystickAxis < 16; joystickAxis++ ) {
                        if( gamepad.joystickAxis[ joystickAxis ] != 0 ) {
                            qCDebug( phxInput ).nospace() << "Axis a" << joystickAxis
                                                          << " from GUID " << GUID << " now activates " << keyToMappingString( key );
                            foundInput = true;
                            value.first = AXIS;
                            value.second = VHat( joystickAxis, -1 );
                            break;
                        }
                    }

                    if( foundInput ) {
                        // Store the new remapping internally
                        gameControllerToJoystick[ GUID ][ remapModeKey ] = value;

                        // Tell SDL2 about it
                        QString mappingString;
                        QString platform( SDL_GetPlatform() );
                        {
                            QString friendlyName = QString( SDL_JoystickName( gamepad.joystickHandle ) );

                            mappingString.append( GUID ).append( "," ).append( friendlyName ).append( "," );

                            for( Key key : gameControllerToJoystick[ GUID ].keys() ) {
                                if( gameControllerToJoystick[ GUID ][ key ].first != INVALID ) {
                                    mappingString.append( keyToMappingString( key ) ).append( ':' )
                                    .append( valToMappingString( gameControllerToJoystick[ GUID ][ key ] ) ).append( ',' );
                                }
                            }


                            mappingString.append( "platform:" ).append( platform ).append( "," );
                            qDebug().nospace() << mappingString;

                            // Give SDL the new mapping string
                            SDL_GameControllerAddMapping( mappingString.toUtf8().constData() );

                            // If this is not a game controller, reopen as one
                            SDL_GameController *gamecontrollerHandle = nullptr;

                            if( !gameControllerHandles[ instanceID ] ) {
                                gamecontrollerHandle = SDL_GameControllerOpen( joystickID );
                                gamepad.gamecontrollerHandle = gamecontrollerHandle;
                                // Store internally so we can inject it into all future events from this instanceID
                                gameControllerHandles[ instanceID ] = gamecontrollerHandle;
                                qDebug() << "Opened newly remapped joystick as a game controller:" << gamecontrollerHandle;
                            }
                        }

                        // Store this mapping to disk
                        {
                            if( !userDataPath.isEmpty() ) {
                                QFile mappingFile( userDataPath + "/gamecontrollerdb.txt" );

                                mappingFile.open( QIODevice::ReadWrite | QIODevice::Text );
                                QByteArray mappingFileData = mappingFile.readAll();

                                if( !mappingFile.isOpen() ) {
                                    qWarning() << "Unable to open mapping file for reading" << mappingFile.errorString();
                                }

                                mappingFile.close();

                                QTextStream mappingFileStreamIn( &mappingFileData );
                                mappingFileStreamIn.setCodec( "UTF-8" );

                                mappingFile.open( QIODevice::WriteOnly | QIODevice::Text );

                                if( !mappingFile.isOpen() ) {
                                    qWarning() << "Unable to open mapping file for writing" << mappingFile.errorString();
                                }

                                QTextStream mappingFileStreamOut( &mappingFile );
                                mappingFileStreamOut.setCodec( "UTF-8" );

                                QString line = "";

                                while( !line.isNull() ) {
                                    line = mappingFileStreamIn.readLine();

                                    // We want to replace the line (any line) for our platform that contains our GUID
                                    // We'll also filter out empty lines
                                    if( line.isEmpty() || ( line.contains( GUID ) && line.contains( platform ) ) ) {
                                        continue;
                                    }

                                    mappingFileStreamOut << line << endl;
                                }

                                mappingFileStreamOut << mappingString << endl;
                                mappingFile.close();
                            } else {
                                qWarning() << "Unable to open controller mapping file, user data path not set";
                            }
                        }

                        // End remap mode, start ignore mode
                        {
                            remapMode = false;
                            ignoreMode = true;
                            ignoreModeGUID = GUID;
                            ignoreModeVal = value;
                            ignoreModeInstanceID = gamepad.instanceID;
                        }

                        // Tell the model we're done
                        {
                            emit setMapping( GUID, keyToMappingString( key ), valToFriendlyString( value ) );
                            emit remappingEnded();
                        }
                    }

                    // Clear all game controller states (joystick states are untouched)
                    for( int i = 0; i < SDL_CONTROLLER_BUTTON_MAX; i++ ) {
                        gamepad.button[ i ] = 0;
                    }

                    for( int i = 0; i < SDL_CONTROLLER_AXIS_MAX; i++ ) {
                        gamepad.axis[ i ] = 0;
                    }
                } else if( remapMode ) {
                    // Clear all gamepad states
                    for( int i = 0; i < SDL_CONTROLLER_BUTTON_MAX; i++ ) {
                        gamepad.button[ i ] = 0;
                    }

                    for( int i = 0; i < SDL_CONTROLLER_AXIS_MAX; i++ ) {
                        gamepad.axis[ i ] = 0;
                    }
                }
            }

            // OR all joystick button, hat and analog states together by GUID for RemapperModel to indicate presses
            {
                for( int i = 0; i < 256; i++ ) {
                    pressed[ GUID ] |= gamepad.joystickButton[ i ];
                }

                for( int i = 0; i < 16; i++ ) {
                    pressed[ GUID ] |= ( gamepad.joystickHat[ i ] != SDL_HAT_CENTERED );
                }

                for( int i = 0; i < 16; i++ ) {
                    pressed[ GUID ] |= ( gamepad.joystickAxis[ i ] != 0 );
                }
            }

            // Apply axis to d-pad, if enabled
            // This will always be enabled if we're not currently playing so GlobalGamepad can use the analog stick
            {
                if( analogToDpad[ GUID ] || !playing ) {
                    // TODO: Support other axes?
                    int xAxis = SDL_CONTROLLER_AXIS_LEFTX;
                    int yAxis = SDL_CONTROLLER_AXIS_LEFTY;

                    // TODO: Let user configure these

                    qreal threshold = 16384.0;

                    // Size in degrees of the arc covering and centered around each cardinal direction
                    // If <90, there will be gaps in the diagonals
                    // If >180, this code will always produce diagonal inputs
                    qreal rangeDegrees = 180.0 - 45.0;

                    // Get axis coords in cartesian coords
                    // Bottom right is positive -> top right is positive
                    qreal xCoord = gamepad.axis[ xAxis ];
                    qreal yCoord = -gamepad.axis[ yAxis ];

                    // Get radius from center
                    QVector2D position( static_cast<float>( xCoord ), static_cast<float>( yCoord ) );
                    qreal radius = static_cast<qreal>( position.length() );

                    // Get angle in degrees
                    qreal angle = qRadiansToDegrees( qAtan2( yCoord, xCoord ) );

                    if( angle < 0.0 ) {
                        angle += 360.0;
                    }

                    if( radius > threshold ) {
                        qreal halfRange = rangeDegrees / 2.0;

                        if( angle > 90.0 - halfRange && angle < 90.0 + halfRange ) {
                            gamepad.button[ SDL_CONTROLLER_BUTTON_DPAD_UP ] = true;
                        }

                        if( angle > 270.0 - halfRange && angle < 270.0 + halfRange ) {
                            gamepad.button[ SDL_CONTROLLER_BUTTON_DPAD_DOWN ] = true;
                        }

                        if( angle > 180.0 - halfRange && angle < 180.0 + halfRange ) {
                            gamepad.button[ SDL_CONTROLLER_BUTTON_DPAD_LEFT ] = true;
                        }

                        if( angle > 360.0 - halfRange || angle < 0.0 + halfRange ) {
                            gamepad.button[ SDL_CONTROLLER_BUTTON_DPAD_RIGHT ] = true;
                        }
                    }
                }
            }

            // Apply d-pad to axis, if enabled
            {
                if( dpadToAnalog[ GUID ] ) {
                    gamepad = mapDpadToAnalog( gamepad );
                }
            }

            // Send updated data out
            {
                // Copy current gamepad into buffer
                this->mutex.lock();
                gamepadBuffer[ gamepadBufferIndex ] = gamepad;
                this->mutex.unlock();

                // Send buffer on its way
                emit dataOut( DataType::Input, &( this->mutex ),
                              reinterpret_cast<void *>( &gamepadBuffer[ gamepadBufferIndex ] ), 0,
                              nodeCurrentTime() );

                // Increment the index
                gamepadBufferIndex = ( gamepadBufferIndex + 1 ) % 100;
            }
            break;
        }

        case DataType::KeyboardInput: {
            // Unpack keyboard states and write to gamepad according to remap data
            {
                mutex->lock();
                KeyboardState keyboard = *reinterpret_cast<KeyboardState *>( data );

                for( int i = keyboard.head; i < keyboard.tail; i = ( i + 1 ) % 128 ) {
                    int key = keyboard.key[ i ];
                    bool pressed = keyboard.pressed[ i ];

                    if( keyboardKeyToSDLButton.contains( key ) ) {
                        keyboardGamepad.button[ keyboardKeyToSDLButton[ key ] ] = pressed ? SDL_PRESSED : SDL_RELEASED;
                    }
                }

                mutex->unlock();
            }

            // OR all key states together and store that value
            for( int i = 0; i < SDL_CONTROLLER_BUTTON_MAX; i++ ) {
                keyboardKeyPressed |= keyboardGamepad.button[ i ];
            }

            // Apply d-pad to axis, if enabled
            if( dpadToAnalogKeyboard ) {
                keyboardGamepad = mapDpadToAnalog( keyboardGamepad, true );
            }

            // Send gamepad on its way
            {
                // Copy current gamepad into buffer
                this->mutex.lock();
                gamepadBuffer[ gamepadBufferIndex ] = keyboardGamepad;
                this->mutex.unlock();

                // Send buffer on its way
                emit dataOut( DataType::Input, &( this->mutex ),
                              reinterpret_cast< void * >( &gamepadBuffer[ gamepadBufferIndex ] ), 0,
                              nodeCurrentTime() );

                // Increment the index
                gamepadBufferIndex = ( gamepadBufferIndex + 1 ) % 100;
            }
            break;
        }

        default: {
            emit dataOut( type, mutex, data, bytes, timeStamp );
            break;
        }
    }
}
示例#24
0
NEON_API int
application_exec(const char *title, APP_STATE *states, size_t states_n) {
    allstates = states;
    states_num = states_n;

    if (SDL_Init(SDL_INIT_EVERYTHING) < 0) {
        LOG_ERROR("%s\n", SDL_GetError());
        return EXIT_FAILURE;
    }

    atexit(SDL_Quit);

    if (TTF_Init() < 0) {
        LOG_ERROR("%s\n", TTF_GetError());
        return EXIT_FAILURE;
    }

    atexit(TTF_Quit);

    if ((states_stack = new_stack(sizeof(APP_STATE), states_n + 1)) == NULL) {
        LOG_ERROR("%s\n", "Can\'t create game states stack");
        return EXIT_FAILURE;
    }

    LOG("%s launched...\n", title);
    LOG("Platform: %s\n", SDL_GetPlatform());

    video_init(title);
    audio_init();

    atexit(application_cleanup);

    application_next_state(0);

    if (is_stack_empty(states_stack)) {
        LOG_CRITICAL("%s\n", "No game states");
        exit(EXIT_FAILURE);
    }

    SDL_Event event;

    Uint64 current = 0;
    Uint64 last = 0;

    float accumulator = 0.0f;

    while(running) {
        frame_begin();

        while(SDL_PollEvent(&event)) {
            ((APP_STATE*)top_stack(states_stack))->on_event(&event);
        }

        asset_process();
        resources_process();

        last = current;
        current = SDL_GetPerformanceCounter();
        Uint64 freq = SDL_GetPerformanceFrequency();

        float delta = (double)(current - last) / (double)freq;

        accumulator += CLAMP(delta, 0.f, 0.2f);

        while(accumulator >= TIMESTEP) {
            accumulator -= TIMESTEP;
            ((APP_STATE*)top_stack(states_stack))->on_update(TIMESTEP);
        }

        ((APP_STATE*)top_stack(states_stack))->on_present(screen.width, screen.height, accumulator / TIMESTEP);
        video_swap_buffers();

        frame_end();

        SDL_Delay(1);
    }

    return EXIT_SUCCESS;
}
示例#25
0
	const char* System::GetPlatformName()
	{
		return SDL_GetPlatform();
	}
示例#26
0
/*
 * Add or update an entry into the Mappings Database
 */
int
SDL_GameControllerAddMappingsFromRW(SDL_RWops * rw, int freerw)
{
    const char *platform = SDL_GetPlatform();
    int controllers = 0;
    char *buf, *line, *line_end, *tmp, *comma, line_platform[64];
    size_t db_size, platform_len;

    if (rw == NULL) {
        return SDL_SetError("Invalid RWops");
    }
    db_size = (size_t)SDL_RWsize(rw);

    buf = (char *)SDL_malloc(db_size + 1);
    if (buf == NULL) {
        if (freerw) {
            SDL_RWclose(rw);
        }
        return SDL_SetError("Could allocate space to not read DB into memory");
    }

    if (SDL_RWread(rw, buf, db_size, 1) != 1) {
        if (freerw) {
            SDL_RWclose(rw);
        }
        SDL_free(buf);
        return SDL_SetError("Could not read DB");
    }

    if (freerw) {
        SDL_RWclose(rw);
    }

    buf[db_size] = '\0';
    line = buf;

    while (line < buf + db_size) {
        line_end = SDL_strchr(line, '\n');
        if (line_end != NULL) {
            *line_end = '\0';
        } else {
            line_end = buf + db_size;
        }

        /* Extract and verify the platform */
        tmp = SDL_strstr(line, SDL_CONTROLLER_PLATFORM_FIELD);
        if (tmp != NULL) {
            tmp += SDL_strlen(SDL_CONTROLLER_PLATFORM_FIELD);
            comma = SDL_strchr(tmp, ',');
            if (comma != NULL) {
                platform_len = comma - tmp + 1;
                if (platform_len + 1 < SDL_arraysize(line_platform)) {
                    SDL_strlcpy(line_platform, tmp, platform_len);
                    if (SDL_strncasecmp(line_platform, platform, platform_len) == 0 &&
                        SDL_GameControllerAddMapping(line) > 0) {
                        controllers++;
                    }
                }
            }
        }

        line = line_end + 1;
    }

    SDL_free(buf);
    return controllers;
}
示例#27
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;
}
示例#28
0
文件: Pi.cpp 项目: lwho/pioneer
void Pi::Init(const std::map<std::string,std::string> &options, bool no_gui)
{
#ifdef PIONEER_PROFILER
	Profiler::reset();
#endif

	Profiler::Timer timer;
	timer.Start();

	OS::EnableBreakpad();
	OS::NotifyLoadBegin();

	FileSystem::Init();
	FileSystem::userFiles.MakeDirectory(""); // ensure the config directory exists
#ifdef PIONEER_PROFILER
	FileSystem::userFiles.MakeDirectory("profiler");
	profilerPath = FileSystem::JoinPathBelow(FileSystem::userFiles.GetRoot(), "profiler");
#endif

	Pi::config = new GameConfig(options);

	if (config->Int("RedirectStdio"))
		OS::RedirectStdio();

	std::string version(PIONEER_VERSION);
	if (strlen(PIONEER_EXTRAVERSION)) version += " (" PIONEER_EXTRAVERSION ")";
	const char* platformName = SDL_GetPlatform();
	if(platformName)
		Output("ver %s on: %s\n\n", version.c_str(), platformName);
	else
		Output("ver %s but could not detect platform name.\n\n", version.c_str());

	Output("%s\n", OS::GetOSInfoString().c_str());

	ModManager::Init();

	Lang::Resource res(Lang::GetResource("core", config->String("Lang")));
	Lang::MakeCore(res);

	Pi::detail.planets = config->Int("DetailPlanets");
	Pi::detail.textures = config->Int("Textures");
	Pi::detail.fracmult = config->Int("FractalMultiple");
	Pi::detail.cities = config->Int("DetailCities");

	// Initialize SDL
	Uint32 sdlInitFlags = SDL_INIT_VIDEO | SDL_INIT_JOYSTICK;
#if defined(DEBUG) || defined(_DEBUG)
	sdlInitFlags |= SDL_INIT_NOPARACHUTE;
#endif
	if (SDL_Init(sdlInitFlags) < 0) {
		Error("SDL initialization failed: %s\n", SDL_GetError());
	}
	SDL_version ver;
	SDL_GetVersion(&ver);
	Output("SDL Version %d.%d.%d\n", ver.major, ver.minor, ver.patch);

	Graphics::RendererOGL::RegisterRenderer();

	// Do rest of SDL video initialization and create Renderer
	Graphics::Settings videoSettings = {};
	videoSettings.rendererType = Graphics::RENDERER_OPENGL;
	videoSettings.width = config->Int("ScrWidth");
	videoSettings.height = config->Int("ScrHeight");
	videoSettings.fullscreen = (config->Int("StartFullscreen") != 0);
	videoSettings.hidden = no_gui;
	videoSettings.requestedSamples = config->Int("AntiAliasingMode");
	videoSettings.vsync = (config->Int("VSync") != 0);
	videoSettings.useTextureCompression = (config->Int("UseTextureCompression") != 0);
	videoSettings.enableDebugMessages = (config->Int("EnableGLDebug") != 0);
	videoSettings.iconFile = OS::GetIconFilename();
	videoSettings.title = "Pioneer";

	Pi::renderer = Graphics::Init(videoSettings);

	Pi::CreateRenderTarget(videoSettings.width, videoSettings.height);
	Pi::rng.IncRefCount(); // so nothing tries to free it
	Pi::rng.seed(time(0));

	InitJoysticks();
	
	// we can only do bindings once joysticks are initialised.
	if (!no_gui) // This re-saves the config file. With no GUI we want to allow multiple instances in parallel.
		KeyBindings::InitBindings();

	joystickEnabled = (config->Int("EnableJoystick")) ? true : false;
	mouseYInvert = (config->Int("InvertMouseY")) ? true : false;
	compactScanner = (config->Int("CompactScanner")) ? true : false;

	navTunnelDisplayed = (config->Int("DisplayNavTunnel")) ? true : false;
	speedLinesDisplayed = (config->Int("SpeedLines")) ? true : false;
	hudTrailsDisplayed = (config->Int("HudTrails")) ? true : false;

	EnumStrings::Init();

	// get threads up
	Uint32 numThreads = config->Int("WorkerThreads");
	const int numCores = OS::GetNumCores();
	assert(numCores > 0);
	if (numThreads == 0) numThreads = std::max(Uint32(numCores) - 1, 1U);
	asyncJobQueue.reset(new AsyncJobQueue(numThreads));
	Output("started %d worker threads\n", numThreads);
	syncJobQueue.reset(new SyncJobQueue);
	
	Output("ShipType::Init()\n");
	// XXX early, Lua init needs it
	ShipType::Init();

	// XXX UI requires Lua  but Pi::ui must exist before we start loading
	// templates. so now we have crap everywhere :/
	Output("Lua::Init()\n");
	Lua::Init();

	Pi::ui.Reset(new UI::Context(Lua::manager, Pi::renderer, Graphics::GetScreenWidth(), Graphics::GetScreenHeight()));

	LuaInit();

	// Gui::Init shouldn't initialise any VBOs, since we haven't tested
	// that the capability exists. (Gui does not use VBOs so far)
	Gui::Init(renderer, Graphics::GetScreenWidth(), Graphics::GetScreenHeight(), 800, 600);

	UI::Box *box = Pi::ui->VBox(5);
	UI::Label *label = Pi::ui->Label("");
	label->SetFont(UI::Widget::FONT_HEADING_NORMAL);
	UI::Gauge *gauge = Pi::ui->Gauge();
	Pi::ui->GetTopLayer()->SetInnerWidget(
		Pi::ui->Margin(10, UI::Margin::HORIZONTAL)->SetInnerWidget(
			Pi::ui->Expand()->SetInnerWidget(
				Pi::ui->Align(UI::Align::MIDDLE)->SetInnerWidget(
					box->PackEnd(UI::WidgetSet(
						label,
						gauge
					))
				)
			)
		)
    );

	draw_progress(gauge, label, 0.0f);

	Output("GalaxyGenerator::Init()\n");
	if (config->HasEntry("GalaxyGenerator"))
		GalaxyGenerator::Init(config->String("GalaxyGenerator"),
			config->Int("GalaxyGeneratorVersion", GalaxyGenerator::LAST_VERSION));
	else
		GalaxyGenerator::Init();

	draw_progress(gauge, label, 0.1f);

	Output("FaceParts::Init()\n");
	FaceParts::Init();
	draw_progress(gauge, label, 0.2f);

	Output("new ModelCache\n");
	modelCache = new ModelCache(Pi::renderer);
	draw_progress(gauge, label, 0.3f);

	Output("Shields::Init\n");
	Shields::Init(Pi::renderer);
	draw_progress(gauge, label, 0.4f);

//unsigned int control_word;
//_clearfp();
//_controlfp_s(&control_word, _EM_INEXACT | _EM_UNDERFLOW | _EM_ZERODIVIDE, _MCW_EM);
//double fpexcept = Pi::timeAccelRates[1] / Pi::timeAccelRates[0];

	Output("BaseSphere::Init\n");
	BaseSphere::Init();
	draw_progress(gauge, label, 0.5f);

	Output("CityOnPlanet::Init\n");
	CityOnPlanet::Init();
	draw_progress(gauge, label, 0.6f);
	
	Output("SpaceStation::Init\n");
	SpaceStation::Init();
	draw_progress(gauge, label, 0.7f);
	
	Output("NavLights::Init\n");
	NavLights::Init(Pi::renderer);
	draw_progress(gauge, label, 0.75f);

	Output("Sfx::Init\n");
	Sfx::Init(Pi::renderer);
	draw_progress(gauge, label, 0.8f);

	if (!no_gui && !config->Int("DisableSound")) {
		Output("Sound::Init\n");
		Sound::Init();
		Sound::SetMasterVolume(config->Float("MasterVolume"));
		Sound::SetSfxVolume(config->Float("SfxVolume"));
		GetMusicPlayer().SetVolume(config->Float("MusicVolume"));

		Sound::Pause(0);
		if (config->Int("MasterMuted")) Sound::Pause(1);
		if (config->Int("SfxMuted")) Sound::SetSfxVolume(0.f);
		if (config->Int("MusicMuted")) GetMusicPlayer().SetEnabled(false);
	}
	draw_progress(gauge, label, 0.9f);

	OS::NotifyLoadEnd();
	draw_progress(gauge, label, 1.0f);

#if 0
	// frame test code

	Frame *root = new Frame(0, "root", 0);
	Frame *p1 = new Frame(root, "p1", Frame::FLAG_HAS_ROT);
	Frame *p1r = new Frame(p1, "p1r", Frame::FLAG_ROTATING);
	Frame *m1 = new Frame(p1, "m1", Frame::FLAG_HAS_ROT);
	Frame *m1r = new Frame(m1, "m1r", Frame::FLAG_ROTATING);
	Frame *p2 = new Frame(root, "p2", Frame::FLAG_HAS_ROT);
	Frame *p2r = new Frame(p2, "pr2", Frame::FLAG_ROTATING);

	p1->SetPosition(vector3d(1000,0,0));
	p1->SetVelocity(vector3d(0,1,0));
	p2->SetPosition(vector3d(0,2000,0));
	p2->SetVelocity(vector3d(-2,0,0));
	p1r->SetAngVelocity(vector3d(0,0,0.0001));
	p1r->SetOrient(matrix3x3d::BuildRotate(M_PI/4, vector3d(0,0,1)));
	p2r->SetAngVelocity(vector3d(0,0,-0.0004));
	p2r->SetOrient(matrix3x3d::BuildRotate(-M_PI/2, vector3d(0,0,1)));
	root->UpdateOrbitRails(0, 0);

	CargoBody *c1 = new CargoBody(Equip::Type::SLAVES);
	c1->SetFrame(p1r);
	c1->SetPosition(vector3d(0,180,0));
//	c1->SetVelocity(vector3d(1,0,0));
	CargoBody *c2 = new CargoBody(Equip::Type::SLAVES);
	c2->SetFrame(p1r);
	c2->SetPosition(vector3d(0,200,0));
//	c2->SetVelocity(vector3d(1,0,0));

	vector3d pos = c1->GetPositionRelTo(p1);
	vector3d vel = c1->GetVelocityRelTo(p1);
	double speed = vel.Length();
	vector3d pos2 = c2->GetPositionRelTo(p1);
	vector3d vel2 = c2->GetVelocityRelTo(p1);
	double speed2 = vel2.Length();

	double speed3 = c2->GetVelocityRelTo(c1).Length();
	c2->SwitchToFrame(p1);
	vector3d vel4 = c2->GetVelocityRelTo(c1);
	double speed4 = c2->GetVelocityRelTo(c1).Length();

	root->UpdateOrbitRails(0, 1.0);

	//buildrotate test

	matrix3x3d m = matrix3x3d::BuildRotate(M_PI/2, vector3d(0,0,1));
	vector3d v = m * vector3d(1,0,0);

/*	vector3d pos = p1r->GetPositionRelTo(p2r);
	vector3d vel = p1r->GetVelocityRelTo(p2r);
	matrix3x3d o1 = p1r->GetOrientRelTo(p2r);
	double speed = vel.Length();
	vector3d pos2 = p2r->GetPositionRelTo(p1r);
	vector3d vel2 = p2r->GetVelocityRelTo(p1r);
	matrix3x3d o2 = p2r->GetOrientRelTo(p1r);
	double speed2 = vel2.Length();
*/	root->UpdateOrbitRails(0, 1.0/60);

	delete p2r; delete p2; delete m1r; delete m1; delete p1r; delete p1; delete root;
	delete c1; delete c2;

#endif

#if 0
	// test code to produce list of ship stats

	FILE *pStatFile = fopen("shipstat.csv","wt");
	if (pStatFile)
	{
		fprintf(pStatFile, "name,modelname,hullmass,capacity,fakevol,rescale,xsize,ysize,zsize,facc,racc,uacc,sacc,aacc,exvel\n");
		for (auto iter : ShipType::types)
		{
			const ShipType *shipdef = &(iter.second);
			SceneGraph::Model *model = Pi::FindModel(shipdef->modelName, false);

			double hullmass = shipdef->hullMass;
			double capacity = shipdef->capacity;

			double xsize = 0.0, ysize = 0.0, zsize = 0.0, fakevol = 0.0, rescale = 0.0, brad = 0.0;
			if (model) {
				std::unique_ptr<SceneGraph::Model> inst(model->MakeInstance());
				model->CreateCollisionMesh();
				Aabb aabb = model->GetCollisionMesh()->GetAabb();
				xsize = aabb.max.x-aabb.min.x;
				ysize = aabb.max.y-aabb.min.y;
				zsize = aabb.max.z-aabb.min.z;
				fakevol = xsize*ysize*zsize;
				brad = aabb.GetRadius();
				rescale = pow(fakevol/(100 * (hullmass+capacity)), 0.3333333333);
			}

			double simass = (hullmass + capacity) * 1000.0;
			double angInertia = (2/5.0)*simass*brad*brad;
			double acc1 = shipdef->linThrust[ShipType::THRUSTER_FORWARD] / (9.81*simass);
			double acc2 = shipdef->linThrust[ShipType::THRUSTER_REVERSE] / (9.81*simass);
			double acc3 = shipdef->linThrust[ShipType::THRUSTER_UP] / (9.81*simass);
			double acc4 = shipdef->linThrust[ShipType::THRUSTER_RIGHT] / (9.81*simass);
			double acca = shipdef->angThrust/angInertia;
			double exvel = shipdef->effectiveExhaustVelocity;

			fprintf(pStatFile, "%s,%s,%.1f,%.1f,%.1f,%.3f,%.1f,%.1f,%.1f,%.1f,%.1f,%.1f,%.1f,%f,%.1f\n",
				shipdef->name.c_str(), shipdef->modelName.c_str(), hullmass, capacity,
				fakevol, rescale, xsize, ysize, zsize, acc1, acc2, acc3, acc4, acca, exvel);
		}
		fclose(pStatFile);
	}
#endif

	luaConsole = new LuaConsole();
	KeyBindings::toggleLuaConsole.onPress.connect(sigc::mem_fun(Pi::luaConsole, &LuaConsole::Toggle));

	planner = new TransferPlanner();

	timer.Stop();
	Output("\n\nLoading took: %lf milliseconds\n", timer.millicycles());
}
示例#29
0
/**
 * \brief Returns the name of the running OS.
 *
 * Possible values are "Windows", "Mac OS X", "Linux", "iOS" and "Android".
 *
 * If the correct OS name is not available, returns a string
 * beginning with the text "Unknown".
 * \return the name of the running OS.
 */
std::string System::get_os() {

  return SDL_GetPlatform();
}