void LcfReader::Read<bool>(bool& ref) { ref = ReadInt() > 0; }
int BBP_read_int(struct plugin_info *PI, const char *rcs, int def) { char buffer[256]; return ReadInt(PI->rcpath, make_key(buffer, PI, rcs), def); }
/*============================================================================= * READ_GADGET *=============================================================================*/ void read_gadget(FILE *icfile, float **out_x,float **out_y,float **out_z) { int i; long no_part; int massflag; char DATA[MAXSTRING]; float fdummy[3]; double ddummy[3]; double x_fac; long pid; /*================= read in GADGET IO header =================*/ if(FORMAT == 2) { GADGET_SKIP; fread(DATA,sizeof(char),blklen,icfile); DATA[4] = '\0'; fprintf(stderr,"reading... %s\n",DATA); GADGET_SKIP; } GADGET_SKIP; ReadInt(icfile,&(gadget.header.np[0]),SWAPBYTES); ReadInt(icfile,&(gadget.header.np[1]),SWAPBYTES); ReadInt(icfile,&(gadget.header.np[2]),SWAPBYTES); ReadInt(icfile,&(gadget.header.np[3]),SWAPBYTES); /* number of particles in current file */ ReadInt(icfile,&(gadget.header.np[4]),SWAPBYTES); ReadInt(icfile,&(gadget.header.np[5]),SWAPBYTES); ReadDouble(icfile,&(gadget.header.massarr[0]),SWAPBYTES); ReadDouble(icfile,&(gadget.header.massarr[1]),SWAPBYTES); ReadDouble(icfile,&(gadget.header.massarr[2]),SWAPBYTES); ReadDouble(icfile,&(gadget.header.massarr[3]),SWAPBYTES); ReadDouble(icfile,&(gadget.header.massarr[4]),SWAPBYTES); ReadDouble(icfile,&(gadget.header.massarr[5]),SWAPBYTES); ReadDouble(icfile,&(gadget.header.expansion),SWAPBYTES); ReadDouble(icfile,&(gadget.header.redshift),SWAPBYTES); ReadInt(icfile,&(gadget.header.flagsfr),SWAPBYTES); ReadInt(icfile,&(gadget.header.flagfeedback),SWAPBYTES); ReadInt(icfile,&(gadget.header.nall[0]),SWAPBYTES); ReadInt(icfile,&(gadget.header.nall[1]),SWAPBYTES); ReadInt(icfile,&(gadget.header.nall[2]),SWAPBYTES); /* total number of particles in simulation */ ReadInt(icfile,&(gadget.header.nall[3]),SWAPBYTES); ReadInt(icfile,&(gadget.header.nall[4]),SWAPBYTES); ReadInt(icfile,&(gadget.header.nall[5]),SWAPBYTES); ReadInt(icfile,&(gadget.header.flagcooling),SWAPBYTES); ReadInt(icfile,&(gadget.header.NumFiles),SWAPBYTES); ReadDouble(icfile,&(gadget.header.BoxSize),SWAPBYTES); ReadDouble(icfile,&(gadget.header.Omega0),SWAPBYTES); ReadDouble(icfile,&(gadget.header.OmegaLambda),SWAPBYTES); ReadDouble(icfile,&(gadget.header.HubbleParam),SWAPBYTES); ReadChars(icfile,&(gadget.header.unused[0]),SIZEOFGADGETHEADER- 6*4- 6*8- 2*8- 2*4- 6*4- 2*4 - 4*8); GADGET_SKIP; /*================= read in GADGET IO header =================*/ /* keep track of no. of particles in each GADGET file */ gadget.np[0][gadget.i_gadget_file] = gadget.header.np[0]; gadget.np[1][gadget.i_gadget_file] = gadget.header.np[1]; gadget.np[2][gadget.i_gadget_file] = gadget.header.np[2]; gadget.np[3][gadget.i_gadget_file] = gadget.header.np[3]; gadget.np[4][gadget.i_gadget_file] = gadget.header.np[4]; gadget.np[5][gadget.i_gadget_file] = gadget.header.np[5]; /* conversion factors to Mpc/h, km/sec, Msun/h */ x_fac = GADGET_LUNIT; //m_fac = GADGET_MUNIT; /* count total no. of particles in current file (and set massflag) */ massflag = 0; no_part = 0; gadget.nall = 0; for(i=0;i<6;i++) { no_part += gadget.header.np[i]; gadget.nall += gadget.header.nall[i]; if(gadget.header.massarr[i] < MZERO && gadget.header.np[i] > 0) massflag=1; } #ifdef _VERB fprintf(stderr,"expansion factor: %lf\n", gadget.header.expansion); fprintf(stderr,"redshift: %lf\n", gadget.header.redshift); fprintf(stderr,"boxsize: %lf (%lf Mpc/h)\n", gadget.header.BoxSize,gadget.header.BoxSize*GADGET_LUNIT); fprintf(stderr,"omega0: %lf\n", gadget.header.Omega0); fprintf(stderr,"lambda0: %lf\n", gadget.header.OmegaLambda); fprintf(stderr,"HubbleParam: %lf\n\n", gadget.header.HubbleParam); fprintf(stderr,"gas: np[0]=%9d\t nall[0]=%9d\t massarr[0]=%g\n",gadget.header.np[0],gadget.header.nall[0],gadget.header.massarr[0]); fprintf(stderr,"halo: np[1]=%9d\t nall[1]=%9d\t massarr[1]=%g\n",gadget.header.np[1],gadget.header.nall[1],gadget.header.massarr[1]); fprintf(stderr,"disk: np[2]=%9d\t nall[2]=%9d\t massarr[2]=%g\n",gadget.header.np[2],gadget.header.nall[2],gadget.header.massarr[2]); fprintf(stderr,"bulge: np[3]=%9d\t nall[3]=%9d\t massarr[3]=%g\n",gadget.header.np[3],gadget.header.nall[3],gadget.header.massarr[3]); fprintf(stderr,"stars: np[4]=%9d\t nall[4]=%9d\t massarr[4]=%g\n",gadget.header.np[4],gadget.header.nall[4],gadget.header.massarr[4]); fprintf(stderr,"bndry: np[5]=%9d\t nall[5]=%9d\t massarr[5]=%g\n",gadget.header.np[5],gadget.header.nall[5],gadget.header.massarr[5]); fprintf(stderr,"\n-> reading %ld/%ld particles from GADGET file #%d/%d...\n\n", no_part,gadget.nall, gadget.i_gadget_file+1, gadget.no_gadget_files); #endif /* allocate particle array (only once when reading the first file, of course!) */ if(gadget.i_gadget_file == 0) { fprintf(stderr,"-> allocating %f GB of RAM for particles\n\n",(float)(gadget.nall*3*sizeof(float))/1024./1024./1024.); if(!((*out_x)=(float *) calloc(gadget.nall, sizeof(float)))) { fprintf(stderr,"\nfailed to allocate memory for GADGET data\n"); exit(1); } if(!((*out_y)=(float *) calloc(gadget.nall, sizeof(float)))) { fprintf(stderr,"\nfailed to allocate memory for GADGET data\n"); exit(1); } if(!((*out_z)=(float *) calloc(gadget.nall, sizeof(float)))) { fprintf(stderr,"\nfailed to allocate memory for GADGET data\n"); exit(1); } } /*================= read in GADGET particles =================*/ if(FORMAT == 2) { GADGET_SKIP; fread(DATA,sizeof(char),blklen,icfile); DATA[4] = '\0'; fprintf(stderr,"reading... %s",DATA); //GADGET_SKIP; GADGET_SKIP; } else { fprintf(stderr,"reading "); } GADGET_SKIP; fprintf(stderr,"(%8.2g MB) ... ",blklen/1024./1024.); for(i=0;i<no_part;i++) { /* read */ if(DGADGET) { ReadDouble(icfile,&(ddummy[0]),SWAPBYTES); ReadDouble(icfile,&(ddummy[1]),SWAPBYTES); ReadDouble(icfile,&(ddummy[2]),SWAPBYTES); } else { ReadFloat(icfile,&(fdummy[0]),SWAPBYTES); ReadFloat(icfile,&(fdummy[1]),SWAPBYTES); ReadFloat(icfile,&(fdummy[2]),SWAPBYTES); } /* get proper position in array */ pid = get_pid(i); /* storage and conversion to comoving physical units */ (*out_x)[pid] = fdummy[0] * x_fac; (*out_y)[pid] = fdummy[1] * x_fac; (*out_z)[pid] = fdummy[2] * x_fac; } fprintf(stderr,"Pos[X]=%12.6g Pos[Y]=%12.6g Pos[Z]=%12.6g ... ",(*out_x)[no_part-1],(*out_y)[no_part-1],(*out_z)[no_part-1]); GADGET_SKIP; fprintf(stderr,"(%8.2g MB) done.\n",blklen/1024./1024.); /*================= read in GADGET particles =================*/ /* massflag == 1 indicates that massarr[i] = 0 which shouldnt be the case for HALOGEN */ if(massflag==1) { fprintf(stderr,"ERROR: HALOGEN does not expect to encounter variable masses\n If needed, please, contact us to implement it\n"); exit(0); } }
/* SetConfParms: set conf parms relevant to HCompV */ void SetConfParms(void) { int i; Boolean b; double f; char buf[MAXSTRLEN]; nParm = GetConfig("HEREST", TRUE, cParm, MAXGLOBS); if (nParm>0) { if (GetConfInt(cParm,nParm,"TRACE",&i)) trace = i; if (GetConfFlt(cParm,nParm,"VARFLOORPERCENTILE",&f)) varFloorPercent = f; if (GetConfBool(cParm,nParm,"SAVEBINARY",&b)) saveBinary = b; if (GetConfBool(cParm,nParm,"BINARYACCFORMAT",&b)) ldBinary = b; /* 2-model reestimation alignment model set */ if (GetConfStr(cParm,nParm,"ALIGNMODELMMF",buf)) { strcpy(al_hmmMMF,buf); al_hmmUsed = TRUE; } if (GetConfStr(cParm,nParm,"ALIGNHMMLIST",buf)) { strcpy(al_hmmLst,buf); al_hmmUsed = TRUE; } /* allow multiple individual model files */ if (GetConfStr(cParm,nParm,"ALIGNMODELDIR",buf)) { strcpy(al_hmmDir,buf); al_hmmUsed = TRUE; } if (GetConfStr(cParm,nParm,"ALIGNMODELEXT",buf)) { strcpy(al_hmmExt,buf); al_hmmUsed = TRUE; } if (GetConfStr(cParm,nParm,"ALIGNXFORMEXT",buf)) { xfInfo.alXFormExt = CopyString(&hmmStack,buf); } if (GetConfStr(cParm,nParm,"ALIGNXFORMDIR",buf)) { xfInfo.alXFormDir = CopyString(&hmmStack,buf); } if (GetConfStr(cParm,nParm,"INXFORMMASK",buf)) { xfInfo.inSpkrPat = CopyString(&hmmStack,buf); } if (GetConfStr(cParm,nParm,"PAXFORMMASK",buf)) { xfInfo.paSpkrPat = CopyString(&hmmStack,buf); } if (GetConfStr(cParm,nParm,"LABFILEMASK",buf)) { labFileMask = (char*)malloc(strlen(buf)+1); strcpy(labFileMask, buf); } if (GetConfStr(cParm,nParm,"UPDATEMODE",buf)) { if (!strcmp (buf, "DUMP")) updateMode = UPMODE_DUMP; else if (!strcmp (buf, "UPDATE")) updateMode = UPMODE_UPDATE; else if (!strcmp (buf, "BOTH")) updateMode = UPMODE_BOTH; else HError(2319, "Unknown UPDATEMODE specified (must be DUMP, UPDATE or BOTH)"); } } } void ReportUsage(void) { printf("\nUSAGE: HERest [options] hmmList dataFiles...\n\n"); printf(" Option Default\n\n"); printf(" -a Use an input linear transform off\n"); printf(" -c f Mixture pruning threshold 10.0\n"); printf(" -d s dir to find hmm definitions current\n"); printf(" -h s set output speaker name pattern *.%%%%%%\n"); printf(" to s, optionally set input and parent patterns\n"); printf(" -l N set max files per speaker off\n"); printf(" -m N set min examples needed per model 3\n"); printf(" -o s extension for new hmm files as src\n"); printf(" -p N set parallel mode to N off\n"); printf(" -r Enable Single Pass Training... \n"); printf(" ...using two parameterisations off\n"); printf(" -s s print statistics to file s off\n"); printf(" -t f [i l] set pruning to f [inc limit] inf\n"); printf(" -u tmvwap update t)rans m)eans v)ars w)ghts tmvw\n"); printf(" a)daptation xform p)rior used \n"); printf(" s)semi-tied xform \n"); printf(" -v f set minimum variance to f 0.0\n"); printf(" -w f set mix weight floor to f*MINMIX 0.0\n"); printf(" -x s extension for hmm files none\n"); printf(" -z s Save all xforms to TMF file s TMF\n"); PrintStdOpts("BEFGHIJKLMSTX"); printf("\n\n"); } void SetuFlags(void) { char *s; s=GetStrArg(); uFlags=(UPDSet) 0; while (*s != '\0') switch (*s++) { case 't': uFlags = (UPDSet) (uFlags+UPTRANS); break; case 'm': uFlags = (UPDSet) (uFlags+UPMEANS); break; case 'v': uFlags = (UPDSet) (uFlags+UPVARS); break; case 'w': uFlags = (UPDSet) (uFlags+UPMIXES); break; case 's': uFlags = (UPDSet) (uFlags+UPSEMIT); break; case 'a': uFlags = (UPDSet) (uFlags+UPXFORM); break; case 'p': uFlags = (UPDSet) (uFlags+UPMAP); break; default: HError(2320,"SetuFlags: Unknown update flag %c",*s); break; } } /* ScriptWord: return next word from script */ char *ScriptWord(FILE *script, char *scriptBuf) { int ch,qch,i; i=0; ch=' '; while (isspace(ch)) ch = fgetc(script); if (ch==EOF) { scriptBuf=NULL; return NULL; } if (ch=='\'' || ch=='"'){ qch = ch; ch = fgetc(script); while (ch != qch && ch != EOF) { scriptBuf[i++] = ch; ch = fgetc(script); } if (ch==EOF) HError(5051,"ScriptWord: Closing quote missing in script file"); } else { do { scriptBuf[i++] = ch; ch = fgetc(script); }while (!isspace(ch) && ch != EOF); } scriptBuf[i] = '\0'; return scriptBuf; } void CheckUpdateSetUp() { AdaptXForm *xf;
/// Read MapFeatureHeader head from file void CSMFMapFile::ReadMapFeatureHeader(MapFeatureHeader& head, CFileHandler& file) { head.numFeatureType = ReadInt(file); head.numFeatures = ReadInt(file); }
bool RSObject::Load(FILE *file,RSMaterialManager *pMM) { int i,j,k; fread(&m_Header,sizeof(m_Header),1,file); if((m_Header.RSMID!=HEADER_RSMID)||(m_Header.Build!=HEADER_BUILD)) { rslog("Incorrect file format. rsm build #%d. #%d required.\n",m_Header.Build,HEADER_BUILD); return false; } m_pMM=pMM; fread(&m_bbox,sizeof(rboundingbox),1,file); m_bbox.Minz=m_bbox.Miny=m_bbox.Minx=100000000; m_bbox.Maxz=m_bbox.Maxy=m_bbox.Maxx=-100000000; ReadInt(nMaterial); materials=new RSMaterial*[nMaterial+1]; // rslog("[ load object :%d mtrl_num %d ]\n",g_obj_cnt,nMaterial); materials[0]=&RSDefaultMaterial; for (i=0;i<nMaterial;i++) { char buf[256]; {int l=fgetc(file);buf[l]=0;if(l) fread(buf,l,1,file);} RSMaterial *pmat=pMM->GetMaterial(buf); materials[i+1]=pmat ? pmat : &RSDefaultMaterial; // rslog("\t-mtrl :%d name %s \n",i,buf); } nMaterial++; // for default material; ReadInt(nMesh); CMesh *mesh=meshes=new CMesh[nMesh]; // rslog("\n\t-mesh num :%d \n\n",nMesh); for(i=0;i<nMesh;i++) { ReadString(mesh->name);strlwr(mesh->name); ReadMatrix(mesh->mat); fread(&mesh->m_bbox,sizeof(rboundingbox),1,file); mesh->m_bbox.Minz=mesh->m_bbox.Miny=mesh->m_bbox.Minx=100000000; mesh->m_bbox.Maxz=mesh->m_bbox.Maxy=mesh->m_bbox.Maxx=-100000000; mesh->center=rvector(0,0,0); ReadInt(mesh->nFaces); CFaces *faces=mesh->faceshead=mesh->nFaces?new CFaces[mesh->nFaces]:NULL; // rslog("\t-mesh face num :%d \n",mesh->nFaces); for(j=0;j<mesh->nFaces;j++) { ReadInt(faces->iMaterial);faces->iMaterial++; // convert to 1-base index ReadInt(faces->nv); faces->tnlvertices=new VERTEX[faces->nv]; fread(faces->tnlvertices,sizeof(VERTEX),faces->nv,file); for(k=0;k<faces->nv;k++) { rvector *pv=(rvector*)(&faces->tnlvertices[k].x); m_BoundingSphereRadius=max(m_BoundingSphereRadius,pv->GetMagnitude()); m_BoundingSphereRadiusXY=max(m_BoundingSphereRadiusXY,rvector(pv->x,pv->y,0).GetMagnitude()); mesh->m_bbox.Minx=min(mesh->m_bbox.Minx,pv->x); mesh->m_bbox.Maxx=max(mesh->m_bbox.Maxx,pv->x); mesh->m_bbox.Miny=min(mesh->m_bbox.Miny,pv->y); mesh->m_bbox.Maxy=max(mesh->m_bbox.Maxy,pv->y); mesh->m_bbox.Minz=min(mesh->m_bbox.Minz,pv->z); mesh->m_bbox.Maxz=max(mesh->m_bbox.Maxz,pv->z); } // rslog("\t\t-mesh face v num :%d \n",faces->nv); if(fgetc(file)==1) { faces->indicies_original=new WORD[faces->nv]; fread(faces->indicies_original,sizeof(WORD),faces->nv,file); } else { ReadInt(faces->ni); faces->indicies=new WORD[faces->ni]; fread(faces->indicies,sizeof(WORD),faces->ni,file); } faces++; } if(strstr(mesh->name,ALIGN_POINT_STRING)) mesh->m_align=RS_ALIGNSTYLE_POINT; else if(strstr(mesh->name,ALIGN_LINE_STRING)) mesh->m_align=RS_ALIGNSTYLE_LINE; else mesh->m_align=RS_ALIGNSTYLE_NONE; MergeBoundingBox(&m_bbox,&mesh->m_bbox); mesh++; } m_ShadowTexture.Create(file); /*// save test { char buf[256]; ReplaceExtension(buf,name,"bmp"); m_ShadowTexture.SaveAsBMP(buf); } //*/ m_hShadowTexture=RSCreateTexture( m_ShadowTexture.GetWidth(),m_ShadowTexture.GetHeight(), (char*)m_ShadowTexture.GetData(),NULL,true,"Object:ShadowTexture"); /* rtexture temp;temp.Create(file); CreateShadowTexture(); */ ReadInt(nAnimSet); if(nAnimSet) { for(i=0;i<nAnimSet;i++) { RSAnimationInfo *ai=new RSAnimationInfo; ai->Load(file); AnimationList.Add(ai); } } GenerateVertexBuffers(); // rslog("\t-mesh ani num :%d \n",nAnimSet); // g_obj_cnt++; return true; }
int USGSDEMDataset::LoadFromFile(VSILFILE *InDem) { // check for version of DEM format CPL_IGNORE_RET_VAL(VSIFSeekL(InDem, 864, 0)); // Read DEM into matrix const int nRow = ReadInt(InDem); const int nColumn = ReadInt(InDem); const bool bNewFormat = VSIFTellL(InDem) >= 1024 || nRow != 1 || nColumn != 1; if (bNewFormat) { CPL_IGNORE_RET_VAL(VSIFSeekL(InDem, 1024, 0)); // New Format int i = ReadInt(InDem); int j = ReadInt(InDem); if ( i != 1 || ( j != 1 && j != 0 ) ) // File OK? { CPL_IGNORE_RET_VAL(VSIFSeekL(InDem, 893, 0)); // Undocumented Format (39109h1.dem) i = ReadInt(InDem); j = ReadInt(InDem); if ( i != 1 || j != 1 ) // File OK? { CPLError( CE_Failure, CPLE_AppDefined, "Does not appear to be a USGS DEM file." ); return FALSE; } else nDataStartOffset = 893; } else nDataStartOffset = 1024; } else nDataStartOffset = 864; CPL_IGNORE_RET_VAL(VSIFSeekL(InDem, 156, 0)); const int nCoordSystem = ReadInt(InDem); const int iUTMZone = ReadInt(InDem); CPL_IGNORE_RET_VAL(VSIFSeekL(InDem, 528, 0)); const int nGUnit = ReadInt(InDem); const int nVUnit = ReadInt(InDem); // Vertical Units in meters if (nVUnit==1) pszUnits = "ft"; else pszUnits = "m"; CPL_IGNORE_RET_VAL(VSIFSeekL(InDem, 816, 0)); const double dxdelta = DConvert(InDem, 12); const double dydelta = DConvert(InDem, 12); if( dydelta == 0 ) return FALSE; fVRes = DConvert(InDem, 12); /* -------------------------------------------------------------------- */ /* Should we treat this as floating point, or GInt16. */ /* -------------------------------------------------------------------- */ if (nVUnit==1 || fVRes < 1.0) eNaturalDataFormat = GDT_Float32; else eNaturalDataFormat = GDT_Int16; /* -------------------------------------------------------------------- */ /* Read four corner coordinates. */ /* -------------------------------------------------------------------- */ CPL_IGNORE_RET_VAL(VSIFSeekL(InDem, 546, 0)); DPoint2 corners[4]; // SW, NW, NE, SE for (int i = 0; i < 4; i++) { corners[i].x = DConvert(InDem, 24); corners[i].y = DConvert(InDem, 24); } // find absolute extents of raw vales DPoint2 extent_min, extent_max; extent_min.x = std::min(corners[0].x, corners[1].x); extent_max.x = std::max(corners[2].x, corners[3].x); extent_min.y = std::min(corners[0].y, corners[3].y); extent_max.y = std::max(corners[1].y, corners[2].y); /* dElevMin = */ DConvert(InDem, 48); /* dElevMax = */ DConvert(InDem, 48); CPL_IGNORE_RET_VAL(VSIFSeekL(InDem, 858, 0)); const int nProfiles = ReadInt(InDem); /* -------------------------------------------------------------------- */ /* Collect the spatial reference system. */ /* -------------------------------------------------------------------- */ OGRSpatialReference sr; bool bNAD83 = true; // OLD format header ends at byte 864 if (bNewFormat) { // year of data compilation CPL_IGNORE_RET_VAL(VSIFSeekL(InDem, 876, 0)); char szDateBuffer[5]; CPL_IGNORE_RET_VAL(VSIFReadL(szDateBuffer, 4, 1, InDem)); /* szDateBuffer[4] = 0; */ // Horizontal datum // 1=North American Datum 1927 (NAD 27) // 2=World Geodetic System 1972 (WGS 72) // 3=WGS 84 // 4=NAD 83 // 5=Old Hawaii Datum // 6=Puerto Rico Datum CPL_IGNORE_RET_VAL(VSIFSeekL(InDem, 890, 0)); char szHorzDatum[3]; CPL_IGNORE_RET_VAL(VSIFReadL( szHorzDatum, 1, 2, InDem )); szHorzDatum[2] = '\0'; const int datum = atoi(szHorzDatum); switch (datum) { case 1: sr.SetWellKnownGeogCS( "NAD27" ); bNAD83 = false; break; case 2: sr.SetWellKnownGeogCS( "WGS72" ); break; case 3: sr.SetWellKnownGeogCS( "WGS84" ); break; case 4: sr.SetWellKnownGeogCS( "NAD83" ); break; case -9: break; default: sr.SetWellKnownGeogCS( "NAD27" ); break; } } else { sr.SetWellKnownGeogCS( "NAD27" ); bNAD83 = false; } if (nCoordSystem == 1) // UTM { if( iUTMZone >= -60 && iUTMZone <= 60 ) { sr.SetUTM( abs(iUTMZone), iUTMZone >= 0 ); if( nGUnit == 1 ) { sr.SetLinearUnitsAndUpdateParameters( SRS_UL_US_FOOT, CPLAtof(SRS_UL_US_FOOT_CONV) ); char szUTMName[128]; snprintf( szUTMName, sizeof(szUTMName), "UTM Zone %d, Northern Hemisphere, us-ft", iUTMZone ); sr.SetNode( "PROJCS", szUTMName ); } } } else if (nCoordSystem == 2) // state plane { if( nGUnit == 1 ) sr.SetStatePlane( iUTMZone, bNAD83, "Foot", CPLAtof(SRS_UL_US_FOOT_CONV) ); else sr.SetStatePlane( iUTMZone, bNAD83 ); } sr.exportToWkt( &pszProjection ); /* -------------------------------------------------------------------- */ /* For UTM we use the extents (really the UTM coordinates of */ /* the lat/long corners of the quad) to determine the size in */ /* pixels and lines, but we have to make the anchors be modulus */ /* the pixel size which what really gets used. */ /* -------------------------------------------------------------------- */ if (nCoordSystem == 1 // UTM || nCoordSystem == 2 // State Plane || nCoordSystem == -9999 ) // unknown { // expand extents modulus the pixel size. extent_min.y = floor(extent_min.y/dydelta) * dydelta; extent_max.y = ceil(extent_max.y/dydelta) * dydelta; // Forcibly compute X extents based on first profile and pixelsize. CPL_IGNORE_RET_VAL(VSIFSeekL(InDem, nDataStartOffset, 0)); /* njunk = */ ReadInt(InDem); /* njunk = */ ReadInt(InDem); /* njunk = */ ReadInt(InDem); /* njunk = */ ReadInt(InDem); const double dxStart = DConvert(InDem, 24); nRasterYSize = static_cast<int>( ( extent_max.y - extent_min.y ) / dydelta + 1.5 ); nRasterXSize = nProfiles; adfGeoTransform[0] = dxStart - dxdelta/2.0; adfGeoTransform[1] = dxdelta; adfGeoTransform[2] = 0.0; adfGeoTransform[3] = extent_max.y + dydelta/2.0; adfGeoTransform[4] = 0.0; adfGeoTransform[5] = -dydelta; } /* -------------------------------------------------------------------- */ /* Geographic -- use corners directly. */ /* -------------------------------------------------------------------- */ else { nRasterYSize = static_cast<int>( ( extent_max.y - extent_min.y ) / dydelta + 1.5 ); nRasterXSize = nProfiles; // Translate extents from arc-seconds to decimal degrees. adfGeoTransform[0] = (extent_min.x - dxdelta/2.0) / 3600.0; adfGeoTransform[1] = dxdelta / 3600.0; adfGeoTransform[2] = 0.0; adfGeoTransform[3] = (extent_max.y + dydelta/2.0) / 3600.0; adfGeoTransform[4] = 0.0; adfGeoTransform[5] = (-dydelta) / 3600.0; } if (!GDALCheckDatasetDimensions(nRasterXSize, nRasterYSize)) { return FALSE; } return TRUE; }
int main(int argc, char *argv[]) { Source src; int tmpInt; float tmpFlt; char *accfn, *s; void Initialise(char *hmmListFn); void Interpolate(void); void UpdateModels(void); void MakeWtAccLists(void); void AttachWtAccLists(void); void StatReport(void); if(InitShell(argc,argv,hsmooth_version,hsmooth_vc_id)<SUCCESS) HError(2400,"HSmooth: InitShell failed"); InitMem(); InitLabel(); InitMath(); InitSigP(); InitWave(); InitAudio(); InitVQ(); InitModel(); if(InitParm()<SUCCESS) HError(2400,"HSmooth: InitParm failed"); InitTrain(); InitUtil(); if (!InfoPrinted() && NumArgs() == 0) ReportUsage(); if (NumArgs() == 0) Exit(0); SetConfParms(); CreateHeap(&hmmStack,"HmmStore", MSTAK, 1, 1.0, 50000, 500000); CreateHMMSet(&hset,&hmmStack,TRUE); while (NextArg() == SWITCHARG) { s = GetSwtArg(); if (strlen(s)!=1) HError(2419,"HSmooth: Bad switch %s; must be single letter",s); switch(s[0]){ case 'b': epsilon = GetChkedFlt(0.0,1.0,s); break; case 'c': maxStep = GetChkedInt(1,1000,s); break; case 'd': if (NextArg()!=STRINGARG) HError(2419,"HSmooth: HMM definition directory expected"); hmmDir = GetStrArg(); break; case 'e': if (NextArg()!=STRINGARG) HError(2419,"HSmooth: HMM definition directory expected"); newDir = GetStrArg(); break; case 'm': minEgs = GetChkedInt(1,1000,s); break; case 'o': if (NextArg()!=STRINGARG) HError(2419,"HSmooth: HMM file extension expected"); newExt = GetStrArg(); break; case 's': stats = TRUE; if (NextArg()!=STRINGARG) HError(2419,"HSmooth: Stats file name expected"); statFN = GetStrArg(); break; case 'u': SetuFlags(); break; case 'v': minVar = GetChkedFlt(0.0,10.0,s); break; case 'w': mixWeightFloor = MINMIX * GetChkedFlt(0.0,10000.0,s); break; case 'x': if (NextArg()!=STRINGARG) HError(2419,"HSmooth: HMM file extension expected"); hmmExt = GetStrArg(); break; case 'B': saveBinary=TRUE; break; case 'H': if (NextArg() != STRINGARG) HError(2419,"HSmooth: HMM macro file name expected"); AddMMF(&hset,GetStrArg()); break; case 'M': if (NextArg()!=STRINGARG) HError(2419,"HSmooth: Output macro file directory expected"); newDir = GetStrArg(); break; case 'T': trace = GetChkedInt(0,0100000,s); break; default: HError(2419,"HSmooth: Unknown switch %s",s); } } if (NextArg() != STRINGARG) HError(2419,"HSmooth: file name of HMM list expected"); Initialise(GetStrArg()); do { if (NextArg()!=STRINGARG) HError(2419,"HSmooth: accumulator file name expected"); accfn = GetStrArg(); src=LoadAccs(&hset,accfn,uFlags); ReadFloat(&src,&tmpFlt,1,ldBinary); totalPr += (LogDouble)tmpFlt; ReadInt(&src,&tmpInt,1,ldBinary); totalT += tmpInt; CloseSource(&src); nBlk++; MakeWtAccLists(); } while (NumArgs()>0); AttachWtAccLists(); Interpolate(); if (stats) StatReport(); UpdateModels(); Exit(0); return (0); /* never reached -- make compiler happy */ }
int main (int argc, char *argv[]) { int st; SimParams params; int max_steps = std::numeric_limits<int>::max(); std::string within_filename, output_filename; po::options_description desc("Options"); desc.add_options() ("help,h", "Print help messages") ("group,g", po::value<std::string>()->default_value("He"), "Group for temperature profiles") ("index,n", po::value<std::string>()->default_value("index.ndx"), ".ndx file containing atomic indices for groups") ("gro", po::value<std::string>()->default_value("conf.gro"), ".gro file containing list of atoms/molecules") ("top", po::value<std::string>()->default_value("topol.top"), ".top file containing atomic/molecular properties") ("within,w", po::value<std::string>(&within_filename)->default_value("within.dat"), ".dat file specifying solvating molecules") ("output,o", po::value<std::string>(&output_filename)->default_value("qDist.txt"), "Output filename"); po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); if (vm.count("help")) { std::cout << desc << "\n"; exit(EXIT_SUCCESS); } std::map<std::string, std::vector<int> > groups; groups = ReadNdx(vm["index"].as<std::string>()); std::vector<Molecule> molecules = GenMolecules(vm["top"].as<std::string>(), params); AtomGroup all_atoms(vm["gro"].as<std::string>(), molecules); AtomGroup selected_group(vm["group"].as<std::string>(), SelectGroup(groups, vm["group"].as<std::string>()), all_atoms); std::fstream within_file(within_filename.c_str()); assert(within_file.is_open()); arma::irowvec within = arma::zeros<arma::irowvec>(selected_group.size()); arma::irowvec nearest = arma::zeros<arma::irowvec>(4); Histogram q_hist(100, 0.01); rvec *x_in = NULL; matrix box_mat; arma::rowvec box = arma::zeros<arma::rowvec>(DIMS); std::string xtc_filename = "prod.xtc"; XDRFILE *xtc_file; params.ExtractTrajMetadata(strdup(xtc_filename.c_str()), (&x_in), box); xtc_file = xdrfile_open(strdup(xtc_filename.c_str()), "r"); params.set_max_time(vm["max_time"].as<double>()); arma::rowvec dx; arma::mat dx_near = arma::zeros<arma::mat>(4,DIMS); arma::rowvec r2 = arma::zeros<arma::rowvec>(selected_group.size()); float time,prec; for (int step=0; step<max_steps; step++) { if(read_xtc(xtc_file, params.num_atoms(), &st, &time, box_mat, x_in, &prec)) break; params.set_box(box_mat); int i = 0; for (std::vector<int>::iterator i_atom = selected_group.begin(); i_atom != selected_group.end(); i_atom++, i++) { selected_group.set_position(i, x_in[*i_atom]); } ReadInt(within, within_file); for (int i_atom = 0; i_atom < selected_group.size(); ++i_atom) { if (!within(i_atom)) continue; selected_group.FindNearestk(selected_group.position(i_atom), params.box(), selected_group.index_to_molecule(i_atom), 4, dx, r2, nearest); int q = 0; for (int i_near = 0; i_near < 4; ++i_near) { FindDxNoShift(dx, selected_group.position(i_atom), selected_group.position(i_near), box); dx_near.row(i_near) = arma::normalise(dx); for (int i_near2 = 0; i_near2 < i_near; ++i_near2) { double sqrt_q = arma::dot(dx_near.row(i_near),dx_near.row(i_near2)) + 1.0/3.0; q += sqrt_q*sqrt_q; } } q_hist.Add(q); } } q_hist.Print(output_filename, true); }
int BeDecode(ScriptValue &sv, StringValue *s, int *pos) { if (s->len < pos[0]) return 0; if (s->value[pos[0]] == 'i') { pos[0] ++; unsigned char *end = strchr(s->value + pos[0], 'e'); __int64 val; if (!ReadInt(s->value + pos[0], end, val)) return 0; CreateIntValue(sv, val); pos[0] = 1+(int)(end-s->value); } else if (s->value[pos[0]] == 'l') { pos[0] ++; CreateListValue(sv, 3); while (s->len > pos[0]) { if (s->value[pos[0]] == 'e') { pos[0] ++; return 1; } ScriptValue sv2; if (!BeDecode(sv2, s, pos) || !sv.listVal->PushBack(sv2)) { sv.Release(); return 0; } } sv.Release(); return 0; } else if (s->value[pos[0]] == 'd') { pos[0] ++; CreateDictValue(sv, 3); while (s->len > pos[0]) { if (s->value[pos[0]] == 'e') { pos[0] ++; return 1; } ScriptValue sv2, sv3; if (!BeDecode(sv2, s, pos)) { sv.Release(); return 0; } if (sv2.type != SCRIPT_STRING || !BeDecode(sv3, s, pos)) { sv2.Release(); sv.Release(); return 0; } if (!sv.dictVal->Add(sv, sv2)) { sv.Release(); return 0; } } sv.Release(); return 0; } else if (s->value[pos[0]] == 'n') { CreateNullValue(sv); pos[0]++; } else if (s->value[pos[0]] == 'f') { pos[0]++; if (pos[0] + 8 > s->len) return 0; double d; memcpy(&d, s->value+pos[0], 8); pos[0] += 8; CreateDoubleValue(sv, d); return 1; } else { unsigned char *end = strchr(s->value + pos[0], ':'); __int64 val; if (!ReadInt(s->value + pos[0], end, val) || val < 0) return 0; pos[0] = 1+(int)(end-s->value); if (pos[0] + val > s->len) return 0; if (!CreateStringValue(sv, s->value+pos[0], (int) val)) return 0; pos[0] += (int) val; } return 1; }
status_t AudioFormatConverter::Read(void* buffer, int64 pos, int64 frames) { TRACE("AudioFormatConverter::Read(%p, %Ld, %Ld)\n", buffer, pos, frames); status_t error = InitCheck(); if (error != B_OK) { TRACE("AudioFormatConverter::Read() done 1\n"); return error; } pos += fOutOffset; if (fFormat.u.raw_audio.format == fSource->Format().u.raw_audio.format && fFormat.u.raw_audio.byte_order == fSource->Format().u.raw_audio.byte_order) { TRACE("AudioFormatConverter::Read() done 2\n"); return fSource->Read(buffer, pos, frames); } int32 inSampleSize = fSource->Format().u.raw_audio.format & media_raw_audio_format::B_AUDIO_SIZE_MASK; int32 outSampleSize = fFormat.u.raw_audio.format & media_raw_audio_format::B_AUDIO_SIZE_MASK; int32 channelCount = fFormat.u.raw_audio.channel_count; int32 inFrameSize = inSampleSize * channelCount; int32 outFrameSize = outSampleSize * channelCount; char* reformatBuffer = NULL; char* inBuffer = (char*)buffer; #ifdef TRACE_AUDIO_CONVERTER char formatString[256]; string_for_format(fSource->Format(), formatString, 256); TRACE(" source format: %s\n", formatString); TRACE(" in format : format: %lx, sample size: %ld, channels: %ld, " "byte order: %lu\n", fSource->Format().u.raw_audio.format, inSampleSize, channelCount, fSource->Format().u.raw_audio.byte_order); TRACE(" out format: format: %lx, sample size: %ld, channels: %ld, " "byte order: %lu\n", fFormat.u.raw_audio.format, outSampleSize, channelCount, fFormat.u.raw_audio.byte_order); #endif // TRACE_AUDIO_CONVERTER if (inSampleSize != outSampleSize) { reformatBuffer = new char[frames * inFrameSize]; inBuffer = reformatBuffer; } error = fSource->Read(inBuffer, pos, frames); // convert samples to host endianess uint32 hostByteOrder = (B_HOST_IS_BENDIAN) ? B_MEDIA_BIG_ENDIAN : B_MEDIA_LITTLE_ENDIAN; if (fSource->Format().u.raw_audio.byte_order != hostByteOrder) { swap_sample_byte_order(inBuffer, fSource->Format().u.raw_audio.format, frames * inFrameSize); } // convert the sample type switch (fSource->Format().u.raw_audio.format) { // float case media_raw_audio_format::B_AUDIO_FLOAT: switch (fFormat.u.raw_audio.format) { case media_raw_audio_format::B_AUDIO_FLOAT: break; case media_raw_audio_format::B_AUDIO_INT: convert(ReadFloat(), WriteInt(), inBuffer, (char*)buffer, frames, inSampleSize, outSampleSize, channelCount); break; case media_raw_audio_format::B_AUDIO_SHORT: convert(ReadFloat(), WriteShort(), inBuffer, (char*)buffer, frames, inSampleSize, outSampleSize, channelCount); break; case media_raw_audio_format::B_AUDIO_UCHAR: convert(ReadFloat(), WriteUChar(), inBuffer, (char*)buffer, frames, inSampleSize, outSampleSize, channelCount); break; case media_raw_audio_format::B_AUDIO_CHAR: convert(ReadFloat(), WriteChar(), inBuffer, (char*)buffer, frames, inSampleSize, outSampleSize, channelCount); break; } break; // int case media_raw_audio_format::B_AUDIO_INT: switch (fFormat.u.raw_audio.format) { case media_raw_audio_format::B_AUDIO_FLOAT: convert(ReadInt(), WriteFloat(), inBuffer, (char*)buffer, frames, inSampleSize, outSampleSize, channelCount); break; case media_raw_audio_format::B_AUDIO_INT: break; case media_raw_audio_format::B_AUDIO_SHORT: convert(ReadInt(), WriteShort(), inBuffer, (char*)buffer, frames, inSampleSize, outSampleSize, channelCount); break; case media_raw_audio_format::B_AUDIO_UCHAR: convert(ReadInt(), WriteUChar(), inBuffer, (char*)buffer, frames, inSampleSize, outSampleSize, channelCount); break; case media_raw_audio_format::B_AUDIO_CHAR: convert(ReadInt(), WriteChar(), inBuffer, (char*)buffer, frames, inSampleSize, outSampleSize, channelCount); break; } break; // short case media_raw_audio_format::B_AUDIO_SHORT: switch (fFormat.u.raw_audio.format) { case media_raw_audio_format::B_AUDIO_FLOAT: convert(ReadShort(), WriteFloat(), inBuffer, (char*)buffer, frames, inSampleSize, outSampleSize, channelCount); break; case media_raw_audio_format::B_AUDIO_INT: convert(ReadShort(), WriteInt(), inBuffer, (char*)buffer, frames, inSampleSize, outSampleSize, channelCount); break; case media_raw_audio_format::B_AUDIO_SHORT: break; case media_raw_audio_format::B_AUDIO_UCHAR: convert(ReadShort(), WriteUChar(), inBuffer, (char*)buffer, frames, inSampleSize, outSampleSize, channelCount); break; case media_raw_audio_format::B_AUDIO_CHAR: convert(ReadShort(), WriteChar(), inBuffer, (char*)buffer, frames, inSampleSize, outSampleSize, channelCount); break; } break; // uchar case media_raw_audio_format::B_AUDIO_UCHAR: switch (fFormat.u.raw_audio.format) { case media_raw_audio_format::B_AUDIO_FLOAT: convert(ReadUChar(), WriteFloat(), inBuffer, (char*)buffer, frames, inSampleSize, outSampleSize, channelCount); break; case media_raw_audio_format::B_AUDIO_INT: convert(ReadUChar(), WriteInt(), inBuffer, (char*)buffer, frames, inSampleSize, outSampleSize, channelCount); break; case media_raw_audio_format::B_AUDIO_SHORT: convert(ReadUChar(), WriteShort(), inBuffer, (char*)buffer, frames, inSampleSize, outSampleSize, channelCount); break; case media_raw_audio_format::B_AUDIO_UCHAR: break; case media_raw_audio_format::B_AUDIO_CHAR: convert(ReadUChar(), WriteChar(), inBuffer, (char*)buffer, frames, inSampleSize, outSampleSize, channelCount); break; } break; // char case media_raw_audio_format::B_AUDIO_CHAR: switch (fFormat.u.raw_audio.format) { case media_raw_audio_format::B_AUDIO_FLOAT: convert(ReadChar(), WriteFloat(), inBuffer, (char*)buffer, frames, inSampleSize, outSampleSize, channelCount); break; case media_raw_audio_format::B_AUDIO_INT: convert(ReadChar(), WriteInt(), inBuffer, (char*)buffer, frames, inSampleSize, outSampleSize, channelCount); break; case media_raw_audio_format::B_AUDIO_SHORT: convert(ReadChar(), WriteShort(), inBuffer, (char*)buffer, frames, inSampleSize, outSampleSize, channelCount); break; case media_raw_audio_format::B_AUDIO_UCHAR: convert(ReadChar(), WriteUChar(), inBuffer, (char*)buffer, frames, inSampleSize, outSampleSize, channelCount); break; case media_raw_audio_format::B_AUDIO_CHAR: break; } break; } // convert samples to output endianess if (fFormat.u.raw_audio.byte_order != hostByteOrder) { swap_sample_byte_order(buffer, fFormat.u.raw_audio.format, frames * outFrameSize); } delete[] reformatBuffer; TRACE("AudioFormatConverter::Read() done\n"); return B_OK; }
GDALDataset *OZIDataset::Open( GDALOpenInfo * poOpenInfo ) { if (!Identify(poOpenInfo)) return NULL; GByte abyHeader[14]; CPLString osImgFilename = poOpenInfo->pszFilename; memcpy(abyHeader, poOpenInfo->pabyHeader, 14); int bOzi3 = (abyHeader[0] == 0x80 && abyHeader[1] == 0x77); VSILFILE* fp = VSIFOpenL(osImgFilename.c_str(), "rb"); if (fp == NULL) return NULL; OZIDataset* poDS = new OZIDataset(); poDS->fp = fp; GByte nRandomNumber = 0; GByte nKeyInit = 0; if (bOzi3) { VSIFSeekL(fp, 14, SEEK_SET); VSIFReadL(&nRandomNumber, 1, 1, fp); //printf("nRandomNumber = %d\n", nRandomNumber); if (nRandomNumber < 0x94) { delete poDS; return NULL; } VSIFSeekL(fp, 0x93, SEEK_CUR); VSIFReadL(&nKeyInit, 1, 1, fp); VSIFSeekL(fp, 0, SEEK_SET); VSIFReadL(abyHeader, 1, 14, fp); OZIDecrypt(abyHeader, 14, nKeyInit); if (!(abyHeader[6] == 0x40 && abyHeader[7] == 0x00 && abyHeader[8] == 0x01 && abyHeader[9] == 0x00 && abyHeader[10] == 0x36 && abyHeader[11] == 0x04 && abyHeader[12] == 0x00 && abyHeader[13] == 0x00)) { delete poDS; return NULL; } VSIFSeekL(fp, 14 + 1 + nRandomNumber, SEEK_SET); int nMagic = ReadInt(fp, bOzi3, nKeyInit); CPLDebug("OZI", "OZI version code : 0x%08X", nMagic); poDS->bOzi3 = bOzi3; } else { VSIFSeekL(fp, 14, SEEK_SET); } GByte abyHeader2[40], abyHeader2_Backup[40]; VSIFReadL(abyHeader2, 40, 1, fp); memcpy(abyHeader2_Backup, abyHeader2, 40); /* There's apparently a relationship between the nMagic number */ /* and the nKeyInit, but I'm too lazy to add switch/cases that might */ /* be not exhaustive, so let's try the 'brute force' attack !!! */ /* It is much so funny to be able to run one in a few microseconds :-) */ int i; for(i = 0; i < 256; i ++) { nKeyInit = (GByte)i; GByte* pabyHeader2 = abyHeader2; if (bOzi3) OZIDecrypt(abyHeader2, 40, nKeyInit); int nHeaderSize = ReadInt(&pabyHeader2); /* should be 40 */ poDS->nRasterXSize = ReadInt(&pabyHeader2); poDS->nRasterYSize = ReadInt(&pabyHeader2); int nDepth = ReadShort(&pabyHeader2); /* should be 1 */ int nBPP = ReadShort(&pabyHeader2); /* should be 8 */ ReadInt(&pabyHeader2); /* reserved */ ReadInt(&pabyHeader2); /* pixel number (height * width) : unused */ ReadInt(&pabyHeader2); /* reserved */ ReadInt(&pabyHeader2); /* reserved */ ReadInt(&pabyHeader2); /* ?? 0x100 */ ReadInt(&pabyHeader2); /* ?? 0x100 */ if (nHeaderSize != 40 || nDepth != 1 || nBPP != 8) { if (bOzi3) { if (nKeyInit != 255) { memcpy(abyHeader2, abyHeader2_Backup,40); continue; } else { CPLDebug("OZI", "Cannot decypher 2nd header. Sorry..."); delete poDS; return NULL; } } else { CPLDebug("OZI", "nHeaderSize = %d, nDepth = %d, nBPP = %d", nHeaderSize, nDepth, nBPP); delete poDS; return NULL; } } else break; } poDS->nKeyInit = nKeyInit; int nSeparator = ReadInt(fp); if (!bOzi3 && nSeparator != 0x77777777) { CPLDebug("OZI", "didn't get end of header2 marker"); delete poDS; return NULL; } poDS->nZoomLevelCount = ReadShort(fp); //CPLDebug("OZI", "nZoomLevelCount = %d", poDS->nZoomLevelCount); if (poDS->nZoomLevelCount < 0 || poDS->nZoomLevelCount >= 256) { CPLDebug("OZI", "nZoomLevelCount = %d", poDS->nZoomLevelCount); delete poDS; return NULL; } /* Skip array of zoom level percentage. We don't need it for GDAL */ VSIFSeekL(fp, sizeof(float) * poDS->nZoomLevelCount, SEEK_CUR); nSeparator = ReadInt(fp); if (!bOzi3 && nSeparator != 0x77777777) { /* Some files have 8 extra bytes before the marker. I'm not sure */ /* what they are used for. So just skeep them and hope that */ /* we'll find the marker */ nSeparator = ReadInt(fp); nSeparator = ReadInt(fp); if (nSeparator != 0x77777777) { CPLDebug("OZI", "didn't get end of zoom levels marker"); delete poDS; return NULL; } } VSIFSeekL(fp, 0, SEEK_END); vsi_l_offset nFileSize = VSIFTellL(fp); poDS->nFileSize = nFileSize; VSIFSeekL(fp, nFileSize - 4, SEEK_SET); int nZoomLevelTableOffset = ReadInt(fp, bOzi3, nKeyInit); if (nZoomLevelTableOffset < 0 || (vsi_l_offset)nZoomLevelTableOffset >= nFileSize) { CPLDebug("OZI", "nZoomLevelTableOffset = %d", nZoomLevelTableOffset); delete poDS; return NULL; } VSIFSeekL(fp, nZoomLevelTableOffset, SEEK_SET); poDS->panZoomLevelOffsets = (int*)CPLMalloc(sizeof(int) * poDS->nZoomLevelCount); for(i=0;i<poDS->nZoomLevelCount;i++) { poDS->panZoomLevelOffsets[i] = ReadInt(fp, bOzi3, nKeyInit); if (poDS->panZoomLevelOffsets[i] < 0 || (vsi_l_offset)poDS->panZoomLevelOffsets[i] >= nFileSize) { CPLDebug("OZI", "panZoomLevelOffsets[%d] = %d", i, poDS->panZoomLevelOffsets[i]); delete poDS; return NULL; } } poDS->papoOvrBands = (OZIRasterBand**)CPLCalloc(sizeof(OZIRasterBand*), poDS->nZoomLevelCount); for(i=0;i<poDS->nZoomLevelCount;i++) { VSIFSeekL(fp, poDS->panZoomLevelOffsets[i], SEEK_SET); int nW = ReadInt(fp, bOzi3, nKeyInit); int nH = ReadInt(fp, bOzi3, nKeyInit); short nTileX = ReadShort(fp, bOzi3, nKeyInit); short nTileY = ReadShort(fp, bOzi3, nKeyInit); if (i == 0 && (nW != poDS->nRasterXSize || nH != poDS->nRasterYSize)) { CPLDebug("OZI", "zoom[%d] inconsistent dimensions for zoom level 0 : nW=%d, nH=%d, nTileX=%d, nTileY=%d, nRasterXSize=%d, nRasterYSize=%d", i, nW, nH, nTileX, nTileY, poDS->nRasterXSize, poDS->nRasterYSize); delete poDS; return NULL; } /* Note (#3895): some files such as world.ozf2 provided with OziExplorer */ /* expose nTileY=33, but have nH=2048, so only require 32 tiles in vertical dimension. */ /* So there's apparently one extra and useless tile that will be ignored */ /* without causing apparent issues */ /* Some other files have more tile in horizontal direction than needed, so let's */ /* accept that. But in that case we really need to keep the nTileX value for IReadBlock() */ /* to work properly */ if ((nW + 63) / 64 > nTileX || (nH + 63) / 64 > nTileY) { CPLDebug("OZI", "zoom[%d] unexpected number of tiles : nW=%d, nH=%d, nTileX=%d, nTileY=%d", i, nW, nH, nTileX, nTileY); delete poDS; return NULL; } GDALColorTable* poColorTable = new GDALColorTable(); GByte abyColorTable[256*4]; VSIFReadL(abyColorTable, 1, 1024, fp); if (bOzi3) OZIDecrypt(abyColorTable, 1024, nKeyInit); int j; for(j=0;j<256;j++) { GDALColorEntry sEntry; sEntry.c1 = abyColorTable[4*j + 2]; sEntry.c2 = abyColorTable[4*j + 1]; sEntry.c3 = abyColorTable[4*j + 0]; sEntry.c4 = 255; poColorTable->SetColorEntry(j, &sEntry); } poDS->papoOvrBands[i] = new OZIRasterBand(poDS, i, nW, nH, nTileX, poColorTable); if (i > 0) { GByte* pabyTranslationTable = poDS->papoOvrBands[i]->GetIndexColorTranslationTo(poDS->papoOvrBands[0], NULL, NULL); delete poDS->papoOvrBands[i]->poColorTable; poDS->papoOvrBands[i]->poColorTable = poDS->papoOvrBands[0]->poColorTable->Clone(); poDS->papoOvrBands[i]->pabyTranslationTable = pabyTranslationTable; } } poDS->SetBand(1, poDS->papoOvrBands[0]); /* -------------------------------------------------------------------- */ /* Initialize any PAM information. */ /* -------------------------------------------------------------------- */ poDS->SetDescription( poOpenInfo->pszFilename ); poDS->TryLoadXML(); /* -------------------------------------------------------------------- */ /* Support overviews. */ /* -------------------------------------------------------------------- */ poDS->oOvManager.Initialize( poDS, poOpenInfo->pszFilename ); return( poDS ); }
CPLErr OZIRasterBand::IReadBlock( int nBlockXOff, int nBlockYOff, void * pImage ) { OZIDataset *poGDS = (OZIDataset *) poDS; int nBlock = nBlockYOff * nXBlocks + nBlockXOff; VSIFSeekL(poGDS->fp, poGDS->panZoomLevelOffsets[nZoomLevel] + 12 + 1024 + 4 * nBlock, SEEK_SET); int nPointer = ReadInt(poGDS->fp, poGDS->bOzi3, poGDS->nKeyInit); if (nPointer < 0 || (vsi_l_offset)nPointer >= poGDS->nFileSize) { CPLError(CE_Failure, CPLE_AppDefined, "Invalid offset for block (%d, %d) : %d", nBlockXOff, nBlockYOff, nPointer); return CE_Failure; } int nNextPointer = ReadInt(poGDS->fp, poGDS->bOzi3, poGDS->nKeyInit); if (nNextPointer <= nPointer + 16 || (vsi_l_offset)nNextPointer >= poGDS->nFileSize || nNextPointer - nPointer > 10 * 64 * 64) { CPLError(CE_Failure, CPLE_AppDefined, "Invalid next offset for block (%d, %d) : %d", nBlockXOff, nBlockYOff, nNextPointer); return CE_Failure; } VSIFSeekL(poGDS->fp, nPointer, SEEK_SET); int nToRead = nNextPointer - nPointer; GByte* pabyZlibBuffer = (GByte*)CPLMalloc(nToRead); if (VSIFReadL(pabyZlibBuffer, nToRead, 1, poGDS->fp) != 1) { CPLError(CE_Failure, CPLE_AppDefined, "Not enough byte read for block (%d, %d)", nBlockXOff, nBlockYOff); CPLFree(pabyZlibBuffer); return CE_Failure; } if (poGDS->bOzi3) OZIDecrypt(pabyZlibBuffer, 16, poGDS->nKeyInit); if (pabyZlibBuffer[0] != 0x78 || pabyZlibBuffer[1] != 0xDA) { CPLError(CE_Failure, CPLE_AppDefined, "Bad ZLIB signature for block (%d, %d) : 0x%02X 0x%02X", nBlockXOff, nBlockYOff, pabyZlibBuffer[0], pabyZlibBuffer[1]); CPLFree(pabyZlibBuffer); return CE_Failure; } z_stream stream; stream.zalloc = (alloc_func)0; stream.zfree = (free_func)0; stream.opaque = (voidpf)0; stream.next_in = pabyZlibBuffer + 2; stream.avail_in = nToRead - 2; int err = inflateInit2(&(stream), -MAX_WBITS); int i; for(i=0;i<64 && err == Z_OK;i++) { stream.next_out = (Bytef*)pImage + (63 - i) * 64; stream.avail_out = 64; err = inflate(& (stream), Z_NO_FLUSH); if (err != Z_OK && err != Z_STREAM_END) break; if (pabyTranslationTable) { int j; GByte* ptr = ((GByte*)pImage) + (63 - i) * 64; for(j=0;j<64;j++) { *ptr = pabyTranslationTable[*ptr]; ptr ++; } } } inflateEnd(&stream); CPLFree(pabyZlibBuffer); return (err == Z_OK || err == Z_STREAM_END) ? CE_None : CE_Failure; }
void LcfReader::Read<int32_t>(int32_t& ref) { ref = ReadInt(); }
Variant Deserializer::ReadVariant(VariantType type) { switch (type) { case VAR_INT: return Variant(ReadInt()); case VAR_BOOL: return Variant(ReadBool()); case VAR_FLOAT: return Variant(ReadFloat()); case VAR_VECTOR2: return Variant(ReadVector2()); case VAR_VECTOR3: return Variant(ReadVector3()); case VAR_VECTOR4: return Variant(ReadVector4()); case VAR_QUATERNION: return Variant(ReadQuaternion()); case VAR_COLOR: return Variant(ReadColor()); case VAR_STRING: return Variant(ReadString()); case VAR_BUFFER: return Variant(ReadBuffer()); // Deserializing pointers is not supported. Return null case VAR_VOIDPTR: case VAR_PTR: ReadUInt(); return Variant((void*)0); case VAR_RESOURCEREF: return Variant(ReadResourceRef()); case VAR_RESOURCEREFLIST: return Variant(ReadResourceRefList()); case VAR_VARIANTVECTOR: return Variant(ReadVariantVector()); case VAR_STRINGVECTOR: return Variant(ReadStringVector()); case VAR_VARIANTMAP: return Variant(ReadVariantMap()); case VAR_INTRECT: return Variant(ReadIntRect()); case VAR_INTVECTOR2: return Variant(ReadIntVector2()); case VAR_MATRIX3: return Variant(ReadMatrix3()); case VAR_MATRIX3X4: return Variant(ReadMatrix3x4()); case VAR_MATRIX4: return Variant(ReadMatrix4()); case VAR_DOUBLE: return Variant(ReadDouble()); default: return Variant(); } }
void IO_UncertSimResults::ReadTableArray(DC_TableArray& tableArray) { tableArray.AllocAndSetSize(ReadInt()); for (int i = 0; i < tableArray.Size(); i++) ReadTable(tableArray[i]); }
const bool ControllerMapping::Load(const std::wstring& filename, const wchar_t* defaultJoystick) { const wchar_t*& joy = defaultJoystick; //shorter so it fits into the layout const wchar_t* filename_c = filename.c_str(); //buttons if(!ReadInt(L"button_1", L"joystick", joy, filename_c, Buttons[eButton1].Joy, -1, 3)) return false; if(!ReadInt(L"button_1", L"button", L"0", filename_c, Buttons[eButton1].Button, 0, NUM_DIGITAL-1)) return false; if(!ReadInt(L"button_2", L"joystick", joy, filename_c, Buttons[eButton2].Joy, -1, 3)) return false; if(!ReadInt(L"button_2", L"button", L"1", filename_c, Buttons[eButton2].Button, 0, NUM_DIGITAL-1)) return false; if(!ReadInt(L"button_3", L"joystick", joy, filename_c, Buttons[eButton3].Joy, -1, 3)) return false; if(!ReadInt(L"button_3", L"button", L"2", filename_c, Buttons[eButton3].Button, 0, NUM_DIGITAL-1)) return false; if(!ReadInt(L"button_4", L"joystick", joy, filename_c, Buttons[eButton4].Joy , -1, 3)) return false; if(!ReadInt(L"button_4", L"button", L"3", filename_c, Buttons[eButton4].Button, 0, NUM_DIGITAL-1)) return false; if(!ReadInt(L"button_start", L"joystick", joy, filename_c, Buttons[eButtonStart].Joy, -1, 3)) return false; if(!ReadInt(L"button_start", L"button", L"7", filename_c, Buttons[eButtonStart].Button, 0, NUM_DIGITAL-1)) return false; if(!ReadInt(L"button_analog_stick", L"joystick", joy, filename_c, Buttons[eButtonJoystick].Joy, -1, 3)) return false; if(!ReadInt(L"button_analog_stick", L"button", L"6", filename_c, Buttons[eButtonJoystick].Button, 0, NUM_DIGITAL-1)) return false; if(!ReadInt(L"button_bumper", L"joystick", joy, filename_c, Buttons[eButtonBumper].Joy, -1, 3)) return false; if(!ReadInt(L"button_bumper", L"button", L"4", filename_c, Buttons[eButtonBumper].Button, 0, NUM_DIGITAL-1)) return false; // axes //position if(!ReadInt(L"axis_x", L"joystick", joy, filename_c, Position[0].Joy, -1, 3)) return false; if(!ReadInt(L"axis_x", L"axis", L"0", filename_c, Position[0].Axis, 0, NUM_ANALOG-1)) return false; if(!ReadBool(L"axis_x",L"inverted", L"false", filename_c, Position[0].Inverted)) return false; if(!ReadInt(L"axis_x", L"range", L"100", filename_c, Position[0].Range, 0, INT_MAX)) return false; if(!ReadInt(L"axis_y", L"joystick", joy, filename_c, Position[1].Joy, -1, 3)) return false; if(!ReadInt(L"axis_y", L"axis", L"1", filename_c, Position[1].Axis, 0, NUM_ANALOG-1)) return false; if(!ReadBool(L"axis_y",L"inverted", L"false", filename_c, Position[1].Inverted)) return false; if(!ReadInt(L"axis_y", L"range", L"100", filename_c, Position[1].Range, 0, INT_MAX)) return false; if(!ReadInt(L"axis_z", L"joystick", joy, filename_c, Position[2].Joy, -1, 3)) return false; if(!ReadInt(L"axis_z", L"axis", L"2", filename_c, Position[2].Axis, 0, NUM_ANALOG-1)) return false; if(!ReadBool(L"axis_z",L"inverted", L"false", filename_c, Position[2].Inverted)) return false; if(!ReadInt(L"axis_z", L"range", L"100", filename_c, Position[2].Range, 0, INT_MAX)) return false; //rotation if(!ReadInt(L"axis_pitch", L"joystick", joy, filename_c, Rotation[ePitch].Joy, -1, 3)) return false; if(!ReadInt(L"axis_pitch", L"axis", L"3", filename_c, Rotation[ePitch].Axis, 0, NUM_ANALOG-1)) return false; if(!ReadBool(L"axis_pitch",L"inverted", L"false", filename_c, Rotation[ePitch].Inverted)) return false; if(!ReadInt(L"axis_pitch", L"range", L"45", filename_c, Rotation[ePitch].Range, 0, 180)) return false; if(!ReadInt(L"axis_yaw", L"joystick", joy, filename_c, Rotation[eYaw].Joy, -1, 3)) return false; if(!ReadInt(L"axis_yaw", L"axis", L"4", filename_c, Rotation[eYaw].Axis, 0, NUM_ANALOG-1)) return false; if(!ReadBool(L"axis_yaw", L"inverted", L"false", filename_c, Rotation[eYaw].Inverted)) return false; if(!ReadInt(L"axis_yaw", L"range", L"45", filename_c, Rotation[eYaw].Range, 0, 180)) return false; if(!ReadInt(L"axis_roll", L"joystick", joy, filename_c, Rotation[eRoll].Joy, -1, 3)) return false; if(!ReadInt(L"axis_roll" , L"axis", L"5", filename_c, Rotation[eRoll].Axis, 0, NUM_ANALOG-1)) return false; if(!ReadBool(L"axis_roll", L"inverted", L"false", filename_c, Rotation[eRoll].Inverted)) return false; if(!ReadInt(L"axis_roll", L"range", L"45", filename_c, Rotation[eRoll].Range, 0, 180)) return false; //trigger if(!ReadBool(L"trigger", L"isAxis", L"false", filename_c, TriggerIsAxis)) return false; if(TriggerIsAxis) { if(!ReadInt(L"trigger", L"joystick", joy, filename_c, TriggerAxis.Joy, -1, 3)) return false; if(!ReadInt(L"trigger", L"axis", L"7", filename_c, TriggerAxis.Axis, 0, NUM_ANALOG-1)) return false; if(!ReadBool(L"trigger",L"inverted", L"false", filename_c, TriggerAxis.Inverted)) return false; if(!ReadBool(L"trigger",L"useFullAxis", L"false",filename_c,TriggerUseFullAxis)) return false; } else { if(!ReadInt(L"trigger", L"joystick", joy, filename_c, TriggerButton.Joy, -1, 3)) return false; if(!ReadInt(L"trigger", L"button", L"5", filename_c, TriggerButton.Button, 0, NUM_DIGITAL-1)) return false; } //analog stick X if(!ReadBool(L"analog_stick_x", L"isAxis", L"true", filename_c, JoystickXIsAxis)) return false; if(JoystickXIsAxis) { if(!ReadInt(L"analog_stick_x", L"joystick", joy, filename_c, JoystickXAxis.Joy, -1, 3)) return false; if(!ReadInt(L"analog_stick_x", L"axis", L"6", filename_c, JoystickXAxis.Axis, 0, NUM_ANALOG-1)) return false; } else { if(!ReadInt(L"analog_stick_x", L"joystick_left", joy, filename_c, JoystickXButtons.Min.Joy, -1, 3)) return false; if(!ReadInt(L"analog_stick_x", L"button_left", L"9", filename_c, JoystickXButtons.Min.Button, 0, NUM_DIGITAL-1)) return false; if(!ReadInt(L"analog_stick_x", L"joystick_right", joy, filename_c, JoystickXButtons.Max.Joy, -1, 3)) return false; if(!ReadInt(L"analog_stick_x", L"button_right", L"10", filename_c, JoystickXButtons.Max.Button, 0, NUM_DIGITAL-1)) return false; } //analog stick Y if(!ReadBool(L"analog_stick_y", L"isAxis", L"true", filename_c, JoystickYIsAxis)) return false; if(JoystickYIsAxis) { if(!ReadInt(L"analog_stick_y", L"joystick", joy, filename_c, JoystickYAxis.Joy, -1, 3)) return false; if(!ReadInt(L"analog_stick_y", L"axis", L"7", filename_c, JoystickYAxis.Axis, 0, NUM_ANALOG-1)) return false; } else { if(!ReadInt(L"analog_stick_y", L"joystick_left", joy, filename_c, JoystickYButtons.Min.Joy, -1, 3)) return false; if(!ReadInt(L"analog_stick_y", L"button_left", L"11", filename_c, JoystickYButtons.Min.Button, 0, NUM_DIGITAL-1)) return false; if(!ReadInt(L"analog_stick_y", L"joystick_right", joy, filename_c, JoystickYButtons.Max.Joy, -1, 3)) return false; if(!ReadInt(L"analog_stick_y", L"button_right", L"12", filename_c, JoystickYButtons.Max.Button, 0, NUM_DIGITAL-1)) return false; } return true; }
bool IO_UncertSimResults::AddUncertRun(const DC_UncertSimResults& resultHeader, const UncertRunResults& results, bool addExisting) { GenAppClearMsgs(); bool openExisting = addExisting && ConvFileC::CFfileExists(fileName); DC_UncertSimResults currHeader; if (openExisting) { if (!ReadFileHeader(currHeader, false)) { GenAppErrorMsg("UncertSimResults", "File contents incompatible"); return false; } if ((currHeader.IsMultiple() && (!resultHeader.IsMultiple())) || ((!currHeader.IsMultiple()) && resultHeader.IsMultiple())) { GenAppErrorMsg("UncertSimResults", "Cannot combine multiple & not multiple"); return false; } if (currHeader.IsMultiple()) { if (currHeader.multipleRunVariableIDs.Size() != resultHeader.multipleRunVariableIDs.Size()) GenAppErrorMsg("UncertSimResults", "Multiple run results different size??"); } } try { SC_IntArray runStartRecs; runStartRecs.SetResizable(); int nextRec, runIndexRecord; if (openExisting) { ReadFileHeader(currHeader, true); ReadNextRecord(); runIndexRecord = GetCurrentRec(); nextRec = ReadInt(); ReadIntArray(runStartRecs); } else { OpenFile(fileName, false); // set up initial header info nRuns = 0; WriteFileHeader(resultHeader); FlushBuffer(nextRec); runIndexRecord = nextRec; // initial header BufferReset(nextRec); WriteInt(0); FlushBuffer(nextRec); // backup and set nextRec BufferReset(runIndexRecord); WriteInt(nextRec); // reflush FlushBuffer(); } int runStart = nextRec; // set to next avail BufferReset(nextRec); // add the run to the end WriteOneRun(results, nextRec); nRuns++; // update header BufferReset(0); WriteFileHeader(resultHeader); FlushBuffer(); // update next avail record BufferReset(runIndexRecord); WriteInt(nextRec); // update run start records runStartRecs += runStart; WriteIntArray(runStartRecs); FlushBuffer(); CloseFile(); return true; } catch (BufFileC::BufferFileError& err) { GenAppErrorMsg("WriteUncertResults", err.errMsg); } CloseFile(); return false; }
/** * Read an integer field from the connection settings provider * @param aField The name of the field to read * @param aValue On return, contains the value of the field read * @returns KErrNone, if successful; otherwise one of the standard Symbian OS error codes * @see DoReadInt */ EXPORT_C TInt MNifIfNotify::ReadInt(const TDesC& aField, TUint32& aValue) { return ReadInt( aField, aValue, NULL ); }
void Settings::Load() { // Read rectangle co-ordinates ReadInt( lpctszMainWindow, _T( "Co-ordsLeft" ), ( int& )m_crMainWindowRect.left ); ReadInt( lpctszMainWindow, _T( "Co-ordsTop" ), ( int& )m_crMainWindowRect.top ); ReadInt( lpctszMainWindow, _T( "Co-ordsRight" ), ( int& )m_crMainWindowRect.right ); ReadInt( lpctszMainWindow, _T( "Co-ordsBottom" ), ( int& )m_crMainWindowRect.bottom ); // Load search options ReadString( lpctszSearchSection, _T( "SrchString" ), m_csLastSrchString ); ReadInt( lpctszSearchSection, _T( "SrchOption" ), m_nLastSearchChoice ); // Load Toolbar settings ReadInt( lpctszToolBarSection, _T( "Depends" ), m_bIsDependsPressed ); ReadInt( lpctszToolBarSection, _T( "FullPath" ), m_bIsFullPathPressed ); // Load divider settings ReadInt( lpctszDividerSection, _T( "Direction" ), m_nDividerDirection ); ReadInt( lpctszDividerSection, _T( "MainDividerSpan" ), m_nMainDividerSpan ); ReadInt( lpctszDividerSection, _T( "ProcessDividerSpan" ), m_nProcessDividerSpan ); ReadInt( lpctszDividerSection, _T( "ModuleDividerSpan" ), m_nModuleDividerSpan ); // Load process detail settings ReadInt( lpctszProcessSection, _T( "ProcessSize" ), m_bProcessSize ); ReadInt( lpctszProcessSection, _T( "ProcessType" ), m_bProcessType ); ReadInt( lpctszProcessSection, _T( "ProcessHWND" ), m_bProcessHwnd ); ReadInt( lpctszProcessSection, _T( "ProcessVersion" ), m_bProcessVersion ); ReadInt( lpctszProcessSection, _T( "ProcessMemInfo" ), m_bProcessMemInfo ); ReadInt( lpctszProcessSection, _T( "ProcessProcTimes" ), m_bProcessTimes ); ReadInt( lpctszProcessSection, _T( "ProcessFileTimes" ), m_bProcessFileTimes ); ReadInt( lpctszProcessSection, _T( "ProcessResInfo" ), m_bProcessGDIResInfo ); ReadInt( lpctszProcessSection, _T( "ProcessPriority" ), m_bProcessPriority ); ReadInt( lpctszProcessSection, _T( "ProcessIOCounters" ), m_bProcessIOCounters ); ReadInt( lpctszProcessSection, _T( "ProcessPrivileges" ), m_bProcessPrivileges ); // Load module display settings ReadInt( lpctszModuleSection, _T( "ModuleCompany" ), m_bModuleCompany ); ReadInt( lpctszModuleSection, _T( "ModuleDescription" ), m_bModuleDescription ); ReadInt( lpctszModuleSection, _T( "ModuleEntryPoint" ), m_bModuleEntryPoint ); ReadInt( lpctszModuleSection, _T( "ModuleFileSize" ), m_bModuleFileSize ); ReadInt( lpctszModuleSection, _T( "ModuleImageSize" ), m_bModuleImageSize ); ReadInt( lpctszModuleSection, _T( "ModuleIndex" ), m_bModuleIndex ); ReadInt( lpctszModuleSection, _T( "ModuleLoadAddress" ), m_bModuleLoadAddress ); ReadInt( lpctszModuleSection, _T( "ModuleName" ), m_bModuleName ); ReadInt( lpctszModuleSection, _T( "ModulePath" ), m_bModulePath ); ReadInt( lpctszModuleSection, _T( "ModuleVersion" ), m_bModuleVersion ); // Read in general settings ReadInt( lpctszGeneralSection, _T( "PromptBeforeKillingProcess" ), m_bPromptBeforeKillingProcess ); }
bool GERBER_IMAGE::ExecuteRS274XCommand( int command, char buff[GERBER_BUFZ], char*& text ) { int code; int seq_len; // not used, just provided int seq_char; bool ok = true; char line[GERBER_BUFZ]; wxString msg; double fcoord; bool x_fmt_known = false; bool y_fmt_known = false; // conv_scale = scaling factor from inch to Internal Unit double conv_scale = IU_PER_MILS * 1000; if( m_GerbMetric ) conv_scale /= 25.4; // DBG( printf( "%22s: Command <%c%c>\n", __func__, (command >> 8) & 0xFF, command & 0xFF ); ) switch( command ) { case FORMAT_STATEMENT: seq_len = 2; while( *text != '*' ) { switch( *text ) { case ' ': text++; break; case 'L': // No Leading 0 m_DecimalFormat = false; m_NoTrailingZeros = false; text++; break; case 'T': // No trailing 0 m_DecimalFormat = false; m_NoTrailingZeros = true; text++; break; case 'A': // Absolute coord m_Relative = false; text++; break; case 'I': // Relative coord m_Relative = true; text++; break; case 'G': case 'N': // Sequence code (followed by one digit: the sequence len) // (sometimes found before the X,Y sequence) // Obscure option text++; seq_char = *text++; if( (seq_char >= '0') && (seq_char <= '9') ) seq_len = seq_char - '0'; break; case 'D': case 'M': // Sequence code (followed by one digit: the sequence len) // (sometimes found after the X,Y sequence) // Obscure option code = *text++; if( ( *text >= '0' ) && ( *text<= '9' ) ) text++; // skip the digit else if( code == 'D' ) // Decimal format: sometimes found, but not really documented m_DecimalFormat = true; break; case 'X': case 'Y': { code = *(text++); char ctmp = *(text++) - '0'; if( code == 'X' ) { x_fmt_known = true; // number of digits after the decimal point (0 to 7 allowed) m_FmtScale.x = *text - '0'; m_FmtLen.x = ctmp + m_FmtScale.x; // m_FmtScale is 0 to 7 // (Old Gerber specification was 0 to 6) if( m_FmtScale.x < 0 ) m_FmtScale.x = 0; if( m_FmtScale.x > 7 ) m_FmtScale.x = 7; } else { y_fmt_known = true; m_FmtScale.y = *text - '0'; m_FmtLen.y = ctmp + m_FmtScale.y; if( m_FmtScale.y < 0 ) m_FmtScale.y = 0; if( m_FmtScale.y > 7 ) m_FmtScale.y = 7; } text++; } break; case '*': break; default: msg.Printf( wxT( "Unknown id (%c) in FS command" ), *text ); ReportMessage( msg ); GetEndOfBlock( buff, text, m_Current_File ); ok = false; break; } } if( !x_fmt_known || !y_fmt_known ) ReportMessage( wxT( "RS274X: Format Statement (FS) without X or Y format" ) ); break; case AXIS_SELECT: // command ASAXBY*% or %ASAYBX*% m_SwapAxis = false; if( strnicmp( text, "AYBX", 4 ) == 0 ) m_SwapAxis = true; break; case MIRROR_IMAGE: // command %MIA0B0*%, %MIA0B1*%, %MIA1B0*%, %MIA1B1*% m_MirrorA = m_MirrorB = 0; while( *text && *text != '*' ) { switch( *text ) { case 'A': // Mirror A axis ? text++; if( *text == '1' ) m_MirrorA = true; break; case 'B': // Mirror B axis ? text++; if( *text == '1' ) m_MirrorB = true; break; default: text++; break; } } break; case MODE_OF_UNITS: code = ReadXCommand( text ); if( code == INCH ) m_GerbMetric = false; else if( code == MILLIMETER ) m_GerbMetric = true; conv_scale = m_GerbMetric ? IU_PER_MILS / 25.4 : IU_PER_MILS; break; case FILE_ATTRIBUTE: // Command %TF ... m_IsX2_file = true; { X2_ATTRIBUTE dummy; dummy.ParseAttribCmd( m_Current_File, buff, GERBER_BUFZ, text ); if( dummy.IsFileFunction() ) { delete m_FileFunction; m_FileFunction = new X2_ATTRIBUTE_FILEFUNCTION( dummy ); } else if( dummy.IsFileMD5() ) { m_MD5_value = dummy.GetPrm( 1 ); } else if( dummy.IsFilePart() ) { m_PartString = dummy.GetPrm( 1 ); } } break; case OFFSET: // command: OFAnnBnn (nn = float number) = layer Offset m_Offset.x = m_Offset.y = 0; while( *text != '*' ) { switch( *text ) { case 'A': // A axis offset in current unit (inch or mm) text++; fcoord = ReadDouble( text ); m_Offset.x = KiROUND( fcoord * conv_scale ); break; case 'B': // B axis offset in current unit (inch or mm) text++; fcoord = ReadDouble( text ); m_Offset.y = KiROUND( fcoord * conv_scale ); break; } } break; case SCALE_FACTOR: m_Scale.x = m_Scale.y = 1.0; while( *text != '*' ) { switch( *text ) { case 'A': // A axis scale text++; m_Scale.x = ReadDouble( text ); break; case 'B': // B axis scale text++; m_Scale.y = ReadDouble( text ); break; } } break; case IMAGE_OFFSET: // command: IOAnnBnn (nn = float number) = Image Offset m_ImageOffset.x = m_ImageOffset.y = 0; while( *text != '*' ) { switch( *text ) { case 'A': // A axis offset in current unit (inch or mm) text++; fcoord = ReadDouble( text ); m_ImageOffset.x = KiROUND( fcoord * conv_scale ); break; case 'B': // B axis offset in current unit (inch or mm) text++; fcoord = ReadDouble( text ); m_ImageOffset.y = KiROUND( fcoord * conv_scale ); break; } } break; case IMAGE_ROTATION: // command IR0* or IR90* or IR180* or IR270* if( strnicmp( text, "0*", 2 ) == 0 ) m_ImageRotation = 0; if( strnicmp( text, "90*", 2 ) == 0 ) m_ImageRotation = 90; if( strnicmp( text, "180*", 2 ) == 0 ) m_ImageRotation = 180; if( strnicmp( text, "270*", 2 ) == 0 ) m_ImageRotation = 270; else ReportMessage( _( "RS274X: Command \"IR\" rotation value not allowed" ) ); break; case STEP_AND_REPEAT: // command SR, like %SRX3Y2I5.0J2*% m_Iterpolation = GERB_INTERPOL_LINEAR_1X; // Start a new Gerber layer GetLayerParams().m_StepForRepeat.x = 0.0; GetLayerParams().m_StepForRepeat.x = 0.0; // offset for Step and Repeat command GetLayerParams().m_XRepeatCount = 1; GetLayerParams().m_YRepeatCount = 1; // The repeat count GetLayerParams().m_StepForRepeatMetric = m_GerbMetric; // the step units while( *text && *text != '*' ) { switch( *text ) { case 'I': // X axis offset text++; GetLayerParams().m_StepForRepeat.x = ReadDouble( text ); break; case 'J': // Y axis offset text++; GetLayerParams().m_StepForRepeat.y = ReadDouble( text ); break; case 'X': // X axis repeat count text++; GetLayerParams().m_XRepeatCount = ReadInt( text ); break; case 'Y': // Y axis offset text++; GetLayerParams().m_YRepeatCount = ReadInt( text ); break; default: text++; break; } } break; case IMAGE_JUSTIFY: // Command IJAnBn* m_ImageJustifyXCenter = false; // Image Justify Center on X axis (default = false) m_ImageJustifyYCenter = false; // Image Justify Center on Y axis (default = false) m_ImageJustifyOffset = wxPoint(0,0); // Image Justify Offset on XY axis (default = 0,0) while( *text && *text != '*' ) { // IJ command is (for A or B axis) AC or AL or A<coordinate> switch( *text ) { case 'A': // A axis justify text++; if( *text == 'C' ) { m_ImageJustifyXCenter = true; text++; } else if( *text == 'L' ) { m_ImageJustifyXCenter = true; text++; } else m_ImageJustifyOffset.x = KiROUND( ReadDouble( text ) * conv_scale); break; case 'B': // B axis justify text++; if( *text == 'C' ) { m_ImageJustifyYCenter = true; text++; } else if( *text == 'L' ) { m_ImageJustifyYCenter = true; text++; } else m_ImageJustifyOffset.y = KiROUND( ReadDouble( text ) * conv_scale); break; default: text++; break; } } if( m_ImageJustifyXCenter ) m_ImageJustifyOffset.x = 0; if( m_ImageJustifyYCenter ) m_ImageJustifyOffset.y = 0; break; case KNOCKOUT: m_Iterpolation = GERB_INTERPOL_LINEAR_1X; // Start a new Gerber layer msg = _( "RS274X: Command KNOCKOUT ignored by GerbView" ) ; ReportMessage( msg ); break; case PLOTTER_FILM: // Command PF <string> // This is an info about film that must be used to plot this file // Has no meaning here. We just display this string msg = wxT( "Plotter Film info:<br>" ); while( *text != '*' ) { msg.Append( *text++ ); } ReportMessage( msg ); break; case ROTATE: // Layer rotation: command like %RO45*% m_Iterpolation = GERB_INTERPOL_LINEAR_1X; // Start a new Gerber layer m_LocalRotation =ReadDouble( text ); // Store layer rotation in degrees break; case IMAGE_NAME: m_ImageName.Empty(); while( *text != '*' ) { m_ImageName.Append( *text++ ); } break; case LAYER_NAME: m_Iterpolation = GERB_INTERPOL_LINEAR_1X; // Start a new Gerber layer GetLayerParams( ).m_LayerName.Empty(); while( *text != '*' ) { GetLayerParams( ).m_LayerName.Append( *text++ ); } break; case IMAGE_POLARITY: if( strnicmp( text, "NEG", 3 ) == 0 ) m_ImageNegative = true; else m_ImageNegative = false; DBG( printf( "%22s: IMAGE_POLARITY m_ImageNegative=%s\n", __func__, m_ImageNegative ? "true" : "false" ); ) break; case LAYER_POLARITY: if( *text == 'C' ) GetLayerParams().m_LayerNegative = true; else GetLayerParams().m_LayerNegative = false; DBG( printf( "%22s: LAYER_POLARITY m_LayerNegative=%s\n", __func__, GetLayerParams().m_LayerNegative ? "true" : "false" ); ) break;
static BOOL ReadCharMetrics(FILE *file, CHAR buffer[], INT bufsize, AFM *afm, AFMMETRICS **p_metrics) { BOOL retval, found; OLD_AFMMETRICS *old_metrics, *encoded_metrics; AFMMETRICS *metrics; INT i, len; retval = ReadInt(file, buffer, bufsize, "StartCharMetrics", &(afm->NumofMetrics), &found); if (retval == FALSE || found == FALSE) { *p_metrics = NULL; return retval; } old_metrics = HeapAlloc(PSDRV_Heap, 0, afm->NumofMetrics * sizeof(*old_metrics)); if (old_metrics == NULL) return FALSE; for (i = 0; i < afm->NumofMetrics; ++i) { retval = ReadLine(file, buffer, bufsize, &len); if (retval == FALSE) goto cleanup_old_metrics; if(len > 0) { retval = ParseCharMetrics(buffer, len, old_metrics + i); if (retval == FALSE || old_metrics[i].C == INT_MAX) goto cleanup_old_metrics; continue; } switch (len) { case 0: --i; continue; case INT_MIN: WARN("Ignoring long line '%32s...'\n", buffer); goto cleanup_old_metrics; /* retval == TRUE */ case EOF: WARN("Unexpected EOF\n"); goto cleanup_old_metrics; /* retval == TRUE */ } } Unicodify(afm, old_metrics); /* wait until glyph names have been read */ qsort(old_metrics, afm->NumofMetrics, sizeof(*old_metrics), OldAFMMetricsByUV); for (i = 0; old_metrics[i].UV == -1; ++i); /* count unencoded glyphs */ afm->NumofMetrics -= i; encoded_metrics = old_metrics + i; afm->Metrics = *p_metrics = metrics = HeapAlloc(PSDRV_Heap, 0, afm->NumofMetrics * sizeof(*metrics)); if (afm->Metrics == NULL) goto cleanup_old_metrics; /* retval == TRUE */ for (i = 0; i < afm->NumofMetrics; ++i, ++metrics, ++encoded_metrics) { metrics->C = encoded_metrics->C; metrics->UV = encoded_metrics->UV; metrics->WX = encoded_metrics->WX; metrics->N = encoded_metrics->N; } HeapFree(PSDRV_Heap, 0, old_metrics); afm->WinMetrics.sAvgCharWidth = PSDRV_CalcAvgCharWidth(afm); return TRUE; cleanup_old_metrics: /* handle fatal or non-fatal errors */ HeapFree(PSDRV_Heap, 0, old_metrics); *p_metrics = NULL; return retval; }
/// Read SMFHeader head from file void CSMFMapFile::ReadMapHeader(SMFHeader& head, CFileHandler& file) { file.Read(head.magic,sizeof(head.magic)); head.version = ReadInt(file); head.mapid = ReadInt(file); head.mapx = ReadInt(file); head.mapy = ReadInt(file); head.squareSize = ReadInt(file); head.texelPerSquare = ReadInt(file); head.tilesize = ReadInt(file); head.minHeight = ReadFloat(file); head.maxHeight = ReadFloat(file); head.heightmapPtr = ReadInt(file); head.typeMapPtr = ReadInt(file); head.tilesPtr = ReadInt(file); head.minimapPtr = ReadInt(file); head.metalmapPtr = ReadInt(file); head.featurePtr = ReadInt(file); head.numExtraHeaders = ReadInt(file); }
unsigned char * BmpToTexture(char *filename, int *width, int *height) { int s, t, e; // counters int numextra; // # extra bytes each line in the file is padded with FILE *fp; unsigned char *texture; int nums, numt; unsigned char *tp; fp = fopen(filename, "rb"); if (fp == NULL) { fprintf(stderr, "Cannot open Bmp file '%s'\n", filename); return NULL; } FileHeader.bfType = ReadShort(fp); // if bfType is not 0x4d42, the file is not a bmp: if (FileHeader.bfType != 0x4d42) { fprintf(stderr, "Wrong type of file: 0x%0x\n", FileHeader.bfType); fclose(fp); return NULL; } FileHeader.bfSize = ReadInt(fp); FileHeader.bfReserved1 = ReadShort(fp); FileHeader.bfReserved2 = ReadShort(fp); FileHeader.bfOffBits = ReadInt(fp); InfoHeader.biSize = ReadInt(fp); InfoHeader.biWidth = ReadInt(fp); InfoHeader.biHeight = ReadInt(fp); nums = InfoHeader.biWidth; numt = InfoHeader.biHeight; InfoHeader.biPlanes = ReadShort(fp); InfoHeader.biBitCount = ReadShort(fp); InfoHeader.biCompression = ReadInt(fp); InfoHeader.biSizeImage = ReadInt(fp); InfoHeader.biXPelsPerMeter = ReadInt(fp); InfoHeader.biYPelsPerMeter = ReadInt(fp); InfoHeader.biClrUsed = ReadInt(fp); InfoHeader.biClrImportant = ReadInt(fp); // fprintf( stderr, "Image size found: %d x %d\n", ImageWidth, ImageHeight ); texture = new unsigned char[3 * nums * numt]; if (texture == NULL) { fprintf(stderr, "Cannot allocate the texture array!\b"); return NULL; } // extra padding bytes: numextra = 4 * (((3 * InfoHeader.biWidth) + 3) / 4) - 3 * InfoHeader.biWidth; // we do not support compression: if (InfoHeader.biCompression != birgb) { fprintf(stderr, "Wrong type of image compression: %d\n", InfoHeader.biCompression); fclose(fp); return NULL; } rewind(fp); fseek(fp, 14 + 40, SEEK_SET); if (InfoHeader.biBitCount == 24) { for (t = 0, tp = texture; t < numt; t++) { for (s = 0; s < nums; s++, tp += 3) { *(tp + 2) = fgetc(fp); // b *(tp + 1) = fgetc(fp); // g *(tp + 0) = fgetc(fp); // r } for (e = 0; e < numextra; e++) { fgetc(fp); } } } fclose(fp); *width = nums; *height = numt; return texture; }
/// Read MapTileHeader head from file void CSMFMapFile::ReadMapTileHeader(MapTileHeader& head, CFileHandler& file) { head.numTileFiles = ReadInt(file); head.numTiles = ReadInt(file); }
/*============================================================================= * READ_GADGET *=============================================================================*/ void read_gadget(FILE *icfile) { long unsigned ipart; double tot_mass[6]; int i,j,k; long no_part; int massflag; char DATA[MAXSTRING]; float fdummy[3]; double ddummy[3]; double x_fac, v_fac, m_fac; long pid, ldummy; unsigned int idummy; /*================= read in GADGET IO header =================*/ if(FORMAT == 2) { GADGET_SKIP; fread(DATA,sizeof(char),blklen,icfile); DATA[4] = '\0'; fprintf(stderr,"reading... %s\n",DATA); //GADGET_SKIP; GADGET_SKIP; } GADGET_SKIP; ReadInt(icfile,&(gadget.header.np[0]),SWAPBYTES); ReadInt(icfile,&(gadget.header.np[1]),SWAPBYTES); ReadInt(icfile,&(gadget.header.np[2]),SWAPBYTES); ReadInt(icfile,&(gadget.header.np[3]),SWAPBYTES); /* number of particles in current file */ ReadInt(icfile,&(gadget.header.np[4]),SWAPBYTES); ReadInt(icfile,&(gadget.header.np[5]),SWAPBYTES); ReadDouble(icfile,&(gadget.header.massarr[0]),SWAPBYTES); ReadDouble(icfile,&(gadget.header.massarr[1]),SWAPBYTES); ReadDouble(icfile,&(gadget.header.massarr[2]),SWAPBYTES); ReadDouble(icfile,&(gadget.header.massarr[3]),SWAPBYTES); ReadDouble(icfile,&(gadget.header.massarr[4]),SWAPBYTES); ReadDouble(icfile,&(gadget.header.massarr[5]),SWAPBYTES); ReadDouble(icfile,&(gadget.header.expansion),SWAPBYTES); ReadDouble(icfile,&(gadget.header.redshift),SWAPBYTES); ReadInt(icfile,&(gadget.header.flagsfr),SWAPBYTES); ReadInt(icfile,&(gadget.header.flagfeedback),SWAPBYTES); ReadInt(icfile,&(gadget.header.nall[0]),SWAPBYTES); ReadInt(icfile,&(gadget.header.nall[1]),SWAPBYTES); ReadInt(icfile,&(gadget.header.nall[2]),SWAPBYTES); /* total number of particles in simulation */ ReadInt(icfile,&(gadget.header.nall[3]),SWAPBYTES); ReadInt(icfile,&(gadget.header.nall[4]),SWAPBYTES); ReadInt(icfile,&(gadget.header.nall[5]),SWAPBYTES); ReadInt(icfile,&(gadget.header.flagcooling),SWAPBYTES); ReadInt(icfile,&(gadget.header.NumFiles),SWAPBYTES); ReadDouble(icfile,&(gadget.header.BoxSize),SWAPBYTES); ReadDouble(icfile,&(gadget.header.Omega0),SWAPBYTES); ReadDouble(icfile,&(gadget.header.OmegaLambda),SWAPBYTES); ReadDouble(icfile,&(gadget.header.HubbleParam),SWAPBYTES); ReadChars(icfile,&(gadget.header.unused[0]),SIZEOFGADGETHEADER- 6*4- 6*8- 2*8- 2*4- 6*4- 2*4 - 4*8); GADGET_SKIP; /*================= read in GADGET IO header =================*/ //exit(0); /* keep track of no. of particles in each GADGET file */ gadget.np[0][gadget.i_gadget_file] = gadget.header.np[0]; gadget.np[1][gadget.i_gadget_file] = gadget.header.np[1]; gadget.np[2][gadget.i_gadget_file] = gadget.header.np[2]; gadget.np[3][gadget.i_gadget_file] = gadget.header.np[3]; gadget.np[4][gadget.i_gadget_file] = gadget.header.np[4]; gadget.np[5][gadget.i_gadget_file] = gadget.header.np[5]; /* conversion factors to Mpc/h, km/sec, Msun/h */ x_fac = GADGET_LUNIT; v_fac = sqrt(gadget.header.expansion); m_fac = GADGET_MUNIT; /* count total no. of particles in current file (and set massflag) */ massflag = 0; no_part = 0; gadget.nall = 0; for(i=0;i<6;i++) { no_part += gadget.header.np[i]; gadget.nall += gadget.header.nall[i]; if(gadget.header.massarr[i] < MZERO && gadget.header.np[i] > 0) massflag=1; } /* be verbose */ fprintf(stderr,"expansion factor: %lf\n", gadget.header.expansion); fprintf(stderr,"redshift: %lf\n", gadget.header.redshift); fprintf(stderr,"boxsize: %lf (%lf Mpc/h)\n", gadget.header.BoxSize,gadget.header.BoxSize*GADGET_LUNIT); fprintf(stderr,"omega0: %lf\n", gadget.header.Omega0); fprintf(stderr,"lambda0: %lf\n", gadget.header.OmegaLambda); fprintf(stderr,"HubbleParam: %lf\n\n", gadget.header.HubbleParam); fprintf(stderr,"gas: np[0]=%9d\t nall[0]=%9d\t massarr[0]=%g\n",gadget.header.np[0],gadget.header.nall[0],gadget.header.massarr[0]); fprintf(stderr,"halo: np[1]=%9d\t nall[1]=%9d\t massarr[1]=%g\n",gadget.header.np[1],gadget.header.nall[1],gadget.header.massarr[1]); fprintf(stderr,"disk: np[2]=%9d\t nall[2]=%9d\t massarr[2]=%g\n",gadget.header.np[2],gadget.header.nall[2],gadget.header.massarr[2]); fprintf(stderr,"bulge: np[3]=%9d\t nall[3]=%9d\t massarr[3]=%g\n",gadget.header.np[3],gadget.header.nall[3],gadget.header.massarr[3]); fprintf(stderr,"stars: np[4]=%9d\t nall[4]=%9d\t massarr[4]=%g\n",gadget.header.np[4],gadget.header.nall[4],gadget.header.massarr[4]); fprintf(stderr,"bndry: np[5]=%9d\t nall[5]=%9d\t massarr[5]=%g\n",gadget.header.np[5],gadget.header.nall[5],gadget.header.massarr[5]); fprintf(stderr,"\n-> reading %ld particles from GADGET file #%d/%d...\n\n", no_part, gadget.i_gadget_file+1, gadget.no_gadget_files); /* allocate particle array (only once when reading the first file, of course!) */ if(gadget.i_gadget_file == 0) { fprintf(stderr,"-> allocating %f GB of RAM for particles\n\n",(float)(gadget.nall*sizeof(struct particle_data))/1024./1024./1024.); if(!(Part=(struct particle_data *) calloc(gadget.nall, sizeof(struct particle_data)))) { fprintf(stderr,"\nfailed to allocate memory for GADGET data\n"); exit(1); } } /*================= read in GADGET particles =================*/ if(FORMAT == 2) { GADGET_SKIP; fread(DATA,sizeof(char),blklen,icfile); DATA[4] = '\0'; fprintf(stderr,"reading... %s",DATA); //GADGET_SKIP; GADGET_SKIP; } else { fprintf(stderr,"reading "); } GADGET_SKIP; fprintf(stderr,"(%8.2g MB) ... ",blklen/1024./1024.); for(i=0;i<no_part;i++) { /* read */ if(DGADGET) { ReadDouble(icfile,&(ddummy[0]),SWAPBYTES); ReadDouble(icfile,&(ddummy[1]),SWAPBYTES); ReadDouble(icfile,&(ddummy[2]),SWAPBYTES); } else { ReadFloat(icfile,&(fdummy[0]),SWAPBYTES); ReadFloat(icfile,&(fdummy[1]),SWAPBYTES); ReadFloat(icfile,&(fdummy[2]),SWAPBYTES); ddummy[0] = fdummy[0]; ddummy[1] = fdummy[1]; ddummy[2] = fdummy[2]; } /* get proper position in Part[] array */ pid = get_pid(i); /* storage and conversion to comoving physical units */ Part[pid].Pos[0] = ddummy[0] * x_fac; Part[pid].Pos[1] = ddummy[1] * x_fac; Part[pid].Pos[2] = ddummy[2] * x_fac; } fprintf(stderr,"Pos[X]=%12.6g Pos[Y]=%12.6g Pos[Z]=%12.6g ... ",Part[no_part-1].Pos[X],Part[no_part-1].Pos[Y],Part[no_part-1].Pos[Z]); GADGET_SKIP; fprintf(stderr,"(%8.2g MB) done.\n",blklen/1024./1024.); /*================= read in GADGET particles =================*/ /*================= read in GADGET velocities =================*/ if(FORMAT == 2) { GADGET_SKIP; fread(DATA,sizeof(char),blklen,icfile); DATA[4] = '\0'; fprintf(stderr,"reading... %s",DATA); //GADGET_SKIP; GADGET_SKIP; } else { fprintf(stderr,"reading "); } GADGET_SKIP; fprintf(stderr,"(%8.2g MB) ... ",blklen/1024./1024.); for(i=0;i<no_part;i++) { /* read */ if(DGADGET) { ReadDouble(icfile,&(ddummy[0]),SWAPBYTES); ReadDouble(icfile,&(ddummy[1]),SWAPBYTES); ReadDouble(icfile,&(ddummy[2]),SWAPBYTES); } else { ReadFloat(icfile,&(fdummy[0]),SWAPBYTES); ReadFloat(icfile,&(fdummy[1]),SWAPBYTES); ReadFloat(icfile,&(fdummy[2]),SWAPBYTES); ddummy[0] = fdummy[0]; ddummy[1] = fdummy[1]; ddummy[2] = fdummy[2]; } /* get proper position in Part[] array */ pid = get_pid(i); /* storage and conversion to comoving physical units */ Part[pid].Vel[0] = ddummy[0] * v_fac; Part[pid].Vel[1] = ddummy[1] * v_fac; Part[pid].Vel[2] = ddummy[2] * v_fac; } fprintf(stderr,"Vel[X]=%12.6g Vel[Y]=%12.6g Vel[Z]=%12.6g ... ",Part[no_part-1].Vel[X],Part[no_part-1].Vel[Y],Part[no_part-1].Vel[Z]); GADGET_SKIP; fprintf(stderr,"(%8.2g MB) done.\n",blklen/1024./1024.); /*================= read in GADGET velocities =================*/ /*================= read in GADGET id's =================*/ if(FORMAT == 2) { GADGET_SKIP; fread(DATA,sizeof(char),blklen,icfile); DATA[4] = '\0'; fprintf(stderr,"reading... %s",DATA); //GADGET_SKIP; GADGET_SKIP; } else { fprintf(stderr,"reading "); } GADGET_SKIP; fprintf(stderr,"(%8.2g MB) ... ",blklen/1024./1024.); for(i=0;i<no_part;i++) { /* get proper position in Part[] array */ pid = get_pid(i); if(LGADGET) { ReadLong(icfile,&ldummy,SWAPBYTES); Part[pid].ID = ldummy; } else { ReadUInt(icfile,&idummy,SWAPBYTES); Part[pid].ID = (long) idummy; } /* check the ID range of the "halo" particles */ if(gadget.header.np[0] <= i && i < gadget.header.np[0]+gadget.header.np[1]) { if(Part[pid].ID > IDmax) IDmax = Part[pid].ID; if(Part[pid].ID < IDmin) IDmin = Part[pid].ID; } } fprintf(stderr,"ID=%12ld ... ",Part[no_part-1].ID); GADGET_SKIP; fprintf(stderr,"(%8.2g MB) done.\n",blklen/1024./1024.); /*================= read in GADGET id's =================*/ k = 0; /* massflag == 1 indicates that massarr[i] = 0 and hence need to read in particle masses */ if(massflag==1) { /*================= read in GADGET individual particle masses =================*/ if(FORMAT == 2) { GADGET_SKIP; fread(DATA,sizeof(char),blklen,icfile); DATA[4] = '\0'; fprintf(stderr,"reading... %s",DATA); //GADGET_SKIP; GADGET_SKIP; } else { fprintf(stderr,"reading "); } GADGET_SKIP; fprintf(stderr,"(%8.2g MB) ... ",blklen/1024./1024.); for(i=0;i<6;i++) { tot_mass[i] = 0.; if (gadget.header.np[i] > 0 && gadget.header.massarr[i] < MZERO ) { fprintf(stderr," %d ",i); for(j=0; j<gadget.header.np[i]; j++) { /* read */ if(DGADGET) { ReadDouble(icfile,&(ddummy[0]),SWAPBYTES); } else { ReadFloat(icfile,&(fdummy[0]),SWAPBYTES); ddummy[0] = fdummy[0]; } /* get proper position in Part[] array */ pid = get_pid(k); /* store */ Part[pid].Mass = ddummy[0]; tot_mass[i] += ddummy[0]; k++; } } else { /* simply copy appropriate massarr[i] to particles */ for(j=0; j<gadget.header.np[i]; j++) { /* get proper position in Part[] array */ pid = get_pid(k); /* store */ Part[pid].Mass = gadget.header.massarr[i]; k++; } tot_mass[i] = gadget.header.np[i]*gadget.header.massarr[i]; } } GADGET_SKIP; fprintf(stderr,"(%8.2g MB) done.\n",blklen/1024./1024.); /*================= read in GADGET individual particle masses =================*/ } /* simply copy appropriate massarr[i] to particles */ else { k=0; for(i=0;i<6;i++) { for(j=0;j<gadget.header.np[i];j++) { /* get proper position in Part[] array */ pid = get_pid(k); /* store */ Part[pid].Mass = gadget.header.massarr[i]; k++; } tot_mass[i] = gadget.header.np[i]*gadget.header.massarr[i]; } } /*============ convert masses to Msun/h and set particle type ============*/ k=0; // 1. gas (no fiddling with Part[].u, please!) i=0; for(j=0; j<gadget.header.np[i]; j++) { pid = get_pid(k); Part[pid].Mass *= m_fac; k++; } // 2. all other species for(i=1; i<6; i++) { for(j=0; j<gadget.header.np[i]; j++) { /* get proper position in Part[] array */ pid = get_pid(k); Part[pid].Mass *= m_fac; Part[pid].u = -i; k++; } } /*================= read in GADGET gas particle energies =================*/ if(gadget.header.np[0] > 0) { if(FORMAT == 2) { GADGET_SKIP; fread(DATA,sizeof(char),blklen,icfile); DATA[4] = '\0'; fprintf(stderr,"reading... %s",DATA); //GADGET_SKIP; GADGET_SKIP; } else { fprintf(stderr,"reading "); } GADGET_SKIP; fprintf(stderr,"(%8.2g MB) ... ",blklen/1024./1024.); for(i=0; i<gadget.header.np[0]; i++) { /* store */ if(DGADGET) { ReadDouble(icfile,&(ddummy[0]),SWAPBYTES); } else { ReadFloat(icfile,&(fdummy[0]),SWAPBYTES); ddummy[0] = fdummy[0]; } /* get proper position in Part[] array */ pid = get_pid(i); /* store additional gas particle property */ Part[pid].u = ddummy[0]; } GADGET_SKIP; fprintf(stderr,"(%8.2g MB) done.\n",blklen/1024./1024.); } /*================= read in GADGET gas particle energies =================*/ /* be verbose */ fprintf(stderr,"\n"); if(gadget.header.np[0] > 0) fprintf(stderr," gas: tot_mass[0]=%16.8g Msun/h (%16.8g Msun/h per particle)\n",tot_mass[0]*GADGET_MUNIT,tot_mass[0]/(double)gadget.header.np[0]*GADGET_MUNIT); if(gadget.header.np[1] > 0) fprintf(stderr," halo: tot_mass[1]=%16.8g Msun/h (%16.8g Msun/h per particle)\n",tot_mass[1]*GADGET_MUNIT,tot_mass[1]/(double)gadget.header.np[1]*GADGET_MUNIT); if(gadget.header.np[2] > 0) fprintf(stderr," disk: tot_mass[2]=%16.8g Msun/h (%16.8g Msun/h per particle)\n",tot_mass[2]*GADGET_MUNIT,tot_mass[2]/(double)gadget.header.np[2]*GADGET_MUNIT); if(gadget.header.np[3] > 0) fprintf(stderr," bulge: tot_mass[3]=%16.8g Msun/h (%16.8g Msun/h per particle)\n",tot_mass[3]*GADGET_MUNIT,tot_mass[3]/(double)gadget.header.np[3]*GADGET_MUNIT); if(gadget.header.np[4] > 0) fprintf(stderr," stars: tot_mass[4]=%16.8g Msun/h (%16.8g Msun/h per particle)\n",tot_mass[4]*GADGET_MUNIT,tot_mass[4]/(double)gadget.header.np[4]*GADGET_MUNIT); if(gadget.header.np[5] > 0) fprintf(stderr," bndry: tot_mass[5]=%16.8g Msun/h (%16.8g Msun/h per particle)\n",tot_mass[5]*GADGET_MUNIT,tot_mass[5]/(double)gadget.header.np[5]*GADGET_MUNIT); fprintf(stderr,"===================================================================\n"); }
void ReadRCSettings() { char temp[MAX_LINE_LENGTH], path[MAX_LINE_LENGTH], defaultpath[MAX_LINE_LENGTH]; int nLen; // First we look for the config file in the same folder as the plugin... GetModuleFileName(hInstance, rcpath, sizeof(rcpath)); nLen = strlen(rcpath) - 1; while (nLen >0 && rcpath[nLen] != '\\') nLen--; rcpath[nLen + 1] = 0; strcpy(temp, rcpath); strcpy(path, rcpath); strcat(temp, "bbseekbar.rc"); strcat(path, "bbseekbarrc"); // ...checking the two possible filenames bbseekbar.rc and bbseekbarrc ... if (FileExists(temp)) strcpy(rcpath, temp); else if (FileExists(path)) strcpy(rcpath, path); // ...if not found, we try the Blackbox directory... else { // ...but first we save the default path (bbseekbar.rc in the same // folder as the plugin) just in case we need it later (see below)... strcpy(defaultpath, temp); GetBlackboxPath(rcpath, sizeof(rcpath)); strcpy(temp, rcpath); strcpy(path, rcpath); strcat(temp, "bbseekbar.rc"); strcat(path, "bbseekbarrc"); if (FileExists(temp)) strcpy(rcpath, temp); else if (FileExists(path)) strcpy(rcpath, path); else // If no config file was found, we use the default path and settings, and return { strcpy(rcpath, defaultpath); xpos = ypos = 10; width = 160; height = 20; alpha = 160; styleType = 1; trackStyleType = 5; knobStyleType = 1; appearance = 0; playerType = 0; alwaysOnTop = false; transparency = false; snapWindow = true; pluginToggle = false; inSlit = false; showBorder = true; allowtip = true; vertical = false; reversed = false; WriteRCSettings(); //write a file for editing later return; } } // If a config file was found we read the plugin settings from the file... xpos = ReadInt(rcpath, "bbseekbar.x:", 10); ypos = ReadInt(rcpath, "bbseekbar.y:", 10); if (xpos >= GetSystemMetrics(SM_CXVIRTUALSCREEN)) xpos = 10; if (ypos >= GetSystemMetrics(SM_CYVIRTUALSCREEN)) ypos = 10; width = ReadInt(rcpath, "bbseekbar.width:", 160); height = ReadInt(rcpath, "bbseekbar.height:", 20); alpha = ReadInt(rcpath, "bbseekbar.alpha:", 160); styleType = ReadInt(rcpath, "bbseekbar.styleType:", 1); trackStyleType = ReadInt(rcpath, "bbseekbar.trackStyleType:", 5); knobStyleType = ReadInt(rcpath, "bbseekbar.knobStyleType:", 1); appearance = ReadInt(rcpath, "bbseekbar.appearance:", 0); playerType = ReadInt(rcpath, "bbseekbar.playerType:", 0); alwaysOnTop = ReadBool(rcpath, "bbseekbar.alwaysontop:", false); transparency = ReadBool(rcpath, "bbseekbar.transparency:", false); snapWindow = ReadBool(rcpath, "bbseekbar.snapwindow:", true); pluginToggle = ReadBool(rcpath, "bbseekbar.pluginToggle:", false); inSlit = ReadBool(rcpath, "bbseekbar.inSlit:", false); showBorder = ReadBool(rcpath, "bbseekbar.showBorder:", true); allowtip = ReadBool(rcpath, "bbseekbar.allowtooltip:", true); vertical = ReadBool(rcpath, "bbseekbar.vertical:", false); reversed = ReadBool(rcpath, "bbseekbar.reversed:", false); }
bool PPD_Base::ReadFromFile() { basePDReadMaj = ReadInt(); basePDReadMin = ReadInt(); ReadFuncObjRef(basePD.plotPenSetObjRef); basePD.plotBackgroundPen = ReadInt(); basePD.plotUwidth = ReadInt(); basePD.plotVheight = ReadInt(); if (basePDReadMaj > 0) { basePD.rightMargin = ReadInt(); basePD.leftMargin = ReadInt(); basePD.topMargin = ReadInt(); basePD.bottomMargin = ReadInt(); } // moved to 2D only in ver 4 if ((basePDReadMaj > 1) && (basePDReadMaj < 4)) bool dummyshowReportArea = ReadBool(); if (basePDReadMaj > 2) { ReadFileName(basePD.tgaOutput.tgaRootFile); if (basePDReadMaj > 9) basePD.tgaOutput.dumpFormat = PC_DumpTGA::DumpFormat(ReadInt()); basePD.tgaOutput.dumpMethod = PC_DumpTGA::TGADumpMethod(ReadInt()); // we rarely ever really want auto on read ... if (basePD.tgaOutput.dumpMethod == PC_DumpTGA::dtga_FullAuto) basePD.tgaOutput.dumpMethod = PC_DumpTGA::dtga_SemiAuto; basePD.tgaOutput.nextIncrement = ReadInt(); if (basePDReadMaj > 6) basePD.tgaOutput.dumpFrameCount = ReadInt(); } if (basePDReadMaj > 4) { ReadFileName(basePD.psOutput.outputFile); basePD.psOutput.outputFormat = PC_PSOutData::OutputFormat(ReadInt()); basePD.psOutput.outputIsPortrait = ReadBool(); basePD.psOutput.pageWidth = ReadDouble(); basePD.psOutput.pageHeight = ReadDouble(); basePD.psOutput.rightMargin = ReadDouble(); basePD.psOutput.leftMargin = ReadDouble(); basePD.psOutput.topMargin = ReadDouble(); basePD.psOutput.bottomMargin = ReadDouble(); if (basePDReadMaj > 5) { basePD.psOutput.lineWidthMultiplier = ReadDouble(); basePD.psOutput.gammaCorrection = ReadDouble(); basePD.psOutput.zBufferMultiplier = ReadDouble(); basePD.psOutput.textLengthMultiplier = ReadDouble(); } if (basePDReadMaj > 8) basePD.psOutput.arialIsHelvetica = ReadBool(); if (basePDReadMaj > 10) basePD.psOutput.nextPSIncrement = ReadInt(); } if (basePDReadMaj > 7) { basePD.plotDefIsActive = ReadBool(); basePD.axesHaveBeenSet = ReadBool(); } return true; }
void Parse_Serverinfo(server_data *s, char *info) { int i, j; char *pinfo; char *tmp; s->passed_filters = 1; s->support_teams = false; // by default server does't support team info per player if (strncmp(info, "\xFF\xFF\xFF\xFFn", 5)) { SetPing(s, -1); return; } pinfo = strchr(info, '\n'); if (pinfo != NULL) *(pinfo++) = 0; info += 5; while (*info == '\\' && s->keysn < MAX_KEYS) { char *i2, *i3; i2 = strchr(info+1, '\\'); if (i2 == NULL) break; i3 = strchr(i2+1, '\\'); if (i3 == NULL) i3 = info + strlen(info); s->keys[s->keysn] = (char *) Q_malloc(i2-info); strlcpy(s->keys[s->keysn], info+1, i2-info); s->values[s->keysn] = (char *) Q_malloc(i3-i2); strlcpy(s->values[s->keysn], i2+1, i3-i2); s->keysn++; info = i3; } // read players for (i = s->spectatorsn = s->playersn = 0; pinfo && strchr(pinfo, '\n'); i++) { qbool spec; int id, frags, time, ping, slen; char name[100], skin[100], team[100]; char *nameptr = name; int top, bottom; int pos; if (s->playersn + s->spectatorsn >= MAX_PLAYERS) break; // man pos = 0; pos += ReadInt(pinfo+pos, &id); pos += ReadInt(pinfo+pos, &frags); pos += ReadInt(pinfo+pos, &time); pos += ReadInt(pinfo+pos, &ping); pos += ReadString(pinfo+pos, name); pos += ReadString(pinfo+pos, skin); pos += ReadInt(pinfo+pos, &top); pos += ReadInt(pinfo+pos, &bottom); pos += ReadString(pinfo+pos, team); if (team[0]) s->support_teams = true; // seems server support team info per player if (ping > 0) { // seems player if relay on ping spec = false; s->playersn++; } else // spec { spec = true; slen = strlen(name); s->spectatorsn++; ping = -ping; if (name[0] == '\\' && name[1] == 's' && name[2] == '\\') nameptr = name+3; // strip \s\<name> else if (slen > 3 && name[slen-3] == '(' && name[slen-2] == 's' && name[slen-1] == ')') name[slen-3] = 0; // strip <name>(s) for old servers } s->players[i] = (playerinfo *)Q_malloc(sizeof(playerinfo)); s->players[i]->id = id; s->players[i]->frags = frags; s->players[i]->time = time; s->players[i]->ping = ping; s->players[i]->spec = spec; s->players[i]->top = Sbar_ColorForMap(top); s->players[i]->bottom = Sbar_ColorForMap(bottom); strlcpy(s->players[i]->name, nameptr, sizeof(s->players[0]->name)); strlcpy(s->players[i]->skin, skin, sizeof(s->players[0]->skin)); strlcpy(s->players[i]->team, team, sizeof(s->players[0]->team)); pinfo = strchr(pinfo, '\n') + 1; } { void *swap; int n; // sort players by frags n = s->playersn + s->spectatorsn - 2; for (i = 0; i <= n; i++) for (j = n; j >= i; j--) if (s->players[j] && s->players[j+1] && s->players[j]->frags < s->players[j+1]->frags) { swap = (void*)s->players[j]; s->players[j] = s->players[j+1]; s->players[j+1] = (playerinfo*)swap; } // sort keys n = s->keysn - 2; for (i = 0; i <= n; i++) for (j = n; j >= i; j--) if (strcasecmp(s->keys[j], s->keys[j+1]) > 0) { swap = (void*)s->keys[j]; s->keys[j] = s->keys[j+1]; s->keys[j+1] = (char*)swap; swap = (void*)s->values[j]; s->values[j] = s->values[j+1]; s->values[j+1] = (char*)swap; } } // fill-in display s->qwfwd = SB_IsServerQWfwd(s); tmp = ValueForKey(s, "hostname"); if (tmp != NULL) snprintf (s->display.name, sizeof (s->display.name),"%-.*s", COL_NAME, tmp); else return; tmp = ValueForKey(s, "fraglimit"); if (tmp != NULL) snprintf(s->display.fraglimit, sizeof (s->display.fraglimit), "%*.*s", COL_FRAGLIMIT, COL_FRAGLIMIT, strlen(tmp) > COL_FRAGLIMIT ? "999" : tmp); tmp = ValueForKey(s, "timelimit"); if (tmp != NULL) snprintf(s->display.timelimit, sizeof (s->display.timelimit), "%*.*s", COL_TIMELIMIT, COL_TIMELIMIT, strlen(tmp) > COL_TIMELIMIT ? "99" : tmp); tmp = ValueForKey(s, "*gamedir"); s->qizmo = false; if (tmp != NULL) snprintf(s->display.gamedir, sizeof (s->display.gamedir) ,"%.*s", COL_GAMEDIR, tmp==NULL ? "" : tmp); else { tmp = ValueForKey(s, "*progs"); if (tmp != NULL && !strcmp(tmp, "666")) { snprintf(s->display.gamedir, sizeof (s->display.gamedir), "qizmo"); s->qizmo = true; } } tmp = ValueForKey(s, "map"); if (tmp != NULL) snprintf(s->display.map, sizeof (s->display.map), "%-.*s", COL_MAP, tmp==NULL ? "" : tmp); tmp = ValueForKey(s, "maxclients"); if (!tmp || strlen(tmp) > 2) tmp = "99"; i = s->playersn > 99 ? 99 : s->playersn; if (i < 1) { s->occupancy = SERVER_EMPTY; } else if (i > 0 && i < atoi(tmp)) { s->occupancy = SERVER_NONEMPTY; } else { s->occupancy = SERVER_FULL; } if (tmp != NULL) snprintf(s->display.players, sizeof (s->display.players), "%2d/%-2s", i, tmp==NULL ? "" : tmp); }
// Read next tag in data stream NBTTag NBT_Reader::ReadData() { if (!data) return TAG_Unknown; // Remove non-list tags and empty lists if (!tags.empty()) { NBTData * last = GetData(); if (last->tag <= TAG_String) RemoveTag(); last = GetData(); if (last->tag == TAG_List && last->size <= 0) RemoveTag(); } // Check for list NBTData * last = GetData(); bool isList = last && last->tag == TAG_List; NBTData * tagdata = CreateTag(); if (isList) { --last->size; tagdata->tag = last->list; } else { BYTE type = 0; // Get type ReadByte(&type); tagdata->tag = (NBTTag)type; // Get name if (tagdata->tag != TAG_End) ReadString(&tagdata->name); } // Read tag switch (tagdata->tag) { case TAG_End: RemoveTag(); RemoveTag(); if (tags.empty()) return TAG_Unknown; return TAG_End; break; case TAG_Byte: tagdata->size = ReadByte(&tagdata->b); break; case TAG_Short: tagdata->size = ReadShort(&tagdata->s); break; case TAG_Int: tagdata->size = ReadInt(&tagdata->i); break; case TAG_Long: tagdata->size = ReadLong(&tagdata->l); break; case TAG_Float: tagdata->size = ReadFloat(&tagdata->f); break; case TAG_Double: tagdata->size = ReadDouble(&tagdata->d); break; case TAG_ByteArray: tagdata->size = ReadByteArray(&tagdata->bas); break; case TAG_String: tagdata->size = ReadString(&tagdata->bas); break; case TAG_List: tagdata->size = ReadList(&tagdata->list); break; case TAG_Compound: ReadCompound(); break; } return tagdata->tag; }