/* ********************************************************************* */ void WriteVTK_Header (FILE *fvtk, Grid *grid) /*! * Write VTK header in parallel or serial mode. * In parallel mode only processor 0 does the actual writing * (see al_io.c/AL_Write_header). * * * \param [in] fvtk pointer to file * \param [in] grid pointer to an array of Grid structures * * \todo Write the grid using several processors. *********************************************************************** */ { int i, j, k; int nx1, nx2, nx3; char header[1024]; float x1, x2, x3; static float ***node_coord, *xnode, *ynode, *znode; /* ------------------------------------------------ get global dimensions ------------------------------------------------ */ nx1 = grid[IDIR].gend + 1 - grid[IDIR].nghost; nx2 = grid[JDIR].gend + 1 - grid[JDIR].nghost; nx3 = grid[KDIR].gend + 1 - grid[KDIR].nghost; /* ------------------------------------------------------------- Allocate memory and define node coordinates only once. ------------------------------------------------------------- */ if (node_coord == NULL){ node_coord = ARRAY_3D(nx2 + JOFFSET, nx1 + IOFFSET, 3, float); #if VTK_FORMAT == RECTILINEAR_GRID xnode = ARRAY_1D(nx1 + IOFFSET, float); ynode = ARRAY_1D(nx2 + JOFFSET, float); znode = ARRAY_1D(nx3 + KOFFSET, float); for (i = 0; i < nx1 + IOFFSET; i++){ x1 = (float)(grid[IDIR].xl_glob[i+IBEG]); if (IsLittleEndian()) SWAP_VAR(x1); xnode[i] = x1; } for (j = 0; j < nx2 + JOFFSET; j++){ x2 = (float)(grid[JDIR].xl_glob[j+JBEG]); if (IsLittleEndian()) SWAP_VAR(x2); ynode[j] = x2; } for (k = 0; k < nx3 + KOFFSET; k++){ x3 = (float)(grid[KDIR].xl_glob[k+KBEG]); if (IsLittleEndian()) SWAP_VAR(x3); #if DIMENSIONS == 2 znode[k] = 0.0; #else znode[k] = x3; #endif } #endif }
static void nm_toBytes(DH_NUMBERS *n, unsigned char *s) { unsigned int result = 0; unsigned char my_char, *p; int i; p = (unsigned char *)n->values; if ( ! IsLittleEndian() ) { i = 0; do { result = 2 * i; i++; my_char = p[result + 1 ]; p[result + 1] = p[result]; p[result] = my_char; } while ( i < n->length ); } memcpy(s, (char *)n->values, n->length * 2); }
static uint64 crcExtract(byte *data, uint32 size) { if (IsLittleEndian()) memrev(data, size); switch (size) { case 1: return data[0]; case 2: { word crc16; memcpy(&crc16, data, sizeof(crc16)); return crc16; } case 4: { uint32 crc32; memcpy(&crc32, data, sizeof(crc32)); return crc32; } case 8: { uint64 crc64; memcpy(&crc64, data, sizeof(crc64)); return crc64; } default: printf("Invalid CRC buffer size: %lu. It must be 1, 2, or 4\n", size); break; } return 0xFFFFFFFF; }
static void bytesToNumbers( DH_NUMBERS *n, unsigned char *s, int len ) { unsigned int result = 0; unsigned char my_char, *p; int i; n->length = len / 2; p = (unsigned char *)n->values; memcpy((char *)n->values, s, len); if ( ! IsLittleEndian() ) { i = 0; do { result = 2 * i; i++; my_char = p[result + 1 ]; p[result + 1] = p[result]; p[result] = my_char; } while ( i < n->length ); } }
// получает поле с размером данных из канала связи. Возвращает размер данных или 0xFFFFFFFF в случае ошибки static uint32 ReceiveLengthField(int Handle, StreamMethod Method, byte *LengthField, byte *LengthFieldSize, uint32 Timeout) { uint32 Size = 0xFFFFFFFF; *LengthFieldSize = 0; byte b; if (recvByte(Handle, Method, &b, Timeout) > 0) { LengthField[0] = b; if (b < 0x80) { Size = b; *LengthFieldSize = 1; } else { byte datasize = b & 0x0F; uint32 data = 0; // datasize не больше 4 байт tBuffer buf; bufInit(&buf, (byte *)&data, datasize); if (recvBuffer(Handle, Method, buf.ptr, buf.dim, Timeout) > 0) { memcpy(LengthField + 1, &data, datasize); if (IsLittleEndian()) memrev(&data, datasize); Size = data; *LengthFieldSize = datasize + 1; } } } return Size; }
extern "C" int gf256_init_(int version) { if (version != GF256_VERSION) { // User's header does not match library version. return -1; } // Avoid multiple initialization if (Initialized) { return 0; } Initialized = true; if (!IsLittleEndian()) { // Architecture is not supported (code won't work without mods). return -2; } gf255_poly_init(DefaultPolynomialIndex); gf256_explog_init(); gf256_muldiv_init(); gf256_inv_init(); gf256_muladd_mem_init(); return 0; }
void CObject::ToBigEndian(char *pData, unsigned int length) { if (!IsLittleEndian()) { return; } ReverseEndian(pData, length); }
// создаёт поле CRC. Возвращает его размер static byte crcMakeField(byte *data, uint32 datasize, byte *crcbuffer) { byte FieldSize = crcGetFieldSize(datasize); switch (FieldSize) { case 1: crcbuffer[0] = CalcCRC8(data, datasize); break; case 2: { word crc16 = CalcCRC16(data, datasize); if (IsLittleEndian()) memrev(&crc16, sizeof(crc16)); memcpy(crcbuffer, &crc16, sizeof(crc16)); break; } case 4: { uint32 crc32 = CalcCRC32(data, datasize); if (IsLittleEndian()) memrev(&crc32, sizeof(crc32)); memcpy(crcbuffer, &crc32, sizeof(crc32)); break; } case 8: { uint64 crc64 = CalcCRC64(data, datasize); if (IsLittleEndian()) memrev(&crc64, sizeof(crc64)); memcpy(crcbuffer, &crc64, sizeof(crc64)); break; } default: printf("Invalid CRCFieldSize size: %d\n", FieldSize); break; } return FieldSize; }
void SoundRecorder::Update() { static float time = 0.0f; time += 1.0f / 60.0f; if ( m_fh == 0 ) return; const unsigned int samplesPerSec = 48000; const unsigned int fps = 60; const int numSamplesPerFrame = samplesPerSec / fps; float data[2][numSamplesPerFrame]; short conversion[numSamplesPerFrame*2]; m_fmodsys->getWaveData( &data[0][0], numSamplesPerFrame, 0 ); // left channel m_fmodsys->getWaveData( &data[1][0], numSamplesPerFrame, 1 ); // right channel int littleEndian = IsLittleEndian(); const float freq = 420.0f; for ( int i = 0; i < numSamplesPerFrame; ++i ) { float val = sinf(2.0f * 3.14159f * freq * 0.016666f * i / (numSamplesPerFrame-1)); // left channel float coeff_left = val;//data[0][i]; short val_left = (short)(coeff_left * 0x7FFF); // right channel float coeff_right = val;//data[1][i]; short val_right = (short)(coeff_right * 0x7FFF); // handle endianness if ( !littleEndian ) { //val_left = ((val_left & 0xff) << 8) | (val_left >> 8); //val_right = ((val_right & 0xff) << 8) | (val_right >> 8); } conversion[i*2+0] = val_left; conversion[i*2+1] = val_right; } fwrite((void*)&conversion[0], sizeof(conversion[0]), numSamplesPerFrame*2, m_fh); m_dataLength += sizeof(conversion); }
void Elf32_Ehdr::Load(vfsStream& f) { e_magic = Read32(f); e_class = Read8(f); e_data = Read8(f); e_curver = Read8(f); e_os_abi = Read8(f); if (IsLittleEndian()) { e_abi_ver = Read64LE(f); e_type = Read16LE(f); e_machine = Read16LE(f); e_version = Read32LE(f); e_entry = Read32LE(f); e_phoff = Read32LE(f); e_shoff = Read32LE(f); e_flags = Read32LE(f); e_ehsize = Read16LE(f); e_phentsize = Read16LE(f); e_phnum = Read16LE(f); e_shentsize = Read16LE(f); e_shnum = Read16LE(f); e_shstrndx = Read16LE(f); } else { e_abi_ver = Read64(f); e_type = Read16(f); e_machine = Read16(f); e_version = Read32(f); e_entry = Read32(f); e_phoff = Read32(f); e_shoff = Read32(f); e_flags = Read32(f); e_ehsize = Read16(f); e_phentsize = Read16(f); e_phnum = Read16(f); e_shentsize = Read16(f); e_shnum = Read16(f); e_shstrndx = Read16(f); } }
void copy_data_to_sound(const common::Data32& data, common::Sample16& sound) { const auto bytes_per_sample = bytes_per_pcm_sample(); const uint32_t pcm_samples_to_copy = data.count() / bytes_per_sample; CHECK(data.count() % bytes_per_sample == 0); CHECK(IsLittleEndian()); // we convert all output to little endian, has to match the machine endianness! if (settings.codec == settings::Audio::Codec::PCM_S16LE) { // optimization: no need to loop sound.copy(common::Sample16((int16_t*)(data.data() + data.a()), pcm_samples_to_copy, nullptr)); } else { CHECK(pcm_samples_to_copy <= sound.count()); int16_t* out = (int16_t*)sound.data() + sound.a(); if (settings.codec == settings::Audio::Codec::PCM_S24LE) { for (uint32_t i = 0, j = 0; i < data.count(); i += bytes_per_sample, ++j) { out[j] = ((int16_t)data(data.a() + i + 2) << CHAR_BIT) + data(data.a() + i + 1); } } else if (settings.codec == settings::Audio::Codec::PCM_S16BE || settings.codec == settings::Audio::Codec::PCM_S24BE) { for (uint32_t i = 0, j = 0; i < data.count(); i += bytes_per_sample, ++j) { out[j] = ((int16_t)data(data.a() + i) << CHAR_BIT) + data(data.a() + i + 1); } } else { CHECK(false); } } };
int gf256_ctx::gf256_init_() { // Avoid multiple initialization if (initialized) { return 0; } if (!IsLittleEndian()) { fprintf(stderr, "gf256_ctx::gf256_init_: Little Endian architecture expected (code won't work without mods)\n"); return -2; } gf255_poly_init(DefaultPolynomialIndex); gf256_explog_init(); gf256_muldiv_init(); gf256_inv_init(); gf256_muladd_mem_init(); initialized = true; fprintf(stderr, "gf256_ctx::gf256_init_: initialized\n"); return 0; }
/*Length of COUNT is 4*/ void EEA3(u8 *CK, u8 *COUNT, u8 BEARER, u8 DIRECTION, u8 *M, u32 LENGTH, u8 *CM) { u8 IV[16] = {0}; u32 i = 0, j = 0, tKeyStreamU32 = 0; u8 *tKeyStreamU8 = (u8*)&tKeyStreamU32; u32 bLENGTH = 0; //Byte LENGTH u32 lbLENGTH = 0; //Left Byte LENGTH u8 bMask = 0, bFlag = 0; IV[0] = COUNT[0]; IV[1] = COUNT[1]; IV[2] = COUNT[2]; IV[3] = COUNT[3]; IV[4] = ((BEARER << 3) | ((DIRECTION & 1)<<2)) & 0xFC; IV[5] = IV[6] = IV[7] = 0; IV[8] = IV[0]; IV[9] = IV[1]; IV[10] = IV[2]; IV[11] = IV[3]; IV[12] = IV[4]; IV[13] = IV[5]; IV[14] = IV[6]; IV[15] = IV[7]; bLENGTH = LENGTH / 8; lbLENGTH = LENGTH % 8; Initialization(CK, IV); for (i=0; i<bLENGTH; i++) { if ((i%4) == 0) { GenerateKeyStream(&tKeyStreamU32, 1); if (IsLittleEndian()) { RevertData(tKeyStreamU8, 4); } } CM[i] = tKeyStreamU8[i%4] ^ M[i]; } if (lbLENGTH) { if ((i%4) == 0) { GenerateKeyStream(&tKeyStreamU32, 1); if (IsLittleEndian()) { RevertData(tKeyStreamU8, 4); } } bMask = 0; bFlag = 0x80; for (j=0; j<lbLENGTH; j++) { bMask |= bFlag; bFlag >>= 1; } CM[i] = ((tKeyStreamU8[i%4] ^ M[i]) & bMask); } }
int ImageBase::readHDF5(size_t select_img) { bool isStack = false; H5infoProvider provider = getProvider(fhdf5); // Provider name int errCode = 0; hid_t dataset; /* Dataset and datatype identifiers */ hid_t filespace; hsize_t dims[4]; // We are not going to support more than 4 dimensions, at this moment. hsize_t nobjEman; hid_t cparms; int rank; String dsname = filename.getBlockName(); // Setting default dataset name if (dsname.empty()) { dsname = provider.second; switch (provider.first) { case EMAN: // Images in stack are stored in separated groups hid_t grpid; grpid = H5Gopen(fhdf5,"/MDF/images/", H5P_DEFAULT); /*herr_t err = */ H5Gget_num_objs(grpid, &nobjEman); dsname = formatString(dsname.c_str(), IMG_INDEX(select_img)); H5Gclose(grpid); break; default: break; } } else { switch (provider.first) { case EMAN: // Images in stack are stored in separated groups nobjEman=1; break; default: break; } } dataset = H5Dopen2(fhdf5, dsname.c_str(), H5P_DEFAULT); if( dataset < 0) REPORT_ERROR(ERR_IO_NOTEXIST, formatString("readHDF5: Dataset '%s' not found",dsname.c_str())); cparms = H5Dget_create_plist(dataset); /* Get properties handle first. */ // Get dataset rank and dimension. filespace = H5Dget_space(dataset); /* Get filespace handle first. */ // rank = H5Sget_simple_extent_ndims(filespace); rank = H5Sget_simple_extent_dims(filespace, dims, NULL); // Offset only set when it is possible to access to data directly offset = (H5D_CONTIGUOUS == H5Pget_layout(cparms))? H5Dget_offset(dataset) : 0; // status = H5Dread(dataset, tid, H5S_ALL, H5S_ALL, H5P_DEFAULT, bm_out); hid_t h5datatype = H5Dget_type(dataset); // Reading byte order switch(H5Tget_order(h5datatype)) { case H5T_ORDER_ERROR: REPORT_ERROR(ERR_IO, "readHDF5: error reading endianness."); break; case H5T_ORDER_LE: swap = IsBigEndian(); break; case H5T_ORDER_BE: swap = IsLittleEndian(); break; default: REPORT_ERROR(ERR_IO, "readHDF5: unknown endianness type, maybe mixed types."); break; } DataType datatype = datatypeH5(h5datatype); MDMainHeader.setValue(MDL_DATATYPE,(int) datatype); // Setting isStack depending on provider switch (provider.first) { case MISTRAL: // rank 3 arrays are stacks isStack = true; break; // case EMAN: // Images in stack are stored in separated groups default: break; } ArrayDim aDim; size_t nDimFile; aDim.xdim = dims[rank-1]; aDim.ydim = (rank>1)?dims[rank-2]:1; aDim.zdim = (rank>3 || (rank==3 && !isStack))?dims[rank-3]:1; if ( provider.first == EMAN ) nDimFile = nobjEman; else nDimFile = ( rank<3 || !isStack )?1:dims[0] ; if (select_img > nDimFile) REPORT_ERROR(ERR_INDEX_OUTOFBOUNDS, formatString("readHDF5 (%s): Image number %lu exceeds stack size %lu", filename.c_str(), select_img, nDimFile)); aDim.ndim = replaceNsize = (select_img == ALL_IMAGES)? nDimFile :1 ; setDimensions(aDim); //Read header only if(dataMode == HEADER || (dataMode == _HEADER_ALL && aDim.ndim > 1)) return errCode; // EMAN stores each image in a separate dataset if ( provider.first == EMAN ) select_img = 1; size_t imgStart = IMG_INDEX(select_img); size_t imgEnd = (select_img != ALL_IMAGES) ? imgStart + 1 : aDim.ndim; MD.clear(); MD.resize(imgEnd - imgStart,MDL::emptyHeader); if (dataMode < DATA) // Don't read data if not necessary but read the header return errCode; if ( H5Pget_layout(cparms) == H5D_CONTIGUOUS ) //We can read it directly readData(fimg, select_img, datatype, 0); else // We read it by hyperslabs { // Allocate memory for image data (Assume xdim, ydim, zdim and ndim are already set //if memory already allocated use it (no resize allowed) mdaBase->coreAllocateReuse(); hid_t memspace; hsize_t offset[4]; // Hyperslab offset in the file hsize_t count[4]; // Size of the hyperslab in the file // Define the offset and count of the hyperslab to be read. switch (rank) { case 4: count[0] = 1; case 3: // if (stack) count[rank-3] = aDim.zdim; offset[rank-2] = 0; case 2: count[rank-2] = aDim.ydim; offset[rank-2] = 0; break; } count[rank-1] = aDim.xdim; offset[rank-1] = 0; aDim.xdim = dims[rank-1]; aDim.ydim = (rank>1)?dims[rank-2]:1; aDim.zdim = (rank == 4)?dims[1]:1; // size_t nDimFile = (rank>2)?dims[0]:1 ; // Define the memory space to read a hyperslab. memspace = H5Screate_simple(rank,count,NULL); size_t data = (size_t) this->mdaBase->getArrayPointer(); size_t pad = aDim.zyxdim*gettypesize(myT()); for (size_t idx = imgStart, imN = 0; idx < imgEnd; ++idx, ++imN) { // Set the offset of the hyperslab to be read offset[0] = idx; if ( H5Sselect_hyperslab(filespace, H5S_SELECT_SET, offset, NULL, count, NULL) < 0 ) REPORT_ERROR(ERR_IO_NOREAD, formatString("readHDF5: Error selecting hyperslab %d from filename %s", imgStart, filename.c_str())); // movePointerTo(ALL_SLICES,imN); // Read if ( H5Dread(dataset, H5Datatype(myT()), memspace, filespace, H5P_DEFAULT, (void*)(data + pad*imN)) < 0 ) REPORT_ERROR(ERR_IO_NOREAD,formatString("readHDF5: Error reading hyperslab %d from filename %s", imgStart, filename.c_str())); } H5Sclose(memspace); } H5Pclose(cparms); H5Sclose(filespace); H5Dclose(dataset); return errCode; }
int main(){ printf("---- FUN WITH STRUCT ----\n\n"); // ------------ Allocation ------------------------------------------- int i, size_of_members, count=0; numbers a_num; numbers n_num[SIZE]; numbers * ptr_num; unsigned char * ptr, * s_num; // ------------ Sizes ------------------------------------------------ printf(">>> SIZE\n"); // The different sizes are due to memory padding, as explored in next section size_of_members = sizeof(char)+sizeof(short)+sizeof(long long int)+sizeof(int); printf("Size of members : %d = %d + %d + %d + %d\n", size_of_members,sizeof(char),sizeof(short),sizeof(long long int),sizeof(int)); printf("Size of a struct : %d\n", sizeof(a_num)); printf("Size of padding bytes : %d = %d - %d\n", sizeof(a_num)-size_of_members, sizeof(a_num), size_of_members); printf("Size of a struct array : %d = %d * %d\n\n", sizeof(n_num),sizeof(a_num),SIZE); // ------------ Hex dump and memory padding -------------------------- printf(">>> HEX and PADDING\n"); // First we set to 0 every byte in the struct // to clear out any possible pre-existing junk memset(&a_num, 0, sizeof(a_num)); // Then we initialize with appropriate values to keep track of: // - endianess // - memory padding a_num.c = 254; // 0xfe a_num.s = USHRT_MAX-1; // 0xfffe a_num.lli = ULLONG_MAX-1; // 0xfffffffffffffffe a_num.i = UINT_MAX-1; // 0xfffffffe // Simple way to get through the struct bytes by making use of a pointer. // You will see several zeros between the members (INTERNAL PADDING) and // maybe even at the end (EXTERNAL PADDING). No predictions can be made // on this behavior since padding is not standardized and strongly // machine- and compiler-dependent printf("Struct content : c = %d lli = %llu s = %d i = %u\n",a_num.c, a_num.lli, a_num.s, a_num.i); printf("Struct hex dump : "); ptr = (unsigned char *) &a_num; for(i=0; i<sizeof(a_num); i++) printf("%02x ", ptr[i]); printf("\nMark long long int : "); for(i=0; i<sizeof(a_num); i++) printf("%s ", ( &ptr[i]>=(unsigned char *) &a_num.lli && &ptr[i]<(unsigned char *) &a_num.lli + sizeof(long long int) )?"xx":"--"); printf("\n\n"); // ------------ Use of memset ---------------------------------------- printf(">>> MEMSET\n"); // We can use memset to clear out the whole struct, using the // struct address as starting point and sizeof() as size, see line 46, // or only a specific part (we choose to clear out the first 6 MSB of // long long int member which amounts to set it equal to short member) // by using the pointer and offsetting it to the desired position ptr = ( (unsigned char *) &(a_num.lli) ) + 2*IsLittleEndian(); // brackets emphasizes order of operations memset(ptr, 0, 6*sizeof(char)); printf("Struct content : c = %d lli = %llu s = %d i = %u\n",a_num.c, a_num.lli, a_num.s, a_num.i); printf("Struct hex dump : "); ptr = (unsigned char *) &a_num; for(i=0; i<sizeof(a_num); i++) printf("%02x ", ptr[i]); printf("\nMark long long int : "); for(i=0; i<sizeof(a_num); i++) printf("%s ", ( &ptr[i]>=(unsigned char *) &a_num.lli && &ptr[i]<(unsigned char *) &a_num.lli + sizeof(long long int) )?"xx":"--"); printf("\n\n"); // ------------ Use of memcpy ---------------------------------------- printf(">>> MEMCPY\n"); // Here we show two way of using memcpy(): // - copying : clean and compact way to duplicate struct content memcpy(&n_num[0], &a_num, sizeof(a_num)); // equivalent to n_num[0]=a_num printf("Copied struct content : c = %d lli = %llu s = %d i = %u\n",n_num[0].c, n_num[0].lli, n_num[0].s, n_num[0].i); printf("Copied struct hex dump : "); ptr = (unsigned char *) &n_num[0]; for(i=0; i<sizeof(a_num); i++) printf("%02x ", ptr[i]); printf("\n"); // - serialization : store the struct byte-wise s_num = (unsigned char *) malloc(sizeof(a_num)); memcpy(s_num, &a_num, sizeof(a_num)); printf("Serialized struct hex dump : "); for(i=0; i<sizeof(a_num); i++) printf("%02x ", s_num[i]); printf("\n\n"); // ------------ Struct and Pointers ---------------------------------- printf(">>> STRUCT POINTERS\n"); // The serialized struct can be still easily accessed by using a pointer ptr_num = (numbers *) s_num; printf("Serialized struct content : c = %d lli = %llu s = %d i = %u\n",ptr_num->c, ptr_num->lli, ptr_num->s, ptr_num->i); return 0; }
/* ********************************************************************* */ void WriteData (const Data *d, Output *output, Grid *grid) /*! * Write data to disk using any of the available formats. * * \param [in] d pointer to PLUTO Data structre * \param [in] output the output structure corresponding to a given * format * \param [in] grid pointer to an array of Grid structures *********************************************************************** */ { int i, j, k, nv; int single_file; size_t dsize; char filename[512], sline[512]; static int last_computed_var = -1; double units[MAX_OUTPUT_VARS]; float ***Vpt3; void *Vpt; FILE *fout, *fbin; time_t tbeg, tend; long long offset; /* ----------------------------------------------------------- Increment the file number and initialize units ----------------------------------------------------------- */ output->nfile++; print1 ("> Writing file #%d (%s) to disk...", output->nfile, output->ext); #ifdef PARALLEL MPI_Barrier (MPI_COMM_WORLD); if (prank == 0) time(&tbeg); #endif for (nv = 0; nv < MAX_OUTPUT_VARS; nv++) units[nv] = 1.0; if (output->cgs) GetCGSUnits(units); /* -------------------------------------------------------- Get user var if necessary -------------------------------------------------------- */ if (last_computed_var != g_stepNumber && d->Vuser != NULL) { ComputeUserVar (d, grid); last_computed_var = g_stepNumber; } /* -------------------------------------------------------- Select the output type -------------------------------------------------------- */ if (output->type == DBL_OUTPUT) { /* ------------------------------------------------------------------- */ /*! - \b DBL output: Double-precision data files can be written using single or multiple file mode. - for single file, serial: we open the file just once before the main variable loop, dump variables and then close. - for single file, parallel the distributed array descriptor sz is different for cell-centered or staggered data type and we thus have to open and close the file after each variable has been dumped. - when writing multiple files we open, write to and close the file one each loop cycle. \note In all cases, the pointer to the data array that has to be written must be cast into (void *) and the starting index of the array must be zero. */ /* ------------------------------------------------------------------- */ int sz; single_file = strcmp(output->mode,"single_file") == 0; dsize = sizeof(double); if (single_file){ /* -- single output file -- */ sprintf (filename, "%s/data.%04d.%s", output->dir,output->nfile, output->ext); offset = 0; #ifndef PARALLEL fbin = OpenBinaryFile (filename, 0, "w"); #endif for (nv = 0; nv < output->nvar; nv++) { if (!output->dump_var[nv]) continue; if (output->stag_var[nv] == -1) { /* -- cell-centered data -- */ sz = SZ; Vpt = (void *)output->V[nv][0][0]; } else if (output->stag_var[nv] == 0) { /* -- x-staggered data -- */ sz = SZ_stagx; Vpt = (void *)(output->V[nv][0][0]-1); } else if (output->stag_var[nv] == 1) { /* -- y-staggered data -- */ sz = SZ_stagy; Vpt = (void *)output->V[nv][0][-1]; } else if (output->stag_var[nv] == 2) { /* -- z-staggered data -- */ sz = SZ_stagz; Vpt = (void *)output->V[nv][-1][0]; } #ifdef PARALLEL fbin = OpenBinaryFile (filename, sz, "w"); AL_Set_offset(sz, offset); #endif WriteBinaryArray (Vpt, dsize, sz, fbin, output->stag_var[nv]); #ifdef PARALLEL offset = AL_Get_offset(sz); CloseBinaryFile(fbin, sz); #endif } #ifndef PARALLEL CloseBinaryFile(fbin, sz); #endif }else{ /* -- multiple files -- */ for (nv = 0; nv < output->nvar; nv++) { if (!output->dump_var[nv]) continue; sprintf (filename, "%s/%s.%04d.%s", output->dir, output->var_name[nv], output->nfile, output->ext); if (output->stag_var[nv] == -1) { /* -- cell-centered data -- */ sz = SZ; Vpt = (void *)output->V[nv][0][0]; } else if (output->stag_var[nv] == 0) { /* -- x-staggered data -- */ sz = SZ_stagx; Vpt = (void *)(output->V[nv][0][0]-1); } else if (output->stag_var[nv] == 1) { /* -- y-staggered data -- */ sz = SZ_stagy; Vpt = (void *)output->V[nv][0][-1]; } else if (output->stag_var[nv] == 2) { /* -- z-staggered data -- */ sz = SZ_stagz; Vpt = (void *)output->V[nv][-1][0]; } fbin = OpenBinaryFile (filename, sz, "w"); WriteBinaryArray (Vpt, dsize, sz, fbin, output->stag_var[nv]); CloseBinaryFile (fbin, sz); } } } else if (output->type == FLT_OUTPUT) { /* ---------------------------------------------------------- FLT output for cell-centered data ---------------------------------------------------------- */ single_file = strcmp(output->mode,"single_file") == 0; if (single_file){ /* -- single output file -- */ sprintf (filename, "%s/data.%04d.%s", output->dir, output->nfile, output->ext); fbin = OpenBinaryFile (filename, SZ_float, "w"); for (nv = 0; nv < output->nvar; nv++) { if (!output->dump_var[nv]) continue; /* Vpt = (void *)(Convert_dbl2flt(output->V[nv],0))[0][0]; */ Vpt3 = Convert_dbl2flt(output->V[nv], units[nv],0); Vpt = (void *)Vpt3[0][0]; WriteBinaryArray (Vpt, sizeof(float), SZ_float, fbin, output->stag_var[nv]); } CloseBinaryFile(fbin, SZ_float); /* BOV_Header(output, filename); */ }else{ /* -- multiple files -- */ for (nv = 0; nv < output->nvar; nv++) { if (!output->dump_var[nv]) continue; sprintf (filename, "%s/%s.%04d.%s", output->dir, output->var_name[nv], output->nfile, output->ext); fbin = OpenBinaryFile (filename, SZ_float, "w"); /* Vpt = (void *)(Convert_dbl2flt(output->V[nv],0))[0][0]; */ Vpt3 = Convert_dbl2flt(output->V[nv], units[nv],0); Vpt = (void *)Vpt3[0][0]; WriteBinaryArray (Vpt, sizeof(float), SZ_float, fbin, output->stag_var[nv]); CloseBinaryFile (fbin, SZ_float); } } }else if (output->type == DBL_H5_OUTPUT || output->type == FLT_H5_OUTPUT){ /* ------------------------------------------------------ HDF5 (static grid) output (single/double precision) ------------------------------------------------------ */ #ifdef USE_HDF5 single_file = YES; WriteHDF5 (output, grid); #else print1 ("! WriteData: HDF5 library not available\n"); return; #endif }else if (output->type == VTK_OUTPUT) { /* ------------------------------------------------------------------- */ /*! - \b VTK output: in order to enable parallel writing, files must be closed and opened again for scalars, since the distributed array descriptors used by ArrayLib (Float_Vect) and (float) are different. This is done using the AL_Get_offset() and AL_Set_offset() functions. */ /* ------------------------------------------------------------------- */ single_file = strcmp(output->mode,"single_file") == 0; sprintf (filename, "%s/data.%04d.%s", output->dir, output->nfile, output->ext); if (single_file){ /* -- single output file -- */ fbin = OpenBinaryFile(filename, SZ_Float_Vect, "w"); WriteVTK_Header(fbin, grid); for (nv = 0; nv < output->nvar; nv++) { /* -- write vectors -- */ if (output->dump_var[nv] != VTK_VECTOR) continue; WriteVTK_Vector (fbin, output->V + nv, units[nv], output->var_name[nv], grid); } #ifdef PARALLEL offset = AL_Get_offset(SZ_Float_Vect); CloseBinaryFile(fbin, SZ_Float_Vect); fbin = OpenBinaryFile(filename, SZ_float, "w"); AL_Set_offset(SZ_float, offset); #endif for (nv = 0; nv < output->nvar; nv++) { /* -- write scalars -- */ if (output->dump_var[nv] != YES) continue; WriteVTK_Scalar (fbin, output->V[nv], units[nv], output->var_name[nv], grid); } CloseBinaryFile(fbin, SZ_float); }else{ /* -- multiple output files -- */ for (nv = 0; nv < output->nvar; nv++) { /* -- write vectors -- */ if (output->dump_var[nv] != VTK_VECTOR) continue; if (strcmp(output->var_name[nv],"vx1") == 0) { sprintf (filename, "%s/vfield.%04d.%s", output->dir, output->nfile, output->ext); }else if (strcmp(output->var_name[nv],"bx1") == 0) { sprintf (filename, "%s/bfield.%04d.%s", output->dir, output->nfile, output->ext); }else{ print1 ("! WriteData: unknown vector type in VTK output\n"); QUIT_PLUTO(1); } fbin = OpenBinaryFile(filename, SZ_Float_Vect, "w"); WriteVTK_Header(fbin, grid); WriteVTK_Vector(fbin, output->V + nv, units[nv], output->var_name[nv], grid); CloseBinaryFile(fbin, SZ_Float_Vect); } for (nv = 0; nv < output->nvar; nv++) { /* -- write scalars -- */ if (output->dump_var[nv] != YES) continue; sprintf (filename, "%s/%s.%04d.%s", output->dir, output->var_name[nv], output->nfile, output->ext); fbin = OpenBinaryFile(filename, SZ_Float_Vect, "w"); WriteVTK_Header(fbin, grid); #ifdef PARALLEL offset = AL_Get_offset(SZ_Float_Vect); CloseBinaryFile(fbin, SZ_Float_Vect); fbin = OpenBinaryFile(filename, SZ_float, "w"); AL_Set_offset(SZ_float, offset); #endif WriteVTK_Scalar(fbin, output->V[nv], units[nv], output->var_name[nv], grid); CloseBinaryFile (fbin, SZ_float); } } }else if (output->type == TAB_OUTPUT) { /* ------------------------------------------------------ Tabulated (ASCII) output ------------------------------------------------------ */ single_file = YES; sprintf (filename,"%s/data.%04d.%s", output->dir, output->nfile, output->ext); WriteTabArray (output, filename, grid); }else if (output->type == PPM_OUTPUT) { /* ------------------------------------------------------ PPM output ------------------------------------------------------ */ single_file = NO; for (nv = 0; nv < output->nvar; nv++) { if (!output->dump_var[nv]) continue; sprintf (filename, "%s/%s.%04d.%s", output->dir, output->var_name[nv], output->nfile, output->ext); WritePPM (output->V[nv], output->var_name[nv], filename, grid); } }else if (output->type == PNG_OUTPUT) { /* ------------------------------------------------------ PNG output ------------------------------------------------------ */ #ifdef USE_PNG single_file = NO; for (nv = 0; nv < output->nvar; nv++) { if (!output->dump_var[nv]) continue; sprintf (filename, "%s/%s.%04d.%s", output->dir, output->var_name[nv], output->nfile, output->ext); WritePNG (output->V[nv], output->var_name[nv], filename, grid); } #else print1 ("! PNG library not available\n"); return; #endif } /* ------------------------------------------------------------- Update corresponding ".out" file ------------------------------------------------------------- */ sprintf (filename,"%s/%s.out",output->dir, output->ext); if (prank == 0) { if (output->nfile == 0) { fout = fopen (filename, "w"); }else { fout = fopen (filename, "r+"); for (nv = 0; nv < output->nfile; nv++) fgets (sline, 512, fout); fseek (fout, ftell(fout), SEEK_SET); } /* -- write a multi-column file -- */ fprintf (fout, "%d %12.6e %12.6e %ld ", output->nfile, g_time, g_dt, g_stepNumber); if (single_file) fprintf (fout,"single_file "); else fprintf (fout,"multiple_files "); if (IsLittleEndian()) fprintf (fout, "little "); else fprintf (fout, "big "); for (nv = 0; nv < output->nvar; nv++) { if (output->dump_var[nv]) fprintf (fout, "%s ", output->var_name[nv]); } fprintf (fout,"\n"); fclose (fout); } #ifdef PARALLEL MPI_Barrier (MPI_COMM_WORLD); if (prank == 0){ time(&tend); print1 (" [%5.2f sec]",difftime(tend,tbeg)); } #endif print1 ("\n"); }
int ImageBase::readEM(size_t select_img, bool isStack) { // EM File formats does not support stacks if (select_img > FIRST_IMAGE & !isStack) REPORT_ERROR(ERR_ARG_INCORRECT, "readEM: EM file format does not support stacks."); EMHead header; if ( fread( &header, EMHEADERSIZE, 1, fimg ) != 1 ) REPORT_ERROR(ERR_IO_NOREAD, formatString("rwEM: cannot read EM main header from file %s" ". Error message: %s", filename.c_str() ,strerror(errno))); // endian: If machine is SGI, OS-9 or MAC: Big Endian, otherwise Litle Endian // Check Machine endianess bool isLE = IsLittleEndian(); if (header.machine == 0 || header.machine == 3 || header.machine == 5) swap = isLE; else if (header.machine == 1 || header.machine == 2 || header.machine == 4 || header.machine == 6) swap = !isLE; else REPORT_ERROR(ERR_IMG_UNKNOWN, "rwEM: Unknown source machine to determine Endianness"); if (swap) swapPage((char *) &header, EMHEADERSIZE - 256, DT_UInt); // EMHEADERSIZE - 256 is to exclude userdata from swapping // Setting image dimensions ArrayDim aDim; if (isStack) { if ( select_img > header.zdim ) REPORT_ERROR(ERR_INDEX_OUTOFBOUNDS, formatString("readEM: %s Image number %lu exceeds stack size %lu", this->filename.c_str(), select_img, header.zdim)); aDim.ndim = (select_img > ALL_IMAGES)? 1 : header.zdim; aDim.zdim = 1; } else { aDim.ndim = 1; aDim.zdim = header.zdim; } aDim.xdim = header.xdim; aDim.ydim= header.ydim; replaceNsize = aDim.ndim; setDimensions(aDim); DataType datatype; switch (header.datatype) { case 1: datatype = DT_SChar; break; case 2: datatype = DT_Short; break; case 4: datatype = DT_Int; break; case 3: case 5: datatype = DT_Float; break; case 8: datatype = DT_CFloat; break; case 9: datatype = DT_CDouble; break; default: REPORT_ERROR(ERR_ARG_INCORRECT, formatString("readEM: Unknown datatype value: %c", header.datatype)); break; } MDMainHeader.setValue(MDL_DATATYPE,(int)datatype); offset = EMHEADERSIZE; // If only header is read: return if (dataMode==HEADER || (dataMode == _HEADER_ALL && aDim.ndim > 1)) // Stop reading if not necessary return 0; size_t imgStart = IMG_INDEX(select_img); size_t imgEnd = (select_img != ALL_IMAGES) ? imgStart + 1 : aDim.ndim; MD.clear(); MD.resize(imgEnd - imgStart,MDL::emptyHeader); /* As MRC does not support stacks, we use the geometry stored in the header for any image when we simulate the file is a stack.*/ if (dataMode == _HEADER_ALL || dataMode == _DATA_ALL) { for ( size_t i = 0; i < imgEnd - imgStart; ++i ) { MD[i].setValue(MDL_SHIFT_X, 0.); MD[i].setValue(MDL_SHIFT_Y, 0.); MD[i].setValue(MDL_SHIFT_Z, 0.); MD[i].setValue(MDL_ORIGIN_X, 0.); MD[i].setValue(MDL_ORIGIN_Y, 0.); MD[i].setValue(MDL_ORIGIN_Z, 0.); } } if ( dataMode < DATA ) // Don't read the individual header and the data if not necessary return 0; readData(fimg, select_img, datatype, 0); return(0); }
void VTKOutput<TDim>:: print(const char* filename, Domain<TDim>& domain) { // get the grid associated to the solution MultiGrid& grid = *domain.grid(); MGSubsetHandler& sh = *domain.subset_handler(); // attach help indices typedef ug::Attachment<int> AVrtIndex; AVrtIndex aVrtIndex; Grid::VertexAttachmentAccessor<AVrtIndex> aaVrtIndex; grid.attach_to_vertices(aVrtIndex); aaVrtIndex.access(grid, aVrtIndex); // get rank of process int rank = 0; #ifdef UG_PARALLEL rank = pcl::ProcRank(); #endif const int si = -1; // get name for *.vtu file std::string name; try{ vtu_filename(name, filename, rank, si, sh.num_subsets()-1, -1); } UG_CATCH_THROW("VTK::print_subset: Can not write vtu - file."); // open the file try { VTKFileWriter File(name.c_str()); // header File << VTKFileWriter::normal; File << "<?xml version=\"1.0\"?>\n"; File << "<VTKFile type=\"UnstructuredGrid\" version=\"0.1\" byte_order=\""; if(IsLittleEndian()) File << "LittleEndian"; else File << "BigEndian"; File << "\">\n"; // opening the grid File << " <UnstructuredGrid>\n"; // get dimension of grid-piece int dim = DimensionOfSubsets(sh); // write piece of grid if(dim >= 0) { try{ write_grid_piece<MGSubsetHandler> (File, aaVrtIndex, domain.position_accessor(), grid, sh, si, dim); } UG_CATCH_THROW("VTK::print: Can not write Subset: "<<si); } else { // if dim < 0, some is wrong with grid, except no element is in the grid if( ((si < 0) && grid.num<Vertex>() != 0) || ((si >=0) && sh.num<Vertex>(si) != 0)) { UG_THROW("VTK::print: Dimension of grid/subset not" " detected correctly although grid objects present."); } write_empty_grid_piece(File); } // write closing xml tags File << " </UnstructuredGrid>\n"; File << "</VTKFile>\n"; // detach help indices grid.detach_from_vertices(aVrtIndex); }