void write_rule_prerequisites (FILE* stream, const char* target, list* dependencies) { void write(void* file_name) { if (file_exists(change_extension(file_name, ".c"))) { fprintf (stream, "%s ", change_extension((char*)file_name, ".o")); } } fprintf(stream, "%s ", change_extension(target, ".o")); list_foreach(dependencies, write); write_newline(stream); }
bool has_source_file_counterpart(void* file_name) { if (string_endswith((char*)file_name, ".c")) { return true; } if (file_exists(change_extension(file_name, ".c"))) { return true; } return false; }
/** * @brief Create a map file and write the TFTF field offsets to it * * Create a TFTF map file from the TFTF blob. * * @param tftf_hdr The TFTF blob to write * @param output_filename Pathname to the TFTF output file. * * @returns Returns true on success, false on failure. */ bool write_tftf_map_file(const tftf_header * tftf_hdr, const char * output_filename) { bool success = false; char map_filename[MAXPATH]; FILE * map_file = NULL; if ((tftf_hdr == NULL) || (output_filename == NULL)) { fprintf(stderr, "ERROR (write_tftf_file): Invalid args\n"); errno = EINVAL; } else { /* Convert the filename.xxx to filename.map if needed */ success = change_extension(map_filename, sizeof(map_filename), output_filename, ".map"); if (!success) { fprintf(stderr, "ERROR: map file path too long\n"); } else { map_file = fopen(map_filename, "w"); if (map_file == NULL) { fprintf(stderr, "ERROR: Can't create map file '%s' (err %d)\n", map_filename, errno); } else { write_tftf_map(tftf_hdr, NULL, 0, map_file); /* Done with the TFTF file. */ fclose(map_file); } } } return success; }
boost::filesystem::path find(string prog) { boost::filesystem::path p = prog; #ifdef _WIN32 p = change_extension(p, ".exe"); #endif if( boost::filesystem::exists(p) ){ #ifndef _WIN32 p = boost::filesystem::initial_path() / p; #endif return p; } { boost::filesystem::path t = boost::filesystem::current_path() / p; if( boost::filesystem::exists(t) ) return t; } try { if( theScope->type("_path") == String ) { string path = theScope->getString("_path"); if( !path.empty() ) { boost::filesystem::path t = boost::filesystem::path(path) / p; if( boost::filesystem::exists(t) ) return t; } } } catch(...) { } { boost::filesystem::path t = boost::filesystem::initial_path() / p; if( boost::filesystem::exists(t) ) return t; } return p; // not found; might find via system path }
static rc_t capture_arguments_and_options( Args * args, context *ctx ) { evaluate_options( args, ctx ); change_extension( &(ctx->dependency_file), DEPENDENCY_EXTENSION ); return 0; }
void write_source_rules (FILE* stream, const file_graph* graph) { void* rename_to_source_extension (void* file_name) { return change_extension((char*)file_name, ".c"); } bool source_file_exists(void* file_name) { return file_exists(change_extension((char*)file_name, ".c")); } void write_file_name (void* file_name) { fprintf(stream, "%s ", (const char*)file_name); }
VirtualShapeVirtualTable::VirtualShapeVirtualTable( const boost::filesystem::path& path, const std::string& codePage, CoordinatesSystem::SRID srid ): SQLiteVirtualTable( GetTableName(path), "VirtualShape(\"" + replace_all_copy(change_extension(path, string()).file_string(), "\\", "\\\\") + "\"," + codePage + "," + lexical_cast<string>(srid) + ")" ) {}
void preprocess_mod_file ( char *filename) /* The file to read */ { Ifs_Table_t ifs_table; /* info read from ifspec.ifs file */ Status_t status; /* Return status */ const char *output_filename; /* * Read the entire ifspec.ifs file and load the data into ifs_table */ status = read_ifs_file (IFSPEC_FILENAME, GET_IFS_TABLE, &ifs_table); if (status != OK) { exit(1); } current_filename = filename; mod_yyin = fopen_cmpp (¤t_filename, "r"); if (mod_yyin == NULL) { print_error("ERROR - Could not open input .mod file: %s", current_filename); exit(1); } output_filename = change_extension (filename, "c"); mod_yyout = fopen_cmpp (&output_filename, "w"); if (mod_yyout == NULL) { print_error("ERROR - Could not open output .c file: %s", output_filename); exit(1); } mod_ifs_table = &ifs_table; mod_num_errors = 0; fprintf (mod_yyout, "#line 1 \"%s\"\n", current_filename); fprintf (mod_yyout, "#include \"ngspice/cm.h\"\n"); fprintf (mod_yyout, "extern void %s(Mif_Private_t *);\n", ifs_table.name.c_fcn_name); fprintf (mod_yyout, "#line 1 \"%s\"\n", current_filename); mod_yylineno = 1; if (mod_yyparse() || (mod_num_errors > 0)) { print_error("Error parsing .mod file: \"%s\"", current_filename); unlink (output_filename); exit (1); } fclose (mod_yyout); mod_yyrestart(NULL); }
void write_source_rule(void* file_name_) { char* file_name = (char*)file_name_; list* header_dependencies = file_graph_dependencies(graph, file_name); write_rule_target(stream, change_extension(file_name, ".o")); write_file_name(file_name); list_foreach(header_dependencies, write_file_name); write_newline(stream); fprintf(stream, "\tgcc -c %s", file_name); write_newline(stream); write_newline(stream); }
boost::filesystem::path ProgramRunner::findProgram( const string &prog ) { boost::filesystem::path p = prog; #ifdef _WIN32 p = change_extension(p, ".exe"); #endif if( boost::filesystem::exists(p) ) { #ifndef _WIN32 p = boost::filesystem::initial_path() / p; #endif return p; } { boost::filesystem::path t = boost::filesystem::current_path() / p; if( boost::filesystem::exists(t) ) return t; } { boost::filesystem::path t = boost::filesystem::initial_path() / p; if( boost::filesystem::exists(t) ) return t; } return p; // not found; might find via system path }
// This is the target of the CreateRemoteThread int main(int argc, char *argv[]) { stp_params_t *stp_params = stp_params_from_args(argc, argv); if (!stp_params) { printf("Invalid command line.\n\n"); printf("Please note that this tool is not intended to be run directly,\n"); printf("you probably want to run stp.exe\n\n"); } else { // running import, if necessary char *img_file; if (stp_params->status == STATUS_LDR_INSTEAD) { // the imported file will go where the output file is img_file = STRDUP(stp_params->output_file); asfPrintStatus("Importing Level 0 data...\n"); import_ceos(stp_params->input_file, img_file, NULL, NULL, NULL, NULL, NULL, 0, 0, -99, -99, NULL, r_AMP, FALSE, FALSE, FALSE, FALSE, TRUE); asfPrintStatus("Import complete.\n"); } else if (stp_params->status == STATUS_STF_INSTEAD) { // the imported file will go where the output file is img_file = appendExt(stp_params->output_file, ""); asfPrintStatus("Importing STF data...\n"); import_stf(stp_params->input_file, img_file, r_AMP, NULL, 0, -99, -99, NULL); asfPrintStatus("Import complete.\n"); } else { // no import necessary-- input to ardop is the original .img file img_file = change_extension(stp_params->input_file, "img"); } // running ardop struct INPUT_ARDOP_PARAMS *params_in; params_in = get_input_ardop_params_struct(img_file, stp_params->output_file); float l_fd, l_fdd, l_fddd; if (stp_params->fd_set) { l_fd = stp_params->fd; params_in->fd = &l_fd; } if (stp_params->fdd_set) { l_fdd = stp_params->fdd; params_in->fdd = &l_fdd; } if (stp_params->fddd_set) { l_fddd = stp_params->fddd; params_in->fddd = &l_fddd; } sprintf(params_in->status, "%s.status", stp_params->output_file); char *tmp_dir = get_dirname(stp_params->output_file); set_asf_tmp_dir(tmp_dir); FREE(tmp_dir); // this stuff shouldn't cause collisions, local stack variables int npatches = 1; params_in->iflag = &(stp_params->debug_flag); params_in->npatches = &npatches; params_in->ifirstline = &(stp_params->ifirstline); ardop(params_in); free(params_in); free(img_file); // success! } return 0; }
int main(int argc, char *argv[]) { FILE *fp; int i; format_srm(); memset(&files, 0, sizeof(files)); if (argc < 2) { Usage: printf("Usage:\n"); printf(" To create a srm file: %s [file.eep] [file.mpk] [file.sra] [file.fla]\n", argv[0]); printf(" To extract a srm file: %s <file.srm>\n\n", argv[0]); printf("Output files will be placed in the same directory of the input files.\n"); exit(EXIT_FAILURE); } for (i = 1; i < argc; ++i) { if (!strcmp(argv[i], "-h") || !strcmp(argv[i], "--help") || !strcmp(argv[i], "/?")) goto Usage; if (ext_matches("srm", argv[i])) strncpy(files.srm, argv[i], 512); if (ext_matches("eep", argv[i])) strncpy(files.eep, argv[i], 512); if (ext_matches("mpk", argv[i])) strncpy(files.mpk, argv[i], 512); if (ext_matches("sra", argv[i])) strncpy(files.sra, argv[i], 512); if (ext_matches("fla", argv[i])) strncpy(files.fla, argv[i], 512); } if (*files.srm) { puts("Running in srm extraction mode"); read_mem(files.srm, &srm, sizeof(srm)); if (!is_empty_mem(srm.eeprom, sizeof(srm.eeprom))) change_extension(files.eep, files.srm, ".eep"); if (!is_empty_mem((uint8_t*)srm.mempack, sizeof(srm.mempack))) change_extension(files.mpk, files.srm, ".mpk"); if (!is_empty_mem(srm.sram, sizeof(srm.sram))) change_extension(files.sra, files.srm, ".sra"); if (!is_empty_mem(srm.flashram, sizeof(srm.flashram))) change_extension(files.fla, files.srm, ".fla"); int over = ((*files.eep && access(files.eep, 0) != -1) || (*files.mpk && access(files.mpk, 0) != -1) || (*files.sra && access(files.sra, 0) != -1) || (*files.fla && access(files.fla, 0) != -1)); if (over && !overwrite_confirm("existing saves in the source directory")) { puts("existing saves unmodified."); exit(EXIT_SUCCESS); } if (*files.eep) write_mem(files.eep, srm.eeprom, sizeof(srm.eeprom)); if (*files.mpk) write_mem(files.mpk, srm.mempack, sizeof(srm.mempack)); if (*files.sra) write_mem(files.sra, srm.sram, sizeof(srm.sram)); if (*files.fla) write_mem(files.fla, srm.flashram, sizeof(srm.flashram)); } else { puts("srm file unspecified, running in srm creation mode"); if (!files.eep && !files.mpk && !files.sra && !files.fla) die("no input files."); /* pick the first filename */ if (!*files.srm) { if (*files.eep) change_extension(files.srm, files.eep, ".srm"); else if (*files.mpk) change_extension(files.srm, files.mpk, ".srm"); else if (*files.sra) change_extension(files.srm, files.sra, ".srm"); else if (*files.fla) change_extension(files.srm, files.fla, ".srm"); if (strlen(files.srm) + 3 > 512) die("path too long"); } if (*files.eep) read_mem(files.eep, srm.eeprom, sizeof(srm.eeprom)); if (*files.mpk) read_mem(files.mpk, srm.mempack, sizeof(srm.mempack)); if (*files.sra) read_mem(files.sra, srm.sram, sizeof(srm.sram)); if (*files.fla) read_mem(files.fla, srm.flashram, sizeof(srm.flashram)); int over = access(files.srm, 0 /*F_OK*/) != -1; if (over && !overwrite_confirm(files.srm)) { printf("%s unmodified.\n", files.srm); exit(EXIT_SUCCESS); } printf("Writting srm data to %s...\n", files.srm); fp = fopen(files.srm, "wb"); if (!fp) { perror(files.srm); exit(EXIT_FAILURE); } fwrite(srm.eeprom, sizeof(srm.eeprom), 1, fp); fwrite(srm.mempack, sizeof(srm.mempack), 1, fp); fwrite(srm.sram, sizeof(srm.sram), 1, fp); fwrite(srm.flashram, sizeof(srm.flashram), 1, fp); fclose(fp); } return EXIT_SUCCESS; }
std::string VirtualShapeVirtualTable::GetTableName( const boost::filesystem::path& path ) { string out(change_extension(path, string()).file_string()); replace_if(out.begin(), out.end(), is_any_of(" \\:/()-+"), '_'); return "shapefile_" + out; }
int run_assembly() { #ifdef _WIN32 struct _timeb time_start, time_end; _ftime(&time_start); #else struct timeb time_start, time_end; ftime(&time_start); #endif exit_code = EXIT_NORMAL; /*extern int generic_map[256]; ZeroMemory(generic_map, 256);*/ program_counter = 0x0000; stats_codesize = stats_datasize = stats_mintime = stats_maxtime = 0; last_label = NULL; error_occurred = false; listing_offset = 0; listing_for_line_done = false; line_start = NULL; old_line_num = 0; in_macro = 0; line_num = 0; #ifdef USE_BUILTIN_FCREATE cur_buf = 0; #endif #ifdef USE_REUSABLES curr_reusable = 0; total_reusables = 0; #endif expr_list = NULL; expr_list_tail = NULL; output_list = NULL; output_list_tail = NULL; assert(curr_input_file != NULL); //read in the input file if (!(mode & MODE_COMMANDLINE)) input_contents = (char *) get_file_contents (curr_input_file); if (!input_contents) { puts ("Couldn't open input file"); return EXIT_FATAL_ERROR; } out_ptr = output_contents; //along with the listing buffer, if required if ((mode & MODE_LIST)) { listing_buf = eb_init (LISTING_BUF_SIZE); listing_offset = 0; listing_on = true; } //find the path of the input file if (is_abs_path(curr_input_file)) { int i; strcpy(temp_path, curr_input_file); for (i = strlen(temp_path) - 1; temp_path[i] != '\\' && temp_path[i] != '/' && i > 0; i--); if (i >= 0) temp_path[i] = '\0'; else strcpy(temp_path, "."); } else { #ifdef WIN32 _getcwd(temp_path, sizeof (temp_path)); #else getcwd(temp_path, sizeof (temp_path)); #endif } //add the the input file's path to the include directories include_dirs = list_prepend (include_dirs, strdup (temp_path)); printf ("Pass one... \n"); int first_pass_session = StartSPASMErrorSession(); run_first_pass ((char *) input_contents); ReplayFatalSPASMErrorSession(first_pass_session); EndSPASMErrorSession(first_pass_session); //free include dirs when done if ((mode & MODE_COMMANDLINE) == 0) { release_file_contents(input_contents); input_contents = NULL; } list_free (include_dirs, true, NULL); include_dirs = NULL; //...and if there's output, run the second pass and write it to the output file if (mode & MODE_SYMTABLE || mode & MODE_NORMAL || mode & MODE_LIST) { printf ("Pass two... \n"); int second_pass_session = StartSPASMErrorSession(); run_second_pass (); ReplaySPASMErrorSession(second_pass_session); EndSPASMErrorSession(second_pass_session); if (mode & MODE_SYMTABLE) { char* fileName = change_extension(output_filename, "lab"); write_labels (fileName); free(fileName); } //run the output through the appropriate program export and write it to a file if (mode & MODE_NORMAL && output_filename != NULL) { write_file (output_contents, out_ptr - output_contents, output_filename); } //write the listing file if necessary if ((mode & MODE_LIST)) { FILE *file; char *name; //get file name name = change_extension (output_filename, "lst"); file = fopen (name, "wb"); if (!file) { printf ("Couldn't open listing file '%s'", name); free (name); return EXIT_FATAL_ERROR; } free (name); if (fwrite (listing_buf->start, 1, listing_offset, file) != listing_offset) { puts ("Error writing to listing file"); fclose (file); return EXIT_FATAL_ERROR; } fclose (file); eb_free(listing_buf); listing_buf = NULL; } //free the output buffer and all the names of input files list_free(input_files, true, NULL); input_files = NULL; } //if there's info to be dumped, do that if (mode & MODE_CODE_COUNTER) { fprintf (stdout, "Size: %u\nMin. execution time: %u\nMax. execution time: %u\n", stats_codesize, stats_mintime, stats_maxtime); } if (mode & MODE_STATS) { fprintf(stdout, "Number of labels: %u\nNumber of defines: %u\nCode size: %u\nData size: %u\nTotal size: %u\n", get_num_labels (), get_num_defines (), stats_codesize, stats_datasize, stats_codesize + stats_datasize); } #ifdef _WIN32 _ftime(&time_end); #else ftime(&time_end); #endif int s_diff = (int) (time_end.time - time_start.time); int ms_diff = time_end.millitm - time_start.millitm; if (ms_diff < 0) { ms_diff += 1000; s_diff -= 1; } else if (ms_diff > 1000) { ms_diff -= 1000; s_diff += 1; } printf("Assembly time: %0.3f seconds\n", (float) s_diff + ((float) ms_diff / 1000.0f)); return exit_code; }
int main (int argc, char **argv) { int curr_arg = 1; bool case_sensitive = false; bool is_storage_initialized = false; use_colors = true; extern WORD user_attributes; user_attributes = save_console_attributes (); atexit (restore_console_attributes_at_exit); //if there aren't enough args, show info if (argc < 2) { puts ("SPASM-ng Z80 Assembler by Spencer Putt and Don Straney"); printf ("Version %s (built on %s @ %s)\n", SPASM_NG_VERSION, __DATE__, __TIME__); #ifdef SPASM_NG_GITREV printf ("Git revision %s\n", SPASM_NG_GITREV); #endif #ifdef _M_X64 puts ("64-bit Version"); #endif #ifdef NO_APPSIGN printf ("\nApp signing is NOT available in this build of SPASM.\n"); #endif puts ("\nspasm [options] <input file> <output file>\n"); puts ("Options:\n-E = Assemble eZ80 code\n-T = Generate code listing\n-C = Code counter mode\n-L = Symbol table mode\n-S = Stats mode\n-O = Don't write to output file"); puts ("-I [directory] = Add include directory\n-A = Labels are cAse-sensitive\n-D<name>[=value] = Create a define 'name' [with 'value']"); puts ("-N = Don't use colors for messages"); puts ("-V <Expression> = Pipe expression directly into assembly"); #if defined(_DEBUG) && defined(WIN32) if (IsDebuggerPresent()) { system("PAUSE"); } #endif return EXIT_NORMAL; } //init stuff mode = MODE_NORMAL; in_macro = 0; //otherwise, get any options curr_input_file = strdup("Commandline"); char *starting_input_file = curr_input_file; while (curr_arg < argc) { if (argv[curr_arg][0] == '-' #ifdef _WINDOWS || argv[curr_arg][0] == '/' #endif ) { switch (argv[curr_arg][1]) { //args for different modes case 'O': mode = mode & (~MODE_NORMAL); break; case 'T': mode |= MODE_LIST; break; case 'C': mode |= MODE_CODE_COUNTER; break; case 'L': mode |= MODE_SYMTABLE; break; case 'S': mode |= MODE_STATS; break; case 'E': mode |= MODE_EZ80; all_opcodes = opcode_list_ez80; break; //handle no-colors flag case 'N': use_colors = false; break; //handle include files too case 'I': { char *dir, *p; //make sure there's another argument after it for the include path if (strlen(argv[curr_arg]) > 2) { dir = strdup (&argv[curr_arg][2]); } else { if (curr_arg >= argc - 1) { printf ("%s used without include path\n", argv[curr_arg]); break; } dir = strdup (argv[++curr_arg]); } for (p = strtok (dir, ";,"); p; p = strtok (NULL, ";,")) { include_dirs = list_append (include_dirs, strdup(p)); } free(dir); break; } //and the case-sensitive flag case 'A': case_sensitive = true; break; //handle adding defines case 'D': { char name[256]; char *ptr; define_t *define; if (!is_storage_initialized) { init_storage(); is_storage_initialized = true; } if (strlen (argv[curr_arg]) > 2) { ptr = &argv[curr_arg][2]; } else { if (curr_arg >= argc - 1) { printf ("%s used without define name", argv[curr_arg]); break; } ptr = argv[++curr_arg]; } read_expr (&ptr, name, "="); define = add_define (strdup (name), NULL); if (*skip_whitespace (++ptr) != '\0') define->contents = strdup (ptr); else set_define (define, "1", 1, false); break; } case 'V': { char *line; //check for something after -V if (strlen(argv[curr_arg]) > 2) { line = &argv[curr_arg][2]; } else { //if not lets fail if (curr_arg >= argc - 1) { printf ("%s used without a line to assemble\n", argv[curr_arg]); return EXIT_FATAL_ERROR; } line = argv[++curr_arg]; } mode |= MODE_COMMANDLINE; curr_input_file = strdup("-v"); input_contents = (char *) malloc (strlen(line) + 1 + 2); output_filename = change_extension (curr_input_file, "bin"); strcpy(input_contents, line); strcat(input_contents, "\n"); break; } default: { #ifndef _TEST #ifdef _WINDOWS printf ("Unrecognized option %s\n", argv[curr_arg]); #ifdef SPASM_NG_ENABLE_COM FreeConsole(); return _AtlModule.WinMain(SW_HIDE); #endif #endif #else printf ("Unrecognized option %s\n", argv[curr_arg]); #endif } } } else { //if it's not a flag, then it must be a filename if (curr_input_file && (curr_input_file != starting_input_file) && !output_filename) output_filename = strdup(argv[curr_arg]); else if ((!curr_input_file) || (curr_input_file == starting_input_file)) curr_input_file = strdup(argv[curr_arg]); } curr_arg++; } // Update case sensitivity settings set_case_sensitive (case_sensitive); //check on filenames if (!(mode & MODE_COMMANDLINE) && curr_input_file == starting_input_file) { puts ("No input file specified"); free(starting_input_file); return EXIT_FATAL_ERROR; } if (curr_input_file != starting_input_file) { free(starting_input_file); } if (!output_filename) { output_filename = change_extension (curr_input_file, "bin"); } if (!is_storage_initialized) { init_storage(); is_storage_initialized = true; } output_contents = (unsigned char *) malloc(output_buf_size); ClearSPASMErrorSessions(); int error = run_assembly(); free(output_filename); output_filename = NULL; if (curr_input_file) { free(curr_input_file); curr_input_file = NULL; } if (include_dirs) { list_free(include_dirs, true, NULL); } free(output_contents); output_contents = NULL; ClearSPASMErrorSessions(); free_storage(); #ifdef _WINDOWS _CrtDumpMemoryLeaks(); if (IsDebuggerPresent()) { system("PAUSE"); } #endif return error; }
int main(int argc, char *argv[]) { image myPic; imageInfo picInfo; int count; char *outputType = NULL; int err; int aCrop = NO; int left = -1, right = -1, top = -1, bottom = -1; double xscale = 1, yscale = 1; double xs2, ys2; int xdim = 0, ydim = 0; int ditherMode = ' '; int mMono = NO; int outType = NO; int scaletofit = NO; int numBits = 1; char *outFile = NULL; char *type = NULL, *ext = NULL; char *p; int nv; double darken = 0; double contrast = 0; double rotate = 0; struct stat sbuf; int blend = NO; static char filename[MAXPATHLEN + 1] = ""; int negative = NO; int enhance = NO; formatInfo fInfo; count = getargs(argc, argv, "nbosabLiRiTiBixdydXiYidcmbpbsbbiDdSbKdfseird", &negative, &outputType, &aCrop, &left, &right, &top, &bottom, &xscale, &yscale, &xdim, &ydim, &ditherMode, &mMono, &outType, &scaletofit, &numBits, &darken, &blend, &contrast, &outFile, &enhance, &rotate ); if (count < 0 || count == argc) { if (count < 0 && -count != '-') fprintf(stderr, "Bad flag: %c\n", -count); fprintf(stderr, "Usage: %s [-options] filename\n" " options:\n" "\tn: make negative\n" "\to: string indicating output format\n" "\ta: auto crop non plotting areas\n" "\tL, R, T, B: specify where to crop picture\n" "\tx, y: specify scale factor in that direction\n" "\tX, Y: specify dimension of picture in that direction\n" "\td: select dither method: (D)ither, (T)hreshold, or (H)alftone\n" "\tm: convert image to monochrome\n" "\tp: dither image for output to printer\n" "\ts: scale image to fill up specified screen\n" "\tb: number of bits to dither to\n" "\tD: how much to brighten image\n" "\tK: contrast level\n" "\tS: blend pixels together when scaling\n" "\tf: file name to save to\n" "\te: contrast for enhance image\n" "\tr: number of degrees to rotate\n" , *argv); exit(1); } for (; count < argc; count++) { if ((err = load_pic(argv[count], &myPic))) { fprintf(stderr, "Cannot load file %s\nError: %s\n", argv[count], picErrorStr(err)); exit(1); } if (!getImageInfo(argv[count], &picInfo)) type = picInfo.extension; if (!outputType) outputType = type; if (!infoForFormat(outputType, &fInfo)) { ext = fInfo.extension; if (scaletofit && !xdim && !ydim && fInfo.maxWidth && fInfo.maxHeight) { xdim = fInfo.maxWidth; ydim = fInfo.maxHeight; } } if (mMono) makeMono(&myPic); if (left >= 0 || right >= 0 || top >= 0 || bottom >= 0) { if (left < 0) left = 0; if (right < 0) right = myPic.width - 1; if (top < 0) top = 0; if (bottom < 0) bottom = myPic.height - 1; cropImage(left, top, right, bottom, &myPic); } if (aCrop) autoCropImage(&myPic, 40); if (rotate) rotateImage(&myPic, (rotate * -3.141592) / 180.0); xs2 = xscale; ys2 = yscale; if (scaletofit) { if (!ydim && xdim) { xs2 = (double) xdim / ((double) myPic.width * xscale) * xscale; ys2 = ((double) xdim / ((double) myPic.width * xscale)) * yscale; } else if (ydim) { xs2 = ((double) ydim / ((double) myPic.height * yscale)) * xscale; ys2 = (double) ydim / ((double) myPic.height * yscale) * yscale; if (xdim && (myPic.width * xs2) > xdim) { xs2 = (double) xdim / ((double) myPic.width * xscale) * xscale; ys2 = ((double) xdim / ((double) myPic.width * xscale)) * yscale; } } } else { if (xdim) xs2 = (double) xdim / (double) myPic.width; if (ydim) ys2 = (double) ydim / (double) myPic.height; } xscale = xs2; yscale = ys2; scaleImage(xscale, yscale, blend, &myPic); if (darken || contrast) adjustImage(&myPic, contrast, darken); if (enhance) { makeMono(&myPic); enhanceImage(&myPic, enhance); } handle_dithering(ditherMode, &myPic, outType, numBits); if (negative) negateImage(&myPic); if (outFile) { strcpy(filename, outFile); if (!stat(filename, &sbuf) && (sbuf.st_mode & S_IFDIR)) { if (filename[strlen(filename) - 1] != '/') strcat(filename, "/"); if ((p = strrchr(argv[count], '/'))) strcat(filename, p + 1); else strcat(filename, argv[count]); } } else strcpy(filename, argv[count]); p = change_extension(filename, type, ext, 0); nv = 2; while (!stat(p, &sbuf)) { p = change_extension(filename, type, ext, nv); nv++; } if ((err = save_pic(p, outputType, &myPic))) { fprintf(stderr, "Cannot save file %s\nError: %s\n", p, picErrorStr(err)); exit(1); } fprintf(stderr, "Saved %s as %s\n", argv[count], p); freeImage(&myPic); } exit(0); return 0; }
int main(int argc, char** argv) { boost::program_options::options_description generic_options; generic_options.add_options() ("help", "display usage information") ("version", "display version information") ("verbose,v", "more verbose output"); boost::program_options::options_description fileio_options; fileio_options.add_options() ("input-file", boost::program_options::value<std::string>(), "input IFC file") ("output-file", boost::program_options::value<std::string>(), "output geometry file"); std::string bounds; std::vector<std::string> entity_vector; boost::program_options::options_description geom_options; geom_options.add_options() ("plan", "Specifies whether to include curves in the output result. Typically " "these are representations of type Plan or Axis. Excluded by default.") ("model", "Specifies whether to include surfaces and solids in the output result. " "Typically these are representations of type Body or Facetation. " "Included by default.") ("weld-vertices", "Specifies whether vertices are welded, meaning that the coordinates " "vector will only contain unique xyz-triplets. This results in a " "manifold mesh which is useful for modelling applications, but might " "result in unwanted shading artefacts in rendering applications.") ("use-world-coords", "Specifies whether to apply the local placements of building elements " "directly to the coordinates of the representation mesh rather than " "to represent the local placement in the 4x3 matrix, which will in that " "case be the identity matrix.") ("convert-back-units", "Specifies whether to convert back geometrical output back to the " "unit of measure in which it is defined in the IFC file. Default is " "to use meters.") ("sew-shells", "Specifies whether to sew the faces of IfcConnectedFaceSets together. " "This is a potentially time consuming operation, but guarantees a " "consistent orientation of surface normals, even if the faces are not " "properly oriented in the IFC file.") #if OCC_VERSION_HEX < 0x60900 // In Open CASCADE version prior to 6.9.0 boolean operations with multiple // arguments where not introduced yet and a work-around was implemented to // subtract multiple openings as a single compound. This hack is obsolete // for newer versions of Open CASCADE. ("merge-boolean-operands", "Specifies whether to merge all IfcOpeningElement operands into a single " "operand before applying the subtraction operation. This may " "introduce a performance improvement at the risk of failing, in " "which case the subtraction is applied one-by-one.") #endif ("disable-opening-subtractions", "Specifies whether to disable the boolean subtraction of " "IfcOpeningElement Representations from their RelatingElements.") ("bounds", boost::program_options::value<std::string>(&bounds), "Specifies the bounding rectangle, for example 512x512, to which the " "output will be scaled. Only used when converting to SVG.") ("include", "Specifies that the entities listed after --entities are to be included") ("exclude", "Specifies that the entities listed after --entities are to be excluded") ("entities", boost::program_options::value< std::vector<std::string> >(&entity_vector)->multitoken(), "A list of entities that should be included in or excluded from the " "geometrical output, depending on whether --ignore or --include is " "specified. Defaults to IfcOpeningElement and IfcSpace to be excluded."); boost::program_options::options_description cmdline_options; cmdline_options.add(generic_options).add(fileio_options).add(geom_options); boost::program_options::positional_options_description positional_options; positional_options.add("input-file", 1); positional_options.add("output-file", 1); boost::program_options::variables_map vmap; try { boost::program_options::store(boost::program_options::command_line_parser(argc, argv). options(cmdline_options).positional(positional_options).run(), vmap); } catch (const boost::program_options::unknown_option& e) { std::cerr << "[Error] Unknown option '" << e.get_option_name() << "'" << std::endl << std::endl; // Usage information will be emitted below } catch (...) { // Catch other errors such as invalid command line syntax } boost::program_options::notify(vmap); if (vmap.count("version")) { printVersion(); return 0; } else if (vmap.count("help") || !vmap.count("input-file")) { printUsage(generic_options, geom_options); return vmap.count("help") ? 0 : 1; } else if (vmap.count("include") && vmap.count("exclude")) { std::cerr << "[Error] --include and --ignore can not be specified together" << std::endl; printUsage(generic_options, geom_options); return 1; } const bool verbose = vmap.count("verbose") != 0; const bool weld_vertices = vmap.count("weld-vertices") != 0; const bool use_world_coords = vmap.count("use-world-coords") != 0; const bool convert_back_units = vmap.count("convert-back-units") != 0; const bool sew_shells = vmap.count("sew-shells") != 0; #if OCC_VERSION_HEX < 0x60900 const bool merge_boolean_operands = vmap.count("merge-boolean-operands") != 0; #endif const bool disable_opening_subtractions = vmap.count("disable-opening-subtractions") != 0; bool include_entities = vmap.count("include") != 0; const bool include_plan = vmap.count("plan") != 0; const bool include_model = vmap.count("model") != 0 || (!include_plan); boost::optional<int> bounding_width, bounding_height; if (vmap.count("bounds") == 1) { int w, h; if (sscanf(bounds.c_str(), "%ux%u", &w, &h) == 2) { bounding_width = w; bounding_height = h; } else { std::cerr << "[Error] Invalid use of --bounds" << std::endl; printUsage(generic_options, geom_options); return 1; } } // Gets the set ifc types to be ignored from the command line. std::set<std::string> entities; for (std::vector<std::string>::const_iterator it = entity_vector.begin(); it != entity_vector.end(); ++it) { const std::string& mixed_case_type = *it; entities.insert(boost::to_lower_copy(mixed_case_type)); } const std::string input_filename = vmap["input-file"].as<std::string>(); // If no output filename is specified a Wavefront OBJ file will be output // to maintain backwards compatibility with the obsolete IfcObj executable. const std::string output_filename = vmap.count("output-file") == 1 ? vmap["output-file"].as<std::string>() : change_extension(input_filename, DEFAULT_EXTENSION); if (output_filename.size() < 5) { printUsage(generic_options, geom_options); return 1; } std::string output_extension = output_filename.substr(output_filename.size()-4); boost::to_lower(output_extension); // If no entities are specified these are the defaults to skip from output if (entity_vector.empty()) { if (output_extension == ".svg") { entities.insert("ifcspace"); include_entities = true; } else { entities.insert("ifcopeningelement"); entities.insert("ifcspace"); } } Logger::SetOutput(&std::cout, &log_stream); Logger::Verbosity(verbose ? Logger::LOG_NOTICE : Logger::LOG_ERROR); if (output_extension == ".xml") { int exit_code = 1; try { XmlSerializer s(output_filename); IfcParse::IfcFile f; if (!f.Init(input_filename)) { Logger::Message(Logger::LOG_ERROR, "Unable to parse .ifc file"); } else { s.setFile(&f); s.finalize(); exit_code = 0; } } catch (...) {} write_log(); return exit_code; } IfcGeom::IteratorSettings settings; settings.set(IfcGeom::IteratorSettings::APPLY_DEFAULT_MATERIALS, true); settings.set(IfcGeom::IteratorSettings::USE_WORLD_COORDS, use_world_coords); settings.set(IfcGeom::IteratorSettings::WELD_VERTICES, weld_vertices); settings.set(IfcGeom::IteratorSettings::SEW_SHELLS, sew_shells); settings.set(IfcGeom::IteratorSettings::CONVERT_BACK_UNITS, convert_back_units); #if OCC_VERSION_HEX < 0x60900 settings.set(IfcGeom::IteratorSettings::FASTER_BOOLEANS, merge_boolean_operands); #endif settings.set(IfcGeom::IteratorSettings::DISABLE_OPENING_SUBTRACTIONS, disable_opening_subtractions); settings.set(IfcGeom::IteratorSettings::INCLUDE_CURVES, include_plan); settings.set(IfcGeom::IteratorSettings::EXCLUDE_SOLIDS_AND_SURFACES, !include_model); GeometrySerializer* serializer; if (output_extension == ".obj") { const std::string mtl_filename = output_filename.substr(0,output_filename.size()-3) + "mtl"; if (!use_world_coords) { Logger::Message(Logger::LOG_NOTICE, "Using world coords when writing WaveFront OBJ files"); settings.set(IfcGeom::IteratorSettings::USE_WORLD_COORDS, true); } serializer = new WaveFrontOBJSerializer(output_filename, mtl_filename); #ifdef WITH_OPENCOLLADA } else if (output_extension == ".dae") { serializer = new ColladaSerializer(output_filename); #endif } else if (output_extension == ".stp") { serializer = new StepSerializer(output_filename); } else if (output_extension == ".igs") { // Not sure why this is needed, but it is. // See: http://tracker.dev.opencascade.org/view.php?id=23679 IGESControl_Controller::Init(); serializer = new IgesSerializer(output_filename); } else if (output_extension == ".svg") { settings.set(IfcGeom::IteratorSettings::DISABLE_TRIANGULATION, true); serializer = new SvgSerializer(output_filename); if (bounding_width && bounding_height) { ((SvgSerializer*) serializer)->setBoundingRectangle( static_cast<double>(*bounding_width), static_cast<double>(*bounding_height) ); } } else { Logger::Message(Logger::LOG_ERROR, "Unknown output filename extension"); write_log(); printUsage(generic_options, geom_options); return 1; } if (!serializer->isTesselated()) { if (weld_vertices) { Logger::Message(Logger::LOG_NOTICE, "Weld vertices setting ignored when writing STEP or IGES files"); } settings.disable_triangulation() = true; } IfcGeom::Iterator<double> context_iterator(settings, input_filename); IfcGeom::ProductFilter productFilter; try { if (include_entities) { productFilter.includeEntities(entities); } else { productFilter.excludeEntities(entities); } context_iterator.setProductFilter(&productFilter, &IfcGeom::ProductFilter::shouldConvertProduct); } catch (const IfcParse::IfcException& e) { std::cout << "[Error] " << e.what() << std::endl; return 1; } if (!serializer->ready()) { Logger::Message(Logger::LOG_ERROR, "Unable to open output file for writing"); write_log(); return 1; } time_t start,end; time(&start); if (!context_iterator.initialize()) { Logger::Message(Logger::LOG_ERROR, "Unable to parse .ifc file or no geometrical entities found"); write_log(); return 1; } serializer->setFile(context_iterator.getFile()); if (convert_back_units) { serializer->setUnitNameAndMagnitude(context_iterator.getUnitName(), static_cast<const float>(context_iterator.getUnitMagnitude())); } else { serializer->setUnitNameAndMagnitude("METER", 1.0f); } serializer->writeHeader(); std::set<std::string> materials; int old_progress = -1; Logger::Status("Creating geometry..."); // The functions IfcGeom::Iterator::get() and IfcGeom::Iterator::next() // wrap an iterator of all geometrical products in the Ifc file. // IfcGeom::Iterator::get() returns an IfcGeom::TriangulationElement or // -BRepElement pointer, based on current settings. (see IfcGeomIterator.h // for definition) IfcGeom::Iterator::next() is used to poll whether more // geometrical entities are available. None of these functions throw // exceptions, neither for parsing errors or geometrical errors. Upon // calling next() the entity to be returned has already been processed, a // true return value guarantees that a successfully processed product is // available. do { const IfcGeom::Element<double>* geom_object = context_iterator.get(); if (serializer->isTesselated()) { serializer->write(static_cast<const IfcGeom::TriangulationElement<double>*>(geom_object)); } else { serializer->write(static_cast<const IfcGeom::BRepElement<double>*>(geom_object)); } const int progress = context_iterator.progress() / 2; if (old_progress!= progress) Logger::ProgressBar(progress); old_progress = progress; } while (context_iterator.next()); serializer->finalize(); delete serializer; Logger::Status("\rDone creating geometry "); write_log(); time(&end); int dif = (int) difftime (end,start); printf ("\nConversion took %d seconds\n", dif ); return 0; }
void ReflectionParser::GenerateFiles(void) { fs::path sourceRootDirectory( m_options.sourceRoot ); fs::path outputFileDirectory( m_options.outputModuleFileDirectory ); m_moduleFileHeaderTemplate = LoadTemplate( kTemplateModuleFileHeader ); if (!m_moduleFileHeaderTemplate.isValid( )) { std::stringstream error; error << "Unable to compile module file header template." << std::endl; error << m_moduleFileHeaderTemplate.errorMessage( ); throw std::exception( error.str( ).c_str( ) ); } m_moduleFileSourceTemplate = LoadTemplate( kTemplateModuleFileSource ); if (!m_moduleFileSourceTemplate.isValid( )) { std::stringstream error; error << "Unable to compile module file source template." << std::endl; error << m_moduleFileSourceTemplate.errorMessage( ); throw std::exception( error.str( ).c_str( ) ); } TemplateData moduleFilesData { TemplateData::Type::List }; fs::path metaCacheFileName = m_options.outputModuleFileDirectory; metaCacheFileName /= ".meta-cache"; auto metaCacheFileExists = exists( metaCacheFileName ); std::string moduleFileCache; for (auto &file : m_moduleFiles) { fs::path filePath( file.first ); // path relative to the source root auto relativeDir = utils::MakeRelativePath( sourceRootDirectory, filePath ) .replace_extension( "" ).string( ); if (relativeDir.find_first_of( ".." ) != std::string::npos) continue; auto outputFile = outputFileDirectory / relativeDir; auto outputFileHeader = change_extension( outputFile, "Generated.h" ); auto outputFileSource = change_extension( outputFile, "Generated.cpp" ); // module file name file.second.name = boost::regex_replace( relativeDir, kSpecialCharsRegex, "_" ); moduleFileCache += file.second.name + '\n'; TemplateData moduleFileData { TemplateData::Type::Object }; moduleFileData[ "name" ] = file.second.name; moduleFileData[ "header" ] = outputFileHeader.string( ); moduleFilesData << moduleFileData; // if the generated file header doesn't exist, we need to regenerate if (m_options.forceRebuild || !metaCacheFileExists || !exists( outputFileHeader )) { generateModuleFile( outputFileHeader, outputFileSource, file.first, file.second ); continue; } auto lastSourceWrite = last_write_time( filePath ); auto lastGeneratedWrite = last_write_time( outputFileHeader ); // if the generated file is older than the source file, we need to regenerate if (lastSourceWrite > lastGeneratedWrite) generateModuleFile( outputFileHeader, outputFileSource, file.first, file.second ); } fs::path moduleCacheFileName = m_options.outputModuleFileDirectory; moduleCacheFileName /= ".meta-cache"; if (!m_options.forceRebuild && metaCacheFileExists) { std::ifstream cacheFile( moduleCacheFileName.string( ) ); std::istreambuf_iterator<char> cacheFileBegin( cacheFile ); std::istreambuf_iterator<char> cacheFileEnd( nullptr ); // the cache is the same, so we don't need to write the source files if (utils::RangeEqual( moduleFileCache.begin( ), moduleFileCache.end( ), cacheFileBegin, cacheFileEnd )) { return; } } // update the cache utils::WriteText( moduleCacheFileName.string( ), moduleFileCache ); // module source file { auto sourceTemplate = LoadTemplate( kTemplateModuleSource ); if (!sourceTemplate.isValid( )) { std::stringstream error; error << "Unable to compile module source template." << std::endl; error << sourceTemplate.errorMessage( ); throw std::exception( error.str( ).c_str( ) ); } TemplateData sourceData { TemplateData::Type::Object }; addGlobalTemplateData( sourceData ); sourceData[ "moduleFile" ] = moduleFilesData; COMPILE_TYPE_TEMPLATES( sourceData, "external", m_externals ); fs::path sourcePath( m_options.outputModuleSource ); fs::create_directory( sourcePath.parent_path( ) ); utils::WriteText( sourcePath.string( ), sourceTemplate.render( sourceData ) ); } }