예제 #1
0
int WriteBinMesh(char *fname) {
  FILE *fptr;
  BINTYPE *data;
  int i, j;
  int idx;
  unsigned char *cdata;

  if (strlen(fname) < 1) {
    return(FALSE);
  }

  if ((fptr = fopen(fname, "w")) == NULL) {
    fprintf(stderr, "Failed to open binary map file for writing\n");
    return(FALSE);
  }

  // write the mesh type
  fprintf(fptr, "%d\n", meshtype);

  // write the mesh dimensions
  fprintf(fptr, "%d %d\n", meshnx, meshny);

  // allocate mem to store the entire mesh in continguous BINTYPE form
  data = (BINTYPE *)calloc(meshnx * meshny * 5, sizeof(BINTYPE));
  idx = 0;
  for (j = 0; j < meshny; j++) {
    for (i = 0; i < meshnx; i++) {
      data[idx++] = mesh[i][j].u;
      data[idx++] = mesh[i][j].v;
      data[idx++] = mesh[i][j].x;
      data[idx++] = mesh[i][j].y;
      data[idx++] = mesh[i][j].i;
    }
  }
  
  cdata  = (unsigned char *)data;

  // switch byte ordering if necessary
  if (!isLittleEndian()) {
    int nrev = ReverseBytes(cdata, meshnx * meshny * 5 * sizeof(BINTYPE), 
			    sizeof(BINTYPE));
    if (nrev != meshnx * meshny * 5) {
      fprintf(stderr, "Did not reverse correct number of values!\n");
      fclose(fptr);
      free(data);
      return(FALSE);
    }
  }
  
  // write the chunk to the file
  fwrite(cdata, sizeof(unsigned char), meshnx * meshny * 5 * sizeof(BINTYPE),
	 fptr);
  
  fclose(fptr);
  free(data);
  return(TRUE);
}
예제 #2
0
main()
{
 if (isLittleEndian()) {
   printf("Machine is Little Endian\n");
 }
 else {
   printf("Machine is Big Endian\n");
 }
}
예제 #3
0
void TelegramFactory::addUINT16(Telegram &p_telegram, const uint16_t p_value) const
{
    if(isLittleEndian())
        p_telegram.addUINT16(p_value);
    else {
        unsigned char *ptr = (unsigned char*) &p_value;
        p_telegram.add(ptr[1]);
        p_telegram.add(ptr[0]);
    }
}
예제 #4
0
파일: dataset.c 프로젝트: Ikulagin/transmem
static inline int cass_read_vecset (cass_vecset_t *vecset, size_t nmemb, CASS_FILE *in) {
    int n = fread(vecset, sizeof(cass_vecset_t), nmemb, in);
    if (!isLittleEndian()) {
        int i;
        assert(sizeof(vecset[0].start_vecid) == sizeof(uint32_t));
        for (i = 0; i < n; i++) {
            vecset[i].num_regions = bswap_int32(vecset[i].num_regions);
            vecset[i].start_vecid = bswap_int32(vecset[i].start_vecid);
        }
    }
    return n;
}
예제 #5
0
파일: dataset.c 프로젝트: Ikulagin/transmem
int cass_dataset_load (cass_dataset_t *ds, CASS_FILE *in, cass_vec_type_t vec_type)
{
	int ret;
	assert(!ds->loaded);
	assert(ds->vec == NULL);
	assert(ds->vecset == NULL);

	if (ds->flags & CASS_DATASET_VECSET)
	{
		ret = CASS_ERR_OUTOFMEM;
		ds->max_vecset = ds->num_vecset * MEM_OVERHEAD;
		ds->vecset = (cass_vecset_t *)malloc(sizeof(cass_vecset_t) * ds->max_vecset);
		if (ds->vecset == NULL) goto err;
		ret = CASS_ERR_IO;
		if (cass_read_vecset(ds->vecset, ds->num_vecset, in) != ds->num_vecset) goto err;
	}

	if (ds->flags & CASS_DATASET_VEC)
	{
		ds->max_vec = ds->num_vec;// * MEM_OVERHEAD;
		ret = CASS_ERR_OUTOFMEM;
		ds->vec = (cass_vec_t *)malloc(ds->vec_size * ds->max_vec);
		if (ds->vec == NULL) goto err;
		ret = CASS_ERR_IO;
        if (isLittleEndian()) {
		    if (cass_read(ds->vec, ds->vec_size, ds->num_vec, in) != ds->num_vec) goto err;
        }
        else {
            if (vec_type == CASS_VEC_INT) {
                unsigned cnt = ds->vec_size / sizeof(int32_t) * ds->num_vec;
                if (cass_read_int32(ds->vec, cnt, in) != cnt) goto err;
            }
            else if (vec_type == CASS_VEC_FLOAT) {
                unsigned cnt = ds->vec_size / sizeof(float) * ds->num_vec;
                if (cass_read_float(ds->vec, cnt, in) != cnt) goto err;
            }
            else if (vec_type == CASS_VEC_BIT) {
		    if (cass_read(ds->vec, ds->vec_size, ds->num_vec, in) != ds->num_vec) goto err;
            }
            else assert(0);
        }
	}

	ds->loaded = 1;

	return 0;

err:
	cass_dataset_release(ds);

	return ret;
}
예제 #6
0
// -- Create -------------------------------------------------------------------
int fvCreate() {
	if(vision != NULL) fvDestroy();
	
	// init vision main class
	vision = new Vision();
	vision->setProcessor(new CVBlobDetector());
	
	// init data structure
	visionData->size = VISION_DATA_SIZE;
	visionData->isLittleEndian = isLittleEndian();
	visionData->buffer = new int[visionData->size];
	return SUCCESS;
}
void IndexPart::writePart(int part, quint32 arrLen) {

    qint64 t0 = GTimer::currentTimeMicros();

    partFiles[part]->open(QIODevice::ReadWrite);
    currentPart = part;

    if (!isLittleEndian()) {
        for (quint32 i=0; i<arrLen; i++) {
            qToLittleEndian(sArray[i], (uchar*)(sArray + i));
            qToLittleEndian(bitMask[i], (uchar*)(bitMask + i));
        }
    }

    partFiles[part]->write((char*)&arrLen, 1 * sizeof(SAType));

    partFiles[part]->write((char*)sArray, arrLen * sizeof(SAType));
    partFiles[part]->write((char*)bitMask, arrLen * sizeof(BMType));

    qint64 t1 = GTimer::currentTimeMicros();
    uchar *values = new uchar[1 + seqLengths[currentPart]/4];
    int i = 0;
    int bitNum = 0;
    BitsTable bt;
    const quint32 *bitTable = bt.getBitMaskCharBits(DNAAlphabet_NUCL);

    for (quint32 j=0; j<seqLengths[currentPart]; j++) {
        if (0 == bitNum) {
            values[i] = 0;
        }
        values[i] = (values[i]<<2);
        values[i] |= bitTable[uchar(*(seq+j))];
        bitNum += 2;
        if (bitNum >= 8) {
            bitNum = 0;
            i++;
        }
    }

    if (bitNum > 0) {
        values[i] <<= 8-bitNum;
    }
    algoLog.trace(QString("IndexPart::writePart some bits table time %1 ms").arg((GTimer::currentTimeMicros() - t1) / double(1000), 0, 'f', 3));

    partFiles[part]->write((char*)values, 1 + seqLengths[currentPart]/4);

    delete[] values;

    qint64 t2 = GTimer::currentTimeMicros();
    algoLog.trace(QString("IndexPart::writePart time %1 ms").arg((t2 - t0) / double(1000), 0, 'f', 3));
}
예제 #8
0
    float BsonDeserizer::ReadFloat()
    {
        float* pFloat = (float*)this->m_pPtr;

        this->m_pPtr += 4;
#if LITTLE_ENDIAN_ONLY
        BEHAVIAC_ASSERT(isLittleEndian());

        return *pFloat;
#else

        if (isLittleEndian())
        {
            return *pFloat;
        }

        uint8_t* pByte = (uint8_t*)pFloat;

        int32_t uint32 = (pByte[0] << 24 | pByte[1] << 16 | pByte[2] << 8 | pByte[3]);

        return (float&)uint32;
#endif//LITTLE_ENDIAN_ONLY
    }
