IOResult PolyOperation::SaveBasics (ISave *isave) { isave->BeginChunk (kSelection); mSelection.Save (isave); isave->EndChunk (); ULONG nb; Tab<int> paramList; GetParameters (paramList); for (int i=0; i<paramList.Count (); i++) { int id = paramList[i]; isave->BeginChunk (kParameter); isave->Write (&id, sizeof(int), &nb); isave->Write (Parameter(id), ParameterSize(id), &nb); isave->EndChunk (); } return IO_OK; }
void CSearchParamsWnd::OnBnClickedStart() { m_ctlMore.EnableWindow(FALSE); if (m_ctlOpts.GetEditCtrl()->GetSafeHwnd()) m_ctlOpts.CommitEditCtrl(); SSearchParams* pParams = GetParameters(); if (pParams) { if (!pParams->strExpression.IsEmpty()) { if (m_pacSearchString && m_pacSearchString->IsBound()) m_pacSearchString->AddItem(pParams->strExpression, 0); m_searchdlg->StartSearch(pParams); } else delete pParams; } }
/*============================================================================*/ MyFontDialog:: MyFontDialog(LPLOGFONT lplfInitial /* = NULL */, DWORD dwFlags /* = 0 */, HDC hdcPrinter /* = 0 */) /* Create an object having the specified log font given in lplfInitial and having the attributes specified by dwFlags. If lplfInitial is NULL, use a default font. *-----------------------------------------------------------------------------*/ : CFontDialog(lplfInitial, dwFlags, hdcPrinter) { SetBoxTitle(_T("Font")); RecordFontMetrics(); if (!lplfInitial) { // default font, 10pt Courier New m_Font.CreatePointFont(10, _T("Courier New")); } CHOOSEFONT cf = GetParameters(); cf.Flags |= dwFlags | CF_EFFECTS | CF_SHOWHELP; SetParameters(cf); SetChoiceFont(m_Font); }
void GLTexture2D::Load() { auto fileOptions = GetParameters(); auto filename = application->GetConfig().resourceBase + "/" + fileOptions[0]; if (!boost::filesystem::exists(filename)) { LOG(ERROR) << "File \"" << filename.c_str() << L"\" cannot be opened."; throw resource_loading_error() << ::boost::errinfo_file_name(filename) << resid_info(id) << errdesc_info("Cannot open include file."); } auto format = FreeImage_GetFileType(filename.c_str()); auto flags = 0; if (format == FIF_JPEG) { flags = JPEG_ACCURATE; } else if (format == FIF_TARGA) { flags = TARGA_LOAD_RGB888; } auto bitmap = FreeImage_Load(format, filename.c_str(), flags); auto bitmap32 = FreeImage_ConvertTo32Bits(bitmap); auto width = FreeImage_GetWidth(bitmap32); auto height = FreeImage_GetHeight(bitmap32); auto redMask = FreeImage_GetRedMask(bitmap32); auto greenMask = FreeImage_GetGreenMask(bitmap32); auto blueMask = FreeImage_GetBlueMask(bitmap32); void* data = FreeImage_GetBits(bitmap32); GLenum fmt = GL_RGBA; if (redMask > greenMask && greenMask > blueMask) fmt = GL_BGRA; auto internalFmt = GL_RGBA8; for (unsigned int i = 1; i < fileOptions.size(); ++i) { boost::trim(fileOptions[i]); if (fileOptions[i] == "sRGB" && application->GetConfig().useSRGB) internalFmt = GL_SRGB8_ALPHA8; } TextureDescriptor texDesc(4, internalFmt, fmt, GL_UNSIGNED_BYTE); texture = std::make_unique<GLTexture>(width, height, texDesc, data); FreeImage_Unload(bitmap32); FreeImage_Unload(bitmap); Resource::Load(); }
void CGUIIncludes::LoadIncludes(const TiXmlElement *node) { if (!node) return; const TiXmlElement* child = node->FirstChildElement("include"); while (child) { const char *tagName = child->Attribute("name"); if (tagName && child->FirstChild()) { // we'll parse and store parameter list with defaults when include definition is first encountered // if there's a <definition> tag only use its body as the actually included part const TiXmlElement *definitionTag = child->FirstChildElement("definition"); const TiXmlElement *includeBody = definitionTag ? definitionTag : child; // if there's a <param> tag there also must be a <definition> tag Params defaultParams; bool haveParamTags = GetParameters(child, "default", defaultParams); if (haveParamTags && !definitionTag) CLog::Log(LOGWARNING, "Skin has invalid include definition: %s", tagName); else m_includes.insert({ tagName, { *includeBody, std::move(defaultParams) } }); } else if (child->Attribute("file")) { std::string file = g_SkinInfo->GetSkinPath(child->Attribute("file")); const char *condition = child->Attribute("condition"); if (condition) { // load include file if condition evals to true if (g_infoManager.Register(condition)->Get()) Load_Internal(file); } else Load_Internal(file); } child = child->NextSiblingElement("include"); } }
double * wavread(char* filename, int *fs, int *nbit, int *wav_length) { FILE *fp = fopen(filename, "rb"); if (NULL == fp) { printf("File not found.\n"); return NULL; } if (CheckHeader(fp) == false) { fclose(fp); return NULL; } if (GetParameters(fp, fs, nbit, wav_length) == false) { fclose(fp); return NULL; } double *waveform = calloc(*wav_length, sizeof(double)); if (waveform == NULL) return NULL; int quantization_byte = *nbit / 8; double zero_line = pow(2.0, *nbit - 1); double tmp, sign_bias; unsigned char for_int_number[4]; for (int i = 0; i < *wav_length; ++i) { sign_bias = tmp = 0.0; fread(for_int_number, 1, quantization_byte, fp); // "data" if (for_int_number[quantization_byte-1] >= 128) { sign_bias = pow(2.0, *nbit - 1); for_int_number[quantization_byte - 1] = for_int_number[quantization_byte - 1] & 0x7F; } for (int j = quantization_byte - 1; j >= 0; --j) tmp = tmp * 256.0 + for_int_number[j]; waveform[i] = (tmp - sign_bias) / zero_line; } fclose(fp); return waveform; }
void PolyOperation::GetValues (IParamBlock2 *pBlock, TimeValue t, Interval & ivalid) { Tab<int> paramList; GetParameters (paramList); for (int i=0; i<paramList.Count(); i++) { int id = paramList[i]; void *prmtr = Parameter(id); if (prmtr == NULL) continue; ParamType2 type = pBlock->GetParameterType (id); if (type == TYPE_INT) { int *iparam = (int *) prmtr; pBlock->GetValue (paramList[i], t, *iparam, ivalid); } else if (type == TYPE_FLOAT) { float *fparam = (float *)prmtr; pBlock->GetValue (id, t, *fparam, ivalid); } } }
void SceneManager::SaveLevel(Ogre::String levelfile) { Msg msg; msg.typeID = GlobalMessageIDs::SAVELEVEL_BEGIN; MessageSystem::Instance().MulticastMessage(msg, true); ShowEditorMeshes(false); LoadSave::SaveSystem *ss=LoadSave::LoadSave::Instance().CreateSaveFile(levelfile, levelfile + ".xml"); DataMap map; GetParameters(&map); ss->SaveObject(&map, "LevelParams"); std::vector<GameObjectPtr> objects; for (auto i = mGameObjects.begin(); i != mGameObjects.end(); i++) objects.push_back(i->second); ss->SaveAtom("vector<GameObjectPtr>", &objects, "Objects"); //ss->SaveObject(AIManager::Instance().GetNavigationMesh(), "WayMesh"); ss->CloseFiles(); ICE_DELETE ss; msg.typeID = GlobalMessageIDs::SAVELEVEL_END; MessageSystem::Instance().MulticastMessage(msg, true); }
int main(int argc, char **argv) { Parameters *parameters; ULONG FP = 0; ULONG FN = 0; ULONG TP = 0; ULONG TN = 0; double FPRate; double TPRate; double error; if (argc != 3) { fprintf(stderr, "USAGE: %s <subsfile> <graphfile>\n", argv[0]); exit(1); } parameters = GetParameters(argc, argv); Test(argv[1], argv[2], parameters, &TP, &TN, &FP, &FN); // compute and output stats FPRate = ((double) FP) / ((double) (TN+FP)); TPRate = ((double) TP) / ((double) (FN+TP)); error = ((double) (FP+FN)) / ((double) (TP+TN+FP+FN)); fprintf(stdout, "TP = %lu\nTN = %lu\nFP = %lu\nFN = %lu\n", TP, TN, FP, FN); fprintf(stdout, "(TP+FN) = %lu\n(TN+FP) = %lu\n", (TP+FN), (TN+FP)); fprintf(stdout, "(TP+TN+FP+FN) = %lu\n", (TP+TN+FP+FN)); fprintf(stdout, "(FP/(TN+FP)) = %f\n", FPRate); fprintf(stdout, "(TP/(FN+TP)) = %f\n", TPRate); fprintf(stdout, "Error = %f\n", error); fflush(stdout); FreeParameters(parameters); return 0; }
void wavread(const char* filename, int *fs, int *nbit, double *x) { FILE *fp = fopen(filename, "rb"); if (NULL == fp) { printf("File not found.\n"); return; } if (0 == CheckHeader(fp)) { fclose(fp); return; } int x_length; if (0 == GetParameters(fp, fs, nbit, &x_length)) { fclose(fp); return; } int quantization_byte = *nbit / 8; double zero_line = pow(2.0, *nbit - 1); double tmp, sign_bias; unsigned char for_int_number[4]; for (int i = 0; i < x_length; ++i) { sign_bias = tmp = 0.0; fread(for_int_number, 1, quantization_byte, fp); // "data" if (for_int_number[quantization_byte-1] >= 128) { sign_bias = pow(2.0, *nbit - 1); for_int_number[quantization_byte - 1] = for_int_number[quantization_byte - 1] & 0x7F; } for (int j = quantization_byte - 1; j >= 0; --j) tmp = tmp * 256.0 + for_int_number[j]; x[i] = (tmp - sign_bias) / zero_line; } fclose(fp); }
/** * Constructor. * @param shaderFilename the shaders file name */ Shader::Shader(const std::string& shaderFilename, ApplicationBase* app) : Resource(shaderFilename, app), shader(0), type(GL_VERTEX_SHADER), strType("vertex") { auto shaderDefinition = GetParameters(); if (boost::ends_with(shaderDefinition[0], ".fp")) { type = GL_FRAGMENT_SHADER; strType = "fragment"; } else if (boost::ends_with(shaderDefinition[0], ".gp")) { type = GL_GEOMETRY_SHADER; strType = "geometry"; } else if (boost::ends_with(shaderDefinition[0], ".tcp")) { type = GL_TESS_CONTROL_SHADER; strType = "tesselation control"; } else if (boost::ends_with(shaderDefinition[0], ".tep")) { type = GL_TESS_EVALUATION_SHADER; strType = "tesselation evaluation"; } else if (boost::ends_with(shaderDefinition[0], ".cp")) { type = GL_COMPUTE_SHADER; strType = "compute"; } }
void CLevel::SaveToFile() { if (!m_sFile.length()) { TAssert(m_sFile.length()); TError("Can't find level file \'" + m_sFile + "\' to save.\n"); return; } std::basic_ofstream<tchar> f(m_sFile.c_str()); tstring sMessage = "// Generated by the Tinker Engine\n// Feel free to modify\n\n"; f.write(sMessage.data(), sMessage.length()); tstring sName = "Name: " + m_sName + "\n"; f.write(sName.data(), sName.length()); tstring sGameMode = "GameMode: " + m_sGameMode + "\n\n"; f.write(sGameMode.data(), sGameMode.length()); for (size_t i = 0; i < m_aLevelEntities.size(); i++) { auto pEntity = &m_aLevelEntities[i]; tstring sEntity = "Entity: " + pEntity->GetClass() + "\n{\n"; f.write(sEntity.data(), sEntity.length()); if (pEntity->GetName().length()) { tstring sName = "\tName: " + pEntity->GetName() + "\n"; f.write(sName.data(), sName.length()); } for (auto it = pEntity->GetParameters().begin(); it != pEntity->GetParameters().end(); it++) { if (it->first == "Name") continue; tstring sName = "\t" + it->first + ": " + it->second + "\n"; f.write(sName.data(), sName.length()); } for (size_t j = 0; j < pEntity->GetOutputs().size(); j++) { auto pOutput = &pEntity->GetOutputs()[j]; tstring sOutput = "\n\tOutput: " + pOutput->m_sOutput + "\n\t{\n"; f.write(sOutput.data(), sOutput.length()); if (pOutput->m_sTargetName.length()) { tstring sTarget = "\t\tTarget: " + pOutput->m_sTargetName + "\n"; f.write(sTarget.data(), sTarget.length()); } if (pOutput->m_sInput.length()) { tstring sInput = "\t\tInput: " + pOutput->m_sInput + "\n"; f.write(sInput.data(), sInput.length()); } if (pOutput->m_sArgs.length()) { tstring sArgs = "\t\tArgs: " + pOutput->m_sArgs + "\n"; f.write(sArgs.data(), sArgs.length()); } if (pOutput->m_bKill) { tstring sKill = "\t\tKill: yes\n"; f.write(sKill.data(), sKill.length()); } tstring sClose = "\t}\n"; f.write(sClose.data(), sClose.length()); } tstring sClose = "}\n\n"; f.write(sClose.data(), sClose.length()); } TMsg("Wrote level file '" + m_sFile + "'\n"); }
Rcpp::List CEnv::GetData() { return GetParameters(t->GetParameterList()); }
static int Init( filter_t *p_filter ) { filter_sys_t *p_sys = p_filter->p_sys; const video_format_t *p_fmti = &p_filter->fmt_in.video; video_format_t *p_fmto = &p_filter->fmt_out.video; if( IsFmtSimilar( p_fmti, &p_sys->fmt_in ) && IsFmtSimilar( p_fmto, &p_sys->fmt_out ) && p_sys->ctx ) { return VLC_SUCCESS; } Clean( p_filter ); /* Init with new parameters */ ScalerConfiguration cfg; if( GetParameters( &cfg, p_fmti, p_fmto, p_sys->i_sws_flags ) ) { msg_Err( p_filter, "format not supported" ); return VLC_EGENERIC; } if( p_fmti->i_width <= 0 || p_fmto->i_width <= 0 ) { msg_Err( p_filter, "0 width not supported" ); return VLC_EGENERIC; } /* swscale does not like too small width */ p_sys->i_extend_factor = 1; while( __MIN( p_fmti->i_width, p_fmto->i_width ) * p_sys->i_extend_factor < MINIMUM_WIDTH) p_sys->i_extend_factor++; const unsigned i_fmti_width = p_fmti->i_width * p_sys->i_extend_factor; const unsigned i_fmto_width = p_fmto->i_width * p_sys->i_extend_factor; for( int n = 0; n < (cfg.b_has_a ? 2 : 1); n++ ) { const int i_fmti = n == 0 ? cfg.i_fmti : PIX_FMT_GRAY8; const int i_fmto = n == 0 ? cfg.i_fmto : PIX_FMT_GRAY8; struct SwsContext *ctx; ctx = sws_getContext( i_fmti_width, p_fmti->i_height, i_fmti, i_fmto_width, p_fmto->i_height, i_fmto, cfg.i_sws_flags | p_sys->i_cpu_mask, p_sys->p_src_filter, p_sys->p_dst_filter, 0 ); if( n == 0 ) p_sys->ctx = ctx; else p_sys->ctxA = ctx; } if( p_sys->ctxA ) { p_sys->p_src_a = picture_New( VLC_CODEC_GREY, i_fmti_width, p_fmti->i_height, 0, 1 ); p_sys->p_dst_a = picture_New( VLC_CODEC_GREY, i_fmto_width, p_fmto->i_height, 0, 1 ); } if( p_sys->i_extend_factor != 1 ) { p_sys->p_src_e = picture_New( p_fmti->i_chroma, i_fmti_width, p_fmti->i_height, 0, 1 ); p_sys->p_dst_e = picture_New( p_fmto->i_chroma, i_fmto_width, p_fmto->i_height, 0, 1 ); if( p_sys->p_src_e ) memset( p_sys->p_src_e->p[0].p_pixels, 0, p_sys->p_src_e->p[0].i_pitch * p_sys->p_src_e->p[0].i_lines ); if( p_sys->p_dst_e ) memset( p_sys->p_dst_e->p[0].p_pixels, 0, p_sys->p_dst_e->p[0].i_pitch * p_sys->p_dst_e->p[0].i_lines ); } if( !p_sys->ctx || ( cfg.b_has_a && ( !p_sys->ctxA || !p_sys->p_src_a || !p_sys->p_dst_a ) ) || ( p_sys->i_extend_factor != 1 && ( !p_sys->p_src_e || !p_sys->p_dst_e ) ) ) { msg_Err( p_filter, "could not init SwScaler and/or allocate memory" ); Clean( p_filter ); return VLC_EGENERIC; } p_sys->b_add_a = cfg.b_add_a; p_sys->b_copy = cfg.b_copy; p_sys->fmt_in = *p_fmti; p_sys->fmt_out = *p_fmto; p_sys->b_swap_uvi = cfg.b_swap_uvi; p_sys->b_swap_uvo = cfg.b_swap_uvo; video_format_ScaleCropAr( p_fmto, p_fmti ); #if 0 msg_Dbg( p_filter, "%ix%i chroma: %4.4s -> %ix%i chroma: %4.4s extend by %d", p_fmti->i_width, p_fmti->i_height, (char *)&p_fmti->i_chroma, p_fmto->i_width, p_fmto->i_height, (char *)&p_fmto->i_chroma, p_sys->i_extend_factor ); #endif return VLC_SUCCESS; }
/***************************************************************************** * OpenScaler: probe the filter and return score *****************************************************************************/ static int OpenScaler( vlc_object_t *p_this ) { filter_t *p_filter = (filter_t*)p_this; filter_sys_t *p_sys; int i_sws_mode; if( GetParameters( NULL, &p_filter->fmt_in.video, &p_filter->fmt_out.video, 0 ) ) return VLC_EGENERIC; /* */ p_filter->pf_video_filter = Filter; /* Allocate the memory needed to store the decoder's structure */ if( ( p_filter->p_sys = p_sys = malloc(sizeof(filter_sys_t)) ) == NULL ) return VLC_ENOMEM; /* Set CPU capabilities */ p_sys->i_cpu_mask = GetSwsCpuMask(); /* */ i_sws_mode = var_CreateGetInteger( p_filter, "swscale-mode" ); switch( i_sws_mode ) { case 0: p_sys->i_sws_flags = SWS_FAST_BILINEAR; break; case 1: p_sys->i_sws_flags = SWS_BILINEAR; break; case 2: p_sys->i_sws_flags = SWS_BICUBIC; break; case 3: p_sys->i_sws_flags = SWS_X; break; case 4: p_sys->i_sws_flags = SWS_POINT; break; case 5: p_sys->i_sws_flags = SWS_AREA; break; case 6: p_sys->i_sws_flags = SWS_BICUBLIN; break; case 7: p_sys->i_sws_flags = SWS_GAUSS; break; case 8: p_sys->i_sws_flags = SWS_SINC; break; case 9: p_sys->i_sws_flags = SWS_LANCZOS; break; case 10: p_sys->i_sws_flags = SWS_SPLINE; break; default: p_sys->i_sws_flags = SWS_BICUBIC; i_sws_mode = 2; break; } p_sys->p_src_filter = NULL; p_sys->p_dst_filter = NULL; /* Misc init */ p_sys->ctx = NULL; p_sys->ctxA = NULL; p_sys->p_src_a = NULL; p_sys->p_dst_a = NULL; p_sys->p_src_e = NULL; p_sys->p_dst_e = NULL; memset( &p_sys->fmt_in, 0, sizeof(p_sys->fmt_in) ); memset( &p_sys->fmt_out, 0, sizeof(p_sys->fmt_out) ); if( Init( p_filter ) ) { if( p_sys->p_src_filter ) sws_freeFilter( p_sys->p_src_filter ); free( p_sys ); return VLC_EGENERIC; } msg_Dbg( p_filter, "%ix%i chroma: %4.4s -> %ix%i chroma: %4.4s with scaling using %s", p_filter->fmt_in.video.i_width, p_filter->fmt_in.video.i_height, (char *)&p_filter->fmt_in.video.i_chroma, p_filter->fmt_out.video.i_width, p_filter->fmt_out.video.i_height, (char *)&p_filter->fmt_out.video.i_chroma, ppsz_mode_descriptions[i_sws_mode] ); return VLC_SUCCESS; }
extern int main(int argc, char **argv) { //Variable Declaration pthread_t pthreads[640]; int threadID[640]; int i=0; int j=0; int rtn=0; ULONGLONG startTicks = 0; /* Variables to capture the file name and the file pointer*/ char fileName[MAX_PATH]; FILE *hFile; struct statistics* buffer; int statisticsSize = 0; /*Variable to Captutre Information at the Application Level*/ struct applicationStatistics appStats; char mainFileName[MAX_PATH]; FILE *hMainFile; //Get perfCallibrationValue callibrationValue = getPerfCallibrationValue(); printf("Callibration Value for this Platform %llu \n", callibrationValue); //Get Parameters if(GetParameters(argc, argv)) { printf("Error in obtaining the parameters\n"); exit(-1); } //Assign Values to Application Statistics Members appStats.relationId=RELATION_ID; appStats.operationTime=0; appStats.buildNumber = "999.99"; appStats.processCount = USE_PROCESS_COUNT; appStats.threadCount = THREAD_COUNT; appStats.repeatCount = REPEAT_COUNT; printf("RELATION ID : %d\n", appStats.relationId); printf("Process Count : %d\n", appStats.processCount); printf("Thread Count : %d\n", appStats.threadCount); printf("Repeat Count : %d\n", appStats.repeatCount); //Open file for Application Statistics Collection snprintf(mainFileName, MAX_PATH, "main_nativecriticalsection_%d_.txt",appStats.relationId); hMainFile = fopen(mainFileName, "w+"); if(hMainFile == NULL) { printf("Error in opening main file for write\n"); } for (i=0;i<THREAD_COUNT;i++) { threadID[i] = i; } statisticsSize = sizeof(struct statistics); snprintf(fileName, MAX_PATH, "%d_thread_nativecriticalsection_%d_.txt", USE_PROCESS_COUNT, RELATION_ID); hFile = fopen(fileName, "w+"); if(hFile == NULL) { printf("Error in opening file for write for process [%d]\n", USE_PROCESS_COUNT); } // For each thread we will log operations failed (int), passed (int), total (int) // and number of ticks (DWORD) for the operations resultBuffer = new ResultBuffer( THREAD_COUNT, statisticsSize); //Call Test Case Setup Routine if (0!=setuptest()) { //Error Condition printf("Error Initializing Test Case\n"); exit(-1); } //Accquire Lock if (0!=pthread_mutex_lock(&g_mutex)) { //Error Condition printf("Error Accquiring Lock\n"); exit(-1); } //USE NATIVE METHOD TO GET TICK COUNT startTicks = GetTicks(); /*Loop to create number THREAD_COUNT number of threads*/ for (i=0;i< THREAD_COUNT;i++) { //printf("Creating Thread Count %d\n", i); //printf("Thread arrary value = %d\n", threadID[i]); rtn=pthread_create(&pthreads[i], NULL, waitforworkerthreads, &threadID[i]); if (0 != rtn) { /* ERROR Condition */ printf("Error: pthread Creat, %s \n", strerror(rtn)); exit(-1); } } //printf("Main Thread waits to recevie signal when all threads are done\n"); pthread_cond_wait(&g_cv2,&g_mutex); //printf("Main thread has received signal\n"); /*Signal Threads to Start Working*/ //printf("Raise signal for all threads to start working\n"); if (0!=pthread_cond_broadcast(&g_cv)) { //Error Condition printf("Error Broadcasting Conditional Event\n"); exit(-1); } //Release the lock if (0!=pthread_mutex_unlock(&g_mutex)) { //Error Condition printf("Error Releasing Lock\n"); exit(-1); } /*Join Threads */ while (j < THREAD_COUNT) { if (0 != pthread_join(pthreads[j],NULL)) { //Error Condition printf("Error Joining Threads\n"); exit(-1); } j++; } /*Write Application Results to File*/ //CAPTURE NATIVE TICK COUNT HERE appStats.operationTime = (DWORD)(GetTicks() - startTicks)/callibrationValue; /* Write Results to a file*/ if(hFile!= NULL) { for( i = 0; i < THREAD_COUNT; i++ ) { buffer = (struct statistics *)resultBuffer->getResultBuffer(i); fprintf(hFile, "%d,%d,%d,%d,%lu,%d\n", buffer->processId, buffer->operationsFailed, buffer->operationsPassed, buffer->operationsTotal, buffer->operationTime, buffer->relationId ); //printf("Iteration %d over\n", i); } } fclose(hFile); //Call Test Case Cleanup Routine if (0!=cleanuptest()) { //Error Condition printf("Error Cleaning up Test Case"); exit(-1); } if(hMainFile!= NULL) { printf("Writing to Main File \n"); fprintf(hMainFile, "%lu,%d,%d,%d,%d,%s\n", appStats.operationTime, appStats.relationId, appStats.processCount, appStats.threadCount, appStats.repeatCount, appStats.buildNumber); } fclose(hMainFile); return 0; }
int main( int argc, char* argv[] ) { /* char getprm = 0, isfile = 0;*/ int i; char command = 0, argument = -1; char file[256], file2[256], Error[256], *s; #ifdef __unix__ set_keypress(); #endif file[0] = 0; file2[0] = 0; ReturnVideoInfo = TEXTVER_ReturnVideoInfo; check_event = TEXTVER_check_event; Debug = TEXTVER_Debug; eol = TEXTVER_eol; QU_getline = TEXTVER_getline; putline = TEXTVER_putline; if( argc > 1 ) { if( strcmp( argv[1], "-z" ) == 0 ) { command = 1; /* calc a ZBuffer */ } else if( strcmp( argv[1], "-i" ) == 0 ) { command = 2; /* calc an image */ } else if( strcmp( argv[1], "-p" ) == 0 ) { command = 3; /* write parameters */ } else if( strcmp( argv[1], "-c" ) == 0 ) { command = 4; /* continue calculation */ } else if( strcmp( argv[1], "-h" ) == 0 ) { command = 5; /* help */ } } if( argc > 2 ) { strcpy( file, argv[2] ); if( strrchr( file, '.' ) ) { for( i = 0; i < strlen( file ); i++ ) { file[i] = tolower( ( int )file[i] ); } if( strcmp( strrchr( file, '.' ), ".ini" ) == 0 ) { argument = 1; /* ini file */ } else if( strcmp( strrchr( file, '.' ), ".png" ) == 0 ) { argument = 2; /* png file */ } else if( strcmp( strrchr( file, '.' ), ".zpn" ) == 0 ) { argument = 3; /* zpn file */ } else if( file[0] == 0 ) { argument = 0; } strcpy( file, argv[2] ); } } if( argc > 3 ) { strcpy( file2, argv[3] ); } switch( command ) { case 1: if( argument == 0 ) { printf( "You didn´t specify an ini-file.\nUse -h for help.\n" ); endprg(); return( -1 ); } if( argument != 1 ) { printf( "The file you specified has not the suffix '.ini', but it will be assumed to\n" ); printf( "be an ini file.\n" ); } ParseAndCalculate( file, Error, 1 ); break; case 2: if( argument == 1 ) { ParseAndCalculate( file, Error, 0 ); } else if( argument == 3 ) { ImgFromZBuf( file, file2, Error ); } else { printf( "You didn´t specify an ini- or zpn-file.\nUse -h for help.\n" ); endprg(); return( -1 ); } break; case 3: if( argument == 0 ) { printf( "No file given. Use -h for help.\n" ); endprg(); return( -1 ); } GetParameters( file, Error ); break; case 4: if( argument != 2 && argument != 3 ) { printf( "Given file is neither png nor zpn.\n" ); endprg(); return( -1 ); } if( argument == 2 ) { ParseAndCalculate( file, Error, 0 ); } if( argument == 3 ) { ParseAndCalculate( file, Error, 1 ); } break; case 5: strncpy( file, argv[0], 256 ); s = strrchr( file, '/' ); if( s == NULL ) { s = strrchr( file, '\\' ); } if( s == NULL ) { s = ( char* )&file[0]; } else { s++; } printf( "\n%s %s%s%s\n%s", PROGNAME, PROGVERSION, PROGSUBVERSION, PROGSTATE, "A 3d fractal generation program\n" ); printf( "Copyright (C) 1997-2002 Dirk Meyer\n" ); printf( "email: [email protected]\n" ); printf( "WWW: http://www.physcip.uni-stuttgart.de/phy11733/index_e.html\n" ); printf( "Mailing-List: http://groups.yahoo.com/group/quat/\n" ); printf( "\nThis program is distributed under the terms of the\n" ); printf( "GNU General Public License Version 2 (See file 'COPYING' for details)\n\n" ); printf( "-z <ini-file> begin calculation of a ZBuffer\n" ); printf( "-i [<ini-file> | <zpn-file> [& <ini-file>]]\n" ); printf( " begin calculation of an image [using an ini-file | a\n" ); printf( " ZBuffer [& replacing parameters from ini-file]]\n" ); printf( "-p <png- or zpn-file> read fractal parameters from image or ZBuffer and\n" ); printf( " write them to raw data (ini)\n" ); printf( "-c <png- or zpn-file> continue calculation of image or ZBuffer\n" ); printf( "-h Show help text\n" ); endprg(); return( 0 ); default: printf( "Didn't understand the given parameters. For help use -h\n" ); endprg(); return( -1 ); } if( Error[0] != 0 ) { printf( "%s\n", Error ); } endprg(); return( 0 ); }
int main(int argc, char **argv) { Parameters *parameters; ULONG numLabels; Graph *g1; Graph *g2; Graph *g2compressed; InstanceList *instanceList; ULONG numInstances; ULONG subSize, graphSize, compressedSize; double subDL, graphDL, compressedDL; double value; Label label; parameters = GetParameters(argc, argv); g1 = ReadGraph(argv[argc - 2], parameters->labelList, parameters->directed); g2 = ReadGraph(argv[argc - 1], parameters->labelList, parameters->directed); instanceList = FindInstances(g1, g2, parameters); numInstances = CountInstances(instanceList); printf("Found %lu instances.\n\n", numInstances); g2compressed = CompressGraph(g2, instanceList, parameters); // Compute and print compression-based measures subSize = GraphSize(g1); graphSize = GraphSize(g2); compressedSize = GraphSize(g2compressed); value = ((double) graphSize) / (((double) subSize) + ((double) compressedSize)); printf("Size of graph = %lu\n", graphSize); printf("Size of substructure = %lu\n", subSize); printf("Size of compressed graph = %lu\n", compressedSize); printf("Value = %f\n\n", value); // Compute and print MDL based measures numLabels = parameters->labelList->numLabels; subDL = MDL(g1, numLabels, parameters); graphDL = MDL(g2, numLabels, parameters); numLabels++; // add one for new "SUB" vertex label if ((parameters->allowInstanceOverlap) && (InstancesOverlap(instanceList))) numLabels++; // add one for new "OVERLAP" edge label compressedDL = MDL(g2compressed, numLabels, parameters); // add extra bits to describe where external edges connect to instances compressedDL += ExternalEdgeBits(g2compressed, g1, numInstances); value = graphDL / (subDL + compressedDL); printf("DL of graph = %f\n", graphDL); printf("DL of substructure = %f\n", subDL); printf("DL of compressed graph = %f\n", compressedDL); printf("Value = %f\n\n", value); if (parameters->outputToFile) { // first, actually add "SUB" and "OVERLAP" labels label.labelType = STRING_LABEL; label.labelValue.stringLabel = SUB_LABEL_STRING; StoreLabel(& label, parameters->labelList); label.labelValue.stringLabel = OVERLAP_LABEL_STRING; StoreLabel(& label, parameters->labelList); parameters->posGraph = g2compressed; WriteGraphToDotFile(parameters->outFileName, parameters); printf("Compressed graph written to dot file %s\n", parameters->outFileName); } FreeGraph(g2compressed); FreeInstanceList(instanceList); FreeGraph(g1); FreeGraph(g2); FreeParameters(parameters); return 0; }
static int Init( filter_t *p_filter ) { filter_sys_t *p_sys = p_filter->p_sys; const video_format_t *p_fmti = &p_filter->fmt_in.video; video_format_t *p_fmto = &p_filter->fmt_out.video; if( p_fmti->orientation != p_fmto->orientation ) return VLC_EGENERIC; if( video_format_IsSimilar( p_fmti, &p_sys->fmt_in ) && video_format_IsSimilar( p_fmto, &p_sys->fmt_out ) && p_sys->ctx ) { return VLC_SUCCESS; } Clean( p_filter ); /* Init with new parameters */ ScalerConfiguration cfg; if( GetParameters( &cfg, p_fmti, p_fmto, p_sys->i_sws_flags ) ) { msg_Err( p_filter, "format not supported" ); return VLC_EGENERIC; } if( p_fmti->i_visible_width <= 0 || p_fmti->i_visible_height <= 0 || p_fmto->i_visible_width <= 0 || p_fmto->i_visible_height <= 0 ) { msg_Err( p_filter, "invalid scaling: %ix%i -> %ix%i", p_fmti->i_visible_width, p_fmti->i_visible_height, p_fmto->i_visible_width, p_fmto->i_visible_height); return VLC_EGENERIC; } p_sys->desc_in = vlc_fourcc_GetChromaDescription( p_fmti->i_chroma ); p_sys->desc_out = vlc_fourcc_GetChromaDescription( p_fmto->i_chroma ); if( p_sys->desc_in == NULL || p_sys->desc_out == NULL ) return VLC_EGENERIC; /* swscale does not like too small width */ p_sys->i_extend_factor = 1; while( __MIN( p_fmti->i_visible_width, p_fmto->i_visible_width ) * p_sys->i_extend_factor < MINIMUM_WIDTH) p_sys->i_extend_factor++; const unsigned i_fmti_visible_width = p_fmti->i_visible_width * p_sys->i_extend_factor; const unsigned i_fmto_visible_width = p_fmto->i_visible_width * p_sys->i_extend_factor; for( int n = 0; n < (cfg.b_has_a ? 2 : 1); n++ ) { const int i_fmti = n == 0 ? cfg.i_fmti : PIX_FMT_GRAY8; const int i_fmto = n == 0 ? cfg.i_fmto : PIX_FMT_GRAY8; struct SwsContext *ctx; ctx = sws_getContext( i_fmti_visible_width, p_fmti->i_visible_height, i_fmti, i_fmto_visible_width, p_fmto->i_visible_height, i_fmto, cfg.i_sws_flags | p_sys->i_cpu_mask, p_sys->p_src_filter, p_sys->p_dst_filter, 0 ); if( n == 0 ) p_sys->ctx = ctx; else p_sys->ctxA = ctx; } if( p_sys->ctxA ) { p_sys->p_src_a = picture_New( VLC_CODEC_GREY, i_fmti_visible_width, p_fmti->i_visible_height, 0, 1 ); p_sys->p_dst_a = picture_New( VLC_CODEC_GREY, i_fmto_visible_width, p_fmto->i_visible_height, 0, 1 ); } if( p_sys->i_extend_factor != 1 ) { p_sys->p_src_e = picture_New( p_fmti->i_chroma, i_fmti_visible_width, p_fmti->i_visible_height, 0, 1 ); p_sys->p_dst_e = picture_New( p_fmto->i_chroma, i_fmto_visible_width, p_fmto->i_visible_height, 0, 1 ); if( p_sys->p_src_e ) memset( p_sys->p_src_e->p[0].p_pixels, 0, p_sys->p_src_e->p[0].i_pitch * p_sys->p_src_e->p[0].i_lines ); if( p_sys->p_dst_e ) memset( p_sys->p_dst_e->p[0].p_pixels, 0, p_sys->p_dst_e->p[0].i_pitch * p_sys->p_dst_e->p[0].i_lines ); } if( !p_sys->ctx || ( cfg.b_has_a && ( !p_sys->ctxA || !p_sys->p_src_a || !p_sys->p_dst_a ) ) || ( p_sys->i_extend_factor != 1 && ( !p_sys->p_src_e || !p_sys->p_dst_e ) ) ) { msg_Err( p_filter, "could not init SwScaler and/or allocate memory" ); Clean( p_filter ); return VLC_EGENERIC; } if (p_filter->b_allow_fmt_out_change) { /* * If the transformation is not homothetic we must modify the * aspect ratio of the output format in order to have the * output picture displayed correctly and not stretched * horizontally or vertically. * WARNING: this is a hack, ideally this should not be needed * and the vout should update its video format instead. */ unsigned i_sar_num = p_fmti->i_sar_num * p_fmti->i_visible_width; unsigned i_sar_den = p_fmti->i_sar_den * p_fmto->i_visible_width; vlc_ureduce(&i_sar_num, &i_sar_den, i_sar_num, i_sar_den, 65536); i_sar_num *= p_fmto->i_visible_height; i_sar_den *= p_fmti->i_visible_height; vlc_ureduce(&i_sar_num, &i_sar_den, i_sar_num, i_sar_den, 65536); p_fmto->i_sar_num = i_sar_num; p_fmto->i_sar_den = i_sar_den; } p_sys->b_add_a = cfg.b_add_a; p_sys->b_copy = cfg.b_copy; p_sys->fmt_in = *p_fmti; p_sys->fmt_out = *p_fmto; p_sys->b_swap_uvi = cfg.b_swap_uvi; p_sys->b_swap_uvo = cfg.b_swap_uvo; #if 0 msg_Dbg( p_filter, "%ix%i (%ix%i) chroma: %4.4s -> %ix%i (%ix%i) chroma: %4.4s extend by %d", p_fmti->i_visible_width, p_fmti->i_visible_height, p_fmti->i_width, p_fmti->i_height, (char *)&p_fmti->i_chroma, p_fmto->i_visible_width, p_fmto->i_visible_height, p_fmto->i_width, p_fmto->i_height, (char *)&p_fmto->i_chroma, p_sys->i_extend_factor ); #endif return VLC_SUCCESS; }
int __cdecl main (int argc, char **argv) { /* * Parameter to the threads that will be created */ DWORD dwThrdParam = 0; HANDLE hThread[64]; unsigned int i = 0; DWORD dwStart; /* Variables to capture the file name and the file pointer*/ char fileName[MAX_PATH_FNAME]; char processFileName[MAX_PATH_FNAME]; FILE *hFile,*hProcessFile; struct processStatistics processStats; struct statistics* buffer; int statisticsSize = 0; /* * PAL Initialize */ if(0 != (PAL_Initialize(argc, argv))) { return FAIL; } if(GetParameters(argc, argv)) { Fail("Error in obtaining the parameters\n"); } /*setup file for process result collection */ _snprintf(processFileName, MAX_PATH_FNAME, "%d_process_criticalsection_%d_.txt", USE_PROCESS_COUNT, RELATION_ID); hProcessFile = fopen(processFileName, "w+"); if(hProcessFile == NULL) { Fail("Error in opening file to write process results for process [%d]\n", USE_PROCESS_COUNT); } //Initialize Process Stats Variables processStats.operationTime = 0; processStats.processId = USE_PROCESS_COUNT; processStats.relationId = RELATION_ID; //Will change later //Start Process Time Capture dwStart = GetTickCount(); //setup file for thread result collection statisticsSize = sizeof(struct statistics); _snprintf(fileName, MAX_PATH_FNAME, "%d_thread_criticalsection_%d_.txt", USE_PROCESS_COUNT, RELATION_ID); hFile = fopen(fileName, "w+"); if(hFile == NULL) { Fail("Error in opening file for write for process [%d]\n", USE_PROCESS_COUNT); } // For each thread we will log operations failed (int), passed (int), total (int) // and number of ticks (DWORD) for the operations resultBuffer = new ResultBuffer( THREAD_COUNT, statisticsSize); /* * Call the Setup Routine */ setup(); //Create Thread Count Worker Threads while (i< THREAD_COUNT) { dwThrdParam = i; hThread[i] = CreateThread( NULL, 0, enterandleavecs, (LPVOID)dwThrdParam, 0, &dwThreadId); if ( NULL == hThread[i] ) { Fail ( "CreateThread() returned NULL. Failing test.\n" "GetLastError returned %d\n", GetLastError()); } i++; } /* * Set Event to signal all threads to start using the CS */ if (0==SetEvent(g_hEvent)) { Fail ( "SetEvent returned Zero. Failing test.\n" "GetLastError returned %d\n", GetLastError()); } /* * Wait for worker threads to complete * */ if ( WAIT_OBJECT_0 != WaitForMultipleObjects (THREAD_COUNT,hThread,TRUE, INFINITE)) { Fail ( "WaitForMultipleObject Failed. Failing test.\n" "GetLastError returned %d\n", GetLastError()); } //Get the end time of the process processStats.operationTime = GetTickCount() - dwStart; //Write Process Result Contents to File if(hProcessFile!= NULL) { fprintf(hProcessFile, "%d,%lu,%d\n", processStats.processId, processStats.operationTime, processStats.relationId ); } if (0!=fclose(hProcessFile)) { Fail("Unable to write process results to file" "GetLastError returned %d\n", GetLastError()); } /*Write Threads Results to a file*/ if(hFile!= NULL) { for( i = 0; i < THREAD_COUNT; i++ ) { buffer = (struct statistics *)resultBuffer->getResultBuffer(i); fprintf(hFile, "%d,%d,%d,%d,%lu,%d\n", buffer->processId, buffer->operationsFailed, buffer->operationsPassed, buffer->operationsTotal, buffer->operationTime, buffer->relationId ); //Trace("Iteration %d over\n", i); } } if (0!=fclose(hFile)) { Fail("Unable to write thread results to file" "GetLastError returned %d\n", GetLastError()); } /* Logging for the test case over, clean up the handles */ //Trace("Contents of the buffer are [%s]\n", resultBuffer->getResultBuffer()); //Call Cleanup for Test Case cleanup(); //Trace("Value of GLOBAL COUNTER %d \n", GLOBAL_COUNTER); return (PASS); }
DllExport bool GWFile::Deliver(char *stamp, void *data, long numOfBytes) { CreateDirectory(GetParameters()); char *trackName = CreateFullName(GetParameters(), "track.dat"); FILE *trackFile = _fsopen(trackName, "r+", _SH_DENYRW); int fileNumber = 1; if(trackFile) { fscanf(trackFile, "%d", &fileNumber); rewind(trackFile); } else { trackFile = _fsopen(trackName, "w", _SH_DENYRW); if(!trackFile) { delete trackName; return(false); } } char shortName[32]; sprintf(shortName, "record%d.dat", fileNumber); char *fileName = CreateFullName(GetParameters(), shortName); FILE *dataFile = _fsopen(fileName, "wb", _SH_DENYRW); if(!dataFile) { fprintf(trackFile, "%d\n", fileNumber); fclose(trackFile); delete trackName; delete fileName; return(false); } size_t stampSize = strlen(stamp) + 1; fwrite(&stampSize, sizeof(stampSize), 1, dataFile); fwrite(stamp, stampSize, 1, dataFile); fwrite(&numOfBytes, sizeof(numOfBytes), 1, dataFile); if(numOfBytes) fwrite(data, numOfBytes, 1, dataFile); fclose(dataFile); fileNumber++; fprintf(trackFile, "%d\n", fileNumber); fclose(trackFile); delete trackName; delete fileName; return(true); }
Material *Scene::CreateMaterial(const std::string &propName, const Properties &prop) { const std::string matType = Properties::ExtractField(propName, 2); if (matType == "") throw std::runtime_error("Syntax error in " + propName); const std::string matName = Properties::ExtractField(propName, 3); if (matName == "") throw std::runtime_error("Syntax error in " + propName); if (matType == "matte") { const std::vector<float> vf = GetParameters(prop, propName, 3, "1.0 1.0 1.0"); const Spectrum col(vf.at(0), vf.at(1), vf.at(2)); return new MatteMaterial(col); } else if (matType == "light") { const std::vector<float> vf = GetParameters(prop, propName, 3, "1.0 1.0 1.0"); const Spectrum gain(vf.at(0), vf.at(1), vf.at(2)); return new AreaLightMaterial(gain); } else if (matType == "mirror") { const std::vector<float> vf = GetParameters(prop, propName, 4, "1.0 1.0 1.0 1.0"); const Spectrum col(vf.at(0), vf.at(1), vf.at(2)); return new MirrorMaterial(col, vf.at(3) != 0.f); } else if (matType == "mattemirror") { const std::vector<float> vf = GetParameters(prop, propName, 7, "1.0 1.0 1.0 1.0 1.0 1.0 1.0"); const Spectrum Kd(vf.at(0), vf.at(1), vf.at(2)); const Spectrum Kr(vf.at(3), vf.at(4), vf.at(5)); return new MatteMirrorMaterial(Kd, Kr, vf.at(6) != 0.f); } else if (matType == "glass") { const std::vector<float> vf = GetParameters(prop, propName, 10, "1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.5 1.0 1.0"); const Spectrum Krfl(vf.at(0), vf.at(1), vf.at(2)); const Spectrum Ktrn(vf.at(3), vf.at(4), vf.at(5)); return new GlassMaterial(Krfl, Ktrn, vf.at(6), vf.at(7), vf.at(8) != 0.f, vf.at(9) != 0.f); } else if (matType == "metal") { const std::vector<float> vf = GetParameters(prop, propName, 5, "1.0 1.0 1.0 10.0 1.0"); const Spectrum col(vf.at(0), vf.at(1), vf.at(2)); return new MetalMaterial(col, vf.at(3), vf.at(4) != 0.f); } else if (matType == "mattemetal") { const std::vector<float> vf = GetParameters(prop, propName, 8, "1.0 1.0 1.0 1.0 1.0 1.0 10.0 1.0"); const Spectrum Kd(vf.at(0), vf.at(1), vf.at(2)); const Spectrum Kr(vf.at(3), vf.at(4), vf.at(5)); return new MatteMetalMaterial(Kd, Kr, vf.at(6), vf.at(7) != 0.f); } else if (matType == "archglass") { const std::vector<float> vf = GetParameters(prop, propName, 8, "1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0"); const Spectrum Krfl(vf.at(0), vf.at(1), vf.at(2)); const Spectrum Ktrn(vf.at(3), vf.at(4), vf.at(5)); return new ArchGlassMaterial(Krfl, Ktrn, vf.at(6) != 0.f, vf.at(7) != 0.f); } else if (matType == "alloy") { const std::vector<float> vf = GetParameters(prop, propName, 9, "1.0 1.0 1.0 1.0 1.0 1.0 10.0 0.8 1.0"); const Spectrum Kdiff(vf.at(0), vf.at(1), vf.at(2)); const Spectrum Krfl(vf.at(3), vf.at(4), vf.at(5)); return new AlloyMaterial(Kdiff, Krfl, vf.at(6), vf.at(7), vf.at(8) != 0.f); } else throw std::runtime_error("Unknown material type " + matType); return (Material*)0; }
Scene::Scene(const std::string &fileName,uint width, uint height ,const int aType ) { accelType = aType; extMeshCache = new ExtMeshCache(); texMapCache = new TextureMapCache(); SDL_LOG("Reading scene: " << fileName); scnProp = new Properties(fileName); //-------------------------------------------------------------------------- // Read camera position and target //-------------------------------------------------------------------------- std::vector<float> vf = GetParameters(*scnProp, "scene.camera.lookat", 6, "10.0 0.0 0.0 0.0 0.0 0.0"); Point o(vf.at(0), vf.at(1), vf.at(2)); Point t(vf.at(3), vf.at(4), vf.at(5)); SDL_LOG("Camera postion: " << o); SDL_LOG("Camera target: " << t); vf = GetParameters(*scnProp, "scene.camera.up", 3, "0.0 0.0 0.1"); const Vector up(vf.at(0), vf.at(1), vf.at(2)); camera = new PerspectiveCamera(o, t, up); camera->lensRadius = scnProp->GetFloat("scene.camera.lensradius", 0.f); camera->focalDistance = scnProp->GetFloat("scene.camera.focaldistance", 10.f); camera->fieldOfView = scnProp->GetFloat("scene.camera.fieldofview", 45.f); // Check if camera motion blur is enabled if (scnProp->GetInt("scene.camera.motionblur.enable", 0)) { camera->motionBlur = true; vf = GetParameters(*scnProp, "scene.camera.motionblur.lookat", 6, "10.0 1.0 0.0 0.0 1.0 0.0"); camera->mbOrig = Point(vf.at(0), vf.at(1), vf.at(2)); camera->mbTarget = Point(vf.at(3), vf.at(4), vf.at(5)); vf = GetParameters(*scnProp, "scene.camera.motionblur.up", 3, "0.0 0.0 0.1"); camera->mbUp = Vector(vf.at(0), vf.at(1), vf.at(2)); } //-------------------------------------------------------------------------- // Read all materials //-------------------------------------------------------------------------- std::vector<std::string> matKeys = scnProp->GetAllKeys("scene.materials."); if (matKeys.size() == 0) throw std::runtime_error("No material definition found"); for (std::vector<std::string>::const_iterator matKey = matKeys.begin(); matKey != matKeys.end(); ++matKey) { const std::string &key = *matKey; const std::string matType = Properties::ExtractField(key, 2); if (matType == "") throw std::runtime_error("Syntax error in " + key); const std::string matName = Properties::ExtractField(key, 3); if (matName == "") throw std::runtime_error("Syntax error in " + key); SDL_LOG("Material definition: " << matName << " [" << matType << "]"); Material *mat = CreateMaterial(key, *scnProp); materialIndices[matName] = materials.size(); materials.push_back(mat); } //-------------------------------------------------------------------------- // Read all objects .ply file //-------------------------------------------------------------------------- std::vector<std::string> objKeys = scnProp->GetAllKeys("scene.objects."); if (objKeys.size() == 0) throw std::runtime_error("Unable to find object definitions"); double lastPrint = WallClockTime(); unsigned int objCount = 0; for (std::vector<std::string>::const_iterator objKey = objKeys.begin(); objKey != objKeys.end(); ++objKey) { const std::string &key = *objKey; // Check if it is the root of the definition of an object otherwise skip const size_t dot1 = key.find(".", std::string("scene.objects.").length()); if (dot1 == std::string::npos) continue; const size_t dot2 = key.find(".", dot1 + 1); if (dot2 != std::string::npos) continue; const std::string objName = Properties::ExtractField(key, 3); if (objName == "") throw std::runtime_error("Syntax error in " + key); // Build the object const std::vector<std::string> args = scnProp->GetStringVector(key, ""); const std::string plyFileName = args.at(0); const double now = WallClockTime(); if (now - lastPrint > 2.0) { SDL_LOG("PLY object count: " << objCount); lastPrint = now; } ++objCount; //SDL_LOG("PLY object [" << objName << "] file name: " << plyFileName); // Check if I have to calculate normal or not const bool usePlyNormals = (scnProp->GetInt(key + ".useplynormals", 0) != 0); // Check if I have to use an instance mesh or not ExtMesh *meshObject; if (scnProp->IsDefined(key + ".transformation")) { const std::vector<float> vf = GetParameters(*scnProp, key + ".transformation", 16, "1.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 1.0"); const Matrix4x4 mat( vf.at(0), vf.at(4), vf.at(8), vf.at(12), vf.at(1), vf.at(5), vf.at(9), vf.at(13), vf.at(2), vf.at(6), vf.at(10), vf.at(14), vf.at(3), vf.at(7), vf.at(11), vf.at(15)); const Transform trans(mat); meshObject = extMeshCache->GetExtMesh(plyFileName, usePlyNormals, trans); } else meshObject = extMeshCache->GetExtMesh(plyFileName, usePlyNormals); objectIndices[objName] = objects.size(); objects.push_back(meshObject); // Get the material const std::string matName = Properties::ExtractField(key, 2); if (matName == "") throw std::runtime_error("Syntax error in material name: " + matName); if (materialIndices.count(matName) < 1) throw std::runtime_error("Unknown material: " + matName); Material *mat = materials[materialIndices[matName]]; // Check if it is a light sources if (mat->IsLightSource()) { SDL_LOG("The " << objName << " object is a light sources with " << meshObject->GetTotalTriangleCount() << " triangles"); AreaLightMaterial *light = (AreaLightMaterial *)mat; objectMaterials.push_back(mat); for (unsigned int i = 0; i < meshObject->GetTotalTriangleCount(); ++i) { TriangleLight *tl = new TriangleLight(light, static_cast<unsigned int>(objects.size()) - 1, i, objects); lights.push_back(tl); } } else { SurfaceMaterial *surfMat = (SurfaceMaterial *)mat; objectMaterials.push_back(surfMat); } // [old deprecated syntax] Check if there is a texture map associated to the object if (args.size() > 1) { // Check if the object has UV coords if (!meshObject->HasUVs()) throw std::runtime_error("PLY object " + plyFileName + " is missing UV coordinates for texture mapping"); TexMapInstance *tm = texMapCache->GetTexMapInstance(args.at(1), 2.2f); objectTexMaps.push_back(tm); objectBumpMaps.push_back(NULL); objectNormalMaps.push_back(NULL); } else { // Check for if there is a texture map associated to the object with the new syntax const std::string texMap = scnProp->GetString(key + ".texmap", ""); if (texMap != "") { // Check if the object has UV coords if (!meshObject->HasUVs()) throw std::runtime_error("PLY object " + plyFileName + " is missing UV coordinates for texture mapping"); const float gamma = scnProp->GetFloat(key + ".texmap.gamma", 2.2f); TexMapInstance *tm = texMapCache->GetTexMapInstance(texMap, gamma); objectTexMaps.push_back(tm); } else objectTexMaps.push_back(NULL); /** * Check if there is an alpha map associated to the object * If there is, the map is added to a previously added texturemap. * If no texture map (diffuse map) is detected, a black texture * is created and the alpha map is added to it. --PC */ const std::string alphaMap = scnProp->GetString(key + ".alphamap", ""); if (alphaMap != "") { // Got an alpha map, retrieve the textureMap and add the alpha channel to it. const std::string texMap = scnProp->GetString(key + ".texmap", ""); const float gamma = scnProp->GetFloat(key + ".texmap.gamma", 2.2f); TextureMap *tm; if (!(tm = texMapCache->FindTextureMap(texMap, gamma))) { SDL_LOG("Alpha map " << alphaMap << " is for a materials without texture. A black texture has been created for support!"); // We have an alpha map without a diffuse texture. In this case we need to create // a texture map filled with black tm = new TextureMap(alphaMap, gamma, 1.0, 1.0, 1.0); tm->AddAlpha(alphaMap); TexMapInstance *tmi = texMapCache->AddTextureMap(alphaMap, tm); // Remove the NULL inserted above, when no texmap was found. Without doing this the whole thing will not work objectTexMaps.pop_back(); // Add the new texture to the chain objectTexMaps.push_back(tmi); } else { // Add an alpha map to the pre-existing diffuse texture tm->AddAlpha(alphaMap); } } // Check for if there is a bump map associated to the object const std::string bumpMap = scnProp->GetString(key + ".bumpmap", ""); if (bumpMap != "") { // Check if the object has UV coords if (!meshObject->HasUVs()) throw std::runtime_error("PLY object " + plyFileName + " is missing UV coordinates for bump mapping"); const float scale = scnProp->GetFloat(key + ".bumpmap.scale", 1.f); BumpMapInstance *bm = texMapCache->GetBumpMapInstance(bumpMap, scale); objectBumpMaps.push_back(bm); } else objectBumpMaps.push_back(NULL); // Check for if there is a normal map associated to the object const std::string normalMap = scnProp->GetString(key + ".normalmap", ""); if (normalMap != "") { // Check if the object has UV coords if (!meshObject->HasUVs()) throw std::runtime_error("PLY object " + plyFileName + " is missing UV coordinates for normal mapping"); NormalMapInstance *nm = texMapCache->GetNormalMapInstance(normalMap); objectNormalMaps.push_back(nm); } else objectNormalMaps.push_back(NULL); } } SDL_LOG("PLY object count: " << objCount); //-------------------------------------------------------------------------- // Check if there is an infinitelight source defined //-------------------------------------------------------------------------- const std::vector<std::string> ilParams = scnProp->GetStringVector("scene.infinitelight.file", ""); if (ilParams.size() > 0) { const float gamma = scnProp->GetFloat("scene.infinitelight.gamma", 2.2f); TexMapInstance *tex = texMapCache->GetTexMapInstance(ilParams.at(0), gamma); // Check if I have to use InfiniteLightBF method if (scnProp->GetInt("scene.infinitelight.usebruteforce", 0)) { SDL_LOG("Using brute force infinite light sampling"); infiniteLight = new InfiniteLightBF(tex); useInfiniteLightBruteForce = true; } else { if (ilParams.size() == 2) infiniteLight = new InfiniteLightPortal(tex, ilParams.at(1)); else infiniteLight = new InfiniteLightIS(tex); // Add the infinite light to the list of light sources lights.push_back(infiniteLight); useInfiniteLightBruteForce = false; } std::vector<float> vf = GetParameters(*scnProp, "scene.infinitelight.gain", 3, "1.0 1.0 1.0"); infiniteLight->SetGain(Spectrum(vf.at(0), vf.at(1), vf.at(2))); vf = GetParameters(*scnProp, "scene.infinitelight.shift", 2, "0.0 0.0"); infiniteLight->SetShift(vf.at(0), vf.at(1)); infiniteLight->Preprocess(); } else { infiniteLight = NULL; useInfiniteLightBruteForce = false; } //-------------------------------------------------------------------------- // Check if there is a SkyLight defined //-------------------------------------------------------------------------- const std::vector<std::string> silParams = scnProp->GetStringVector("scene.skylight.dir", ""); if (silParams.size() > 0) { if (infiniteLight) throw std::runtime_error("Can not define a skylight when there is already an infinitelight defined"); std::vector<float> sdir = GetParameters(*scnProp, "scene.skylight.dir", 3, "0.0 0.0 1.0"); const float turb = scnProp->GetFloat("scene.skylight.turbidity", 2.2f); std::vector<float> gain = GetParameters(*scnProp, "scene.skylight.gain", 3, "1.0 1.0 1.0"); SkyLight *sl = new SkyLight(turb, Vector(sdir.at(0), sdir.at(1), sdir.at(2))); infiniteLight = sl; sl->SetGain(Spectrum(gain.at(0), gain.at(1), gain.at(2))); sl->Init(); useInfiniteLightBruteForce = true; } //-------------------------------------------------------------------------- // Check if there is a SunLight defined //-------------------------------------------------------------------------- const std::vector<std::string> sulParams = scnProp->GetStringVector("scene.sunlight.dir", ""); if (sulParams.size() > 0) { std::vector<float> sdir = GetParameters(*scnProp, "scene.sunlight.dir", 3, "0.0 0.0 1.0"); const float turb = scnProp->GetFloat("scene.sunlight.turbidity", 2.2f); const float relSize = scnProp->GetFloat("scene.sunlight.relsize", 1.0f); std::vector<float> gain = GetParameters(*scnProp, "scene.sunlight.gain", 3, "1.0 1.0 1.0"); SunLight *sunLight = new SunLight(turb, relSize, Vector(sdir.at(0), sdir.at(1), sdir.at(2))); sunLight->SetGain(Spectrum(gain.at(0), gain.at(1), gain.at(2))); sunLight->Init(); lights.push_back(sunLight); } //-------------------------------------------------------------------------- camera->Update(width, height); }
RAVELOG_WARN("there are no used bodies in this configuration\n"); } FOREACH(itbody, vusedbodies) { KinBody::KinBodyStateSaverPtr statesaver; if( (*itbody)->IsRobot() ) { statesaver.reset(new RobotBase::RobotStateSaver(RaveInterfaceCast<RobotBase>(*itbody), KinBody::Save_LinkTransformation|KinBody::Save_LinkEnable|KinBody::Save_ActiveDOF|KinBody::Save_ActiveManipulator|KinBody::Save_LinkVelocities)); } else { statesaver.reset(new KinBody::KinBodyStateSaver(*itbody, KinBody::Save_LinkTransformation|KinBody::Save_LinkEnable|KinBody::Save_ActiveDOF|KinBody::Save_ActiveManipulator|KinBody::Save_LinkVelocities)); } vstatesavers.push_back(statesaver); } uint32_t basetime = utils::GetMilliTime(); TrajectoryTimingParametersConstPtr parameters = boost::dynamic_pointer_cast<TrajectoryTimingParameters const>(GetParameters()); vector<ParabolicRamp::Vector> path; path.reserve(ptraj->GetNumWaypoints()); vector<dReal> vtrajpoints; ptraj->GetWaypoints(0,ptraj->GetNumWaypoints(),vtrajpoints,_parameters->_configurationspecification); ParabolicRamp::Vector q(_parameters->GetDOF()); for(size_t i = 0; i < ptraj->GetNumWaypoints(); ++i) { std::copy(vtrajpoints.begin()+i*_parameters->GetDOF(),vtrajpoints.begin()+(i+1)*_parameters->GetDOF(),q.begin()); if( path.size() >= 2 ) { // check if collinear by taking angle const ParabolicRamp::Vector& x0 = path[path.size()-2]; const ParabolicRamp::Vector& x1 = path[path.size()-1]; dReal dotproduct=0,x0length2=0,x1length2=0; for(size_t i = 0; i < q.size(); ++i) { dReal dx0=x0[i]-q[i];
int __cdecl main(INT argc, CHAR **argv) { unsigned int i = 0; HANDLE hThread[MAXIMUM_WAIT_OBJECTS]; DWORD threadId[MAXIMUM_WAIT_OBJECTS]; WCHAR *wcObjName = NULL; char ObjName[MAX_PATH] = "SHARED_EVENT"; DWORD dwParam = 0; int returnCode = 0; /* Variables to capture the file name and the file pointer at thread level*/ char fileName[MAX_PATH]; FILE *pFile = NULL; struct statistics* buffer = NULL; int statisticsSize = 0; /* Variables to capture the file name and the file pointer at process level*/ char processFileName[MAX_PATH]; FILE *pProcessFile = NULL; struct ProcessStats processStats; DWORD dwStartTime; testStatus = PASS; if(0 != (PAL_Initialize(argc, argv))) { return ( FAIL ); } ZeroMemory( objectSuffix, MAX_PATH ); if(GetParameters(argc, argv)) { Fail("Error in obtaining the parameters\n"); } // Trace("Process created, value of process count is [%d]\n", USE_PROCESS_COUNT); if(argc == 5) { strncat(ObjName, objectSuffix, MAX_PATH - (sizeof(ObjName) + 1) ); } /* Register the start time */ dwStartTime = GetTickCount(); processStats.relationId = RELATION_ID; processStats.processId = USE_PROCESS_COUNT; _snprintf(processFileName, MAX_PATH, "%d_process_event_%d_.txt", USE_PROCESS_COUNT, RELATION_ID); pProcessFile = fopen(processFileName, "w+"); if(pProcessFile == NULL) { Fail("Error:%d: in opening Process File for write for process [%d]\n", GetLastError(), USE_PROCESS_COUNT); } statisticsSize = sizeof(struct statistics); _snprintf(fileName, MAX_PATH, "%d_thread_event_%d_.txt", USE_PROCESS_COUNT, RELATION_ID); pFile = fopen(fileName, "w+"); if(pFile == NULL) { Fail("Error:%d: in opening thread file for write for process [%d]\n", GetLastError(), USE_PROCESS_COUNT); } // For each thread we will log operations failed (int), passed (int), total (int) // and number of ticks (DWORD) for the operations resultBuffer = new ResultBuffer( THREAD_COUNT, statisticsSize); wcObjName = convert(ObjName); StartTestsEvHandle = CreateEvent( NULL, /* lpEventAttributes*/ TRUE, /* bManualReset */ FALSE, /* bInitialState */ NULL); /* name of Event */ if( StartTestsEvHandle == NULL ) { Fail("Error:%d: Unexpected failure " "to create %s Event for process count %d\n", GetLastError(), sTmpEventName, USE_PROCESS_COUNT ); } /* Create StartTest Event */ hEventHandle = OpenEventW( EVENT_ALL_ACCESS, /* lpEventAttributes, inheritable to child processes*/ FALSE, /* bAutomaticReset */ wcObjName ); if( hEventHandle == NULL) { Fail("Unable to create Event handle for process id [%d], returned error [%d]\n", i, GetLastError()); } /* We already assume that the Event was created previously*/ for( i = 0; i < THREAD_COUNT; i++ ) { dwParam = (int) i; //Create thread hThread[i] = CreateThread( NULL, /* no security attributes */ 0, /* use default stack size */ (LPTHREAD_START_ROUTINE)Run_Thread,/* thread function */ (LPVOID)dwParam, /* argument to thread function */ 0, /* use default creation flags */ &threadId[i] /* returns the thread identifier*/ ); if(hThread[i] == NULL) { Fail("Create Thread failed for %d process, and GetLastError value is %d\n", USE_PROCESS_COUNT, GetLastError()); } } if (!SetEvent(StartTestsEvHandle)) { Fail("Set Event for Start Tests failed for %d process, and GetLastError value is %d\n", USE_PROCESS_COUNT, GetLastError()); } /* Test running */ returnCode = WaitForMultipleObjects( THREAD_COUNT, hThread, TRUE, INFINITE); if( WAIT_OBJECT_0 != returnCode ) { Trace("Wait for Object(s) for %d process returned %d, and GetLastError value is %d\n", USE_PROCESS_COUNT, returnCode, GetLastError()); testStatus = FAIL; } processStats.operationTime = GetTimeDiff(dwStartTime); /* Write to a file*/ if(pFile!= NULL) { for( i = 0; i < THREAD_COUNT; i++ ) { buffer = (struct statistics *)resultBuffer->getResultBuffer(i); returnCode = fprintf(pFile, "%d,%d,%d,%d,%lu,%d\n", buffer->processId, buffer->operationsFailed, buffer->operationsPassed, buffer->operationsTotal, buffer->operationTime, buffer->relationId ); // Trace("Iteration %d over\n", i); } } if(fclose(pFile)) { Trace("Error: fclose failed for pFile at Process %d\n", USE_PROCESS_COUNT); testStatus = FAIL; } fprintf(pProcessFile, "%d,%d,%d\n", USE_PROCESS_COUNT, processStats.operationTime, processStats.relationId ); if(fclose(pProcessFile)) { Trace("Error: fclose failed for pProcessFile at Process %d\n", USE_PROCESS_COUNT); testStatus = FAIL; } /* Logging for the test case over, clean up the handles */ // Trace("Test Thread %d done\n", USE_PROCESS_COUNT); for( i = 0; i < THREAD_COUNT; i++ ) { if(!CloseHandle(hThread[i]) ) { Trace("Error:%d: CloseHandle failed for Process [%d] hThread[%d]\n", GetLastError(), USE_PROCESS_COUNT, i); testStatus = FAIL; } } if(!CloseHandle(StartTestsEvHandle)) { Trace("Error:%d: CloseHandle failed for Process [%d] StartTestsEvHandle\n", GetLastError(), USE_PROCESS_COUNT); testStatus = FAIL; } if(!CloseHandle(hEventHandle)) { Trace("Error:%d: CloseHandle failed for Process [%d] hEventHandle\n", GetLastError(), USE_PROCESS_COUNT); testStatus = FAIL; } free(wcObjName); PAL_Terminate(); return testStatus; }
int __cdecl main(INT argc, CHAR **argv) { unsigned int i = 0; HANDLE hProcess[MAXIMUM_WAIT_OBJECTS]; STARTUPINFO si[MAXIMUM_WAIT_OBJECTS]; PROCESS_INFORMATION pi[MAXIMUM_WAIT_OBJECTS]; char lpCommandLine[MAX_PATH] = ""; int returnCode = 0; DWORD processReturnCode = 0; int testReturnCode = PASS; char fileName[MAX_PATH]; FILE *pFile = NULL; DWORD dwStartTime; struct TestStats testStats; if(0 != (PAL_Initialize(argc, argv))) { return ( FAIL ); } if(GetParameters(argc, argv)) { Fail("Error in obtaining the parameters\n"); } /* Register the start time */ dwStartTime = GetTickCount(); testStats.relationId = 0; testStats.relationId = RELATION_ID; testStats.processCount = PROCESS_COUNT; testStats.threadCount = THREAD_COUNT; testStats.repeatCount = REPEAT_COUNT; testStats.buildNumber = getBuildNumber(); _snprintf(fileName, MAX_PATH, "main_wfmo_%d_.txt",testStats.relationId); pFile = fopen(fileName, "w+"); if(pFile == NULL) { Fail("Error in opening main file for write\n"); } for( i = 0; i < PROCESS_COUNT; i++ ) { ZeroMemory( lpCommandLine, MAX_PATH ); if ( _snprintf( lpCommandLine, MAX_PATH-1, "mutex %d %d %d %d %d", i, THREAD_COUNT, REPEAT_COUNT, SLEEP_LENGTH, RELATION_ID) < 0 ) { Trace ("Error: Insufficient commandline string length for for iteration [%d]\n", i); } /* Zero the data structure space */ ZeroMemory ( &pi[i], sizeof(pi[i]) ); ZeroMemory ( &si[i], sizeof(si[i]) ); /* Set the process flags and standard io handles */ si[i].cb = sizeof(si[i]); //Create Process if(!CreateProcess( NULL, /* lpApplicationName*/ lpCommandLine, /* lpCommandLine */ NULL, /* lpProcessAttributes */ NULL, /* lpThreadAttributes */ TRUE, /* bInheritHandles */ 0, /* dwCreationFlags, */ NULL, /* lpEnvironment */ NULL, /* pCurrentDirectory */ &si[i], /* lpStartupInfo */ &pi[i] /* lpProcessInformation */ )) { Fail("Process Not created for [%d], the error code is [%d]\n", i, GetLastError()); } else { hProcess[i] = pi[i].hProcess; // Trace("Process created for [%d]\n", i); } } returnCode = WaitForMultipleObjects( PROCESS_COUNT, hProcess, TRUE, INFINITE); if( WAIT_OBJECT_0 != returnCode ) { Trace("Wait for Object(s) @ Main thread for %d processes returned %d, and GetLastError value is %d\n", PROCESS_COUNT, returnCode, GetLastError()); } for( i = 0; i < PROCESS_COUNT; i++ ) { /* check the exit code from the process */ if( ! GetExitCodeProcess( pi[i].hProcess, &processReturnCode ) ) { Trace( "GetExitCodeProcess call failed for iteration %d with error code %u\n", i, GetLastError() ); testReturnCode = FAIL; } if(processReturnCode == FAIL) { Trace( "Process [%d] failed and returned FAIL\n", i); testReturnCode = FAIL; } if(!CloseHandle(pi[i].hThread)) { Trace("Error:%d: CloseHandle failed for Process [%d] hThread\n", GetLastError(), i); } if(!CloseHandle(pi[i].hProcess) ) { Trace("Error:%d: CloseHandle failed for Process [%d] hProcess\n", GetLastError(), i); } } testStats.operationTime = GetTimeDiff(dwStartTime); fprintf(pFile, "%d,%d,%d,%d,%d,%s\n", testStats.operationTime, testStats.relationId, testStats.processCount, testStats.threadCount, testStats.repeatCount, testStats.buildNumber); if(fclose(pFile)) { Trace("Error: fclose failed for pFile\n"); testReturnCode = FAIL; } if( testReturnCode == PASS) { Trace("Test Passed\n"); } else { Trace("Test Failed\n"); } PAL_Terminate(); return testReturnCode; }
//Main Entry for the Thread Suspension Test Case int __cdecl main (int argc, char **argv) { /* * Parameter to the threads that will be created */ DWORD dwThrdParam = 0; DWORD dwStart; /* Variables to capture the file name and the file pointer*/ char fileName[MAX_PATH]; char processFileName[MAX_PATH]; FILE *hFile, *hProcessFile; struct statistics* buffer; struct processStatistics *processBuffer; struct processStatistics processStats; struct statistics* tmpBuf = NULL; int statisticsSize = 0; DWORD dwThreadId=0; HANDLE hMainThread; unsigned int i = 0; int j = 0; /* * PAL Initialize */ if(0 != (PAL_Initialize(argc, argv))) { return FAIL; } //Get Parameters if(GetParameters(argc, argv)) { Fail("Error in obtaining the parameters\n"); } //Setup for Process Result Collection statisticsSize = sizeof(struct statistics); _snprintf(processFileName, MAX_PATH, "%d_process_threadsuspension_%d_.txt", USE_PROCESS_COUNT, RELATION_ID); hProcessFile = fopen(processFileName, "w+"); if(hProcessFile == NULL) { Fail("Error in opening file to write process results for process [%d]\n", USE_PROCESS_COUNT); } //Initialize Process Stats Variables processStats.operationTime = 0; processStats.processId = USE_PROCESS_COUNT; processStats.relationId = RELATION_ID; //Start Process Time Capture dwStart = GetTickCount(); //Setup for Thread Result Collection statisticsSize = sizeof(struct statistics); _snprintf(fileName, MAX_PATH, "%d_thread_threadsuspension_%d_.txt", USE_PROCESS_COUNT,RELATION_ID); hFile = fopen(fileName, "w+"); if(hFile == NULL) { Fail("Error in opening file to write thread results for process [%d]\n", USE_PROCESS_COUNT); } // For each thread we will log relationid (int), processid (int), operations failed (int), passed (int), total (int) // and number of ticks (DWORD) for the operations resultBuffer = new ResultBuffer( 1, statisticsSize); /* * Call the Setup Routine */ setup(); Trace("WORKER_THREAD_MULTIPLIER_COUNT: %d \n", WORKER_THREAD_MULTIPLIER_COUNT); //Create WORKER_THREAD_MULTIPLIER_COUNT Instances of each type of worker thread for (i=0;i<WORKER_THREAD_MULTIPLIER_COUNT;i++) { /* * Create readfile thread */ hThread[0][i] = CreateThread( NULL, 0, readfile, NULL, 0, &dwThreadId); if ( NULL == hThread[0][i] ) { Fail ( "CreateThread() returned NULL. Failing test.\n" "GetLastError returned %d\n", GetLastError()); } /* * Create Enter and Leave Critical Section Thread */ hThread[1][i] = CreateThread( NULL, 0, enterandleave_cs, NULL, 0, &dwThreadId); if ( NULL == hThread[1][i] ) { Fail ( "CreateThread() returned NULL. Failing test.\n" "GetLastError returned %d\n", GetLastError()); } /* * Create Allocate and Free Memory Thread */ hThread[2][i] = CreateThread( NULL, 0, allocateandfree_memory, NULL, 0, &dwThreadId); if ( NULL == hThread[2][i]) { Fail ( "CreateThread() returned NULL. Failing test.\n" "GetLastError returned %d\n", GetLastError()); } /* * Create Work in tight Loop thread */ hThread[3][i] = CreateThread( NULL, 0, doworkintightloop_cs, NULL, 0, &dwThreadId); if ( NULL == hThread[3][i]) { Fail ( "CreateThread() returned NULL. Failing test.\n" "GetLastError returned %d\n", GetLastError()); } } /* * Create Main test case thread that Suspends and Resumes Threads */ hMainThread = CreateThread( NULL, 0, suspendandresumethreads, (LPVOID)dwThrdParam, 0, &dwThreadId); if ( NULL == hMainThread ) { Fail ( "CreateThread() returned NULL. Failing test.\n" "GetLastError returned %d\n", GetLastError()); } /* * Set Event to allow all threads to start */ if (0==SetEvent(g_hEvent)) { Fail ( "SetEvent returned Zero. Failing test.\n" "GetLastError returned %d\n", GetLastError()); } /* * Wait for main thread to complete * */ if (WAIT_OBJECT_0 != WaitForSingleObject (hMainThread, INFINITE)) { Fail ("Main: Wait for Single Object (mainThread) failed. Failing test.\n" "GetLastError returned %d\n", GetLastError()); } //Get the end time of the process processStats.operationTime = GetTickCount() - dwStart; //Write Process Result Contents to File if(hProcessFile!= NULL) { fprintf(hProcessFile, "%d,%lu,%d\n", processStats.processId, processStats.operationTime, processStats.relationId ); } if (0!=fclose(hProcessFile)) { Fail("Unable to write process results to file" "GetLastError returned %d\n", GetLastError()); } //Write to log file //Trace("# of Read File Operations %d\n", g_readfileoperation); //Trace("# of Enter and Leace CS Operations %d\n", g_enterleavecsoperation); //Trace("# of Do Work In Tight Loop Operations %d\n", g_doworintightloop); //Trace("# of Allocate and Free Operations %d\n", g_allocatefreeoperation); //Write Thread Result Contents to File if(hFile!= NULL) { for( i = 0; i < 1; i++ ) { buffer = (struct statistics *)resultBuffer->getResultBuffer(i); fprintf(hFile, "%d,%d,%d,%d,%lu,%d\n", buffer->processId, buffer->operationsFailed, buffer->operationsPassed, buffer->operationsTotal, buffer->operationTime, buffer->relationId ); } } if (0!=fclose(hFile)) { Fail("Unable to write thread results to file" "GetLastError returned %d\n", GetLastError()); } cleanup(); if (failFlag == TRUE) { return FAIL; } else { return PASS; } }
int main (int argc, char *argv[]) { int i, Sense; long lj; char s[513]; GetParameters (ControllerNumber); Roll.CurrentAdjustedReading = 0; Roll.LastRawReading = 0; Pitch.CurrentAdjustedReading = 0; Pitch.LastRawReading = 0; Yaw.CurrentAdjustedReading = 0; Yaw.LastRawReading = 0; fprintf (stdout, "yaACA3 Apollo ACA simulation, ver " VER(NVER) ", built " __DATE__ " " __TIME__ "\n"); fprintf (stdout, "Copyright 2009 by Ronald S. Burkey\n"); fprintf (stdout, "Refer to http://www.ibiblio.org/apollo/index.html for more information.\n"); Portnum = 19803; for (i = 1; i < argc; i++) { if (1 == sscanf (argv[i], "--ip=%s", s)) { strcpy (NonDefaultHostname, s); Hostname = NonDefaultHostname; } else if (1 == sscanf (argv[i], "--port=%ld", &lj)) { Portnum = lj; if (Portnum <= 0 || Portnum >= 0x10000) { fprintf (stdout, "The --port switch is out of range. Must be 1-64K.\n"); goto Help; } } else if (1 == sscanf (argv[i], "--delay=%ld", &lj)) { StartupDelay = lj; } else if (1 == sscanf (argv[i], "--controller=%ld", &lj)) { if (lj < 0 || lj > 1) { fprintf (stdout, "Only --controller=0 and --controller=1 are allowed.\n"); goto Help; } else ControllerNumber = lj; } else if (1 == sscanf (argv[i], "--pitch=-%ld", &lj)) { Pitch.PositiveSense = 0; Pitch.Axis = lj; CfgExisted = 0; } else if (1 == sscanf (argv[i], "--pitch=+%ld", &lj) || 1 == sscanf (argv[i], "--pitch=%ld", &lj)) { Pitch.PositiveSense = 1; Pitch.Axis = lj; CfgExisted = 0; } else if (1 == sscanf (argv[i], "--roll=-%ld", &lj)) { Roll.PositiveSense = 0; Roll.Axis = lj; CfgExisted = 0; } else if (1 == sscanf (argv[i], "--roll=+%ld", &lj) || 1 == sscanf (argv[i], "--roll=%ld", &lj)) { Roll.PositiveSense = 1; Roll.Axis = lj; CfgExisted = 0; } else if (1 == sscanf (argv[i], "--yaw=-%ld", &lj)) { Yaw.PositiveSense = 0; Yaw.Axis = lj; CfgExisted = 0; } else if (1 == sscanf (argv[i], "--yaw=+%ld", &lj) || 1 == sscanf (argv[i], "--yaw=%ld", &lj)) { Yaw.PositiveSense = 1; Yaw.Axis = lj; CfgExisted = 0; } else { Help: fprintf (stdout, "USAGE:\n"); fprintf (stdout, "\tyaACA3 [OPTIONS]\n"); fprintf (stdout, "The available options are:\n"); fprintf (stdout, "--ip=Hostname\n"); fprintf (stdout, "\tThe yaACA2 program and the yaAGC Apollo Guidance Computer simulation\n"); fprintf (stdout, "\texist in a \"client/server\" relationship, in which the yaACA2 program\n"); fprintf (stdout, "\tneeds to be aware of the IP address or symbolic name of the host \n"); fprintf (stdout, "\tcomputer running the yaAGC program. By default, this is \"localhost\",\n"); fprintf (stdout, "\tmeaning that both yaACA2 and yaAGC are running on the same computer.\n"); fprintf (stdout, "--port=Portnumber\n"); fprintf (stdout, "\tBy default, yaACA2 attempts to connect to the yaAGC program using port\n"); fprintf (stdout, "\tnumber %d. However, if more than one instance of yaACA2 is being\n", Portnum); fprintf (stdout, "\trun, or if yaAGC has been configured to listen on different ports, then\n"); fprintf (stdout, "\tdifferent port settings for yaACA2 are needed. Note that by default,\n"); fprintf (stdout, "\tyaAGC listens for new connections on ports %d-%d.\n", 19697, 19697 + 10 - 1); fprintf (stdout, "--delay=N\n"); fprintf (stdout, "\t\"Start-up delay\", in ms. Defaults to %d. What the start-up\n", StartupDelay); fprintf (stdout, "\tdelay does is to prevent yaACA2 from attempting to communicate with\n"); fprintf (stdout, "\tyaAGC for a brief time after power-up. This option is really only\n"); fprintf (stdout, "\tuseful in Win32, to work around a problem with race-conditions at\n"); fprintf (stdout, "\tstart-up.\n"); fprintf (stdout, "--roll=N\n"); fprintf (stdout, "--pitch=N\n"); fprintf (stdout, "--yaw=N\n"); fprintf (stdout, "\tThese options allow you to relate the axis numbers (0, 1, ...) by\n"); fprintf (stdout, "\twhich the joystick controller works to physical axes (pitch, roll,\n"); fprintf (stdout, "\tyaw) by which the spacecraft works. In almost all cases --roll=0\n"); fprintf (stdout, "\tand --pitch=1 (the defaultswill be correct, but the --yaw=N setting\n"); fprintf (stdout, "\tvaries from target platform to target platform, and joystick model\n"); fprintf (stdout, "\tto joystick model. Once you use these command-line switches once,\n"); fprintf (stdout, "\tthe settings are saved to a configuration file and you don't have\n"); fprintf (stdout, "\tto use them again. The axis-number N can optionally be preceded by\n"); fprintf (stdout, "\ta \'-\' to indicate that the sense of the axis is reversed from the\n"); fprintf (stdout, "\tdefault expectation. For example, if axis 5 was used for yaw, but\n"); fprintf (stdout, "\tyou found you were getting yaw left where you expected yaw-right, you\n"); fprintf (stdout, "\tshould use--yaw=-5 rather than --yaw=5.\n"); fprintf (stdout, "--controller=N\n"); fprintf (stdout, "\tIn case there are two joystick controllers attached, this allows\n"); fprintf (stdout, "\tselection of just one of them. The default is N=0, but N=1 is also\n"); fprintf (stdout, "\tallowed. If there are more than two attached, only the first two can\n"); fprintf (stdout, "\tbe accessed.\n"); return (1); } } if (!CfgExisted) WriteParameters (ControllerNumber); // Now we start polling the joystick from time to time. The way Allegro works is to // maintain an array containing info on each joystick. This array is updated only when // poll_joystick is called (which you have to do explicitly). To see what has changed, // we maintain a copy of the joy[] array. while (1) { // Sleep for a while so that this job won't monopolize CPU cycles. #ifdef WIN32 Sleep (UPDATE_INTERVAL); #else // WIN32 struct timespec req, rem; req.tv_sec = 0; req.tv_nsec = 1000000 * UPDATE_INTERVAL; nanosleep (&req, &rem); #endif // WIN32 ServiceJoystick_sdl (); // Get joystick physical values. if (Initialization >= 2) { UpdateJoystick (); // Translate physical to logical values. PrintJoy (); // Display them locally. } PulseACA (); // Manage server connection. } #ifndef SOLARIS return (0); #endif }
DllExport bool GWFile::Receive(char **stamp, void **data, long *numOfBytes) { char *trackName = CreateFullName(GetParameters(), "track.dat"); FILE *trackFile = _fsopen(trackName, "r+", _SH_DENYRW); int fileNumber = 1; if(trackFile) { fscanf(trackFile, "%d", &fileNumber); rewind(trackFile); } else { delete trackName; return(false); } fileNumber--; char shortName[32]; sprintf(shortName, "record%d.dat", fileNumber); char *fileName = CreateFullName(GetParameters(), shortName); FILE *dataFile = _fsopen(fileName, "rb", _SH_DENYRW); if(!dataFile) { fprintf(trackFile, "%d\n", fileNumber+1); fclose(trackFile); delete trackName; delete fileName; return(false); } size_t stampSize = 0; fread(&stampSize, sizeof(stampSize), 1, dataFile); *stamp = new char[stampSize]; fread(*stamp, stampSize, 1, dataFile); fread(numOfBytes, sizeof(*numOfBytes), 1, dataFile); if(*numOfBytes) { *data = malloc(*numOfBytes); fread(*data, *numOfBytes, 1, dataFile); } else { *data = NULL; } fclose(dataFile); remove(fileName); fprintf(trackFile, "%d\n", fileNumber); fclose(trackFile); delete trackName; delete fileName; return(true); }
int main(int argc, char **argv) { struct tms tmsstart, tmsend; clock_t startTime, endTime; static long clktck = 0; time_t iterationStartTime; time_t iterationEndTime; SubList *subList; Substructure *normSub = NULL; Parameters *parameters; FILE *outputFile; ULONG iteration; BOOLEAN done; clktck = sysconf(_SC_CLK_TCK); startTime = times(&tmsstart); printf("GBAD %s\n\n", GBAD_VERSION); parameters = GetParameters(argc, argv); // compress positive graphs with predefined subs, if given if (parameters->numPreSubs > 0) CompressWithPredefinedSubs(parameters); PrintParameters(parameters); if (parameters->iterations > 1) printf("----- Iteration 1 -----\n\n"); iteration = 1; parameters->currentIteration = iteration; done = FALSE; while ((iteration <= parameters->iterations) && (!done)) { iterationStartTime = time(NULL); if (iteration > 1) printf("----- Iteration %lu -----\n\n", iteration); printf("%lu positive graphs: %lu vertices, %lu edges", parameters->numPosEgs, parameters->posGraph->numVertices, parameters->posGraph->numEdges); if (parameters->evalMethod == EVAL_MDL) printf(", %.0f bits\n", parameters->posGraphDL); else printf("\n"); printf("%lu unique labels\n", parameters->labelList->numLabels); printf("\n"); if ((parameters->prob) && (iteration > 1)) { // // If GBAD-P option chosen, after the first iteration, we no longer // care about minsize of maxsize after the first iteration (if the // user specified these parameters), as we are just dealing with // single extensions from the normative - so set it to where we // just look at substructures that are composed of the normative // pattern (SUB_) and the single vertex extension. // parameters->minVertices = 1; parameters->maxVertices = 2; } // // If the user has specified a normative pattern, on the first iteration // need to save the top-N substructures, where N is what the user // specified with the -norm parameter. // ULONG saveNumBestSubs = parameters->numBestSubs; if ((iteration == 1) && (!parameters->noAnomalyDetection) && (parameters->norm > parameters->numBestSubs)) parameters->numBestSubs = parameters->norm; // // -prune is useful to get to the initial normative pattern, but // possibly detremental to discovering anomalies... so, turn off // pruning (in case it was turned on), so that it is not used in // future iterations. // if ((parameters->prob) && (iteration > 1)) { parameters->prune = FALSE; } subList = DiscoverSubs(parameters, iteration); // // Now that we have the best substructure(s), return the user // specified number of best substructures to its original value. // if (iteration == 1) parameters->numBestSubs = saveNumBestSubs; if (subList->head == NULL) { done = TRUE; printf("No substructures found.\n\n"); } else { // // GBAD-MDL // if (parameters->mdl) GBAD_MDL(subList,parameters); // // GBAD-MPS // if (parameters->mps) { GBAD_MPS(subList,parameters); } // // GBAD-P // if (parameters->prob) { normSub = GBAD_P(subList,iteration,parameters); } // write output to stdout if (parameters->outputLevel > 1) { printf("\nBest %lu substructures:\n\n", CountSubs (subList)); PrintSubList(subList, parameters); } else { printf("\nBest substructure: "); if ((CountSubs(subList) > 0) && (subList->head->sub != NULL)) PrintSub(subList->head->sub, parameters); else printf("None."); printf("\n\n"); } // write machine-readable output to file, if given if (parameters->outputToFile) { outputFile = fopen(parameters->outFileName, "a"); if (outputFile == NULL) { printf("WARNING: unable to write to output file %s,", parameters->outFileName); printf("disabling\n"); parameters->outputToFile = FALSE; } WriteGraphToFile(outputFile, subList->head->sub->definition, parameters->labelList, 0, 0, subList->head->sub->definition->numVertices, TRUE); fclose(outputFile); } if (iteration < parameters->iterations) { // Another iteration? if (parameters->evalMethod == EVAL_SETCOVER) { printf("Removing positive examples covered by"); printf(" best substructure.\n\n"); RemovePosEgsCovered(subList->head->sub, parameters); } else { // // For the GBAD-P algorithm, multiple iterations will need // to be performed, and if it is the first iteration // AND the user has specified a different normative // pattern (other than the best one), we need to // use the substructure that was set above. // if ((iteration == 1) && (parameters->prob)) { printf("Compressing graph by best substructure (%lu):\n", parameters->norm); PrintSub(normSub,parameters); printf("\n"); CompressFinalGraphs(normSub, parameters, iteration, FALSE); } else CompressFinalGraphs(subList->head->sub, parameters, iteration, FALSE); } // check for stopping condition // if set-covering, then no more positive examples // if MDL or size, then positive graph contains no edges if (parameters->evalMethod == EVAL_SETCOVER) { if (parameters->numPosEgs == 0) { done = TRUE; printf("Ending iterations - "); printf("all positive examples covered.\n\n"); } } else { if (parameters->posGraph->numEdges == 0) { done = TRUE; printf("Ending iterations - graph fully compressed.\n\n"); } } } if ((iteration == parameters->iterations) && (parameters->compress)) { if (parameters->evalMethod == EVAL_SETCOVER) WriteUpdatedGraphToFile(subList->head->sub, parameters); else WriteCompressedGraphToFile(subList->head->sub, parameters, iteration); } } // // Need to store information regarding initial best substructure, for use // in future GBAD-P calculations // if ((parameters->prob) && (iteration == 1) && (subList->head != NULL)) { parameters->numPreviousInstances = subList->head->sub->numInstances; } if ((parameters->prob) && (iteration > 1) && (subList->head != NULL)) parameters->numPreviousInstances = subList->head->sub->numInstances; FreeSubList(subList); if (parameters->iterations > 1) { iterationEndTime = time(NULL); printf("Elapsed time for iteration %lu = %lu seconds.\n\n", iteration, (iterationEndTime - iterationStartTime)); } iteration++; parameters->currentIteration = iteration; } FreeParameters(parameters); endTime = times(&tmsend); printf("\nGBAD done (elapsed CPU time = %7.2f seconds).\n", (endTime - startTime) / (double) clktck); return 0; }