// returns the first valid (long) integer value from the current position. // initial characters that are not digits (or the minus sign) are skipped // function is terminated by the first character that is not a digit. long Stream::parseInt() { return parseInt(NO_SKIP_CHAR); // terminate on first non-digit character (or timeout) }
/** * Parses a line from client. (Overloading from superclass) */ void ClientBMDSmartView::_parseline() { if (!strcmp(_buffer,"")) { _section = 0; } else if (!strcmp_P(_buffer,PSTR("PROTOCOL PREAMBLE:"))) { //strcmp_P("RAM STRING", PSTR("FLASH STRING")); _section = 1; _hasInitialized = true; if (_serialOutput) Serial.println(F("Connection confirmed, getting status")); } else if (!strcmp_P(_buffer,PSTR("SMARTVIEW DEVICE:"))) { _section = 2; } else if (!strcmp_P(_buffer,PSTR("NETWORK:"))) { _section = 3; } else if (!strcmp_P(_buffer,PSTR("MONITOR A:"))) { _section = 4; } else if (!strcmp_P(_buffer,PSTR("MONITOR B:"))) { _section = 5; } else { _bufferReadIndex = 0; switch(_section) { case 4: // Monitor A or B: case 5: if (isNextPartOfBuffer_P(PSTR("Brightness: "))) { _Smart_brightness[_section-4] = parseInt(); if (_serialOutput>1) { Serial.print(F("Brightness, Mon ")); Serial.print(_section-4); Serial.print(F(": ")); Serial.println(_Smart_brightness[_section-4]); } } if (isNextPartOfBuffer_P(PSTR("Contrast: "))) { _Smart_contrast[_section-4] = parseInt(); if (_serialOutput>1) { Serial.print(F("Contrast, Mon ")); Serial.print(_section-4); Serial.print(F(": ")); Serial.println(_Smart_contrast[_section-4]); } } if (isNextPartOfBuffer_P(PSTR("Saturation: "))) { _Smart_saturation[_section-4] = parseInt(); if (_serialOutput>1) { Serial.print(F("Saturation, Mon ")); Serial.print(_section-4); Serial.print(F(": ")); Serial.println(_Smart_saturation[_section-4]); } } if (isNextPartOfBuffer_P(PSTR("Identify: "))) { if (isNextPartOfBuffer_P(PSTR("true"))) { _Smart_identify[_section-4] = true; } else { _Smart_identify[_section-4] = false; } if (_serialOutput>1) { Serial.print(F("Identify, Mon ")); Serial.print(_section-4); Serial.print(F(": ")); Serial.println(_Smart_identify[_section-4]); } } if (isNextPartOfBuffer_P(PSTR("Border: "))) { if (isNextPartOfBuffer_P(PSTR("None"))) { _Smart_border[_section-4] = 0; } else if (isNextPartOfBuffer_P(PSTR("Red"))) { _Smart_border[_section-4] = 1; } else if (isNextPartOfBuffer_P(PSTR("Green"))) { _Smart_border[_section-4] = 2; } else if (isNextPartOfBuffer_P(PSTR("Blue"))) { _Smart_border[_section-4] = 3; /* } else if (isNextPartOfBuffer_P(PSTR("White"))) { // Doesn't work yet? _Smart_border[_section-4] = 4; */ } else { _Smart_border[_section-4] = 255; } if (_serialOutput>1) { Serial.print(F("Identify, Mon ")); Serial.print(_section-4); Serial.print(F(": ")); Serial.println(_Smart_border[_section-4]); } } if (isNextPartOfBuffer_P(PSTR("WidescreenSD: "))) { if (isNextPartOfBuffer_P(PSTR("auto"))) { _Smart_widescreenSD[_section-4] = 0; } else if (isNextPartOfBuffer_P(PSTR("on"))) { _Smart_widescreenSD[_section-4] = 1; } else if (isNextPartOfBuffer_P(PSTR("off"))) { _Smart_widescreenSD[_section-4] = 2; } else { _Smart_widescreenSD[_section-4] = 255; } if (_serialOutput>1) { Serial.print(F("WidescreenSD, Mon ")); Serial.print(_section-4); Serial.print(F(": ")); Serial.println(_Smart_widescreenSD[_section-4]); } } if (isNextPartOfBuffer_P(PSTR("ScopeMode: "))) { if (isNextPartOfBuffer_P(PSTR("Picture"))) { _Smart_scopeMode[_section-4] = 0; } else if (isNextPartOfBuffer_P(PSTR("AudioDbfs"))) { _Smart_scopeMode[_section-4] = 1; } else if (isNextPartOfBuffer_P(PSTR("AudioDbvu"))) { _Smart_scopeMode[_section-4] = 2; } else if (isNextPartOfBuffer_P(PSTR("Histogram"))) { _Smart_scopeMode[_section-4] = 3; } else if (isNextPartOfBuffer_P(PSTR("ParadeRGB"))) { _Smart_scopeMode[_section-4] = 4; } else if (isNextPartOfBuffer_P(PSTR("ParadeYUV"))) { _Smart_scopeMode[_section-4] = 5; } else if (isNextPartOfBuffer_P(PSTR("Vector100"))) { _Smart_scopeMode[_section-4] = 6; } else if (isNextPartOfBuffer_P(PSTR("Vector75"))) { _Smart_scopeMode[_section-4] = 7; } else if (isNextPartOfBuffer_P(PSTR("WaveformLuma"))) { _Smart_scopeMode[_section-4] = 8; } else { _Smart_scopeMode[_section-4] = 255; } if (_serialOutput>1) { Serial.print(F("ScopeMode, Mon ")); Serial.print(_section-4); Serial.print(F(": ")); Serial.println(_Smart_scopeMode[_section-4]); } } if (isNextPartOfBuffer_P(PSTR("AudioChannel: "))) { _Smart_audioChannel[_section-4] = parseInt(); if (_serialOutput>1) { Serial.print(F("AudioChannel, Mon ")); Serial.print(_section-4); Serial.print(F(": ")); Serial.println(_Smart_audioChannel[_section-4]); } } break; } } }
Colour getColour() const { return Colour ((uint32) parseInt (editor.value.getStringValue (false))); }
int main( int argc, char* argv[] ){ setbuf(stdout, NULL); // set buffer to null, so prints ALWAYS print (for debug purposes mainly) bool verify = false; bool printtime = true; // Command line parsing char c; while ((c = getopt (argc, argv, "nc:s:p:T:t:w:hv")) != -1){ switch( c ) { case 'n': // print time printtime = false; break; case 'c': // cores cores = parseInt( optarg ); if( cores <= 0 ){ fprintf(stderr, "cores must be greater than 0: %d\n", cores); exit( 0 ); } break; case 'p': // problem size problemSize = parseInt( optarg ); if( problemSize <= 0 ){ fprintf(stderr, "problemSize must be greater than 0: %d\n", problemSize); exit( 0 ); } break; case 'T': // T (time steps) T = parseInt( optarg ); if( T <= 0 ){ fprintf(stderr, "T must be greater than 0: %d\n", T); exit( 0 ); } break; case 't': // timeBand timeBand = parseInt( optarg ); if( timeBand <= 0 ){ fprintf(stderr, "t must be greater than 0: %d\n", T); exit( 0 ); } break; case 'w': // width width_max = parseInt( optarg ); if( width_max <= 0 ){ fprintf(stderr, "w must be greater than 0: %d\n", T); exit( 0 ); } break; case 'h': // help printf("usage: %s\n-n \t dont print time \n-p <problem size> \t problem size in elements \n-T <time steps>\t number of time steps\n-c <cores>\tnumber of threads\n-w <tile width>\t the width of the tile\n-t <tile height>\t the number of timesteps in a tile\n-h\tthis dialogue\n-v\tverify output\n", argv[0]); exit(0); case 'v': // verify; verify = true; break; case '?': if (optopt == 'p') fprintf (stderr, "Option -%c requires positive int argument: problem size.\n", optopt); else if (optopt == 'T') fprintf (stderr, "Option -%c requires positive int argument: T.\n", optopt); else if (optopt == 's') fprintf (stderr, "Option -%c requires int argument: subset_s.\n", optopt); else if (optopt == 'c') fprintf (stderr, "Option -%c requires int argument: number of cores.\n", optopt); else if (isprint (optopt)) fprintf (stderr, "Unknown option `-%c'.\n", optopt); else fprintf(stderr, "Unknown option character `\\x%x'.\n", optopt); exit(0); default: exit(0); } } initJacobi(); initTrapezoid(); initSpace(); double time = test_1(); if( printtime ){ printf( "Time: %f\n", time ); } if( verify ){ verifyResult( true ); } }
// Odd case where 'exec' is allowed to be 0, to accomodate a caller in WebCore. double parseDateFromNullTerminatedCharacters(const char* dateString, bool& haveTZ, int& offset) { haveTZ = false; offset = 0; // This parses a date in the form: // Tuesday, 09-Nov-99 23:12:40 GMT // or // Sat, 01-Jan-2000 08:00:00 GMT // or // Sat, 01 Jan 2000 08:00:00 GMT // or // 01 Jan 99 22:00 +0100 (exceptions in rfc822/rfc2822) // ### non RFC formats, added for Javascript: // [Wednesday] January 09 1999 23:12:40 GMT // [Wednesday] January 09 23:12:40 GMT 1999 // // We ignore the weekday. // Skip leading space skipSpacesAndComments(dateString); long month = -1; const char *wordStart = dateString; // Check contents of first words if not number while (*dateString && !isASCIIDigit(*dateString)) { if (isASCIISpace(*dateString) || *dateString == '(') { if (dateString - wordStart >= 3) month = findMonth(wordStart); skipSpacesAndComments(dateString); wordStart = dateString; } else dateString++; } // Missing delimiter between month and day (like "January29")? if (month == -1 && wordStart != dateString) month = findMonth(wordStart); skipSpacesAndComments(dateString); if (!*dateString) return std::numeric_limits<double>::quiet_NaN(); // ' 09-Nov-99 23:12:40 GMT' char* newPosStr; long day; if (!parseLong(dateString, &newPosStr, 10, &day)) return std::numeric_limits<double>::quiet_NaN(); dateString = newPosStr; if (!*dateString) return std::numeric_limits<double>::quiet_NaN(); if (day < 0) return std::numeric_limits<double>::quiet_NaN(); int year = 0; if (day > 31) { // ### where is the boundary and what happens below? if (*dateString != '/') return std::numeric_limits<double>::quiet_NaN(); // looks like a YYYY/MM/DD date if (!*++dateString) return std::numeric_limits<double>::quiet_NaN(); if (day <= std::numeric_limits<int>::min() || day >= std::numeric_limits<int>::max()) return std::numeric_limits<double>::quiet_NaN(); year = static_cast<int>(day); if (!parseLong(dateString, &newPosStr, 10, &month)) return std::numeric_limits<double>::quiet_NaN(); month -= 1; dateString = newPosStr; if (*dateString++ != '/' || !*dateString) return std::numeric_limits<double>::quiet_NaN(); if (!parseLong(dateString, &newPosStr, 10, &day)) return std::numeric_limits<double>::quiet_NaN(); dateString = newPosStr; } else if (*dateString == '/' && month == -1) { dateString++; // This looks like a MM/DD/YYYY date, not an RFC date. month = day - 1; // 0-based if (!parseLong(dateString, &newPosStr, 10, &day)) return std::numeric_limits<double>::quiet_NaN(); if (day < 1 || day > 31) return std::numeric_limits<double>::quiet_NaN(); dateString = newPosStr; if (*dateString == '/') dateString++; if (!*dateString) return std::numeric_limits<double>::quiet_NaN(); } else { if (*dateString == '-') dateString++; skipSpacesAndComments(dateString); if (*dateString == ',') dateString++; if (month == -1) { // not found yet month = findMonth(dateString); if (month == -1) return std::numeric_limits<double>::quiet_NaN(); while (*dateString && *dateString != '-' && *dateString != ',' && !isASCIISpace(*dateString)) dateString++; if (!*dateString) return std::numeric_limits<double>::quiet_NaN(); // '-99 23:12:40 GMT' if (*dateString != '-' && *dateString != '/' && *dateString != ',' && !isASCIISpace(*dateString)) return std::numeric_limits<double>::quiet_NaN(); dateString++; } } if (month < 0 || month > 11) return std::numeric_limits<double>::quiet_NaN(); // '99 23:12:40 GMT' if (year <= 0 && *dateString) { if (!parseInt(dateString, &newPosStr, 10, &year)) return std::numeric_limits<double>::quiet_NaN(); } // Don't fail if the time is missing. long hour = 0; long minute = 0; long second = 0; if (!*newPosStr) dateString = newPosStr; else { // ' 23:12:40 GMT' if (!(isASCIISpace(*newPosStr) || *newPosStr == ',')) { if (*newPosStr != ':') return std::numeric_limits<double>::quiet_NaN(); // There was no year; the number was the hour. year = -1; } else { // in the normal case (we parsed the year), advance to the next number dateString = ++newPosStr; skipSpacesAndComments(dateString); } parseLong(dateString, &newPosStr, 10, &hour); // Do not check for errno here since we want to continue // even if errno was set becasue we are still looking // for the timezone! // Read a number? If not, this might be a timezone name. if (newPosStr != dateString) { dateString = newPosStr; if (hour < 0 || hour > 23) return std::numeric_limits<double>::quiet_NaN(); if (!*dateString) return std::numeric_limits<double>::quiet_NaN(); // ':12:40 GMT' if (*dateString++ != ':') return std::numeric_limits<double>::quiet_NaN(); if (!parseLong(dateString, &newPosStr, 10, &minute)) return std::numeric_limits<double>::quiet_NaN(); dateString = newPosStr; if (minute < 0 || minute > 59) return std::numeric_limits<double>::quiet_NaN(); // ':40 GMT' if (*dateString && *dateString != ':' && !isASCIISpace(*dateString)) return std::numeric_limits<double>::quiet_NaN(); // seconds are optional in rfc822 + rfc2822 if (*dateString ==':') { dateString++; if (!parseLong(dateString, &newPosStr, 10, &second)) return std::numeric_limits<double>::quiet_NaN(); dateString = newPosStr; if (second < 0 || second > 59) return std::numeric_limits<double>::quiet_NaN(); } skipSpacesAndComments(dateString); if (strncasecmp(dateString, "AM", 2) == 0) { if (hour > 12) return std::numeric_limits<double>::quiet_NaN(); if (hour == 12) hour = 0; dateString += 2; skipSpacesAndComments(dateString); } else if (strncasecmp(dateString, "PM", 2) == 0) { if (hour > 12) return std::numeric_limits<double>::quiet_NaN(); if (hour != 12) hour += 12; dateString += 2; skipSpacesAndComments(dateString); } } } // The year may be after the time but before the time zone. if (isASCIIDigit(*dateString) && year == -1) { if (!parseInt(dateString, &newPosStr, 10, &year)) return std::numeric_limits<double>::quiet_NaN(); dateString = newPosStr; skipSpacesAndComments(dateString); } // Don't fail if the time zone is missing. // Some websites omit the time zone (4275206). if (*dateString) { if (strncasecmp(dateString, "GMT", 3) == 0 || strncasecmp(dateString, "UTC", 3) == 0) { dateString += 3; haveTZ = true; } if (*dateString == '+' || *dateString == '-') { int o; if (!parseInt(dateString, &newPosStr, 10, &o)) return std::numeric_limits<double>::quiet_NaN(); dateString = newPosStr; if (o < -9959 || o > 9959) return std::numeric_limits<double>::quiet_NaN(); int sgn = (o < 0) ? -1 : 1; o = abs(o); if (*dateString != ':') { if (o >= 24) offset = ((o / 100) * 60 + (o % 100)) * sgn; else offset = o * 60 * sgn; } else { // GMT+05:00 ++dateString; // skip the ':' int o2; if (!parseInt(dateString, &newPosStr, 10, &o2)) return std::numeric_limits<double>::quiet_NaN(); dateString = newPosStr; offset = (o * 60 + o2) * sgn; } haveTZ = true; } else { for (size_t i = 0; i < WTF_ARRAY_LENGTH(known_zones); ++i) { if (0 == strncasecmp(dateString, known_zones[i].tzName, strlen(known_zones[i].tzName))) { offset = known_zones[i].tzOffset; dateString += strlen(known_zones[i].tzName); haveTZ = true; break; } } } } skipSpacesAndComments(dateString); if (*dateString && year == -1) { if (!parseInt(dateString, &newPosStr, 10, &year)) return std::numeric_limits<double>::quiet_NaN(); dateString = newPosStr; skipSpacesAndComments(dateString); } // Trailing garbage if (*dateString) return std::numeric_limits<double>::quiet_NaN(); // Y2K: Handle 2 digit years. if (year >= 0 && year < 100) { if (year < 50) year += 2000; else year += 1900; } return ymdhmsToSeconds(year, month + 1, day, hour, minute, second) * msPerSecond; }
/** Implements the parsing of expressions that are part of the core language The core language supports: - Functions (but not closures) - Integer literals (decimal only) - String literals - Tuple literals [a,b] - If-else expressions - Sequencing blocks with {a;b} - Function calls fun(a,b) */ Tuple coreParseExpr(Input* input) { // Consume whitespace input->eatWS(); // Numerical constant if (isdigit(input->peekCh())) { return parseInt(input); } // String literal if (input->matchCh('\'')) { return parseStringLit(input, '\''); } if (input->matchCh('\"')) { return parseStringLit(input, '\"'); } // Tuple expression if (input->matchCh('[')) { return Tuple{ Tuple("tuple"), parseExprList(input, ']') }; } // Block/sequence expression (i.e { a; b; c } if (input->matchCh('{')) { return parseBlockExpr(input, '}'); } // Keywords if (isalnum(input->peekCh())) { // If expression if (input->matchStr("if")) return parseIfExpr(input); // Let expression if (input->matchStr("let")) return parseLetExpr(input); // Function definition expression if (input->matchStr("fun")) return parseFunExpr(input); // Function call expression if (input->matchStr("call")) return parseCallExpr(input); } // Host/magic constants if (input->matchCh('$')) { return parseHostRef(input); } // Variable references if (input->peekCh() == '_' || isalpha(input->peekCh())) { return parseIdent(input); } // Parsing failed throw ParseError(input, "failed to parse expression"); }
int main(int argc, char *argv[]) { glslang::InitializeProcess(); #if PPSSPP_PLATFORM(RPI) bcm_host_init(); #endif putenv((char*)"SDL_VIDEO_CENTERED=1"); SDL_SetHint(SDL_HINT_VIDEO_MINIMIZE_ON_FOCUS_LOSS, "0"); if (VulkanMayBeAvailable()) { printf("Vulkan might be available.\n"); } else { printf("Vulkan is not available.\n"); } int set_xres = -1; int set_yres = -1; bool portrait = false; bool set_ipad = false; float set_dpi = 1.0f; float set_scale = 1.0f; // Produce a new set of arguments with the ones we skip. int remain_argc = 1; const char *remain_argv[256] = { argv[0] }; Uint32 mode = 0; for (int i = 1; i < argc; i++) { if (!strcmp(argv[i],"--fullscreen")) mode |= SDL_WINDOW_FULLSCREEN_DESKTOP; else if (set_xres == -2) set_xres = parseInt(argv[i]); else if (set_yres == -2) set_yres = parseInt(argv[i]); else if (set_dpi == -2) set_dpi = parseFloat(argv[i]); else if (set_scale == -2) set_scale = parseFloat(argv[i]); else if (!strcmp(argv[i],"--xres")) set_xres = -2; else if (!strcmp(argv[i],"--yres")) set_yres = -2; else if (!strcmp(argv[i],"--dpi")) set_dpi = -2; else if (!strcmp(argv[i],"--scale")) set_scale = -2; else if (!strcmp(argv[i],"--ipad")) set_ipad = true; else if (!strcmp(argv[i],"--portrait")) portrait = true; else { remain_argv[remain_argc++] = argv[i]; } } std::string app_name; std::string app_name_nice; std::string version; bool landscape; NativeGetAppInfo(&app_name, &app_name_nice, &landscape, &version); bool joystick_enabled = true; if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER | SDL_INIT_AUDIO) < 0) { fprintf(stderr, "Failed to initialize SDL with joystick support. Retrying without.\n"); joystick_enabled = false; if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) < 0) { fprintf(stderr, "Unable to initialize SDL: %s\n", SDL_GetError()); return 1; } } // TODO: How do we get this into the GraphicsContext? #ifdef USING_EGL if (EGL_Open()) return 1; #endif // Get the video info before doing anything else, so we don't get skewed resolution results. // TODO: support multiple displays correctly SDL_DisplayMode displayMode; int should_be_zero = SDL_GetCurrentDisplayMode(0, &displayMode); if (should_be_zero != 0) { fprintf(stderr, "Could not get display mode: %s\n", SDL_GetError()); return 1; } g_DesktopWidth = displayMode.w; g_DesktopHeight = displayMode.h; SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetSwapInterval(1); // Is resolution is too low to run windowed if (g_DesktopWidth < 480 * 2 && g_DesktopHeight < 272 * 2) { mode |= SDL_WINDOW_FULLSCREEN_DESKTOP; } if (mode & SDL_WINDOW_FULLSCREEN_DESKTOP) { pixel_xres = g_DesktopWidth; pixel_yres = g_DesktopHeight; g_Config.bFullScreen = true; } else { // set a sensible default resolution (2x) pixel_xres = 480 * 2 * set_scale; pixel_yres = 272 * 2 * set_scale; if (portrait) { std::swap(pixel_xres, pixel_yres); } g_Config.bFullScreen = false; } set_dpi = 1.0f / set_dpi; if (set_ipad) { pixel_xres = 1024; pixel_yres = 768; } if (!landscape) { std::swap(pixel_xres, pixel_yres); } if (set_xres > 0) { pixel_xres = set_xres; } if (set_yres > 0) { pixel_yres = set_yres; } float dpi_scale = 1.0f; if (set_dpi > 0) { dpi_scale = set_dpi; } dp_xres = (float)pixel_xres * dpi_scale; dp_yres = (float)pixel_yres * dpi_scale; // Mac / Linux char path[2048]; const char *the_path = getenv("HOME"); if (!the_path) { struct passwd* pwd = getpwuid(getuid()); if (pwd) the_path = pwd->pw_dir; } strcpy(path, the_path); if (path[strlen(path)-1] != '/') strcat(path, "/"); NativeInit(remain_argc, (const char **)remain_argv, path, "/tmp", nullptr); // Use the setting from the config when initing the window. if (g_Config.bFullScreen) mode |= SDL_WINDOW_FULLSCREEN_DESKTOP; int x = SDL_WINDOWPOS_UNDEFINED_DISPLAY(getDisplayNumber()); int y = SDL_WINDOWPOS_UNDEFINED; pixel_in_dps_x = (float)pixel_xres / dp_xres; pixel_in_dps_y = (float)pixel_yres / dp_yres; g_dpi_scale_x = dp_xres / (float)pixel_xres; g_dpi_scale_y = dp_yres / (float)pixel_yres; g_dpi_scale_real_x = g_dpi_scale_x; g_dpi_scale_real_y = g_dpi_scale_y; printf("Pixels: %i x %i\n", pixel_xres, pixel_yres); printf("Virtual pixels: %i x %i\n", dp_xres, dp_yres); GraphicsContext *graphicsContext = nullptr; SDL_Window *window = nullptr; std::string error_message; if (g_Config.iGPUBackend == (int)GPUBackend::OPENGL) { SDLGLGraphicsContext *ctx = new SDLGLGraphicsContext(); if (ctx->Init(window, x, y, mode, &error_message) != 0) { printf("GL init error '%s'\n", error_message.c_str()); } graphicsContext = ctx; } else if (g_Config.iGPUBackend == (int)GPUBackend::VULKAN) { SDLVulkanGraphicsContext *ctx = new SDLVulkanGraphicsContext(); if (!ctx->Init(window, x, y, mode, &error_message)) { printf("Vulkan init error '%s' - falling back to GL\n", error_message.c_str()); g_Config.iGPUBackend = (int)GPUBackend::OPENGL; SetGPUBackend((GPUBackend)g_Config.iGPUBackend); delete ctx; SDLGLGraphicsContext *glctx = new SDLGLGraphicsContext(); glctx->Init(window, x, y, mode, &error_message); graphicsContext = glctx; } else { graphicsContext = ctx; } } bool useEmuThread = g_Config.iGPUBackend == (int)GPUBackend::OPENGL; SDL_SetWindowTitle(window, (app_name_nice + " " + PPSSPP_GIT_VERSION).c_str()); // Since we render from the main thread, there's nothing done here, but we call it to avoid confusion. if (!graphicsContext->InitFromRenderThread(&error_message)) { printf("Init from thread error: '%s'\n", error_message.c_str()); } #ifdef MOBILE_DEVICE SDL_ShowCursor(SDL_DISABLE); #endif if (!useEmuThread) { NativeInitGraphics(graphicsContext); NativeResized(); } SDL_AudioSpec fmt, ret_fmt; memset(&fmt, 0, sizeof(fmt)); fmt.freq = 44100; fmt.format = AUDIO_S16; fmt.channels = 2; fmt.samples = 2048; fmt.callback = &mixaudio; fmt.userdata = (void *)0; if (SDL_OpenAudio(&fmt, &ret_fmt) < 0) { ELOG("Failed to open audio: %s", SDL_GetError()); } else { if (ret_fmt.samples != fmt.samples) // Notify, but still use it ELOG("Output audio samples: %d (requested: %d)", ret_fmt.samples, fmt.samples); if (ret_fmt.freq != fmt.freq || ret_fmt.format != fmt.format || ret_fmt.channels != fmt.channels) { ELOG("Sound buffer format does not match requested format."); ELOG("Output audio freq: %d (requested: %d)", ret_fmt.freq, fmt.freq); ELOG("Output audio format: %d (requested: %d)", ret_fmt.format, fmt.format); ELOG("Output audio channels: %d (requested: %d)", ret_fmt.channels, fmt.channels); ELOG("Provided output format does not match requirement, turning audio off"); SDL_CloseAudio(); } } // Audio must be unpaused _after_ NativeInit() SDL_PauseAudio(0); if (joystick_enabled) { joystick = new SDLJoystick(); } else { joystick = nullptr; } EnableFZ(); int framecount = 0; bool mouseDown = false; if (useEmuThread) { EmuThreadStart(graphicsContext); } graphicsContext->ThreadStart(); while (true) { SDL_Event event; while (SDL_PollEvent(&event)) { float mx = event.motion.x * g_dpi_scale_x; float my = event.motion.y * g_dpi_scale_y; switch (event.type) { case SDL_QUIT: g_QuitRequested = 1; break; #if !defined(MOBILE_DEVICE) case SDL_WINDOWEVENT: switch (event.window.event) { case SDL_WINDOWEVENT_RESIZED: { Uint32 window_flags = SDL_GetWindowFlags(window); bool fullscreen = (window_flags & SDL_WINDOW_FULLSCREEN); pixel_xres = event.window.data1; pixel_yres = event.window.data2; dp_xres = (float)pixel_xres * dpi_scale; dp_yres = (float)pixel_yres * dpi_scale; NativeResized(); // Set variable here in case fullscreen was toggled by hotkey g_Config.bFullScreen = fullscreen; // Hide/Show cursor correctly toggling fullscreen if (lastUIState == UISTATE_INGAME && fullscreen && !g_Config.bShowTouchControls) { SDL_ShowCursor(SDL_DISABLE); } else if (lastUIState != UISTATE_INGAME || !fullscreen) { SDL_ShowCursor(SDL_ENABLE); } break; } default: break; } break; #endif case SDL_KEYDOWN: { if (event.key.repeat > 0) { break;} int k = event.key.keysym.sym; KeyInput key; key.flags = KEY_DOWN; auto mapped = KeyMapRawSDLtoNative.find(k); if (mapped == KeyMapRawSDLtoNative.end() || mapped->second == NKCODE_UNKNOWN) { break; } key.keyCode = mapped->second; key.deviceId = DEVICE_ID_KEYBOARD; NativeKey(key); break; } case SDL_KEYUP: { if (event.key.repeat > 0) { break;} int k = event.key.keysym.sym; KeyInput key; key.flags = KEY_UP; auto mapped = KeyMapRawSDLtoNative.find(k); if (mapped == KeyMapRawSDLtoNative.end() || mapped->second == NKCODE_UNKNOWN) { break; } key.keyCode = mapped->second; key.deviceId = DEVICE_ID_KEYBOARD; NativeKey(key); break; } case SDL_TEXTINPUT: { int pos = 0; int c = u8_nextchar(event.text.text, &pos); KeyInput key; key.flags = KEY_CHAR; key.keyCode = c; key.deviceId = DEVICE_ID_KEYBOARD; NativeKey(key); break; } case SDL_MOUSEBUTTONDOWN: switch (event.button.button) { case SDL_BUTTON_LEFT: { mouseDown = true; TouchInput input; input.x = mx; input.y = my; input.flags = TOUCH_DOWN | TOUCH_MOUSE; input.id = 0; NativeTouch(input); KeyInput key(DEVICE_ID_MOUSE, NKCODE_EXT_MOUSEBUTTON_1, KEY_DOWN); NativeKey(key); } break; case SDL_BUTTON_RIGHT: { KeyInput key(DEVICE_ID_MOUSE, NKCODE_EXT_MOUSEBUTTON_2, KEY_DOWN); NativeKey(key); } break; } break; case SDL_MOUSEWHEEL: { KeyInput key; key.deviceId = DEVICE_ID_MOUSE; if (event.wheel.y > 0) { key.keyCode = NKCODE_EXT_MOUSEWHEEL_UP; } else { key.keyCode = NKCODE_EXT_MOUSEWHEEL_DOWN; } key.flags = KEY_DOWN; NativeKey(key); // SDL2 doesn't consider the mousewheel a button anymore // so let's send the KEY_UP right away. // Maybe KEY_UP alone will suffice? key.flags = KEY_UP; NativeKey(key); } case SDL_MOUSEMOTION: if (mouseDown) { TouchInput input; input.x = mx; input.y = my; input.flags = TOUCH_MOVE | TOUCH_MOUSE; input.id = 0; NativeTouch(input); } break; case SDL_MOUSEBUTTONUP: switch (event.button.button) { case SDL_BUTTON_LEFT: { mouseDown = false; TouchInput input; input.x = mx; input.y = my; input.flags = TOUCH_UP | TOUCH_MOUSE; input.id = 0; NativeTouch(input); KeyInput key(DEVICE_ID_MOUSE, NKCODE_EXT_MOUSEBUTTON_1, KEY_UP); NativeKey(key); } break; case SDL_BUTTON_RIGHT: { KeyInput key(DEVICE_ID_MOUSE, NKCODE_EXT_MOUSEBUTTON_2, KEY_UP); NativeKey(key); } break; } break; default: if (joystick) { joystick->ProcessInput(event); } break; } } if (g_QuitRequested) break; const uint8_t *keys = SDL_GetKeyboardState(NULL); if (emuThreadState == (int)EmuThreadState::DISABLED) { UpdateRunLoop(); } if (g_QuitRequested) break; #if !defined(MOBILE_DEVICE) if (lastUIState != GetUIState()) { lastUIState = GetUIState(); if (lastUIState == UISTATE_INGAME && g_Config.bFullScreen && !g_Config.bShowTouchControls) SDL_ShowCursor(SDL_DISABLE); if (lastUIState != UISTATE_INGAME && g_Config.bFullScreen) SDL_ShowCursor(SDL_ENABLE); } #endif if (framecount % 60 == 0) { // glsl_refresh(); // auto-reloads modified GLSL shaders once per second. } if (emuThreadState != (int)EmuThreadState::DISABLED) { if (!graphicsContext->ThreadFrame()) break; } graphicsContext->SwapBuffers(); ToggleFullScreenIfFlagSet(window); time_update(); framecount++; } if (useEmuThread) { EmuThreadStop(); while (emuThreadState != (int)EmuThreadState::STOPPED) { // Need to keep eating frames to allow the EmuThread to exit correctly. graphicsContext->ThreadFrame(); } EmuThreadJoin(); } delete joystick; if (!useEmuThread) { NativeShutdownGraphics(); } graphicsContext->Shutdown(); graphicsContext->ThreadEnd(); graphicsContext->ShutdownFromRenderThread(); NativeShutdown(); delete graphicsContext; SDL_PauseAudio(1); SDL_CloseAudio(); SDL_Quit(); #if PPSSPP_PLATFORM(RPI) bcm_host_deinit(); #endif glslang::FinalizeProcess(); ILOG("Leaving main"); return 0; }
void Shell::write(size_t argc, const std::string* argv) { if(argc < 2) { printError(ERR_ARGS_INVALID); return; } bool parseSuc; //获取文件描述符 int fd = parseInt(argv[0], parseSuc); if(!parseSuc) { printError(ERR_ARGS_INVALID); return; } enum Types {STRING, INT8, INT16, INT32, INT64}; Types type = Types::STRING; for(size_t i = 2; i < argc; ++i) { const std::string& arg = argv[i]; if(arg == "-s") //以文字模式插入 type = Types::STRING; else if(arg == "-i8") //以int8模式插入 type = Types::INT8; else if(arg == "-16") //以int16模式插入 type = Types::INT16; else if(arg == "-i32") //输int32模式插入 type = Types::INT32; else if(arg == "-i64") //输int64模式插入 type = Types::INT64; } int result; int64_t n64; int32_t n32; int16_t n16; int8_t n8; if(type != Types::STRING) { int64_t n64 = parseInt(argv[1], parseSuc); if(!parseSuc) { printError(ERR_ARGS_INVALID); return; } n32 = n64; n16 = n64; n8 = n64; } switch (type) { case Types::STRING: result = session->writeFile(fd, argv[1].c_str(), argv[1].size()); break; case Types::INT8: result = session->writeFile(fd, (char*) &n8, sizeof(n8)); break; case Types::INT16: result = session->writeFile(fd, (char*) &n16, sizeof(n16)); break; case Types::INT32: result = session->writeFile(fd, (char*) &n32, sizeof(n32)); break; case Types::INT64: result = session->writeFile(fd, (char*) &n64, sizeof(n64)); break; } if(result < 0) { printError(session->getErrno()); return; } std::cout << "write " << result << " bytes" << std::endl; }
void Shell::read(size_t argc, const std::string* argv) { if(argc < 2) { printError(ERR_ARGS_INVALID); return; } bool parseSuc; //获取文件描述符 int fd = parseInt(argv[0], parseSuc); if(!parseSuc) { printError(ERR_ARGS_INVALID); return; } int len = parseInt(argv[1], parseSuc); if(!parseSuc || len <= 0) { printError(ERR_ARGS_INVALID); return; } enum Types {STRING, INT8, INT16, INT32, INT64}; Types type = Types::STRING; for(size_t i = 2; i < argc; ++i) { const std::string& arg = argv[i]; if(arg == "-s") //以文字模式插入 type = Types::STRING; else if(arg == "-i8") //以int8模式插入 type = Types::INT8; else if(arg == "-16") //以int16模式插入 type = Types::INT16; else if(arg == "-i32") //输int32模式插入 type = Types::INT32; else if(arg == "-i64") //输int64模式插入 type = Types::INT64; } int result; std::unique_ptr<char> buf(new char[len + 1]); result = session->readFile(fd, buf.get(), len); if(result < 0) { printError(session->getErrno()); return; } if(result > 0) { buf.get()[result] = '\0'; int64_t intRs; if(type != Types::STRING) { intRs = parseInt(std::string(buf.get()), parseSuc); if(!parseSuc) { printError(ERR_RS_IS_NOT_NUM); return; } } int8_t int8rs = intRs; switch (type) { case Types::STRING: std::cout << buf.get() << std::endl; break; case Types::INT8: std::cout << (int) int8rs << std::endl; break; case Types::INT16: std::cout << (int16_t) intRs << std::endl; break; case Types::INT32: std::cout << (int32_t) intRs << std::endl; break; case Types::INT64: std::cout << (int64_t) intRs << std::endl; break; } } std::cout << "read " << result << " bytes" << std::endl; }
PyObject* VRPyTransform::setPhysicsActivationMode(VRPyTransform* self, PyObject *args) { if (!self->valid()) return NULL; int i = parseInt(args); self->objPtr->getPhysics()->setActivationMode(i); Py_RETURN_TRUE; }
std::string LoadMtl ( std::map<std::string, material_t>& material_map, const char* filename, const char* mtl_basepath) { material_map.clear(); std::stringstream err; std::string filepath; if (mtl_basepath) { filepath = std::string(mtl_basepath) + std::string(filename); } else { filepath = std::string(filename); } std::ifstream ifs(filepath.c_str()); if (!ifs) { err << "Cannot open file [" << filepath << "]" << std::endl; return err.str(); } material_t material; int maxchars = 8192; // Alloc enough size. std::vector<char> buf(maxchars); // Alloc enough size. while (ifs.peek() != -1) { ifs.getline(&buf[0], maxchars); std::string linebuf(&buf[0]); // Trim newline '\r\n' or '\r' if (linebuf.size() > 0) { if (linebuf[linebuf.size()-1] == '\n') linebuf.erase(linebuf.size()-1); } if (linebuf.size() > 0) { if (linebuf[linebuf.size()-1] == '\n') linebuf.erase(linebuf.size()-1); } // Skip if empty line. if (linebuf.empty()) { continue; } // Skip leading space. const char* token = linebuf.c_str(); token += strspn(token, " \t"); assert(token); if (token[0] == '\0') continue; // empty line if (token[0] == '#') continue; // comment line // new mtl if ((0 == strncmp(token, "newmtl", 6)) && isSpace((token[6]))) { // flush previous material. material_map.insert(std::pair<std::string, material_t>(material.name, material)); // initial temporary material InitMaterial(material); // set new mtl name char namebuf[4096]; token += 7; sscanf(token, "%s", namebuf); material.name = namebuf; continue; } // ambient if (token[0] == 'K' && token[1] == 'a' && isSpace((token[2]))) { token += 2; float r, g, b; parseFloat3(r, g, b, token); material.ambient[0] = r; material.ambient[1] = g; material.ambient[2] = b; continue; } // diffuse if (token[0] == 'K' && token[1] == 'd' && isSpace((token[2]))) { token += 2; float r, g, b; parseFloat3(r, g, b, token); material.diffuse[0] = r; material.diffuse[1] = g; material.diffuse[2] = b; continue; } // specular if (token[0] == 'K' && token[1] == 's' && isSpace((token[2]))) { token += 2; float r, g, b; parseFloat3(r, g, b, token); material.specular[0] = r; material.specular[1] = g; material.specular[2] = b; continue; } // transmittance if (token[0] == 'K' && token[1] == 't' && isSpace((token[2]))) { token += 2; float r, g, b; parseFloat3(r, g, b, token); material.transmittance[0] = r; material.transmittance[1] = g; material.transmittance[2] = b; continue; } // ior(index of refraction) if (token[0] == 'N' && token[1] == 'i' && isSpace((token[2]))) { token += 2; material.ior = parseFloat(token); continue; } // emission if(token[0] == 'K' && token[1] == 'e' && isSpace(token[2])) { token += 2; float r, g, b; parseFloat3(r, g, b, token); material.emission[0] = r; material.emission[1] = g; material.emission[2] = b; continue; } // shininess if(token[0] == 'N' && token[1] == 's' && isSpace(token[2])) { token += 2; material.shininess = parseFloat(token); continue; } // illum model if (0 == strncmp(token, "illum", 5) && isSpace(token[5])) { token += 6; material.illum = parseInt(token); continue; } // dissolve if ((token[0] == 'd' && isSpace(token[1]))) { token += 1; material.dissolve = parseFloat(token); continue; } if (token[0] == 'T' && token[1] == 'r' && isSpace(token[2])) { token += 2; material.dissolve = parseFloat(token); continue; } // ambient texture if ((0 == strncmp(token, "map_Ka", 6)) && isSpace(token[6])) { token += 7; material.ambient_texname = token; continue; } // diffuse texture if ((0 == strncmp(token, "map_Kd", 6)) && isSpace(token[6])) { token += 7; material.diffuse_texname = token; continue; } // specular texture if ((0 == strncmp(token, "map_Ks", 6)) && isSpace(token[6])) { token += 7; material.specular_texname = token; continue; } // normal texture if (IsBumpMap(token)) { while (*token == '-') { // parse bump map options... if((0 == strncmp(token, "-bm", 3)) && isSpace(token[3])) { token += 4; material.bump_scale = parseFloat(token); } else { ParseUnsupportedBumpModifier(token, err); } // skip space token += strspn(token, " \t"); } material.normal_texname = token; continue; } // unknown parameter const char* _space = strchr(token, ' '); if(!_space) { _space = strchr(token, '\t'); } if(_space) { int len = _space - token; std::string key(token, len); std::string value = _space + 1; material.unknown_parameter.insert(std::pair<std::string, std::string>(key, value)); } } // flush last material. material_map.insert(std::pair<std::string, material_t>(material.name, material)); return err.str(); }
StyleParam::Value StyleParam::parseString(StyleParamKey key, const std::string& _value) { switch (key) { case StyleParamKey::extrude: { if (_value == "true") { return glm::vec2(NAN, NAN); } if (_value == "false") { return glm::vec2(0, 0) ; } auto vec2 = glm::vec2(NAN, NAN); if (!parseVec2(_value, { Unit::meter, Unit::pixel }, vec2)) { LOGW("Invalid extrude parameter '%s'.", _value.c_str()); } return vec2; } case StyleParamKey::text_wrap: { int textWrap; if (_value == "true") return textWrap; if (_value == "false") return std::numeric_limits<uint32_t>::max(); if (parseInt(_value, textWrap) > 0) { return static_cast<uint32_t>(textWrap); } } case StyleParamKey::offset: { auto vec2 = glm::vec2(0.f, 0.f); if (!parseVec2(_value, { Unit::pixel }, vec2) || isnan(vec2.y)) { LOGW("Invalid offset parameter '%s'.", _value.c_str()); } return vec2; } case StyleParamKey::size: { auto vec2 = glm::vec2(0.f, 0.f); if (!parseVec2(_value, { Unit::pixel }, vec2)) { LOGW("Invalid size parameter '%s'.", _value.c_str()); } return vec2; } case StyleParamKey::transition_hide_time: case StyleParamKey::transition_show_time: case StyleParamKey::transition_selected_time: { float time = 0.0f; if (!parseTime(_value, time)) { LOGW("Invalid time param '%s'", _value.c_str()); } return time; } case StyleParamKey::align: case StyleParamKey::anchor: case StyleParamKey::font_family: case StyleParamKey::font_weight: case StyleParamKey::font_style: case StyleParamKey::text_source: case StyleParamKey::transform: case StyleParamKey::sprite: case StyleParamKey::sprite_default: case StyleParamKey::style: return _value; case StyleParamKey::font_size: { float fontSize = 0.f; if (!parseFontSize(_value, fontSize)) { LOGW("Invalid font-size '%s'.", _value.c_str()); } return fontSize; } case StyleParamKey::centroid: case StyleParamKey::interactive: case StyleParamKey::visible: case StyleParamKey::collide: if (_value == "true") { return true; } if (_value == "false") { return false; } LOGW("Bool value required for capitalized/visible. Using Default."); break; case StyleParamKey::order: case StyleParamKey::outline_order: case StyleParamKey::priority: { int num; if (parseInt(_value, num) > 0) { return static_cast<uint32_t>(num); } break; } case StyleParamKey::width: case StyleParamKey::outline_width: { ValueUnitPair width; width.unit = Unit::meter; int pos = parseValueUnitPair(_value, 0, width); if (pos < 0) { logMsg("Warning: Invalid width value '%s'\n", _value.c_str()); width.value = 2.0f; width.unit = Unit::pixel; } return Width(width); } case StyleParamKey::font_stroke_width: { double num; if (parseFloat(_value, num) > 0) { return static_cast<float>(num); } break; } case StyleParamKey::color: case StyleParamKey::outline_color: case StyleParamKey::font_fill: case StyleParamKey::font_stroke_color: return parseColor(_value); case StyleParamKey::cap: case StyleParamKey::outline_cap: return static_cast<uint32_t>(CapTypeFromString(_value)); case StyleParamKey::join: case StyleParamKey::outline_join: return static_cast<uint32_t>(JoinTypeFromString(_value)); case StyleParamKey::none: break; } return none_type{}; }
void ParseText( const string& fileLoc ){ ifstream file; file.open( fileLoc.c_str(), ios::binary ); vector< string > array; scene_t * scn = 0; string line; string music_path; string CG_path; while( getline( file, line ) ){ if( line.size() > 0 && line[ line.size() - 1 ] == '\r' ) line.resize( line.size()-1 ); if( tolower( line.substr( 0, 2 ) == "//" ) ){ assert( scn != 0 ); string temporary = line.substr( 2 ); switch( ext( temporary ) ){ case IMAGE_EXTENSION: CG_path = temporary; break; case SOUND_EXTENSION: music_path = temporary; break; default: cerr << "WARNING : PARSER DOESN'T KNOW WHAT TO DO WITH THIS LINE BELLOW" << endl; cerr << " " << line << endl; break; } } else { array = explode( ':', line ); if( array.size() == 2 && array[1] == ""){ scn = &scenes[ array[0] ]; //it's dangerous if it's not cleared music_path.clear(); } else if( array.size() >= 2 ){ assert( scn != 0 ); scn -> log_array.resize( scn -> log_array.size() + 1 ); if( music_path.size() != 0 ){ //copy the parsed music_path scn -> log_array.back().music_path = music_path; //remove it after copy music_path.clear(); } if( CG_path.size() != 0 ){ scn -> log_array.back().CG_path = CG_path; CG_path.clear(); } int i = 0; scn -> log_array.back().name = array[i++]; scn -> log_array.back().text = array[i++]; while( i < array.size() ){ if( ext( array[i] ) == IMAGE_EXTENSION ){ scn -> log_array.back().image_path.push_back( array[i++] ); assert( i != array.size() ); scn -> log_array.back().image_align.push_back( parseInt( array[i++] ) ); continue; } else if( ext( array[i]) == SOUND_EXTENSION ){ scn -> log_array.back().soundFx_path.push_back( array[i++] ); continue; } i++; } } } } file.close(); }
int main(int argc, char *argv[]) { #ifdef RPI bcm_host_init(); #endif putenv((char*)"SDL_VIDEO_CENTERED=1"); std::string app_name; std::string app_name_nice; bool landscape; NativeGetAppInfo(&app_name, &app_name_nice, &landscape); net::Init(); #ifdef __APPLE__ // Make sure to request a somewhat modern GL context at least - the // latest supported by MacOSX (really, really sad...) // Requires SDL 2.0 // We really should upgrade to SDL 2.0 soon. //SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); //SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2); #endif if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK | SDL_INIT_AUDIO) < 0) { fprintf(stderr, "Unable to initialize SDL: %s\n", SDL_GetError()); return 1; } #ifdef USING_EGL if (EGL_Open()) return 1; #endif // Get the video info before doing anything else, so we don't get skewed resolution results. const SDL_VideoInfo* desktopVideoInfo = SDL_GetVideoInfo(); g_DesktopWidth = desktopVideoInfo->current_w; g_DesktopHeight = desktopVideoInfo->current_h; SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_SWAP_CONTROL, 1); int mode; #ifdef USING_GLES2 mode = SDL_SWSURFACE | SDL_FULLSCREEN; #else mode = SDL_OPENGL | SDL_RESIZABLE; #endif int set_xres = -1; int set_yres = -1; bool portrait = false; bool set_ipad = false; float set_dpi = 1.0f; float set_scale = 1.0f; for (int i = 1; i < argc; i++) { if (!strcmp(argv[i],"--fullscreen")) mode |= SDL_FULLSCREEN; if (set_xres == -2) { set_xres = parseInt(argv[i]); } else if (set_yres == -2) { set_yres = parseInt(argv[i]); } if (set_dpi == -2) set_dpi = parseFloat(argv[i]); if (set_scale == -2) set_scale = parseFloat(argv[i]); if (!strcmp(argv[i],"--xres")) set_xres = -2; if (!strcmp(argv[i],"--yres")) set_yres = -2; if (!strcmp(argv[i],"--dpi")) set_dpi = -2; if (!strcmp(argv[i],"--scale")) set_scale = -2; if (!strcmp(argv[i],"--ipad")) set_ipad = true; if (!strcmp(argv[i],"--portrait")) portrait = true; } if (mode & SDL_FULLSCREEN) { const SDL_VideoInfo* info = SDL_GetVideoInfo(); pixel_xres = info->current_w; pixel_yres = info->current_h; #ifdef PPSSPP g_Config.bFullScreen = true; #endif } else { // set a sensible default resolution (2x) pixel_xres = 480 * 2 * set_scale; pixel_yres = 272 * 2 * set_scale; if (portrait) { std::swap(pixel_xres, pixel_yres); } #ifdef PPSSPP g_Config.bFullScreen = false; #endif } set_dpi = 1.0f / set_dpi; if (set_ipad) { pixel_xres = 1024; pixel_yres = 768; } if (!landscape) { std::swap(pixel_xres, pixel_yres); } if (set_xres > 0) { pixel_xres = set_xres; } if (set_yres > 0) { pixel_yres = set_yres; } float dpi_scale = 1.0f; if (set_dpi > 0) { dpi_scale = set_dpi; } dp_xres = (float)pixel_xres * dpi_scale; dp_yres = (float)pixel_yres * dpi_scale; g_Screen = SDL_SetVideoMode(pixel_xres, pixel_yres, 0, mode); if (g_Screen == NULL) { fprintf(stderr, "SDL SetVideoMode failed: Unable to create OpenGL screen: %s\n", SDL_GetError()); SDL_Quit(); return 2; } #ifdef USING_EGL EGL_Init(); #endif #ifdef PPSSPP SDL_WM_SetCaption((app_name_nice + " " + PPSSPP_GIT_VERSION).c_str(), NULL); #endif #ifdef MOBILE_DEVICE SDL_ShowCursor(SDL_DISABLE); #endif #ifndef USING_GLES2 if (GLEW_OK != glewInit()) { printf("Failed to initialize glew!\n"); return 1; } if (GLEW_VERSION_2_0) { printf("OpenGL 2.0 or higher.\n"); } else { printf("Sorry, this program requires OpenGL 2.0.\n"); return 1; } #endif #ifdef _MSC_VER // VFSRegister("temp/", new DirectoryAssetReader("E:\\Temp\\")); TCHAR path[MAX_PATH]; SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, path); PathAppend(path, (app_name + "\\").c_str()); #else // Mac / Linux char path[512]; const char *the_path = getenv("HOME"); if (!the_path) { struct passwd* pwd = getpwuid(getuid()); if (pwd) the_path = pwd->pw_dir; } strcpy(path, the_path); if (path[strlen(path)-1] != '/') strcat(path, "/"); #endif #ifdef _WIN32 NativeInit(argc, (const char **)argv, path, "D:\\", "BADCOFFEE"); #else NativeInit(argc, (const char **)argv, path, "/tmp", "BADCOFFEE"); #endif pixel_in_dps = (float)pixel_xres / dp_xres; g_dpi_scale = dp_xres / (float)pixel_xres; printf("Pixels: %i x %i\n", pixel_xres, pixel_yres); printf("Virtual pixels: %i x %i\n", dp_xres, dp_yres); NativeInitGraphics(); NativeResized(); SDL_AudioSpec fmt, ret_fmt; memset(&fmt, 0, sizeof(fmt)); fmt.freq = 44100; fmt.format = AUDIO_S16; fmt.channels = 2; fmt.samples = 2048; fmt.callback = &mixaudio; fmt.userdata = (void *)0; if (SDL_OpenAudio(&fmt, &ret_fmt) < 0) { ELOG("Failed to open audio: %s", SDL_GetError()); } else { if (ret_fmt.freq != 44100 || ret_fmt.format != AUDIO_S16 || ret_fmt.channels != 2 || fmt.samples != 2048) { ELOG("Sound buffer format does not match requested format."); ELOG("Output audio freq: %d (requested: %d)", ret_fmt.freq, 44100); ELOG("Output audio format: %d (requested: %d)", ret_fmt.format, AUDIO_S16); ELOG("Output audio channels: %d (requested: %d)", ret_fmt.channels, 2); ELOG("Output audio samples: %d (requested: %d)", ret_fmt.samples, 2048); } if (ret_fmt.freq != 44100 || ret_fmt.format != AUDIO_S16 || ret_fmt.channels != 2) { ELOG("Provided output format does not match requirement, turning audio off"); SDL_CloseAudio(); } else { ELOG("Provided output audio format is usable, thus using it"); } } // Audio must be unpaused _after_ NativeInit() SDL_PauseAudio(0); #ifndef _WIN32 joystick = new SDLJoystick(); #endif EnableFZ(); int framecount = 0; float t = 0; float lastT = 0; uint32_t pad_buttons = 0; // legacy pad buttons while (true) { input_state.accelerometer_valid = false; input_state.mouse_valid = true; SDL_Event event; while (SDL_PollEvent(&event)) { float mx = event.motion.x * g_dpi_scale; float my = event.motion.y * g_dpi_scale; switch (event.type) { case SDL_QUIT: g_QuitRequested = 1; break; #if !defined(MOBILE_DEVICE) case SDL_VIDEORESIZE: { g_Screen = SDL_SetVideoMode(event.resize.w, event.resize.h, 0, SDL_OPENGL | SDL_RESIZABLE); if (g_Screen == NULL) { fprintf(stderr, "SDL SetVideoMode failed: Unable to create OpenGL screen: %s\n", SDL_GetError()); SDL_Quit(); return 2; } pixel_xres = event.resize.w; pixel_yres = event.resize.h; dp_xres = (float)pixel_xres * dpi_scale; dp_yres = (float)pixel_yres * dpi_scale; NativeResized(); break; } #endif case SDL_KEYDOWN: { int k = event.key.keysym.sym; KeyInput key; key.flags = KEY_DOWN; key.keyCode = KeyMapRawSDLtoNative.find(k)->second; key.deviceId = DEVICE_ID_KEYBOARD; NativeKey(key); for (int i = 0; i < ARRAY_SIZE(legacyKeyMap); i++) { if (legacyKeyMap[i] == key.keyCode) pad_buttons |= 1 << i; } break; } case SDL_KEYUP: { int k = event.key.keysym.sym; KeyInput key; key.flags = KEY_UP; key.keyCode = KeyMapRawSDLtoNative.find(k)->second; key.deviceId = DEVICE_ID_KEYBOARD; NativeKey(key); for (int i = 0; i < ARRAY_SIZE(legacyKeyMap); i++) { if (legacyKeyMap[i] == key.keyCode) pad_buttons &= ~(1 << i); } break; } case SDL_MOUSEBUTTONDOWN: switch (event.button.button) { case SDL_BUTTON_LEFT: { input_state.pointer_x[0] = mx; input_state.pointer_y[0] = my; input_state.pointer_down[0] = true; input_state.mouse_valid = true; TouchInput input; input.x = mx; input.y = my; input.flags = TOUCH_DOWN; input.id = 0; NativeTouch(input); KeyInput key(DEVICE_ID_MOUSE, NKCODE_EXT_MOUSEBUTTON_1, KEY_DOWN); NativeKey(key); } break; case SDL_BUTTON_RIGHT: { KeyInput key(DEVICE_ID_MOUSE, NKCODE_EXT_MOUSEBUTTON_2, KEY_DOWN); NativeKey(key); } break; case SDL_BUTTON_WHEELUP: { KeyInput key; key.deviceId = DEVICE_ID_MOUSE; key.keyCode = NKCODE_EXT_MOUSEWHEEL_UP; key.flags = KEY_DOWN; NativeKey(key); } break; case SDL_BUTTON_WHEELDOWN: { KeyInput key; key.deviceId = DEVICE_ID_MOUSE; key.keyCode = NKCODE_EXT_MOUSEWHEEL_DOWN; key.flags = KEY_DOWN; NativeKey(key); } break; } break; case SDL_MOUSEMOTION: if (input_state.pointer_down[0]) { input_state.pointer_x[0] = mx; input_state.pointer_y[0] = my; input_state.mouse_valid = true; TouchInput input; input.x = mx; input.y = my; input.flags = TOUCH_MOVE; input.id = 0; NativeTouch(input); } break; case SDL_MOUSEBUTTONUP: switch (event.button.button) { case SDL_BUTTON_LEFT: { input_state.pointer_x[0] = mx; input_state.pointer_y[0] = my; input_state.pointer_down[0] = false; input_state.mouse_valid = true; //input_state.mouse_buttons_up = 1; TouchInput input; input.x = mx; input.y = my; input.flags = TOUCH_UP; input.id = 0; NativeTouch(input); KeyInput key(DEVICE_ID_MOUSE, NKCODE_EXT_MOUSEBUTTON_1, KEY_UP); NativeKey(key); } break; case SDL_BUTTON_RIGHT: { KeyInput key(DEVICE_ID_MOUSE, NKCODE_EXT_MOUSEBUTTON_2, KEY_UP); NativeKey(key); } break; case SDL_BUTTON_WHEELUP: { KeyInput key; key.deviceId = DEVICE_ID_DEFAULT; key.keyCode = NKCODE_EXT_MOUSEWHEEL_UP; key.flags = KEY_UP; NativeKey(key); } break; case SDL_BUTTON_WHEELDOWN: { KeyInput key; key.deviceId = DEVICE_ID_DEFAULT; key.keyCode = NKCODE_EXT_MOUSEWHEEL_DOWN; key.flags = KEY_UP; NativeKey(key); } break; } break; default: #ifndef _WIN32 joystick->ProcessInput(event); #endif break; } } if (g_QuitRequested) break; const uint8 *keys = (const uint8 *)SDL_GetKeyState(NULL); SimulateGamepad(keys, &input_state); input_state.pad_buttons = pad_buttons; UpdateInputState(&input_state, true); NativeUpdate(input_state); if (g_QuitRequested) break; NativeRender(); #if defined(PPSSPP) && !defined(MOBILE_DEVICE) if (lastUIState != globalUIState) { lastUIState = globalUIState; if (lastUIState == UISTATE_INGAME && g_Config.bFullScreen && !g_Config.bShowTouchControls) SDL_ShowCursor(SDL_DISABLE); if (lastUIState != UISTATE_INGAME && g_Config.bFullScreen) SDL_ShowCursor(SDL_ENABLE); } #endif EndInputState(&input_state); if (framecount % 60 == 0) { // glsl_refresh(); // auto-reloads modified GLSL shaders once per second. } #ifdef USING_EGL eglSwapBuffers(g_eglDisplay, g_eglSurface); #else if (!keys[SDLK_TAB] || t - lastT >= 1.0/60.0) { SDL_GL_SwapBuffers(); lastT = t; } #endif ToggleFullScreenIfFlagSet(); time_update(); t = time_now(); framecount++; } #ifndef _WIN32 delete joystick; #endif // Faster exit, thanks to the OS. Remove this if you want to debug shutdown // The speed difference is only really noticable on Linux. On Windows you do notice it though #ifndef MOBILE_DEVICE exit(0); #endif NativeShutdownGraphics(); SDL_PauseAudio(1); SDL_CloseAudio(); NativeShutdown(); #ifdef USING_EGL EGL_Close(); #endif SDL_Quit(); net::Shutdown(); #ifdef RPI bcm_host_deinit(); #endif exit(0); return 0; }
Integer::Integer(String *s) { val = parseInt(s); }
LytSeqInfo* LayoutParser::addSeq(char* s, LytCtgData* ctg) { LytSeqInfo* seq; //s must be the line with sequence data char* p=strchrs(s," \t"); if (p==NULL) return NULL; p++; char c; int slen, soffs, clpL, clpR; clpL=0;clpR=0; if (sscanf(p,"%c %d %d %d %d", &c, &slen, &soffs, &clpL, &clpR)<3) return NULL; p--; *p='\0'; if ((seq=seqinfo.Find(s))!=NULL) { GMessage("Sequence '%s' already found for contig '%s (%d nt)'\n" " so it cannot be added for contig '%s (%d nt)'\n", s, seq->contig->name, seq->contig->len, ctg->name, ctg->len); return NULL; } seq = new LytSeqInfo(s, ctg, soffs, (c=='-') ? 1 : 0, slen, clpL, clpR); seqinfo.shkAdd(seq->name, seq); ctg->seqs.Add(seq); //parse optional extensions, if any p+=strlen(s); //position p after the seqname char* m=NULL; int segEnd, segRclip,nextsegStart, nextsegLclip, prevSegStart; char segSplice, nextsegSplice; while ((m=strchr(p,':'))!=NULL) { switch (*(m-1)) { case 'G': //segmenting info prevSegStart=soffs+clpL-1; p=m+1; //p to the beginning of G: data //accumulate the total length in lenSegs while (*p>='1' && *p<='9') { segEnd=0; segRclip=0; nextsegStart=0; nextsegLclip=0; segSplice=0; nextsegSplice=0; if (!parseInt(p,segEnd)) GError("Error [segment] at LayoutParser for %s at: %s\n", s, m-1); if (*p=='c') { p++; if (!parseInt(p,segRclip)) GError("Error [segment] at LayoutParser for %s at: %s\n", s, m-1); } if (*p=='S' || *p=='s') { segSplice=*p; p++; } if (*p!='-') GError("Error [segment] at LayoutParser for %s at: %s\n", s, m-1); else p++; if (!parseInt(p,nextsegStart)) GError("Error [segment] at LayoutParser for %s at: %s\n", s, m-1); if (*p=='c') { p++; if (!parseInt(p,nextsegLclip)) GError("Error [segment] at LayoutParser for %s at: %s\n", s, m-1); } if (*p=='S' || *p=='s') { nextsegSplice=*p; p++; } seq->addInterSeg(segEnd,nextsegStart,segRclip,nextsegLclip, segSplice, nextsegSplice); prevSegStart=nextsegStart; // if (*p==',') p++; else break; } //while inter-segment parsing break; // 'G:' case case 'L': //clone mates list p=m+1; //p to the beginning of L: data break; case 'D': //difference sequence p=m+1; //p to the beginning of D: data break; case 'S': //actual sequence p=m+1; //p to the beginning of S: data break; default: p=m+1;//next attribute } } return seq; }
void read_data() { int uid, n, iid, stmp, day, hr, min, sec; double score; ssize_t didx = 0; unsigned int uidx=0, ridx=0, iidx=0; ssize_t size; char *data = (char *)open_read("trainIdx1.txt", &size); int sum = 0; int start = 0; mu = 0; while(1) { if ( parseInt(data, &didx, &uid, size) ) { break; } //printf("' %c\n", data[didx-1]); if (umap.count(uid) == 0) { uidx = umaplen; umaplen++; umap[uid] = uidx; users[uidx].id = uid; } else { uidx = imap[uid]; } parseInt(data, &didx, &n, size); users[uidx].count = n; users[uidx].start = start; start += n; for(int i =0; i < n; i++) { parseInt(data, &didx, &iid, size); parseInt(data, &didx, &stmp, size); parseInt(data, &didx, &day, size); parseInt(data, &didx, &hr, size); parseInt(data, &didx, &min, size); parseInt(data, &didx, &sec, size); score = (double) stmp / SCORENORM; day -= 2672; mu += score; if( imap.count(iid) == 0) { iidx = imaplen; imaplen ++; imap[iid] = iidx; items[iidx].id = iid; items[iidx].count = 0; items[iidx].artistid = -1; items[iidx].albumid = -1; } else { iidx = imap[iid]; assert(items[iidx].id == iid); } items[iidx].count += 1; ratings[ridx].item = iidx; ratings[ridx].rating = score; ratings[ridx].day = day; assert(ratings[ridx].rating <= 100); ridx++; } } munmap(data, size); read_validate(); read_tests(); nItems = imaplen; nUsers = umaplen; nRatings = ridx; mu /= (double)ridx; printf("nRatings = %d\n", nRatings); printf("mu = %lg\n", mu); char vfile[256]; strcpy(vfile, tmpdir); strcat(vfile,"values"); FILE *tmp = fopen(vfile, "w"); fprintf(tmp, "%u %u %u %u %u %25.18lg\n", nRatings, nUsers, nItems, nValidations, nTests, mu); for(int i = 0 ; i < nUsers; i++ ) { fprintf(tmp, "%d\n", users[i].id); } for(int i = 0 ; i < nItems; i++ ) { fprintf(tmp, "%d\n", items[i].id); } fclose(tmp); }
CocoDeviceWrapper::CocoDeviceWrapper(int width, int height, String command) { HWND ParentWindow = NULL; int top = CW_USEDEFAULT; int left = CW_USEDEFAULT; DWORD style = WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_OVERLAPPEDWINDOW; if (command) { Array<String>* vArgs = command.split("="); for (auto i = 0; i < vArgs->size(); i++) { if ((*vArgs)[i] == "-ds") { String hw = (*vArgs)[i + 1]; ParentWindow = (HWND) parseInt(hw); if(ParentWindow) style = WS_POPUP | WS_CLIPCHILDREN | WS_CLIPSIBLINGS; } } delete vArgs; } // Initialize common controls. INITCOMMONCONTROLSEX icc; icc.dwSize = sizeof(icc); icc.dwICC = ICC_WIN95_CLASSES; InitCommonControlsEx(&icc); // Create a window rect and expand it by border size. LONG dx = 0; LONG dy = 0; RECT rc; if (!ParentWindow) { SetRect(&rc, 0, 0, width, height); AdjustWindowRectEx(&rc, WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_OVERLAPPEDWINDOW, FALSE, WS_EX_APPWINDOW | WS_EX_WINDOWEDGE); dx = GetSystemMetrics(SM_CXSCREEN) - (rc.right - rc.left); dy = GetSystemMetrics(SM_CYSCREEN) - (rc.bottom - rc.top); } else { GetWindowRect(ParentWindow, &rc); width = rc.right - rc.left; height = rc.bottom - rc.top; } // Get Module m_hInstance = GetModuleHandle(NULL); // Class for our main window. LPCTSTR MainWndClass = L"Win32 Coconut2D Application"; WNDCLASSEX wc; wc.cbSize = sizeof(wc); wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; wc.lpfnWndProc = MainWndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = m_hInstance; wc.hIcon = (HICON) LoadImage(m_hInstance, MAKEINTRESOURCE(IDI_APPICON), IMAGE_ICON, 0, 0, LR_DEFAULTSIZE | LR_DEFAULTCOLOR | LR_SHARED); wc.hIconSm = (HICON) LoadImage(m_hInstance, MAKEINTRESOURCE(IDI_APPICON), IMAGE_ICON, GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), LR_DEFAULTCOLOR | LR_SHARED); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = CreateSolidBrush(0); wc.lpszMenuName = NULL; wc.lpszClassName = MainWndClass; // Register our window classes RegisterClassEx(&wc); // Create instance of main window. m_glHWND = CreateWindowEx(WS_EX_APPWINDOW | WS_EX_WINDOWEDGE, MainWndClass, L"$(PROJECT_NAME)", style, left, top, width, height, NULL, NULL, m_hInstance, NULL); // Get Window hDC, show window and force a paint. m_glHDC = GetDC(m_glHWND); ShowWindow(m_glHWND, SW_SHOW); UpdateWindow(m_glHWND); SetForegroundWindow(m_glHWND); SetFocus(m_glHWND); // Keep window size information for OpenGL calculations screen.width = width; screen.height = height; screen.pixelRatio = 1.0f; screen.top = 0; screen.isPortrait = (screen.height > screen.width); screen.rotation = fxScreen::Rotation::NONE; // Initialize OpenGL PIXELFORMATDESCRIPTOR pdf; pdf.nSize = sizeof(PIXELFORMATDESCRIPTOR); pdf.nVersion = 1; pdf.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER | PFD_TYPE_RGBA; pdf.iPixelType = PFD_TYPE_RGBA; pdf.cColorBits = 32; pdf.cDepthBits = 16; pdf.iLayerType = PFD_MAIN_PLANE; int iPixelFormat = ChoosePixelFormat(m_glHDC, &pdf); if(iPixelFormat!=0) { if(SetPixelFormat(m_glHDC, iPixelFormat, &pdf)) { m_OpenGLContext = wglCreateContext(m_glHDC); if(wglMakeCurrent(m_glHDC, m_OpenGLContext)) { glEnable(GL_TEXTURE_2D); glDisable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); glDisable(GL_LIGHTING); glDisable(GL_DITHER); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } } } glewInit(); // Create the HTMLWindow and HTMLDocument window = new HTMLWindow(); window->setScreen(screen); window->innerWidth = screen.width; window->innerHeight = screen.height; window->devicePixelRatio = screen.pixelRatio; window->deviceRotation = 0.0f; global = window; document = window->document; // Create a WebGL Canvas engine = new GameEngine(); // Read clock frequency and adjust to milliseconds LARGE_INTEGER freq, m_TCurrent, m_TFirst, m_TLast; QueryPerformanceFrequency(&freq); double currentTime, ellapsedTime, m_Freq = double(freq.QuadPart)/1000.0; QueryPerformanceCounter(&m_TFirst); m_TLast = m_TFirst; alive = true; do { // Get total and elapsed milliseconds since last tick. QueryPerformanceCounter(&m_TCurrent); currentTime = (double(m_TCurrent.QuadPart) - double(m_TFirst.QuadPart)) / m_Freq; ellapsedTime = (double(m_TCurrent.QuadPart) - double(m_TLast.QuadPart)) / m_Freq; if (ParentWindow) { GetWindowRect(ParentWindow, &rc); width = rc.right - rc.left; height = rc.bottom - rc.top; SetWindowPos(m_glHWND, HWND_TOPMOST, rc.left, rc.top, width, height, SWP_ASYNCWINDOWPOS); } else { GetClientRect(m_glHWND, &rc); width = rc.right - rc.left; height = rc.bottom - rc.top; } // Update Window Size (stick to parent window) screen.width = width + 1; screen.height = height + 1; window->innerWidth = screen.width; window->innerHeight = screen.height; if(ellapsedTime>=16.0) { // Tick APIs (HTML, HTTP, Audio, Video, Physics, etc.) HandleDeviceEvents(); tick(); // Mark last time for next cycle. m_TLast = m_TCurrent; } Sleep(0); } while(alive); };
std::string LoadMtl ( std::map<std::string, int>& material_map, std::vector<material_t>& materials, std::istream& inStream) { material_map.clear(); std::stringstream err; material_t material; int maxchars = 8192; // Alloc enough size. std::vector<char> buf(maxchars); // Alloc enough size. while (inStream.peek() != -1) { inStream.getline(&buf[0], maxchars); std::string linebuf(&buf[0]); // Trim newline '\r\n' or '\n' if (linebuf.size() > 0) { if (linebuf[linebuf.size()-1] == '\n') linebuf.erase(linebuf.size()-1); } if (linebuf.size() > 0) { if (linebuf[linebuf.size()-1] == '\r') linebuf.erase(linebuf.size()-1); } // Skip if empty line. if (linebuf.empty()) { continue; } // Skip leading space. const char* token = linebuf.c_str(); token += strspn(token, " \t"); assert(token); if (token[0] == '\0') continue; // empty line if (token[0] == '#') continue; // comment line // new mtl if ((0 == strncmp(token, "newmtl", 6)) && isSpace((token[6]))) { // flush previous material. if (!material.name.empty()) { material_map.insert(std::pair<std::string, int>(material.name, materials.size())); materials.push_back(material); } // initial temporary material InitMaterial(material); // set new mtl name char namebuf[4096]; token += 7; sscanf(token, "%s", namebuf); material.name = namebuf; continue; } // ambient if (token[0] == 'K' && token[1] == 'a' && isSpace((token[2]))) { token += 2; float r, g, b; parseFloat3(r, g, b, token); material.ambient[0] = r; material.ambient[1] = g; material.ambient[2] = b; continue; } // diffuse if (token[0] == 'K' && token[1] == 'd' && isSpace((token[2]))) { token += 2; float r, g, b; parseFloat3(r, g, b, token); material.diffuse[0] = r; material.diffuse[1] = g; material.diffuse[2] = b; continue; } // specular if (token[0] == 'K' && token[1] == 's' && isSpace((token[2]))) { token += 2; float r, g, b; parseFloat3(r, g, b, token); material.specular[0] = r; material.specular[1] = g; material.specular[2] = b; continue; } // transmittance if (token[0] == 'K' && token[1] == 't' && isSpace((token[2]))) { token += 2; float r, g, b; parseFloat3(r, g, b, token); material.transmittance[0] = r; material.transmittance[1] = g; material.transmittance[2] = b; continue; } // ior(index of refraction) if (token[0] == 'N' && token[1] == 'i' && isSpace((token[2]))) { token += 2; material.ior = parseFloat(token); continue; } // emission if(token[0] == 'K' && token[1] == 'e' && isSpace(token[2])) { token += 2; float r, g, b; parseFloat3(r, g, b, token); material.emission[0] = r; material.emission[1] = g; material.emission[2] = b; continue; } // shininess if(token[0] == 'N' && token[1] == 's' && isSpace(token[2])) { token += 2; material.shininess = parseFloat(token); continue; } // illum model if (0 == strncmp(token, "illum", 5) && isSpace(token[5])) { token += 6; material.illum = parseInt(token); continue; } // dissolve if ((token[0] == 'd' && isSpace(token[1]))) { token += 1; material.dissolve = parseFloat(token); continue; } if (token[0] == 'T' && token[1] == 'r' && isSpace(token[2])) { token += 2; material.dissolve = parseFloat(token); continue; } // ambient texture if ((0 == strncmp(token, "map_Ka", 6)) && isSpace(token[6])) { token += 7; material.ambient_texname = token; continue; } // diffuse texture if ((0 == strncmp(token, "map_Kd", 6)) && isSpace(token[6])) { token += 7; material.diffuse_texname = token; continue; } // specular texture if ((0 == strncmp(token, "map_Ks", 6)) && isSpace(token[6])) { token += 7; material.specular_texname = token; continue; } // normal texture if ((0 == strncmp(token, "map_Ns", 6)) && isSpace(token[6])) { token += 7; material.normal_texname = token; continue; } // unknown parameter const char* _space = strchr(token, ' '); if(!_space) { _space = strchr(token, '\t'); } if(_space) { int len = _space - token; std::string key(token, len); std::string value = _space + 1; material.unknown_parameter.insert(std::pair<std::string, std::string>(key, value)); } } // flush last material. material_map.insert(std::pair<std::string, int>(material.name, materials.size())); materials.push_back(material); return err.str(); }
StyleParam::Value StyleParam::parseString(StyleParamKey key, const std::string& _value) { switch (key) { case StyleParamKey::extrude: { return parseExtrudeString(_value); } case StyleParamKey::text_wrap: { int textWrap; if (_value == "true") return textWrap; if (_value == "false") return std::numeric_limits<uint32_t>::max(); if (parseInt(_value, textWrap) > 0) { return static_cast<uint32_t>(textWrap); } } case StyleParamKey::offset: { auto vec2 = glm::vec2(0.f, 0.f); if (!parseVec2(_value, { Unit::pixel }, vec2) || std::isnan(vec2.y)) { LOGW("Invalid offset parameter '%s'.", _value.c_str()); } return vec2; } case StyleParamKey::size: { auto vec2 = glm::vec2(0.f, 0.f); if (!parseVec2(_value, { Unit::pixel }, vec2)) { LOGW("Invalid size parameter '%s'.", _value.c_str()); } return vec2; } case StyleParamKey::transition_hide_time: case StyleParamKey::transition_show_time: case StyleParamKey::transition_selected_time: { float time = 0.0f; if (!parseTime(_value, time)) { LOGW("Invalid time param '%s'", _value.c_str()); } return time; } case StyleParamKey::font_family: case StyleParamKey::font_weight: case StyleParamKey::font_style: { std::string normalized = _value; std::transform(normalized.begin(), normalized.end(), normalized.begin(), ::tolower); return normalized; } case StyleParamKey::align: case StyleParamKey::anchor: case StyleParamKey::text_source: case StyleParamKey::transform: case StyleParamKey::sprite: case StyleParamKey::sprite_default: case StyleParamKey::style: case StyleParamKey::outline_style: case StyleParamKey::repeat_group: return _value; case StyleParamKey::font_size: { float fontSize = 0.f; if (!parseFontSize(_value, fontSize)) { LOGW("Invalid font-size '%s'.", _value.c_str()); } return fontSize; } case StyleParamKey::centroid: case StyleParamKey::interactive: case StyleParamKey::tile_edges: case StyleParamKey::visible: case StyleParamKey::collide: if (_value == "true") { return true; } if (_value == "false") { return false; } LOGW("Bool value required for capitalized/visible. Using Default."); break; case StyleParamKey::order: case StyleParamKey::outline_order: case StyleParamKey::priority: { int num; if (parseInt(_value, num) > 0) { return static_cast<uint32_t>(num); } break; } case StyleParamKey::repeat_distance: { ValueUnitPair repeatDistance; repeatDistance.unit = Unit::pixel; int pos = parseValueUnitPair(_value, 0, repeatDistance); if (pos < 0) { LOGW("Invalid repeat distance value '%s'", _value.c_str()); repeatDistance.value = 256.0f; repeatDistance.unit = Unit::pixel; } else { if (repeatDistance.unit != Unit::pixel) { LOGW("Invalid unit provided for repeat distance"); } } return Width(repeatDistance); } case StyleParamKey::width: case StyleParamKey::outline_width: { ValueUnitPair width; width.unit = Unit::meter; int pos = parseValueUnitPair(_value, 0, width); if (pos < 0) { LOGW("Invalid width value '%s'", _value.c_str()); width.value = 2.0f; width.unit = Unit::pixel; } return Width(width); } case StyleParamKey::miter_limit: case StyleParamKey::outline_miter_limit: case StyleParamKey::font_stroke_width: { double num; if (parseFloat(_value, num) > 0) { return static_cast<float>(num); } break; } case StyleParamKey::color: case StyleParamKey::outline_color: case StyleParamKey::font_fill: case StyleParamKey::font_stroke_color: return parseColor(_value); case StyleParamKey::cap: case StyleParamKey::outline_cap: return static_cast<uint32_t>(CapTypeFromString(_value)); case StyleParamKey::join: case StyleParamKey::outline_join: return static_cast<uint32_t>(JoinTypeFromString(_value)); default: break; } return none_type{}; }
int main(int argc, char **argv) { char *filename, *docFile, *codeDir, *srcSuffix, *flagFile, *consModule; char arg, *optarg, *buildFile, *apiFile, *xmlFile; int optnr, exceptions, tracing, releaseGIL, parts, protHack, docs; int timestamp, was_flagFile; KwArgs kwArgs; FILE *file; sipSpec spec; stringList *versions, *backstops, *xfeatures, *extracts; /* Initialise. */ sipVersion = SIP_VERSION_STR; includeDirList = NULL; versions = NULL; backstops = NULL; xfeatures = NULL; buildFile = NULL; codeDir = NULL; docFile = NULL; srcSuffix = NULL; flagFile = NULL; was_flagFile = FALSE; apiFile = NULL; xmlFile = NULL; consModule = NULL; extracts = NULL; exceptions = FALSE; tracing = FALSE; releaseGIL = FALSE; parts = 0; kwArgs = NoKwArgs; protHack = FALSE; docs = FALSE; timestamp = TRUE; /* Parse the command line. */ optnr = 1; while ((arg = parseopt(argc, argv, "hVa:b:B:ec:d:gI:j:km:op:Prs:t:Twx:X:z:", &flagFile, &optnr, &optarg)) != '\0') switch (arg) { case 'o': /* Generate docstrings. */ docs = TRUE; break; case 'p': /* The name of the consolidated module. */ consModule = optarg; break; case 'P': /* Enable the protected/public hack. */ protHack = TRUE; break; case 'a': /* Where to generate the API file. */ apiFile = optarg; break; case 'm': /* Where to generate the XML file. */ xmlFile = optarg; break; case 'b': /* Generate a build file. */ buildFile = optarg; break; case 'B': /* Define a backstop. */ appendString(&backstops, optarg); break; case 'e': /* Enable exceptions. */ exceptions = TRUE; break; case 'g': /* Always release the GIL. */ releaseGIL = TRUE; break; case 'j': /* Generate the code in this number of parts. */ parts = parseInt(optarg,'j'); break; case 'z': /* Read a file for the next flags. */ if (flagFile != NULL) fatal("The -z flag cannot be specified in an argument file\n"); flagFile = optarg; was_flagFile = TRUE; break; case 'c': /* Where to generate the code. */ codeDir = optarg; break; case 'd': /* Where to generate the documentation. */ docFile = optarg; break; case 't': /* Which platform or version to generate code for. */ appendString(&versions,optarg); break; case 'T': /* * Disable the timestamp in the header of generated files. It is * now ignored apart from triggering a deprecation warning. */ timestamp = FALSE; break; case 'x': /* Which features are disabled. */ appendString(&xfeatures,optarg); break; case 'X': /* Which extracts are to be created. */ appendString(&extracts, optarg); break; case 'I': /* Where to get included files from. */ appendString(&includeDirList,optarg); break; case 'r': /* Enable tracing. */ tracing = TRUE; break; case 's': /* The suffix to use for source files. */ srcSuffix = optarg; break; case 'w': /* Enable warning messages. */ warnings = TRUE; break; case 'k': /* Allow keyword arguments in functions and methods. */ kwArgs = AllKwArgs; break; case 'h': /* Help message. */ help(); break; case 'V': /* Display the version number. */ version(); break; default: usage(); } if (optnr < argc) { file = NULL; filename = argv[optnr++]; if (optnr < argc) usage(); } else { file = stdin; filename = "stdin"; } /* Issue warnings after they (might) have been enabled. */ if (docFile != NULL) warning(DeprecationWarning, "the -d flag is deprecated\n"); if (kwArgs != NoKwArgs) warning(DeprecationWarning, "the -k flag is deprecated\n"); if (!timestamp) warning(DeprecationWarning, "the -T flag is ignored and deprecated\n"); if (was_flagFile) warning(DeprecationWarning, "the -z flag is deprecated\n"); /* Parse the input file. */ parse(&spec, file, filename, versions, backstops, xfeatures, kwArgs, protHack); /* Verify and transform the parse tree. */ transform(&spec); /* Generate code. */ generateCode(&spec, codeDir, buildFile, docFile, srcSuffix, exceptions, tracing, releaseGIL, parts, versions, xfeatures, consModule, docs, FALSE); /* Generate any extracts. */ generateExtracts(&spec, extracts); /* Generate the API file. */ if (apiFile != NULL) generateAPI(&spec, spec.module, apiFile); /* Generate the XML export. */ if (xmlFile != NULL) generateXML(&spec, spec.module, xmlFile); /* All done. */ return 0; }
double strtod(const char *s, char **endp) { while (isspace(*s)) { s++; } bool neg = false; if (*s == '-') { neg = true; s++; } else if (*s == '+') { s++; } else if (!isdigit(*s) && *s != '.') { errno = EINVAL; return 0.0; } const char *radix = NULL; const char *expSym = NULL; const char *end = s; //layout should be: <int> radix <frac> expSym <+/-><exp> while (*end) { if (*end == '.') { if (!radix && !expSym) { radix = end; } else { errno = EINVAL; return 0.0; } } else if (*end == 'E' || *end == 'e') { if (!expSym) { expSym = end; } else { errno = EINVAL; return 0.0; } } else if (!isdigit(*end)) { break; } end++; } if (endp){ *endp = (char *)end; } if (!expSym) { expSym = end; } if (!radix) { radix = expSym; } double ret = parseInt(s, radix); //parse fraction const char *i = radix + 1; if (radix != expSym) { double div = 10.0; while (i != expSym) { ret += (*i - '0') / div; div *= 10; i++; } } if (neg) { ret = -ret; } if (expSym == end) { return ret; } i = expSym + 1; bool expNeg = false; if (*i == '-') { expNeg = true; i++; } else if (*i == '+' || isdigit(*i)) { if (*i == '+') { i++; } } else { return ret; } long exp = parseInt(i, end); float mul = 10; float retmul = 1; while (exp) { if (exp & 1) { retmul *= mul; } mul = mul * mul; exp >>= 1; } if (expNeg) { ret /= retmul; } else { ret *= retmul; } return ret; }
/* * Load configuration from File. */ void Config::load( const std::string& filename ){ XmlReader reader( filename ); while( reader.read() ) { if( reader.getNodeType() == XML_READER_TYPE_ELEMENT) { const std::string& element = (const char*) reader.getName(); if( element == "video" ) { XmlReader::AttributeIterator iter(reader); while(iter.next()) { const char* name = (const char*) iter.getName(); const char* value = (const char*) iter.getValue(); if( strcmp( name, "useOpenGL" ) == 0 ) { useOpenGL = parseBool(value, false); } else if( strcmp(name, "x" ) == 0 ) { videoX = parseInt( value, 800, 640 ); } else if(strcmp(name, "y") == 0 ) { videoY = parseInt( value, 600, 480 ); } else if(strcmp(name, "fullscreen") == 0) { useFullScreen = parseBool(value, false); } else if(strcmp(name, "restartOnChangeScreen") == 0) { restartOnChangeScreen = parseBool(value, true); } else if(strcmp(name, "WorldSideLen") == 0) { world.len(parseInt(value, WORLD_SIDE_LEN, 50, 10000)); }else { std::cerr << "Config::load# Unknown attribute '" << name; std::cerr << "' in element '" << element << "' from " << filename << ".\n"; } } } else if ( element == "audio" ) { XmlReader::AttributeIterator iter(reader); while(iter.next()) { const char* name = (const char*) iter.getName(); const char* value = (const char*) iter.getValue(); if(strcmp(name, "soundVolume" ) == 0) { soundVolume = parseInt(value, 100, 0, 100); } else if(strcmp(name, "musicVolume") == 0) { musicVolume = parseInt(value, 100, 0, 100); } else if(strcmp(name, "soundEnabled") == 0) { soundEnabled = parseBool(value, true); } else if(strcmp(name, "musicEnabled") == 0) { musicEnabled = parseBool(value, true); } else if(strcmp(name, "musicTheme") == 0) { musicTheme = value; } else { std::cerr << "Config::load# Unknown attribute '" << name; std::cerr << "' in element '" << element << "' from " << filename << ".\n"; } } } else if ( element == "game" ) { XmlReader::AttributeIterator iter(reader); while(iter.next()) { const char* name = (const char*) iter.getName(); const char* value = (const char*) iter.getValue(); if( strcmp(name, "monthgraphW" ) == 0 ){ monthgraphW = parseInt(value, 120, 0); } else if( strcmp(name, "monthgraphH" ) == 0 ){ monthgraphH = parseInt(value, 64, 0); } else if( strcmp(name, "quickness" ) == 0 ){ quickness = parseInt(value, 2, 1, 100); } else if( strcmp(name, "language" ) == 0 ){ language = value; } else if(strcmp(name, "WorldSideLen") == 0) { world.len(parseInt(value, WORLD_SIDE_LEN, 50, 10000)); } else if(strcmp(name, "binarySaveGames") == 0) { binary_mode = parseBool(value, true); } else if(strcmp(name, "seed_compression") == 0) { seed_compression = parseBool(value, true); } else if(strcmp(name, "carsEnabled") == 0) { carsEnabled = parseBool(value, true); }else { std::cerr << "Config::load# Unknown attribute '" << name; std::cerr << "' in element '" << element << "' from " << filename << ".\n"; } } } else { std::cerr << "Config::load# Unknown element '" << element << "' in "<< filename << ".\n"; } } } }
int main( int argc, char *argv[] ) { QCoreApplication app( argc, argv ); // --interpolation-method=NearestNeighbor|Bilinear QString outputDirectory; int outputTileLevel = -1; int threadCount = QThread::idealThreadCount(); int clusterSize = 0; // cluster size 0 makes no sense bool onlySimulate = false; QVector<ReadOnlyMapDefinition> mapSources; // input: type, tile-level, base-dir|file // --input,type=NasaWW,tile-level=8,base-directory=<dir>,interpolation-method=Bilinear // --input,type=Image,file=<file> enum { HelpOption = 1, InputOption, OutputDirectoryOption, OutputTileLevelOption, JobsOption, ClusterSizeOption, SimulateOption }; static struct option long_options[] = { {"help", no_argument, NULL, HelpOption }, {"input", required_argument, NULL, InputOption }, {"output-directory", required_argument, NULL, OutputDirectoryOption }, {"output-tile-level", required_argument, NULL, OutputTileLevelOption }, {"jobs", required_argument, NULL, JobsOption }, {"cluster-size", required_argument, NULL, ClusterSizeOption }, {"simulate", no_argument, NULL, SimulateOption }, {0, 0, 0, 0 } }; while ( true ) { int option_index = 0; int const opt = getopt_long( argc, argv, "", long_options, &option_index ); if ( opt == -1 ) break; switch ( opt ) { case HelpOption: printUsage(); exit( EXIT_SUCCESS ); case InputOption: mapSources.push_back( parseInput( optarg )); break; case OutputDirectoryOption: outputDirectory = parseString( optarg ); break; case OutputTileLevelOption: outputTileLevel = parseInt( optarg ); break; case JobsOption: threadCount = parseInt( optarg ); break; case ClusterSizeOption: clusterSize = parseInt( optarg ); break; case SimulateOption: onlySimulate = true; break; case '?': break; } } qDebug() << "\noutput directory:" << outputDirectory << "\noutput tile level:" << outputTileLevel << "\ncluster size:" << clusterSize << "\nthreads:" << threadCount << "\ninputs:" << mapSources; if (onlySimulate) exit( EXIT_SUCCESS ); NasaWorldWindToOpenStreetMapConverter converter; converter.setMapSources( mapSources ); converter.setOsmBaseDirectory( QDir( outputDirectory )); converter.setOsmTileLevel( outputTileLevel ); converter.setOsmTileClusterEdgeLengthTiles( clusterSize ); converter.setThreadCount( threadCount ); QObject::connect( &converter, SIGNAL(finished()), &app, SLOT(quit())); QVector<QPair<Thread*, OsmTileClusterRenderer*> > renderThreads = converter.start(); app.exec(); QVector<QPair<Thread*, OsmTileClusterRenderer*> >::iterator pos = renderThreads.begin(); QVector<QPair<Thread*, OsmTileClusterRenderer*> >::iterator const end = renderThreads.end(); for (; pos != end; ++pos ) { (*pos).first->stop(); (*pos).first->wait(); delete (*pos).second; } return EXIT_SUCCESS; }
int main() { SpaceId newProc; OpenFileId input = ConsoleInput; OpenFileId output = ConsoleOutput; char prompt[2], ch, buffer[60], cmd[20], arg[40]; char* quit, ls, exec, path, echo, mkdir, rm, create, open, cd, close, read, write; int bufferSize, bufferIndex, cmdIndex, argIndex; OpenFileId fd; prompt[0] = '-'; prompt[1] = '-'; while( 1 ) { Print("nachos:// ", 's'); bufferSize = 0; do { Read(&buffer[bufferSize], 1, input); } while( buffer[bufferSize++] != '\n' ); buffer[--bufferSize] = '\0'; bufferIndex = 0; cmdIndex = 0; while(bufferIndex < bufferSize && buffer[bufferIndex] != '\0' && buffer[bufferIndex] != ' ') { cmd[cmdIndex++] = buffer[bufferIndex++]; } cmd[cmdIndex] = '\0'; while(bufferIndex < bufferSize && buffer[bufferIndex] == ' ') { bufferIndex++; } argIndex = 0; while(bufferIndex < bufferSize && buffer[bufferIndex] != '\0' && buffer[bufferIndex] != ' ') { arg[argIndex++] = buffer[bufferIndex++]; } arg[argIndex] = '\0'; if(cmdIndex > 0) { if(argIndex > 0 && strcmp("exec", cmd, 4) == 0) { newProc = Exec(arg); if(newProc < 0) { Print("unable to run ", 's'); Println(arg, 's'); continue; } Print("SpaceId : ", 's'); Println(newProc, 'd'); Join(newProc); } if(strcmp("join", cmd, 4) == 0) { if(newProc >= 0) Join(newProc); } if(strcmp("ls", cmd, 2) == 0) { LS(); } if(strcmp("quit", cmd, 4) == 0) { Exit(0); } if(strcmp("halt", cmd, 4) == 0) { Halt(); } if(strcmp("path", cmd, 4) == 0) { Path(); } if(strcmp("help", cmd, 4) == 0) { Println("ls,echo,mkdir,cd,rm is the same as linux", 's'); Println("create a new file with: create [filename]", 's'); Println("open a file with: open [filename]", 's'); Println("close a file with: close [filename]", 's'); Println("write an opened file with: write [content]", 's'); Println("read an opened file with: read", 's'); Println("close an opened file with: close", 's'); Println("show current path with: path", 's'); Println("exit system with: exit", 's'); Println("halt system with: halt", 's'); } if(argIndex > 0 && strcmp("echo", cmd, 4) == 0) { Println(arg, 's'); } if(argIndex > 0 && strcmp("mkdir", cmd, 5) == 0) { MKDir(arg); } if(argIndex > 0 && strcmp("cd", cmd, 2) == 0) { CDDir(arg); } if(argIndex > 0 && strcmp("rm", cmd, 2) == 0) { Remove(arg); } if(argIndex > 0 && strcmp("create", cmd, 6) == 0) { Create(arg); } if(argIndex > 0 && strcmp("open", cmd, 4) == 0) { fd = Open(arg); } if(strcmp("close", cmd, 5) == 0) { Close(fd); } if(argIndex > 0 && strcmp("write", cmd, 5) == 0) { Write(arg, argIndex, fd); } if(strcmp("read", cmd, 4) == 0) { int readNum = Read(arg, 40, fd); arg[readNum] = '\0'; Println(arg, 's'); } if(strcmp("send", cmd, 4) == 0) { int num = parseInt(arg, argIndex); PutMsg(num, newProc); } if(strcmp("get", cmd, 3) == 0) { int num = GetMsg(); Println(num, 'd'); } if(strcmp("ts", cmd, 2) == 0) { TS(); } } } }
ReadOnlyMapDefinition parseInput( char * subopts ) { if ( !subopts ) qFatal("Missing argument for '--input'"); enum { TypeOption = 0, BaseDirectoryOption, FileOption, TileLevelOption, InterpolationOption, CacheSizeOption, TheEnd }; char optionType[] = "type"; char optionBaseDirectory[] = "base-directory"; char optionFile[] = "file"; char optionTileLevel[] = "tile-level"; char optionInterpolationMethod[] = "interpolation-method"; char optionCacheSize[] = "cache-size"; char * const input_opts[] = { optionType, optionBaseDirectory, optionFile, optionTileLevel, optionInterpolationMethod, optionCacheSize, NULL }; ReadOnlyMapDefinition mapDefinition; char * value; while ( *subopts != '\0' ) { switch ( getsubopt( &subopts, input_opts, &value )) { case TypeOption: mapDefinition.setMapType( parseType( value )); break; case BaseDirectoryOption: mapDefinition.setBaseDirectory( parseString( value )); break; case FileOption: mapDefinition.setFileName( parseString( value )); break; case TileLevelOption: mapDefinition.setTileLevel( parseInt( value )); break; case InterpolationOption: mapDefinition.setInterpolationMethod( parseInterpolationMethod( value )); break; case CacheSizeOption: mapDefinition.setCacheSizeBytes( parseInt( value )); break; default: qFatal("Unrecognized input suboption."); } } return mapDefinition; }
int VSSValue::asInt() const { int i = 0; parseInt(i); return i; }
void OBJFileReader::parseLine(const char*& current, const char* endOfLine) { if(matchCommand(current, "v")) positions.push_back(parseVec3(current)); else if(matchCommand(current, "vn")) normals.push_back(parseVec3(current)); else if(matchCommand(current, "vt")) texcoords.push_back(parseVec2(current)); else if(matchCommand(current, "f")) // face { int count = 0; while(!errThisLine && *current) { VertInfo nfo; nfo.pos = parseIndex(current, positions.size()); if(*current == '/') nfo.tex = parseIndex(++current, texcoords.size()); else nfo.tex = -1; if(*current == '/') nfo.norm = parseIndex(++current, normals.size()); else nfo.norm = -1; if(*current && !isspace(*current)) diagnostic(false, current, "unexpected character after vertex indices"); vertices.push_back(nfo); count++; } if(count < 3) diagnostic(false, current, "need at least 3 vertices for a face"); else if(count > 4) diagnostic(true, current, "non-tri/quad face"); FaceInfo nfo; nfo.start = vertices.size() - count; nfo.count = count; nfo.mtrl = currentMaterial; nfo.smoothing_group = currentSmoothingGroup; faces.push_back(nfo); } else if(matchCommand(current, "g")) // group { current = endOfLine; } else if(matchCommand(current, "o")) // object { current = endOfLine; } else if(matchCommand(current, "s")) // smooth shading { if(matchCommand(current, "off")) currentSmoothingGroup = -1; else currentSmoothingGroup = parseInt(current) - 1; } else if(matchCommand(current, "usemtl")) { currentMaterial = findMaterial(current); current = endOfLine; } else if(matchCommand(current, "mtllib")) { MTLFileReader mtlreader; if(!mtlreader.read((basepath + current).c_str())) diagnostic(false, current, "error reading material library"); else { materials.swap(mtlreader.materials); current = endOfLine; defaultMaterial = -1; defaultMaterial = findMaterial("default"); sVERIFY(defaultMaterial != -1); currentMaterial = defaultMaterial; } } else diagnostic(false, current, "unknown command"); }
void RenderState::StateBlock::setState(const std::string& name, const std::string& value) { if (name.compare("blend") == 0) { setBlend(parseBoolean(value)); } else if (name.compare("blendSrc") == 0) { setBlendSrc(parseBlend(value)); } else if (name.compare("blendDst") == 0) { setBlendDst(parseBlend(value)); } else if (name.compare("cullFace") == 0) { setCullFace(parseBoolean(value)); } else if (name.compare("cullFaceSide") == 0) { setCullFaceSide(parseCullFaceSide(value)); } else if (name.compare("frontFace") == 0) { setFrontFace(parseFrontFace(value)); } else if (name.compare("depthTest") == 0) { setDepthTest(parseBoolean(value)); } else if (name.compare("depthWrite") == 0) { setDepthWrite(parseBoolean(value)); } else if (name.compare("depthFunc") == 0) { setDepthFunction(parseDepthFunc(value)); } else if (name.compare("stencilTest") == 0) { setStencilTest(parseBoolean(value)); } else if (name.compare("stencilWrite") == 0) { setStencilWrite(parseUInt(value)); } else if (name.compare("stencilFunc") == 0) { setStencilFunction(parseStencilFunc(value), _stencilFunctionRef, _stencilFunctionMask); } else if (name.compare("stencilFuncRef") == 0) { setStencilFunction(_stencilFunction, parseInt(value), _stencilFunctionMask); } else if (name.compare("stencilFuncMask") == 0) { setStencilFunction(_stencilFunction, _stencilFunctionRef, parseUInt(value)); } else if (name.compare("stencilOpSfail") == 0) { setStencilOperation(parseStencilOp(value), _stencilOpDpfail, _stencilOpDppass); } else if (name.compare("stencilOpDpfail") == 0) { setStencilOperation(_stencilOpSfail, parseStencilOp(value), _stencilOpDppass); } else if (name.compare("stencilOpDppass") == 0) { setStencilOperation(_stencilOpSfail, _stencilOpDpfail, parseStencilOp(value)); } else { CCLOG("Unsupported render state string '%s'.", name.c_str()); } }
/** * Prepares output table with all necessary statistics * @return */ void MappedContigStatTable::prepareTable(int index) { //cout << "preparing " << index << "\n"; cout.flush(); MappedContig* contig = &(*(mapped_sps_proj->contigs))[index]; if (contig->length == 0) { values.resize(0); return; } //cout << "preparing 1 " << index << "\n"; cout.flush(); pair<string, bool> dflt("", false); int numRows = ((contig->length - 1) * 12) + 10 + 35; vector<pair<string, bool> > dflt_vec(2, dflt); values.resize(numRows, dflt_vec); //cout << "preparing 2 " << index << "\n"; cout.flush(); setValue(0, 0, "Contig Index", true); setValue(0, 1, parseInt(index)); values[1].resize(0); setValue(2, 0, "# of Vertices", true); setValue(2, 1, parseInt(contig->length)); setValue(3, 0, "# of Assembled Spectra", true); setValue(3, 1, parseInt(contig->numSpecs)); setValue(4, 0, "# of Assembled Peptides", true); setValue(4, 1, parseInt(contig->numPeptides)); setValue(5, 0, "# of Assembled Annotated Spectra", true); setValue(5, 1, parseInt(contig->getNumAnnotSpec())); setValue(6, 0, "# of Assembled Mapped Spectra", true); setValue(6, 1, parseInt(contig->getNumMappedSpec())); values[7].resize(0); setValue(8, 0, "% Annotated Vertices from b or y", true); setValue(8, 1, parseFloat(contig->getPercBYVerts(), 1)); setValue(9, 0, "% Annotated Vertices from b", true); setValue(9, 1, parseFloat(contig->getPercBVerts(), 1)); setValue(10, 0, "% Annotated Vertices from y", true); setValue(10, 1, parseFloat(contig->getPercYVerts(), 1)); values[11].resize(0); setValue(12, 0, "Chimeric", true); string val = (contig->chimeric) ? "1" : "0"; setValue(12, 1, val); values[13].resize(0); setValue(14, 0, "% Annotated Vertices Correct", true); setValue(14, 1, parseFloat(contig->getPercVerts(3), 1)); setValue(15, 0, "% Annotated Vertices Chimeric", true); setValue(15, 1, parseFloat(contig->getPercVerts(2), 1)); setValue(16, 0, "% Annotated Vertices Incorrect", true); setValue(16, 1, parseFloat(contig->getPercVerts(1), 1)); setValue(17, 0, "% Un-annotated Vertices", true); setValue(17, 1, parseFloat(contig->getPercVerts(0), 1)); values[18].resize(0); pair<float, float> res = contig->getPercCallsAcc(2); setValue(19, 0, "# Annotated Gaps Correct", true); setValue(19, 1, parseFloat(res.first, 0)); res = contig->getPercCallsAcc(1); setValue(20, 0, "# Annotated Gaps Incorrect", true); setValue(20, 1, parseFloat(res.first, 0)); res = contig->getPercCallsAcc(0); setValue(21, 0, "# Un-annotated Gaps", true); setValue(21, 1, parseFloat(res.first, 0)); values[22].resize(0); res = contig->getPercCallsLen(0); setValue(23, 0, "# Single Jump Calls", true); setValue(23, 1, parseFloat(res.first, 0)); res = contig->getPercCallsAcc(1); setValue(24, 0, "# Consec Gap Calls", true); setValue(24, 1, parseFloat(res.first, 0)); res = contig->getPercCallsAcc(2); setValue(25, 0, "# Non-consec Gap Calls", true); setValue(25, 1, parseFloat(res.first, 0)); values[26].resize(0); setValue(27, 0, "Inspect Protein Index", true); setValue(27, 1, parseInt(contig->starProtIdx)); setValue(28, 0, "Matchma Protein Index", true); setValue(28, 1, parseInt(contig->vertProtIdx)); setValue(29, 0, "Matchma Reversed", true); val = (contig->reversed) ? "1" : "0"; setValue(29, 1, val); setValue(30, 0, "Matchma AA Coverage", true); setValue(30, 1, parseInt(contig->lastResidue - contig->firstResidue + 1)); setValue(31, 0, "Matchma Beg Residue Index", true); setValue(31, 1, parseInt(contig->firstResidue)); setValue(32, 0, "Matchma End Residue Index", true); setValue(32, 1, parseInt(contig->lastResidue)); values[33].resize(0); values[34].resize(7, dflt); setValue(34, 0, "Abruijn Vertex/Gap", true); setValue(34, 1, "Mass", true); setValue(34, 2, "Residue Idx", true); setValue(34, 3, "Intensity", true); setValue(34, 4, "Label", true); setValue(34, 5, "Annotation", true); setValue(34, 6, "Assembled Ions", true); string sep("-----"); string list_sep = ";"; for (int i = 0; i < contig->length; i++) { int tr = (i * 12) + 35; for (int j = 0; j < 10; j++) { values[tr + j].resize(contig->abruijnVerts[i].starPeaks.size() + 7, dflt); } setValue(tr, 0, parseInt(i)); setValue(tr, 1, parseFloat(contig->abruijnVerts[i].getMass(), 1)); val = (contig->abruijnVerts[i].residueIdx >= 0) ? parseInt(contig->abruijnVerts[i].residueIdx) : ""; setValue(tr, 2, val); setValue(tr, 3, parseFloat(contig->abruijnVerts[i].getIntensity(), 1)); setValue(tr, 4, MappedVertex::Labels[contig->abruijnVerts[i].label]); setValue(tr, 5, contig->abruijnVerts[i].annotation); setValue(tr, 6, "Spectrum Idx", true); setValue(tr + 1, 6, "Spectrum Rev", true); setValue(tr + 2, 6, "Spectrum Ident", true); setValue(tr + 3, 6, "Peak Idx", true); setValue(tr + 4, 6, "Peak Mass", true); setValue(tr + 5, 6, "Peak Endpt", true); setValue(tr + 6, 6, "Protein Idx", true); setValue(tr + 7, 6, "Residue Idx", true); setValue(tr + 8, 6, "Annotation", true); for (int j = 0; j < contig->abruijnVerts[i].starPeaks.size(); j++) { int tc = j + 7; MappedPeak* pk = contig->abruijnVerts[i].starPeaks[j]; MappedSpectrum* spec = &((*mapped_sps_proj->spectra)[pk->specIdx]); setValue(tr, tc, parseInt(pk->specIdx)); val = (spec->reversed) ? "1" : "0"; setValue(tr + 1, tc, val); val = (spec->identified) ? "1" : "0"; setValue(tr + 2, tc, val); setValue(tr + 3, tc, parseInt(pk->peakIdx)); setValue(tr + 4, tc, parseFloat(pk->getMass(), 1)); val = (pk->endpt) ? "1" : "0"; setValue(tr + 5, tc, val); string prot_str = ""; string res_str = ""; if (spec->mapped) { bool startL = true; for (map<int, list<int> >::iterator protIt = spec->residueIdxs.begin(); protIt != spec->residueIdxs.end(); protIt++) { for (list<int>::iterator resIt = protIt->second.begin(); resIt != protIt->second.end(); resIt++) { if (!startL) { prot_str.append(list_sep); if (pk->mapped) { res_str.append(list_sep); } } startL = false; prot_str.append(parseInt(protIt->first)); if (pk->mapped) { if (pk->BpeptideIdx >= 0) { res_str.append(parseInt((*resIt) + pk->BpeptideIdx)); } if (pk->YpeptideIdx >= 0) { if (pk->BpeptideIdx >= 0) { res_str.append(list_sep); } res_str.append(parseInt((*resIt) + pk->YpeptideIdx)); } } } } } setValue(tr + 6, tc, prot_str); setValue(tr + 7, tc, res_str); setValue(tr + 8, tc, pk->annotation); setValue(tr + 9, tc, sep, true); } for (int j = 0; j < 7; j++) { setValue(tr + 9, j, sep, true); } if (i < contig->length - 1) { for (int j = 10; j < 12; j++) { values[tr + j].resize(5, dflt); } string gap = ""; gap.append(parseInt(i)); gap.append("-"); gap.append(parseInt(i + 1)); setValue(tr + 10, 0, gap); setValue(tr + 10, 1, parseFloat(contig->abruijnGaps[i].getMass(), 1)); setValue(tr + 10, 3, parseFloat(contig->abruijnGaps[i].getIntensity(), 1)); setValue(tr + 10, 4, MappedGap::Labels[contig->abruijnGaps[i].label]); for (int j = 0; j < 5; j++) { setValue(tr + 11, j, sep, true); } } } }