예제 #9
0
    uint16_t BsonDeserizer::ReadUInt16()
    {
        uint16_t* pUInt16 = (uint16_t*)this->m_pPtr;

        this->m_pPtr += 2;
#if LITTLE_ENDIAN_ONLY
        BEHAVIAC_ASSERT(isLittleEndian());

        return *pUInt16;
#else

        if (isLittleEndian())
        {
            return *pUInt16;
        }

        uint8_t* pByte = (uint8_t*)pUInt16;

        int32_t uint32 = (pByte[0] << 8 | pByte[1]);

        return uint32;
#endif//LITTLE_ENDIAN_ONLY
    }
예제 #10
0
//Convert bitmap info header from file to memory byte order or back
void ConvertBmih(BITMAPINFOHDR *bmih) {
  if (!isLittleEndian()) {
    bmih->biSize = swap_32(bmih->biSize);
    bmih->biWidth = swap_32(bmih->biWidth);
    bmih->biHeight = swap_32(bmih->biHeight);
    bmih->biPlanes = swap_16(bmih->biPlanes);
    bmih->biBitCount = swap_16(bmih->biBitCount);
    bmih->biCompression = swap_32(bmih->biCompression);
    bmih->biSizeImage = swap_32(bmih->biSizeImage);
    bmih->biXPelsPerMeter = swap_32(bmih->biXPelsPerMeter);
    bmih->biYPelsPerMeter = swap_32(bmih->biYPelsPerMeter);
    bmih->biClrUsed = swap_32(bmih->biClrUsed);
    bmih->biClrImportant = swap_32(bmih->biClrImportant);
  }
}
예제 #11
0
void generate(int dim, char* filename)
{
	#if (!defined MPI_VERSION || MPI_VERSION<2) && (defined BGQ)
	std::cerr<<"Error: MPI-2 is required for CCNI."<<std::endl;
	exit(1);
	#endif
	static unsigned long tstart;

	int rank=0;
	#ifdef MPI_VERSION
	rank = MPI::COMM_WORLD.Get_rank();
	int np = MPI::COMM_WORLD.Get_size();
	#endif
	#ifdef DEBUG
	if (rank==0) {
		if (!isLittleEndian()) std::cout<<"Byte order is big-endian."<<std::endl;
	}
	#endif
	if (dim == 2)	{
		const int edge = 8192;
		int number_of_fields = 5120000;
		grid<2,sparse<phi_type> > initGrid(0, 0, edge, 0, edge);
		if (rank==0) std::cout<<"Grid origin: ("<<g0(initGrid,0)<<','<<g0(initGrid,1)<<"),"
			                      <<" dimensions: "<<g1(initGrid,0)-g0(initGrid,0)<<" × "<<g1(initGrid,1)-g0(initGrid,1)
			                      <<" with "<<number_of_fields<<" seeds"<<std::flush;
		#ifdef MPI_VERSION
		number_of_fields /= np;
		if (rank==0) std::cout<<", "<<number_of_fields<<" per rank"<<std::flush;
		if (rank==0 && number_of_fields % np != 0)
			std::cerr<<"\nWarning: Tessellation may hang with uneven distribution of seeds per thread."<<std::endl;
		#endif
		if (rank==0) std::cout<<"."<<std::endl;

		#if (!defined MPI_VERSION) && (defined BGQ)
		std::cerr<<"Error: Blue Gene requires MPI."<<std::endl;
		std::exit(-1);
		#endif
		tstart = time(NULL);
		tessellate<2,phi_type>(initGrid, number_of_fields);
		if (rank==0) std::cout<<"Tessellation complete ("<<time(NULL)-tstart<<" sec)."<<std::endl;
		#ifdef MPI_VERSION
		MPI::COMM_WORLD.Barrier();
		#endif
		tstart=time(NULL);
		output(initGrid, filename);
		if (rank==0) std::cout<<"Voronoi tessellation written to "<<filename<<" ("<<time(NULL)-tstart<<" sec)."<<std::endl;
	}
}
예제 #12
0
int main(void)
{
	{/* check the byte order of local environment */
		if(isLittleEndian()) printf("The host is little endian\n");
		else printf("The host is big endian\n");
	}
	{/*big endian integer to little endian */
		srand((unsigned)time(NULL));
		int num = rand();
		printf("big endian number %d is converted to little endian number %d\n",
				num, big2littlei(num));
	}
	{/*little endian integer to big endian */
		srand((unsigned)time(NULL));
		int num = rand();
		printf("little endian number %d is converted to big endian number %d\n",
				num, little2bigi(num));
	}
	return 0;
}
/********************************************************************
* Connect to API
* Returns a socket descriptor
********************************************************************/
int apiConnect(char *szIPaddr, int iPort) {
    int fdSock;
    struct sockaddr_in address;
    int iConnectResult;
    int iLen;

    WORD    versionWanted = MAKEWORD(1, 1);
    WSADATA wsaData;

    WSAStartup(versionWanted, &wsaData);

    fdSock = socket(AF_INET, SOCK_STREAM, 0);

    address.sin_family      = AF_INET;
    address.sin_addr.s_addr = inet_addr(szIPaddr);
    address.sin_port        = htons(iPort);
    iLen = sizeof(address);

    DEBUG ? printf("Connecting to %s\n", szIPaddr) : 0;

    iConnectResult = connect(fdSock, (struct sockaddr *)&address, iLen);

    if (iConnectResult == -1) {
        //perror ("Connection problem");
        //exit(1);
        return iConnectResult;
    } else {
        DEBUG ? printf("Successfully connected to %s\n", szIPaddr) : 0;
    }

    // determine endianness of this machine
    // iLittleEndian will be set to 1 if we are
    // on a little endian machine...otherwise
    // we are assumed to be on a big endian processor
    iLittleEndian = isLittleEndian();

    return fdSock;
}
예제 #14
0
/*  Output:	Double-precision array */
void Copy24BitPCM_ToDouble(void* buffer, void* outputSignal, 
                           int_T numSamples, int_T numChannels)
{
    uint8_T *data = (uint8_T *)buffer;
    int_T i;
    int32_T intSample;
    uint8_T* bytePtr;
    real_T* y = (real_T*)outputSignal;
    int_T channel;

    bytePtr = (uint8_T*) &intSample;

    if(isLittleEndian()) {
        for(i=0; i < numSamples; i++)
            for(channel = 0; channel < numChannels; channel++)
            {
                bytePtr[0] = 0;
                bytePtr[1] = *data++;
                bytePtr[2] = *data++;
                bytePtr[3] = *data++;
                y[numSamples * channel + i] = 
                    (real_T) ((real_T)intSample / (MAX_int32_T+1.0));
            }
    }
    else {
        for(i=0; i < numSamples; i++)
            for(channel = 0; channel < numChannels; channel++)
            {
                bytePtr[0] = *data++;
                bytePtr[1] = *data++;
                bytePtr[2] = *data++;
                bytePtr[3] = 0;
                y[numSamples * channel + i] = 
                    (real_T) ((real_T)intSample / (MAX_int32_T+1.0));
            }
    }
}
sf_count_t sf_readf_short(SNDFILE *handle, short *ptr, sf_count_t desiredFrames)
{
    if (handle == NULL || handle->mode != SFM_READ || ptr == NULL || !handle->remaining ||
            desiredFrames <= 0) {
        return 0;
    }
    if (handle->remaining < (size_t) desiredFrames)
        desiredFrames = handle->remaining;
    size_t desiredBytes = desiredFrames * handle->bytesPerFrame;
    // does not check for numeric overflow
    size_t actualBytes = fread(ptr, sizeof(char), desiredBytes, handle->stream);
    size_t actualFrames = actualBytes / handle->bytesPerFrame;
    handle->remaining -= actualFrames;
    switch (handle->info.format & SF_FORMAT_SUBMASK) {
    case SF_FORMAT_PCM_U8:
        memcpy_to_i16_from_u8(ptr, (unsigned char *) ptr, actualFrames * handle->info.channels);
        break;
    case SF_FORMAT_PCM_16:
        if (!isLittleEndian())
            my_swab(ptr, actualFrames * handle->info.channels);
        break;
    }
    return actualFrames;
}
bool IndexPart::load(int part) {

    qint64 t0 = GTimer::currentTimeMicros();

    assert(part < partCount);
    if (part == currentPart) {
        return true;
    }
    currentPart = part;
    qint64 size = 0;
    if (!partFiles[part]->isOpen()) {
        partFiles[part]->open(QIODevice::ReadOnly);
    }
    partFiles[part]->seek(0);

    char *buff = NULL;

    size_t needRead = 0;

    needRead = 1*sizeof(SAType);
    buff = (char*)&(saLengths[currentPart]);
    size = partFiles[part]->read(buff, needRead);
    SAFE_POINT(static_cast<quint64>(size) == needRead, "Index format error", false);

    needRead = saLengths[currentPart]*sizeof(SAType);
    buff = (char*)sArray;
    size = partFiles[part]->read(buff, needRead);
    SAFE_POINT(static_cast<quint64>(size) == needRead, "Index format error", false);

    needRead = saLengths[currentPart]*sizeof(BMType);
    buff = (char*)bitMask;
    size = partFiles[part]->read(buff, needRead);
    SAFE_POINT(static_cast<quint64>(size) == needRead, "Index format error", false);

    uchar *bitSeq = new uchar[1 + seqLengths[currentPart]/4];
    size = partFiles[part]->read((char*)bitSeq, 1 + seqLengths[currentPart]/4);
    assert(size == 1 + seqLengths[currentPart]/4);
    if (size != 1 + seqLengths[currentPart]/4) {
        delete[] bitSeq;
        return false;
    }

    refFile->seek(seqStarts[currentPart]);
    size = refFile->read(seq, seqLengths[currentPart]);
    assert(size == seqLengths[currentPart]);
    if (size != seqLengths[currentPart]) {
        delete[] bitSeq;
        return false;
    }

    for (quint32 i=0; i<saLengths[currentPart]; i++) {
        if (!isLittleEndian()) {
            sArray[i] = qFromLittleEndian<quint32>((uchar*)(sArray + i));
        }
    }

    qint64 t1 = GTimer::currentTimeMicros();
    algoLog.trace(QString("IndexPart::load time %1 ms").arg((t1 - t0) / double(1000), 0, 'f', 3));

    delete[] bitSeq;
    return true;
}
예제 #17
0
파일: dicom.cpp 프로젝트: fiking/SIFT3D
/* Helper function to read a DICOM file using C++ */
static int read_dcm_cpp(const char *path, Image *const im) {

        // Read the image metadata
        Dicom dicom(path);
        if (!dicom.isValid())
                return SIFT3D_FAILURE;

        // Load the DicomImage object
        DicomImage dicomImage(path);
        if (dicomImage.getStatus() != EIS_Normal) {
                SIFT3D_ERR("read_dcm_cpp: failed to open image %s (%s)\n",
                        path, DicomImage::getString(dicomImage.getStatus()));
                return SIFT3D_FAILURE;
        }

        // Initialize the image fields
        im->nx = dicom.getNx();
        im->ny = dicom.getNy();
        im->nz = dicom.getNz();
        im->nc = dicom.getNc();
        im->ux = dicom.getUx();
        im->uy = dicom.getUy();
        im->uz = dicom.getUz();

        // Resize the output
        im_default_stride(im);
        if (im_resize(im))
                return SIFT3D_FAILURE;

        // Get the bit depth of the image
        const int bufNBits = 32;
        const int depth = dicomImage.getDepth();
        if (depth > bufNBits) {
                SIFT3D_ERR("read_dcm_cpp: buffer is insufficiently wide "
                        "for %d-bit data of image %s \n", depth, path);
                return SIFT3D_FAILURE;
        }

        // Get the number of bits by which we need to shift the 32-bit data, to
        // recover the original resolution (DICOM uses Big-endian encoding)
        const uint32_t shift = isLittleEndian() ? 
                static_cast<uint32_t>(bufNBits - depth) : 0;

        // Read each frame
        for (int i = 0; i < im->nz; i++) { 

                // Get a pointer to the data, rendered as a 32-bit int
                const uint32_t *const frameData = 
                        static_cast<const uint32_t *const>(
                                dicomImage.getOutputData(
                                        static_cast<int>(bufNBits), i));
                if (frameData == NULL) {
                        SIFT3D_ERR("read_dcm_cpp: could not get data from "
                                "image %s frame %d (%s)\n", path, i, 
                                DicomImage::getString(dicomImage.getStatus()));
                        return SIFT3D_FAILURE;
                }

                // Copy the frame
                const int x_start = 0;
                const int y_start = 0;
                const int z_start = i;
                const int x_end = im->nx - 1;
                const int y_end = im->ny - 1;
                const int z_end = z_start;
                int x, y, z;
                SIFT3D_IM_LOOP_LIMITED_START(im, x, y, z, x_start, x_end,
                        y_start, y_end, z_start, z_end)

                        // Get the voxel and shift it to match the original
                        // magnitude 
                        const uint32_t vox =
                                frameData[x + y * im->nx] >> shift;

                        // Convert to float and write to the output image
                        SIFT3D_IM_GET_VOX(im, x, y, z, 0) =
                                static_cast<float>(vox);

                SIFT3D_IM_LOOP_END
        }

        return SIFT3D_SUCCESS;
}
예제 #18
0
파일: serial.cpp 프로젝트: vjanjic/Projects
void InitSim(char const *fileName)
{
  std::cout << "Loading file \"" << fileName << "\"..." << std::endl;
  std::ifstream file(fileName, std::ios::binary);
  if(!file) {
    std::cerr << "Error opening file. Aborting." << std::endl;
    exit(1);
  }

  //Always use single precision float variables b/c file format uses single precision
  float restParticlesPerMeter_le;
  int numParticles_le;
  file.read((char *)&restParticlesPerMeter_le, FILE_SIZE_FLOAT);
  file.read((char *)&numParticles_le, FILE_SIZE_INT);
  if(!isLittleEndian()) {
    restParticlesPerMeter = bswap_float(restParticlesPerMeter_le);
    numParticles          = bswap_int32(numParticles_le);
  } else {
    restParticlesPerMeter = restParticlesPerMeter_le;
    numParticles          = numParticles_le;
  }
  cellpool_init(&pool, numParticles);

  h = kernelRadiusMultiplier / restParticlesPerMeter;
  hSq = h*h;

#ifndef ENABLE_DOUBLE_PRECISION
  fptype coeff1 = 315.0 / (64.0*pi*powf(h,9.0));
  fptype coeff2 = 15.0 / (pi*powf(h,6.0));
  fptype coeff3 = 45.0 / (pi*powf(h,6.0));
#else
  fptype coeff1 = 315.0 / (64.0*pi*pow(h,9.0));
  fptype coeff2 = 15.0 / (pi*pow(h,6.0));
  fptype coeff3 = 45.0 / (pi*pow(h,6.0));
#endif //ENABLE_DOUBLE_PRECISION
  fptype particleMass = 0.5*doubleRestDensity / (restParticlesPerMeter*restParticlesPerMeter*restParticlesPerMeter);
  densityCoeff = particleMass * coeff1;
  pressureCoeff = 3.0*coeff2 * 0.50*stiffnessPressure * particleMass;
  viscosityCoeff = viscosity * coeff3 * particleMass;

  Vec3 range = domainMax - domainMin;
  nx = (int)(range.x / h);
  ny = (int)(range.y / h);
  nz = (int)(range.z / h);
  assert(nx >= 1 && ny >= 1 && nz >= 1);
  numCells = nx*ny*nz;
  std::cout << "Number of cells: " << numCells << std::endl;
  delta.x = range.x / nx;
  delta.y = range.y / ny;
  delta.z = range.z / nz;
  assert(delta.x >= h && delta.y >= h && delta.z >= h);

  //make sure Cell structure is multiple of estiamted cache line size
  assert(sizeof(Cell) % CACHELINE_SIZE == 0);
  //make sure helper Cell structure is in sync with real Cell structure
#pragma warning( disable : 1684) // warning #1684: conversion from pointer to same-sized integral type (potential portability problem)
  assert(offsetof(struct Cell_aux, padding) == offsetof(struct Cell, padding));

#if defined(WIN32)
  cells = (struct Cell*)_aligned_malloc(sizeof(struct Cell) * numCells, CACHELINE_SIZE);
  cells2 = (struct Cell*)_aligned_malloc(sizeof(struct Cell) * numCells, CACHELINE_SIZE);
  cnumPars = (int*)_aligned_malloc(sizeof(int) * numCells, CACHELINE_SIZE);
  cnumPars2 = (int*)_aligned_malloc(sizeof(int) * numCells, CACHELINE_SIZE);
  last_cells = (struct Cell **)_aligned_malloc(sizeof(struct Cell *) * numCells, CACHELINE_SIZE);
  assert((cells!=NULL) && (cells2!=NULL) && (cnumPars!=NULL) && (cnumPars2!=NULL) && (last_cells!=NULL)); 
#else
  int rv0 = posix_memalign((void **)(&cells), CACHELINE_SIZE, sizeof(struct Cell) * numCells);
  int rv1 = posix_memalign((void **)(&cells2), CACHELINE_SIZE, sizeof(struct Cell) * numCells);
  int rv2 = posix_memalign((void **)(&cnumPars), CACHELINE_SIZE, sizeof(int) * numCells);
  int rv3 = posix_memalign((void **)(&cnumPars2), CACHELINE_SIZE, sizeof(int) * numCells);
  int rv4 = posix_memalign((void **)(&last_cells), CACHELINE_SIZE, sizeof(struct Cell *) * numCells);
  assert((rv0==0) && (rv1==0) && (rv2==0) && (rv3==0) && (rv4==0));
#endif

  // because cells and cells2 are not allocated via new
  // we construct them here
  for(int i=0; i<numCells; ++i) {
	  new (&cells[i]) Cell;
	  new (&cells2[i]) Cell;
  }

  memset(cnumPars, 0, numCells*sizeof(int));

  //Always use single precision float variables b/c file format uses single precision
  float px, py, pz, hvx, hvy, hvz, vx, vy, vz;
  for(int i = 0; i < numParticles; ++i) {
    file.read((char *)&px, FILE_SIZE_FLOAT);
    file.read((char *)&py, FILE_SIZE_FLOAT);
    file.read((char *)&pz, FILE_SIZE_FLOAT);
    file.read((char *)&hvx, FILE_SIZE_FLOAT);
    file.read((char *)&hvy, FILE_SIZE_FLOAT);
    file.read((char *)&hvz, FILE_SIZE_FLOAT);
    file.read((char *)&vx, FILE_SIZE_FLOAT);
    file.read((char *)&vy, FILE_SIZE_FLOAT);
    file.read((char *)&vz, FILE_SIZE_FLOAT);
    if(!isLittleEndian()) {
      px  = bswap_float(px);
      py  = bswap_float(py);
      pz  = bswap_float(pz);
      hvx = bswap_float(hvx);
      hvy = bswap_float(hvy);
      hvz = bswap_float(hvz);
      vx  = bswap_float(vx);
      vy  = bswap_float(vy);
      vz  = bswap_float(vz);
    }
    int ci = (int)(((fptype)px - domainMin.x) / delta.x);
    int cj = (int)(((fptype)py - domainMin.y) / delta.y);
    int ck = (int)(((fptype)pz - domainMin.z) / delta.z);

    if(ci < 0) ci = 0; else if(ci >= nx) ci = nx-1;
    if(cj < 0) cj = 0; else if(cj >= ny) cj = ny-1;
    if(ck < 0) ck = 0; else if(ck >= nz) ck = nz-1;

    int index = (ck*ny + cj)*nx + ci;
    Cell *cell = &cells[index];

    //go to last cell structure in list
    int np = cnumPars[index];
    while(np > PARTICLES_PER_CELL) {
      cell = cell->next;
      np = np - PARTICLES_PER_CELL;
    }
    //add another cell structure if everything full
    if( (np % PARTICLES_PER_CELL == 0) && (cnumPars[index] != 0) ) {
      cell->next = cellpool_getcell(&pool);
      cell = cell->next;
      np = np - PARTICLES_PER_CELL; // np = 0;
    }

    //add particle to cell
    cell->p[np].x = px;
    cell->p[np].y = py;
    cell->p[np].z = pz;
    cell->hv[np].x = hvx;
    cell->hv[np].y = hvy;
    cell->hv[np].z = hvz;
    cell->v[np].x = vx;
    cell->v[np].y = vy;
    cell->v[np].z = vz;
#ifdef ENABLE_VISUALIZATION
	vMin.x = std::min(vMin.x, cell->v[np].x);
	vMax.x = std::max(vMax.x, cell->v[np].x);
	vMin.y = std::min(vMin.y, cell->v[np].y);
	vMax.y = std::max(vMax.y, cell->v[np].y);
	vMin.z = std::min(vMin.z, cell->v[np].z);
	vMax.z = std::max(vMax.z, cell->v[np].z);
#endif
    ++cnumPars[index];
  }

  std::cout << "Number of particles: " << numParticles << std::endl;
}
예제 #19
0
파일: serial.cpp 프로젝트: vjanjic/Projects
void SaveFile(char const *fileName)
{
  std::cout << "Saving file \"" << fileName << "\"..." << std::endl;

  std::ofstream file(fileName, std::ios::binary);
  assert(file);

  //Always use single precision float variables b/c file format uses single precision
  if(!isLittleEndian()) {
    float restParticlesPerMeter_le;
    int   numParticles_le;

    restParticlesPerMeter_le = bswap_float((float)restParticlesPerMeter);
    numParticles_le      = bswap_int32(numParticles);
    file.write((char *)&restParticlesPerMeter_le, FILE_SIZE_FLOAT);
    file.write((char *)&numParticles_le,      FILE_SIZE_INT);
  } else {
    file.write((char *)&restParticlesPerMeter, FILE_SIZE_FLOAT);
    file.write((char *)&numParticles, FILE_SIZE_INT);
  }

  int count = 0;
  for(int i = 0; i < numCells; ++i) {
    Cell *cell = &cells[i];
    int np = cnumPars[i];
    for(int j = 0; j < np; ++j) {
      //Always use single precision float variables b/c file format uses single precision
      float px, py, pz, hvx, hvy, hvz, vx,vy, vz;
      if(!isLittleEndian()) {
        px  = bswap_float((float)(cell->p[j % PARTICLES_PER_CELL].x));
        py  = bswap_float((float)(cell->p[j % PARTICLES_PER_CELL].y));
        pz  = bswap_float((float)(cell->p[j % PARTICLES_PER_CELL].z));
        hvx = bswap_float((float)(cell->hv[j % PARTICLES_PER_CELL].x));
        hvy = bswap_float((float)(cell->hv[j % PARTICLES_PER_CELL].y));
        hvz = bswap_float((float)(cell->hv[j % PARTICLES_PER_CELL].z));
        vx  = bswap_float((float)(cell->v[j % PARTICLES_PER_CELL].x));
        vy  = bswap_float((float)(cell->v[j % PARTICLES_PER_CELL].y));
        vz  = bswap_float((float)(cell->v[j % PARTICLES_PER_CELL].z));
      } else {
        px  = (float)(cell->p[j % PARTICLES_PER_CELL].x);
        py  = (float)(cell->p[j % PARTICLES_PER_CELL].y);
        pz  = (float)(cell->p[j % PARTICLES_PER_CELL].z);
        hvx = (float)(cell->hv[j % PARTICLES_PER_CELL].x);
        hvy = (float)(cell->hv[j % PARTICLES_PER_CELL].y);
        hvz = (float)(cell->hv[j % PARTICLES_PER_CELL].z);
        vx  = (float)(cell->v[j % PARTICLES_PER_CELL].x);
        vy  = (float)(cell->v[j % PARTICLES_PER_CELL].y);
        vz  = (float)(cell->v[j % PARTICLES_PER_CELL].z);
      }
      file.write((char *)&px,  FILE_SIZE_FLOAT);
      file.write((char *)&py,  FILE_SIZE_FLOAT);
      file.write((char *)&pz,  FILE_SIZE_FLOAT);
      file.write((char *)&hvx, FILE_SIZE_FLOAT);
      file.write((char *)&hvy, FILE_SIZE_FLOAT);
      file.write((char *)&hvz, FILE_SIZE_FLOAT);
      file.write((char *)&vx,  FILE_SIZE_FLOAT);
      file.write((char *)&vy,  FILE_SIZE_FLOAT);
      file.write((char *)&vz,  FILE_SIZE_FLOAT);
      ++count;

      //move pointer to next cell in list if end of array is reached
      if(j % PARTICLES_PER_CELL == PARTICLES_PER_CELL-1) {
        cell = cell->next;
      }
    }
  }
  assert(count == numParticles);
}
예제 #20
0
파일: memory.c 프로젝트: DeadRoolz/jpcsp
JNIEXPORT void JNICALL Java_jpcsp_memory_NativeMemoryUtils_init(JNIEnv * env, jclass self) {
	/* Test the endianness at runtime */
	littleEndian = isLittleEndian();
}
예제 #21
0
파일: sys.cpp 프로젝트: Thooms/pyston
void setupSys() {
    sys_modules_dict = new BoxedDict();
    constants.push_back(sys_modules_dict);

    // This is ok to call here because we've already created the sys_modules_dict
    sys_module = createModule(autoDecref(boxString("sys")));

    // sys_module is what holds on to all of the other modules:
    Py_INCREF(sys_module);
    late_constants.push_back(sys_module);

    sys_module->giveAttrBorrowed("modules", sys_modules_dict);

    BoxedList* sys_path = new BoxedList();
    constants.push_back(sys_path);
    sys_module->giveAttrBorrowed("path", sys_path);

    sys_module->giveAttr("argv", new BoxedList());

    sys_module->giveAttr("exc_info",
                         new BoxedBuiltinFunctionOrMethod(FunctionMetadata::create((void*)sysExcInfo, BOXED_TUPLE, 0),
                                                          "exc_info", exc_info_doc));
    sys_module->giveAttr("exc_clear",
                         new BoxedBuiltinFunctionOrMethod(FunctionMetadata::create((void*)sysExcClear, NONE, 0),
                                                          "exc_clear", exc_clear_doc));
    sys_module->giveAttr(
        "exit", new BoxedBuiltinFunctionOrMethod(FunctionMetadata::create((void*)sysExit, NONE, 1, false, false),
                                                 "exit", { None }, NULL, exit_doc));

    sys_module->giveAttr("warnoptions", new BoxedList());
    sys_module->giveAttrBorrowed("py3kwarning", Py_False);
    sys_module->giveAttr("byteorder", boxString(isLittleEndian() ? "little" : "big"));

    sys_module->giveAttr("platform", boxString(Py_GetPlatform()));

    sys_module->giveAttr("executable", boxString(Py_GetProgramFullPath()));

    sys_module->giveAttr(
        "_getframe",
        new BoxedFunction(FunctionMetadata::create((void*)sysGetFrame, UNKNOWN, 1, false, false), { NULL }));
    sys_module->giveAttr("_current_frames",
                         new BoxedFunction(FunctionMetadata::create((void*)sysCurrentFrames, UNKNOWN, 0)));
    sys_module->giveAttr("getdefaultencoding", new BoxedBuiltinFunctionOrMethod(
                                                   FunctionMetadata::create((void*)sysGetDefaultEncoding, STR, 0),
                                                   "getdefaultencoding", getdefaultencoding_doc));

    sys_module->giveAttr("getfilesystemencoding", new BoxedBuiltinFunctionOrMethod(
                                                      FunctionMetadata::create((void*)sysGetFilesystemEncoding, STR, 0),
                                                      "getfilesystemencoding", getfilesystemencoding_doc));

    sys_module->giveAttr("getrecursionlimit", new BoxedBuiltinFunctionOrMethod(
                                                  FunctionMetadata::create((void*)sysGetRecursionLimit, UNKNOWN, 0),
                                                  "getrecursionlimit", getrecursionlimit_doc));

    // As we don't support compile() etc yet force 'dont_write_bytecode' to true.
    sys_module->giveAttrBorrowed("dont_write_bytecode", Py_True);

    sys_module->giveAttr("prefix", boxString(Py_GetPrefix()));
    sys_module->giveAttr("exec_prefix", boxString(Py_GetExecPrefix()));

    sys_module->giveAttr("copyright",
                         boxString("Copyright 2014-2016 Dropbox.\nAll Rights Reserved.\n\nCopyright (c) 2001-2014 "
                                   "Python Software Foundation.\nAll Rights Reserved.\n\nCopyright (c) 2000 "
                                   "BeOpen.com.\nAll Rights Reserved.\n\nCopyright (c) 1995-2001 Corporation for "
                                   "National Research Initiatives.\nAll Rights Reserved.\n\nCopyright (c) "
                                   "1991-1995 Stichting Mathematisch Centrum, Amsterdam.\nAll Rights Reserved."));

    sys_module->giveAttr("version", boxString(generateVersionString()));
    sys_module->giveAttr("hexversion", boxInt(PY_VERSION_HEX));
    sys_module->giveAttr("subversion", BoxedTuple::create({ autoDecref(boxString("Pyston")), autoDecref(boxString("")),
                                                            autoDecref(boxString("")) }));
    sys_module->giveAttr("maxint", boxInt(PYSTON_INT_MAX));
    sys_module->giveAttr("maxsize", boxInt(PY_SSIZE_T_MAX));

    sys_flags_cls = BoxedClass::create(type_cls, object_cls, 0, 0, sizeof(BoxedSysFlags), false, "flags", false, NULL,
                                       NULL, false);
    sys_flags_cls->giveAttr(
        "__new__", new BoxedFunction(FunctionMetadata::create((void*)BoxedSysFlags::__new__, UNKNOWN, 1, true, true)));
    sys_flags_cls->tp_dealloc = (destructor)BoxedSysFlags::dealloc;
#define ADD(name) sys_flags_cls->giveAttrMember(STRINGIFY(name), T_OBJECT, offsetof(BoxedSysFlags, name));
    ADD(division_warning);
    ADD(bytes_warning);
    ADD(no_user_site);
    ADD(optimize);
#undef ADD

#define SET_SYS_FROM_STRING(key, value) sys_module->giveAttr((key), (value))
#ifdef Py_USING_UNICODE
    SET_SYS_FROM_STRING("maxunicode", PyInt_FromLong(PyUnicode_GetMax()));
#endif

/* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */
#ifndef PY_NO_SHORT_FLOAT_REPR
    SET_SYS_FROM_STRING("float_repr_style", PyString_FromString("short"));
#else
    SET_SYS_FROM_STRING("float_repr_style", PyString_FromString("legacy"));
#endif

    sys_flags_cls->freeze();

    auto sys_str = getStaticString("sys");
    for (auto& md : sys_methods) {
        sys_module->giveAttr(md.ml_name, new BoxedCApiFunction(&md, NULL, sys_str));
    }

    sys_module->giveAttrBorrowed("__displayhook__", sys_module->getattr(autoDecref(internStringMortal("displayhook"))));
    sys_module->giveAttr("flags", new BoxedSysFlags());
}
예제 #22
0
파일: SampleBuffer.cpp 프로젝트: floft/lmms
f_cnt_t SampleBuffer::decodeSampleOGGVorbis( const char * _f,
						int_sample_t * & _buf,
						ch_cnt_t & _channels,
						sample_rate_t & _samplerate )
{
	static ov_callbacks callbacks =
	{
		qfileReadCallback,
		qfileSeekCallback,
		qfileCloseCallback,
		qfileTellCallback
	} ;

	OggVorbis_File vf;

	f_cnt_t frames = 0;

	QFile * f = new QFile( _f );
	if( f->open( QFile::ReadOnly ) == false )
	{
		delete f;
		return 0;
	}

	int err = ov_open_callbacks( f, &vf, NULL, 0, callbacks );

	if( err < 0 )
	{
		switch( err )
		{
			case OV_EREAD:
				printf( "SampleBuffer::decodeSampleOGGVorbis():"
						" media read error\n" );
				break;
			case OV_ENOTVORBIS:
/*				printf( "SampleBuffer::decodeSampleOGGVorbis():"
					" not an Ogg Vorbis file\n" );*/
				break;
			case OV_EVERSION:
				printf( "SampleBuffer::decodeSampleOGGVorbis():"
						" vorbis version mismatch\n" );
				break;
			case OV_EBADHEADER:
				printf( "SampleBuffer::decodeSampleOGGVorbis():"
					" invalid Vorbis bitstream header\n" );
				break;
			case OV_EFAULT:
				printf( "SampleBuffer::decodeSampleOgg(): "
					"internal logic fault\n" );
				break;
		}
		delete f;
		return 0;
	}

	ov_pcm_seek( &vf, 0 );

   	_channels = ov_info( &vf, -1 )->channels;
   	_samplerate = ov_info( &vf, -1 )->rate;

	ogg_int64_t total = ov_pcm_total( &vf, -1 );

	_buf = new int_sample_t[total * _channels];
	int bitstream = 0;
	long bytes_read = 0;

	do
	{
		bytes_read = ov_read( &vf, (char *) &_buf[frames * _channels],
					( total - frames ) * _channels *
							BYTES_PER_INT_SAMPLE,
					isLittleEndian() ? 0 : 1,
					BYTES_PER_INT_SAMPLE, 1, &bitstream );
		if( bytes_read < 0 )
		{
			break;
		}
		frames += bytes_read / ( _channels * BYTES_PER_INT_SAMPLE );
	}
	while( bytes_read != 0 && bitstream == 0 );

	ov_clear( &vf );
	// if buffer isn't empty, convert it to float and write it down

	if ( frames > 0 && _buf != NULL )
	{
		convertIntToFloat ( _buf, frames, _channels);
	}

	return frames;
}
예제 #23
0
파일: RawVFile.cpp 프로젝트: transfix/SDF
SimpleVolumeData* RawVFile::loadFile(const string& fileName)
{
	SimpleVolumeData* simpleVolumeData = new SimpleVolumeData(128, 128, 128);

	FILE *fp=FOPEN(fileName.c_str(), "rb");
	unsigned int i, magic, dims[3], numTimeSteps, numVariables;
	float minExt[4], maxExt[4];

	// check to make sure the file exists
	if (!fp) {
		printf("Error: could not open file\n");
		delete simpleVolumeData; simpleVolumeData = 0;
		return false;
	}

	// read the header
	//
	// read the magic number
	fread(&magic, 1, sizeof(unsigned int), fp);
	if (isLittleEndian()) swapByteOrder(&magic, 1);
	if (magic != 0xBAADBEEF) {
		// doh! this isn't a RawV file
		printf("Error: file format is not recognized. (expecting RawV)\n");
		fclose(fp);
		return false;
	}
	// the dimensions, # of timesteps, # of variables, and min/max extents
	fread(dims, 3, sizeof(unsigned int), fp);
	fread(&numTimeSteps, 1, sizeof(unsigned int), fp);
	fread(&numVariables, 1, sizeof(unsigned int), fp);
	fread(minExt, 4, sizeof(float), fp);
	fread(maxExt, 4, sizeof(float), fp);
	if (isLittleEndian()) {
		swapByteOrder(dims, 3);
		swapByteOrder(&numTimeSteps, 1);
		swapByteOrder(&numVariables, 1);
		swapByteOrder(minExt, 4);
		swapByteOrder(maxExt, 4);
	}

	// call a bunch of set...() functions
	//
	// setNumberOfVariables() has the convenient side effect of cleaning up
	// any data that this instance might already be holding. (effectively wiping
	// the slate clean)
	simpleVolumeData->setNumberOfVariables(numVariables);
	// the rest ...
	simpleVolumeData->setDimensions(dims);
	simpleVolumeData->setMinExtent(minExt);
	simpleVolumeData->setMaxExtent(maxExt);

	// finish reading the header (variable names and types)
	for (i=0; i < numVariables; i++) {
		char name[64];
		unsigned char type;

		// read the type and the name of a variable
		fread(&type, 1, sizeof(unsigned char), fp);
		fread(name, 64, sizeof(char), fp);
		name[63] = '\0'; // just in case
		// call set...() functions
		switch(type) {
			case 1:	simpleVolumeData->setType(i, SimpleVolumeData::UCHAR); break;
			case 2: simpleVolumeData->setType(i, SimpleVolumeData::USHORT); break;
			case 3: simpleVolumeData->setType(i, SimpleVolumeData::ULONG); break;
			case 4: simpleVolumeData->setType(i, SimpleVolumeData::FLOAT); break;
			case 5: simpleVolumeData->setType(i, SimpleVolumeData::DOUBLE); break;
			default: break;
		}
		simpleVolumeData->setName(i, name);
	}
	
	// finally, read the data
	for (i=0; i < numVariables; i++) {
		// now that all the meta-data is filled in, allocate space for the variables
		unsigned char* data = new unsigned char [simpleVolumeData->getDataSize(i)];
		// read the data for this variables first (and only?) timestep
		fread(data, simpleVolumeData->getDataSize(i), 1, fp);
		// swap the byte order if needed
		if (isLittleEndian()) {
			switch(simpleVolumeData->getTypeSize(i)) {
				case 1:
					break;
				case 2:
					swapByteOrder((unsigned short *)data, dims[0]*dims[1]*dims[2]);
					break;
				case 4:
					swapByteOrder((float *)data, dims[0]*dims[1]*dims[2]);
					break;
				case 8:
					swapByteOrder((double *)data, dims[0]*dims[1]*dims[2]);
					break;
				default:
					break;
			}
		}
		simpleVolumeData->setData(i, data);
		// seek past any remaining timesteps
		if (numTimeSteps > 1)
			fseek(fp, simpleVolumeData->getDataSize(i)*(numTimeSteps-1), SEEK_CUR);
	}
	
	// close the file
	fclose(fp);
	
	return simpleVolumeData;
}
예제 #24
0
void ReadFile(char const *fileName, fluid_t *f)
{
  assert(fileName);
  assert(f);

  std::ifstream file(fileName, std::ios::binary);
  if(!file) {
    std::cerr << "Error opening file. Aborting." << std::endl;
    exit(1);
  }

  //Always use single precision float variables b/c file format uses single precision
  float restParticlesPerMeter_le;
  int numParticles_le;
  file.read((char *)&restParticlesPerMeter_le, FILE_SIZE_FLOAT);
  file.read((char *)&numParticles_le, FILE_SIZE_INT);
  if(!isLittleEndian()) {
    f->restParticlesPerMeter = bswap_float(restParticlesPerMeter_le);
    f->numParticles          = bswap_int32(numParticles_le);
  } else {
    f->restParticlesPerMeter = restParticlesPerMeter_le;
    f->numParticles          = numParticles_le;
  }
#if defined(SPARC_SOLARIS)
  f->bbox.min.x = MAXFLOAT;
  f->bbox.min.y = MAXFLOAT;
  f->bbox.min.z = MAXFLOAT;
  f->bbox.max.x = -MAXFLOAT;
  f->bbox.max.y = -MAXFLOAT;
  f->bbox.max.z = -MAXFLOAT;
#else
  f->bbox.min.x = INFINITY;
  f->bbox.min.y = INFINITY;
  f->bbox.min.z = INFINITY;
  f->bbox.max.x = -INFINITY;
  f->bbox.max.y = -INFINITY;
  f->bbox.max.z = -INFINITY;
#endif
  malloc_fluid(f, f->numParticles);

  //Always use single precision float variables b/c file format uses single precision
  float px, py, pz, hvx, hvy, hvz, vx, vy, vz;
  for(int i = 0; i < f->numParticles; ++i)
  {
    file.read((char *)&px, FILE_SIZE_FLOAT);
    file.read((char *)&py, FILE_SIZE_FLOAT);
    file.read((char *)&pz, FILE_SIZE_FLOAT);
    file.read((char *)&hvx, FILE_SIZE_FLOAT);
    file.read((char *)&hvy, FILE_SIZE_FLOAT);
    file.read((char *)&hvz, FILE_SIZE_FLOAT);
    file.read((char *)&vx, FILE_SIZE_FLOAT);
    file.read((char *)&vy, FILE_SIZE_FLOAT);
    file.read((char *)&vz, FILE_SIZE_FLOAT);
    if(!isLittleEndian()) {
      px  = bswap_float(px);
      py  = bswap_float(py);
      pz  = bswap_float(pz);
      hvx = bswap_float(hvx);
      hvy = bswap_float(hvy);
      hvz = bswap_float(hvz);
      vx  = bswap_float(vx);
      vy  = bswap_float(vy);
      vz  = bswap_float(vz);
    }

    //add particle to fluid structure
    f->p[i].x = px;
    f->p[i].y = py;
    f->p[i].z = pz;
    f->hv[i].x = hvx;
    f->hv[i].y = hvy;
    f->hv[i].z = hvz;
    f->v[i].x = vx;
    f->v[i].y = vy;
    f->v[i].z = vz;

    //update bounding box
    if(px < f->bbox.min.x) f->bbox.min.x = px;
    if(py < f->bbox.min.y) f->bbox.min.y = py;
    if(pz < f->bbox.min.z) f->bbox.min.z = pz;
    if(px > f->bbox.max.x) f->bbox.max.x = px;
    if(py > f->bbox.max.y) f->bbox.max.y = py;
    if(pz > f->bbox.max.z) f->bbox.max.z = pz;
  }
}
예제 #25
0
파일: RawIVFile.cpp 프로젝트: transfix/SDF
SimpleVolumeData* RawIVFile::loadFile(const string& fileName)
{
	SimpleVolumeData* simpleVolumeData = new SimpleVolumeData(128, 128, 128);

	FILE *fp=FOPEN(fileName.c_str(), "rb");
	unsigned int dims[3];
	unsigned int temp_numverts, temp_numcells; //for large files, these are meaningless, and anyway not used.
	float minExt[3], maxExt[3], orig[3], span[3];

	// check to make sure the file exists
	if (!fp) {
		printf("Error: could not open file\n");
		delete simpleVolumeData; simpleVolumeData = 0;
		return 0;
	}

	// read the header
	// 
	fread(minExt, 3, sizeof(float), fp);
	fread(maxExt, 3, sizeof(float), fp);
	fread(&temp_numverts, 1, sizeof(unsigned int), fp);
	fread(&temp_numcells, 1, sizeof(unsigned int), fp);
	fread(dims, 3, sizeof(unsigned int), fp);
	fread(orig, 3, sizeof(float), fp);
	fread(span, 3, sizeof(float), fp);
	if (isLittleEndian()) {
		swapByteOrder(minExt, 3);
		swapByteOrder(maxExt, 3);
		swapByteOrder(&temp_numverts, 1);
		swapByteOrder(&temp_numcells, 1);
		swapByteOrder(dims, 3);
		swapByteOrder(orig, 3);
		swapByteOrder(span, 3);
	}

	/*	//// only for NMJ project! //////
		{
			minExt[0] *= 150;
			minExt[1] *= 150;
			minExt[2] *= 150;
		}
		{
			maxExt[0] *= 150;
			maxExt[1] *= 150;
			maxExt[2] *= 150;

			orig[0] *= 150;
			orig[1] *= 150;
			orig[2] *= 150;

			span[0] = span[1] = span[2] = 150;
		}
	*/	/////////////////////////////////


	// find out how large the data is
	Q_ULLONG dataStart = ftell(fp), dataSize;
	fseek(fp, 0, SEEK_END);
	dataSize = ftell(fp) - dataStart;
	fseek(fp, dataStart, SEEK_SET);

	// a small sanity check to make sure this file is valid
	if ((dataSize % ((Q_ULLONG)dims[0]*dims[1]*dims[2])) != 0) {
		printf("Error: rawiv file header dimensions don't match file size");
		fclose(fp);
		return false;
	}
	
	// call some set...() functions
	//
	simpleVolumeData->setNumberOfVariables(1);
	simpleVolumeData->setDimensions(dims);
	simpleVolumeData->setMinExtent(minExt);
	simpleVolumeData->setMaxExtent(maxExt);

	// figure out the data type
	switch (dataSize / ((Q_ULLONG)dims[0]*dims[1]*dims[2])) 
	{
	case 1: simpleVolumeData->setType(0, SimpleVolumeData::UCHAR); break;
	case 2: simpleVolumeData->setType(0, SimpleVolumeData::USHORT); break;
	case 4: simpleVolumeData->setType(0, SimpleVolumeData::FLOAT); break;
	default: simpleVolumeData->setType(0, SimpleVolumeData::NO_TYPE); break;
	}

	// allocate space for the data
	unsigned char * data = (unsigned char*)malloc((Q_ULLONG)sizeof(unsigned char)*dataSize);

	// read the data
	fread(data, dataSize, 1, fp);
	// swap the byte order if needed
	if (isLittleEndian()) {
		switch(simpleVolumeData->getTypeSize(0)) {
			case 1:
				break;
			case 2:
				swapByteOrder((unsigned short *)data, (Q_ULLONG)dims[0]*dims[1]*dims[2]);
				break;
			case 4:
				swapByteOrder((float *)data, (Q_ULLONG)dims[0]*dims[1]*dims[2]);
				break;
			case 8:
				swapByteOrder((double *)data, (Q_ULLONG)dims[0]*dims[1]*dims[2]);
				break;
			default:
				break;
		}
	}

	simpleVolumeData->setData(0, data);
	// close the file

	fclose(fp);
	return simpleVolumeData;
}
예제 #26
0
파일: AudioAlsa.cpp 프로젝트: uro5h/lmms
int AudioAlsa::setHWParams( const ch_cnt_t _channels, snd_pcm_access_t _access )
{
	int err, dir;

	// choose all parameters
	if( ( err = snd_pcm_hw_params_any( m_handle, m_hwParams ) ) < 0 )
	{
		printf( "Broken configuration for playback: no configurations "
				"available: %s\n", snd_strerror( err ) );
		return err;
	}

	// set the interleaved read/write format
	if( ( err = snd_pcm_hw_params_set_access( m_handle, m_hwParams,
							_access ) ) < 0 )
	{
		printf( "Access type not available for playback: %s\n",
							snd_strerror( err ) );
		return err;
	}

	// set the sample format
	if( ( snd_pcm_hw_params_set_format( m_handle, m_hwParams,
						SND_PCM_FORMAT_S16_LE ) ) < 0 )
	{
		if( ( snd_pcm_hw_params_set_format( m_handle, m_hwParams,
						SND_PCM_FORMAT_S16_BE ) ) < 0 )
		{
			printf( "Neither little- nor big-endian available for "
					"playback: %s\n", snd_strerror( err ) );
			return err;
		}
		m_convertEndian = isLittleEndian();
	}
	else
	{
		m_convertEndian = !isLittleEndian();
	}

	// set the count of channels
	if( ( err = snd_pcm_hw_params_set_channels( m_handle, m_hwParams,
							_channels ) ) < 0 )
	{
		printf( "Channel count (%i) not available for playbacks: %s\n"
				"(Does your soundcard not support surround?)\n",
					_channels, snd_strerror( err ) );
		return err;
	}

	// set the sample rate
	if( ( err = snd_pcm_hw_params_set_rate( m_handle, m_hwParams,
						sampleRate(), 0 ) ) < 0 )
	{
		if( ( err = snd_pcm_hw_params_set_rate( m_handle, m_hwParams,
				mixer()->baseSampleRate(), 0 ) ) < 0 )
		{
			printf( "Could not set sample rate: %s\n",
							snd_strerror( err ) );
			return err;
		}
	}

	m_periodSize = mixer()->framesPerPeriod();
	m_bufferSize = m_periodSize * 8;
	dir = 0;
	err = snd_pcm_hw_params_set_period_size_near( m_handle, m_hwParams,
							&m_periodSize, &dir );
	if( err < 0 )
	{
		printf( "Unable to set period size %lu for playback: %s\n",
					m_periodSize, snd_strerror( err ) );
		return err;
	}
	dir = 0;
	err = snd_pcm_hw_params_get_period_size( m_hwParams, &m_periodSize,
									&dir );
	if( err < 0 )
	{
		printf( "Unable to get period size for playback: %s\n",
							snd_strerror( err ) );
	}

	dir = 0;
	err = snd_pcm_hw_params_set_buffer_size_near( m_handle, m_hwParams,
								&m_bufferSize );
	if( err < 0 )
	{
		printf( "Unable to set buffer size %lu for playback: %s\n",
					m_bufferSize, snd_strerror( err ) );
		return ( err );
	}
	err = snd_pcm_hw_params_get_buffer_size( m_hwParams, &m_bufferSize );

	if( 2 * m_periodSize > m_bufferSize )
	{
		printf( "buffer to small, could not use\n" );
		return ( err );
	}


	// write the parameters to device
	err = snd_pcm_hw_params( m_handle, m_hwParams );
	if( err < 0 )
	{
		printf( "Unable to set hw params for playback: %s\n",
							snd_strerror( err ) );
		return ( err );
	}

	return ( 0 );	// all ok
}
예제 #27
0
파일: AudioOss.cpp 프로젝트: qnebra/lmms
AudioOss::AudioOss( bool & _success_ful, Mixer*  _mixer ) :
	AudioDevice( tLimit<ch_cnt_t>(
		ConfigManager::inst()->value( "audiooss", "channels" ).toInt(),
					DEFAULT_CHANNELS, SURROUND_CHANNELS ),
								_mixer ),
	m_convertEndian( false )
{
	_success_ful = false;

	m_audioFD = open( probeDevice().toLatin1().constData(), O_WRONLY, 0 );

	if( m_audioFD == -1 )
	{
		printf( "AudioOss: failed opening audio-device\n" );
		return;
	}


	// Make the file descriptor use blocking writes with fcntl()
	if ( fcntl( m_audioFD, F_SETFL, fcntl( m_audioFD, F_GETFL ) &
							~O_NONBLOCK ) < 0 )
	{
		printf( "could not set audio blocking mode\n" );
		return;
	}

	// set FD_CLOEXEC flag for file descriptor so forked processes
	// do not inherit it
	fcntl( m_audioFD, F_SETFD, fcntl( m_audioFD, F_GETFD ) | FD_CLOEXEC );

	int frag_spec;
	for( frag_spec = 0; static_cast<int>( 0x01 << frag_spec ) <
		mixer()->framesPerPeriod() * channels() *
							BYTES_PER_INT_SAMPLE;
		++frag_spec )
	{
	}

	frag_spec |= 0x00020000;	// two fragments, for low latency

	if ( ioctl( m_audioFD, SNDCTL_DSP_SETFRAGMENT, &frag_spec ) < 0 )
	{
		perror( "SNDCTL_DSP_SETFRAGMENT" );
		printf( "Warning: Couldn't set audio fragment size\n" );
	}

	unsigned int value;
	// Get a list of supported hardware formats
	if ( ioctl( m_audioFD, SNDCTL_DSP_GETFMTS, &value ) < 0 )
	{
		perror( "SNDCTL_DSP_GETFMTS" );
		printf( "Couldn't get audio format list\n" );
		return;
	}

	// Set the audio format
	if( value & AFMT_S16_LE )
	{
		value = AFMT_S16_LE;
	}
	else if( value & AFMT_S16_BE )
	{
		value = AFMT_S16_BE;
	}
	else
	{
		printf(" Soundcard doesn't support signed 16-bit-data\n");
	}
	if ( ioctl( m_audioFD, SNDCTL_DSP_SETFMT, &value ) < 0 )
	{
		perror( "SNDCTL_DSP_SETFMT" );
		printf( "Couldn't set audio format\n" );
		return;
	}
	if( ( isLittleEndian() && ( value == AFMT_S16_BE ) ) ||
			( !isLittleEndian() && ( value == AFMT_S16_LE ) ) )
	{
		m_convertEndian = true;
	}

	// Set the number of channels of output
	value = channels();
	if ( ioctl( m_audioFD, SNDCTL_DSP_CHANNELS, &value ) < 0 )
	{
		perror( "SNDCTL_DSP_CHANNELS" );
		printf( "Cannot set the number of channels\n" );
		return;
	}
	if( value != channels() )
	{
		printf( "Couldn't set number of channels\n" );
		return;
	}

	// Set the DSP frequency
	value = sampleRate();
	if ( ioctl( m_audioFD, SNDCTL_DSP_SPEED, &value ) < 0 )
	{
		perror( "SNDCTL_DSP_SPEED" );
		printf( "Couldn't set audio frequency\n" );
		return;
	}
	if( value != sampleRate() )
	{
		value = mixer()->baseSampleRate();
		if ( ioctl( m_audioFD, SNDCTL_DSP_SPEED, &value ) < 0 )
		{
			perror( "SNDCTL_DSP_SPEED" );
			printf( "Couldn't set audio frequency\n" );
			return;
		}
		setSampleRate( value );
	}

	_success_ful = true;
}
예제 #28
0
void NetUtil::host2Net(const void *source, void *result, size_t length)
{
    if(isLittleEndian())   //只有小字节序才需要转换,大字节序和网络字节序是一致的
        reverseBytes(source, result, length);
}
예제 #29
0
 //: check the system for endianess
 inline bool isBigEndian()
 {
    return !isLittleEndian();
 }   
예제 #30
0
파일: AudioSndio.cpp 프로젝트: qnebra/lmms
AudioSndio::AudioSndio(bool & _success_ful, Mixer * _mixer) :
	AudioDevice( tLimit<ch_cnt_t>(
	    ConfigManager::inst()->value( "audiosndio", "channels" ).toInt(),
	    DEFAULT_CHANNELS, SURROUND_CHANNELS ), _mixer ),
            m_convertEndian ( false )
{
	_success_ful = false;

	QString dev = ConfigManager::inst()->value( "audiosndio", "device" );

	if (dev == "")
	{
		m_hdl = sio_open( NULL, SIO_PLAY, 0 );
	}
	else
	{
		m_hdl = sio_open( dev.toLatin1().constData(), SIO_PLAY, 0 );
	}

	if( m_hdl == NULL )
	{
		printf( "sndio: failed opening audio-device\n" );
		return;
	}

	sio_initpar(&m_par);

	m_par.pchan = channels();
	m_par.bits = 16;
	m_par.le = SIO_LE_NATIVE;
	m_par.rate = sampleRate();
	m_par.round = mixer()->framesPerPeriod();
	m_par.appbufsz = m_par.round * 2;

	if ( (isLittleEndian() && (m_par.le == 0)) ||
	     (!isLittleEndian() && (m_par.le == 1))) {
		m_convertEndian = true;
	}

	struct sio_par reqpar = m_par;

	if (!sio_setpar(m_hdl, &m_par))
	{
		printf( "sndio: sio_setpar failed\n" );
		return;
	}
	if (!sio_getpar(m_hdl, &m_par))
	{
		printf( "sndio: sio_getpar failed\n" );
		return;
	}

	if (reqpar.pchan != m_par.pchan ||
		reqpar.bits != m_par.bits ||
		reqpar.le != m_par.le ||
		(::abs(static_cast<int>(reqpar.rate) - static_cast<int>(m_par.rate)) * 100)/reqpar.rate > 2)
	{
		printf( "sndio: returned params not as requested\n" );
		return;
	}

	if (!sio_start(m_hdl))
	{
		printf( "sndio: sio_start failed\n" );
		return;
	}

	_success_ful = true;
}