Exemplo n.º 1
0
/*
 * Destroys already-used random numbers.  Ensures no sensitive data
 * remains in memory that can be recovered later.  This is also
 * called to "stir in" newly acquired environmental noise bits before
 * removing any random bytes.
 *
 * The transformation is carried out by "encrypting" the data in CFB
 * mode with MD5 as the block cipher.  Then, to make certain the stirring
 * operation is strictly one-way, we destroy the key, getting 64 bytes
 * from the beginning of the pool and using them to reinitialize the
 * key.  These bytes are not returned by randPoolGetBytes().
 *
 * The key for the stirring operation is the XOR of some bytes from the
 * previous pool contents (not provably necessary, but it produces uniformly
 * distributed keys, which "feels better") and the newly added raw noise,
 * which will have a profound effect on every bit in the pool.
 *
 * To make this useful for pseudo-random (that is, repeatable) operations,
 * the MD5 transformation is always done with a consistent byte order.
 * MD5Transform itself works with 32-bit words, not bytes, so the pool,
 * usually an array of bytes, is transformed into an array of 32-bit words,
 * taking each group of 4 bytes in big-endian order.  At the end of the
 * stirring, the transformation is reversed.
 */
void
randPoolStir(void)
{
	int i;
	word32 iv[4];

	/* Convert to word32s for stirring operation */
	byteSwap(randPool, RANDPOOLWORDS);
	byteSwap(randKey, RANDKEYWORDS);

	/* Start IV from last block of randPool */
	memcpy(iv, randPool+RANDPOOLWORDS-4, sizeof(iv));

	/* CFB pass */
	for (i = 0; i < RANDPOOLWORDS; i += 4) {
		MD5Transform(iv, randKey);
		iv[0] = randPool[i  ] ^= iv[0];
		iv[1] = randPool[i+1] ^= iv[1];
		iv[2] = randPool[i+2] ^= iv[2];
		iv[3] = randPool[i+3] ^= iv[3];
	}

	/* Wipe iv from memory */
	iv[3] = iv[2] = iv[1] = iv[0] = 0;

	/* Convert randPool back to bytes for further use */
	byteSwap(randPool, RANDPOOLWORDS);

	/* Get new key */
	memcpy(randKey, randPool, sizeof(randKey));

	/* Set up pointers for future addition or removal of random bytes */
	randKeyAddPos = 0;
	randPoolGetPos = sizeof(randKey);
}
Exemplo n.º 2
0
/*
 * Then there are the systems that are perfectly happy with MSBFirst data, but
 * byte swap the shorts that are used.  We fix that here.
 *
 * The htons() routine is a defined to be a no-op on machines that don't have
 * this problem.
 *
 */
void
SwapBitmaps()
{
	int i;

	byteSwap(normalArrows, 4);
	byteSwap(missile, 1);
	for (i = 0; i < ratBits_width * ratBits_height / 16; i += 64)
		byteSwap((BitCell *) &ratBits[i], 4);
}
Exemplo n.º 3
0
int coReadSTP3::readVoiSlice(FILE *vfp, int voi_num, vector<float> *x, vector<float> *y)
{
    x->clear();
    y->clear();

    for (int voi = 0; voi < MAX_VOIS && voi < voi_total_no; voi++)
    {
        int32_t no_contours;
        if (fread(&no_contours, sizeof(no_contours), 1, vfp) != sizeof(no_contours))
        {
            fprintf(stderr, "fread_48 failed in ReadSTP3.cpp");
        }
        byteSwap(no_contours);
        if (no_contours > 0)
        {
            int32_t no_points;
            if (fread(&no_points, sizeof(no_points), 1, vfp) != sizeof(no_points))
            {
                fprintf(stderr, "fread_49 failed in ReadSTP3.cpp");
            }
            byteSwap(no_points);
            if (voi == voi_num)
            {
                //fprintf(stderr, "slice %d: voi %d, %d contours, %d points\n", i, voi, no_contours, no_points);
                x->reserve(no_points);
                y->reserve(no_points);
            }

            for (int p = 0; p < no_points; p++)
            {
                double d;
                if (fread(&d, sizeof(d), 1, vfp) != sizeof(d))
                {
                    fprintf(stderr, "fread_50 failed in ReadSTP3.cpp");
                }
                if (voi == voi_num)
                {
                    byteSwap(d);
                    y->push_back(float(d / 1023.) * resolution);
                }
                if (fread(&d, sizeof(d), 1, vfp) != sizeof(d))
                {
                    fprintf(stderr, "fread_51 failed in ReadSTP3.cpp");
                }
                if (voi == voi_num)
                {
                    byteSwap(d);
                    x->push_back(float(d / 1023.) * resolution);
                }
            }
        }
    }

    return 0;
}
Exemplo n.º 4
0
 uint32_t PacketOutputStream::finish(void)
 {
     uint32_t value = byteSwap(static_cast<uint32_t>(styxBuffer.size()));
     uint32_t *lengthPtr = reinterpret_cast<uint32_t*>(&styxBuffer[0]);
     *lengthPtr = value;
     return static_cast<uint32_t>(styxBuffer.size());
 }
Exemplo n.º 5
0
void String::copyFromUTF16(const wchar_t *s, size_t length, Type t)
{
  bool swap;
  if(t == UTF16) {
    if(length >= 1 && s[0] == 0xfeff) 
      swap = false; // Same as CPU endian. No need to swap bytes.
    else if(length >= 1 && s[0] == 0xfffe) 
      swap = true;  // Not same as CPU endian. Need to swap bytes.
    else {
      debug("String::copyFromUTF16() - Invalid UTF16 string.");
      return;
    }

    s++;
    length--;
  }
  else 
    swap = (t != WCharByteOrder);

  d->data.resize(length);
  memcpy(&d->data[0], s, length * sizeof(wchar_t));

  if(swap) {
    for(size_t i = 0; i < length; ++i)
      d->data[i] = byteSwap(static_cast<ushort>(s[i]));
  }
}
Exemplo n.º 6
0
void CPHDWriter::DataWriterLittleEndian::operator()(
        const sys::ubyte* data,
        size_t numElements,
        size_t elementSize)
{
    size_t dataProcessed = 0;
    const size_t dataSize = numElements * elementSize;

    while (dataProcessed < dataSize)
    {
        const size_t dataToProcess =
                std::min(mScratchSize, dataSize - dataProcessed);

        memcpy(mScratch.get(),
               data + dataProcessed,
               dataToProcess);

        byteSwap(mScratch.get(),
                 elementSize,
                 dataToProcess / elementSize,
                 mNumThreads);

        mStream.write(mScratch.get(), dataToProcess);

        dataProcessed += dataToProcess;
    }
}
Exemplo n.º 7
0
 void byteSwap(int (*ptr)[2], const int n1, const int n2) {
   assert(n2 == 2);
   for (int i = 0; i < n1; i++) {
     for (int j = 0; j < 2; j++) {
       ptr[i][j] = byteSwap(ptr[i][j]);
     }
   }
 }
Exemplo n.º 8
0
 void byteSwap(double (*ptr)[3], const int n1, const int n2) {
   assert(n2 == 3);
   for (int i = 0; i < n1; i++) {
     for (int j = 0; j < 3; j++) {
       ptr[i][j] = byteSwap(ptr[i][j]);
     }
   }
 }
Exemplo n.º 9
0
void VrmlNodeMultiTouchSensor::handleMultiTouchEvent(int type, int len, const void *buf)
{
    (void)len;
    if (type == MULTI_TOUCH_EVENTS)
    {
        bool visible;
        float pos[3];
        float angle;
        float *fbuf;
        int *ibuf = (int *)buf;
#ifdef BYTESWAP
        byteSwap(*ibuf);
#endif
        visible = (*ibuf) != 0;
        ibuf++;
        int i;
        fbuf = (float *)ibuf;
        for (i = 0; i < 3; i++)
        {
            pos[i] = *fbuf;
// cerr << "bs " << pos[i]<<endl;
#ifdef BYTESWAP
            byteSwap(pos[i]);
#endif
            //cerr << "real " << pos[i]<<endl;
            fbuf++;
        }
        angle = *fbuf;
#ifdef BYTESWAP
        byteSwap(angle);
#endif
        fbuf++;
        char *cbuf = (char *)fbuf;
        cerr << "name:" << cbuf << endl;
        //strcpy(buf,markerName);
        list<VrmlNodeMultiTouchSensor *>::iterator n;
        for (n = multiTouchSensors.begin(); n != multiTouchSensors.end(); ++n)
        {
            if ((*n)->getMarkerName() == std::string(cbuf))
            {
                (*n)->remoteUpdate(visible, pos, angle);
                return;
            }
        }
    }
}
Exemplo n.º 10
0
void AAUDecoder::header()
{
  if(!fd) return;
  //if(errorFlag) return;
  fseek(fd,0,SEEK_SET);
  uint32_t foo;
  fread(&foo,4,1,fd);  // skip magic word...
  uint32_t loc;
  fread(&loc,4,1,fd);
  if(littleEndian) byteSwap(&loc);
  uint32_t size;
  fread(&size,4,1,fd);
  if(littleEndian) byteSwap(&size);
  uint32_t format;
  fread(&format,4,1,fd);
  if(littleEndian) byteSwap(&format);
  uint32_t rate;
  fread(&rate,4,1,fd);
  if(littleEndian) byteSwap(&rate);
  uint32_t channels;
  fread(&channels,4,1,fd);
  if(littleEndian) byteSwap(&channels);
  DEBUG_OUT<<"Sun/NeXT .au file.\n";
  DEBUG_OUT<<"loc: "<<loc<<"\n";
  DEBUG_OUT<<"size: "<<size<<"\n";
  DEBUG_OUT<<"format: "<<format<<"\n";
  DEBUG_OUT<<"rate: "<<rate<<"\n";
  DEBUG_OUT<<"channels: "<<channels<<"\n";
  sampleRate=rate;
  if(channels==2) stereo=true; else stereo=false;
  numBits=8;
  switch(format) {
    case 1: numBits=8; break;  //mu-law
    case 2: numBits=8; break;  //linear
    case 3: numBits=16; break;  //linear
    case 4: numBits=24; break;  //linear
    case 5: numBits=32; break;  //linear
    case 27: numBits=8; break;  //alaw
    default: DEBUG_OUT<<"Some other format...\n"; break;
  }
  dataLoc=loc;
  dataSize=size;
}
Exemplo n.º 11
0
  void byteSwap(double (*ptr)[3][3], const int n1, const int n2, const int n3) {
    assert(n2 == 3);
    assert(n3 == 3);
    for (int i = 0; i < n1; i++) {
      for (int j = 0; j < 3; j++) {
	for (int k = 0; k < 3; k++) {
	  ptr[i][j][k] = byteSwap(ptr[i][j][k]);
	}
      }
    }
  }
Exemplo n.º 12
0
/** get a certain step of a specified field into a given buffer
 * @return =0 ok, errno otherwise, stepNo is ignored
 */
int FuellDruckData::readField(int fieldNo, int stepNo, void *buffer)
{
    (void)stepNo;
    // this implementation wastes some storage, but is faster.
    // Cadmould simulations are vers small, so it's ok.
    float *filebuffer = new float[6 * d_numVert];

    // position behind the min/max fields (2x6)
    d_file = fopen(path_.c_str(), "r");
    if (!d_file
        || fseek(d_file, 12 * sizeof(float), SEEK_SET) != 0)
    {
        d_state = errno;
        return -1;
    }

    // read the complete file
    if (fread(filebuffer, sizeof(float), 6 * d_numVert, d_file) != 6 * d_numVert)
    {
        d_state = errno;
        fclose(d_file);
        d_file = NULL;
        return -1;
    }
    fclose(d_file);
    d_file = NULL;

    // now copy the correct field
    float *fPtr = filebuffer + fieldNo;
    float *bPtr = static_cast<float *>(buffer);
    int i;
    for (i = 0; i < d_numVert; i++)
    {
        *bPtr = *fPtr;
        ++bPtr;
        fPtr += 6;
    }

    // byteswap if we have to
    if (byte_swap)
    {
        byteSwap(d_numVert, buffer);
    }

    // scratch out parts
    //for (i=0;i<d_numVert;i++) {
    //   if (buffer[i]==-1.0)
    //      buffer[i]=FLT_MAX;
    //}

    return 0;
}
Exemplo n.º 13
0
void testUtility(){

 int i,n;
 short int b[]={4,11,8,10,6,8};
 n=6;
 
 printf("\nUtilities\n");
 printf("Byte swap\n");
 
 byteSwap(b, n, 2);

 for (i=0;i<n;i++){
  printf("%d ",b[i]);
 } 
 printf("\n");

 byteSwap(b, n, 2);
 
 for (i=0;i<n;i++){
  printf("%d ",b[i]);
 } 
 printf("\n");

}
Exemplo n.º 14
0
bool DeepStarComponent::loadStaticStars() {
    FILE *dataFile;

    if( !staticStars )
        return true;
    if( !fileOpened )
        return false;

    dataFile = starReader.getFileHandle();
    rewind( dataFile );

    if( !starReader.readHeader() ) {
        qDebug() << "Error reading header of catalog file " << dataFileName << ": " << starReader.getErrorNumber() << ": " << starReader.getError() << endl;
        return false;
    }

    quint8 recordSize = starReader.guessRecordSize();
    if( recordSize != 16 && recordSize != 32 )
    {
        qDebug() << "Cannot understand catalog file " << dataFileName << endl;
        return false;
    }

    //KDE_fseek(dataFile, starReader.getDataOffset(), SEEK_SET);
    QT_FSEEK(dataFile, starReader.getDataOffset(), SEEK_SET);

    qint16 faintmag;
    quint8 htm_level;
    quint16 t_MSpT;

    fread( &faintmag, 2, 1, dataFile );
    if( starReader.getByteSwap() )
        faintmag = bswap_16( faintmag );
    fread( &htm_level, 1, 1, dataFile );
    fread( &t_MSpT, 2, 1, dataFile ); // Unused
    if( starReader.getByteSwap() )
        faintmag = bswap_16( faintmag );


    // TODO: Read the multiplying factor from the dataFile
    m_FaintMagnitude = faintmag / 100.0;

    if( htm_level != m_skyMesh->level() )
        qDebug() << "WARNING: HTM Level in shallow star data file and HTM Level in m_skyMesh do not match. EXPECT TROUBLE" << endl;

    // JM 2012-12-05: Breaking into into 2 loops instead of one previously with multiple IF checks for recordSize
    // While the CPU branch prediction might not suffer any penalities since the branch prediction after a few times
    // should always gets it right. It's better to do it this way to avoid any chances since the compiler might not optimize it.
    if (recordSize == 32)
    {
        for(Trixel i = 0; i < (unsigned int)m_skyMesh->size(); ++i)
        {
            Trixel trixel = i;
            quint64 records = starReader.getRecordCount( i );
            StarBlock *SB = new StarBlock( records );

            if( !SB )
                qDebug() << "ERROR: Could not allocate new StarBlock to hold shallow unnamed stars for trixel " << trixel << endl;

            m_starBlockList.at( trixel )->setStaticBlock( SB );

            for(quint64 j = 0; j < records; ++j)
            {
                bool fread_success = false;
                fread_success = fread( &stardata, sizeof( starData ), 1, dataFile );

                if( !fread_success )
                {
                    qDebug() << "ERROR: Could not read starData structure for star #" << j << " under trixel #" << trixel << endl;
                }

                /* Swap Bytes when required */
                if( starReader.getByteSwap() )
                    byteSwap( &stardata );

                /* Initialize star with data just read. */
                StarObject* star;
                #ifdef KSTARS_LITE
                star = &(SB->addStar( stardata )->star);
                #else
                star = SB->addStar( stardata );
                #endif
                if( star )
                {
                    //KStarsData* data = KStarsData::Instance();
                    //star->EquatorialToHorizontal( data->lst(), data->geo()->lat() );
                    //if( star->getHDIndex() != 0 )
                    if (stardata.HD)
                        m_CatalogNumber.insert( stardata.HD, star );
                }
                else
                {
                    qDebug() << "CODE ERROR: More unnamed static stars in trixel " << trixel << " than we allocated space for!" << endl;
                }
            }
        }
    }
    else
    {
        for(Trixel i = 0; i < (unsigned int)m_skyMesh->size(); ++i)
        {
            Trixel trixel = i;
            quint64 records = starReader.getRecordCount( i );
            StarBlock *SB = new StarBlock( records );

            if( !SB )
                qDebug() << "ERROR: Could not allocate new StarBlock to hold shallow unnamed stars for trixel " << trixel << endl;

            m_starBlockList.at( trixel )->setStaticBlock( SB );

            for(quint64 j = 0; j < records; ++j)
            {
                bool fread_success = false;
                fread_success = fread( &deepstardata, sizeof( deepStarData ), 1, dataFile );

                if( !fread_success )
                {
                    qDebug() << "ERROR: Could not read starData structure for star #" << j << " under trixel #" << trixel << endl;
                }

                /* Swap Bytes when required */
                if( starReader.getByteSwap() )
                    byteSwap( &deepstardata );

                /* Initialize star with data just read. */
                StarObject* star;
                #ifdef KSTARS_LITE
                star = &(SB->addStar( stardata )->star);
                #else
                star = SB->addStar( deepstardata );
                #endif
                if( star )
                {
                    //KStarsData* data = KStarsData::Instance();
                    //star->EquatorialToHorizontal( data->lst(), data->geo()->lat() );
                    //if( star->getHDIndex() != 0 )
                    if (stardata.HD)
                        m_CatalogNumber.insert( stardata.HD, star );
                }
                else
                {
                    qDebug() << "CODE ERROR: More unnamed static stars in trixel " << trixel << " than we allocated space for!" << endl;
                }
            }
        }
    }

    return true;
}
Exemplo n.º 15
0
 void byteSwap(double * ptr, const int n) {
   for (int i = 0; i < n; i++) {
     ptr[i] = byteSwap(ptr[i]);
   }
 }
Exemplo n.º 16
0
static void OME_EndElement(ParserState *state, const xmlChar *name) {
    /* We're at the end of an element. If the element had content, then we
    / need to print "</[elementName]>". If the element did not have
    / content, then we need to print "/>". I'm using a stack to keep track
    / of element's content, so I gotta check the stack and do stack
    / maintence.
    / Iff we are ending a BinData section, then we don't have to touch the
    / stack.
    */
    StructElementInfo *elementInfo;
    size_t nPix;
    OID ImageServerID;

    switch( state->state ) {


    /**************************************************************************
    *
    * Process <BinData>
    * 	write <BinData> contents to file & replace <BinData> with an
    * 	<External> that points to the file
    */
    case IN_BINDATA:
        state->state = PARSER_START;

        /* cleanup */
        b64z_decode_end ( state->binDataInfo->strm );
        free( state->binDataInfo->strm );
        state->binDataInfo->strm = NULL;

        if( state->binDataInfo->compression ) free( state->binDataInfo->compression );
        state->binDataInfo->compression = NULL;
        fclose( state->binDataInfo->BinDataOut );
        state->binDataInfo->BinDataOut = NULL;

        /* omeis transition: replace href with file id
        		fprintf( stdout, "<External xmlns=\"%s\" href=\"%s\" SHA1=\"\"/>", BinNS, state->pixelInfo->outputPath );
        */
        break;

    /*
    * END 'Process <BinData>'
    *
    **************************************************************************/



    /**************************************************************************
    *
    * Process <BinData> inside of <Pixels>
    *
    */
    case IN_BINDATA_UNDER_PIXELS:
        state->state = IN_PIXELS;

        /* Endian check */
        if( state->pixelInfo->bigEndian != bigEndian() &&
                state->pixelInfo->bpp > 1 )
            byteSwap( state->pixelInfo->binDataBuf, (size_t)state->pixelInfo->X * (size_t)state->pixelInfo->Y, state->pixelInfo->bpp );

        /* write a buffered Pixel's plane */
        nPix = setPixelPlane(
                   state->pixelInfo->pixWriter,
                   state->pixelInfo->binDataBuf,
                   state->pixelInfo->theZ,
                   state->pixelInfo->theC,
                   state->pixelInfo->theT );
        if( (unsigned int) nPix * state->pixelInfo->bpp != state->pixelInfo->planeSize ) {
            fprintf( stderr, "Error! tried to write a plane. expected to write %u bytes, actually wrote %u bytes!\n", state->pixelInfo->planeSize, (unsigned int) nPix );
            assert((unsigned int) nPix * state->pixelInfo->bpp == state->pixelInfo->planeSize);
        }

        /* logic to increment indexes based on dimOrder */
        if( strcmp( state->pixelInfo->dimOrder, "XYZCT" ) == 0 ) {
            increment_plane_indexes(
                &( state->pixelInfo->theZ ),
                &( state->pixelInfo->theC ),
                &( state->pixelInfo->theT ),
                state->pixelInfo->Z,
                state->pixelInfo->C,
                state->pixelInfo->T
            );
        } else if( strcmp( state->pixelInfo->dimOrder, "XYZTC" ) == 0 ) {
            increment_plane_indexes(
                &( state->pixelInfo->theZ ),
                &( state->pixelInfo->theT ),
                &( state->pixelInfo->theC ),
                state->pixelInfo->Z,
                state->pixelInfo->T,
                state->pixelInfo->C
            );
        } else if( strcmp( state->pixelInfo->dimOrder, "XYTZC" ) == 0 ) {
            increment_plane_indexes(
                &( state->pixelInfo->theT ),
                &( state->pixelInfo->theZ ),
                &( state->pixelInfo->theC ),
                state->pixelInfo->T,
                state->pixelInfo->Z,
                state->pixelInfo->C
            );
        } else if( strcmp( state->pixelInfo->dimOrder, "XYTCZ" ) == 0 ) {
            increment_plane_indexes(
                &( state->pixelInfo->theT ),
                &( state->pixelInfo->theC ),
                &( state->pixelInfo->theZ ),
                state->pixelInfo->T,
                state->pixelInfo->C,
                state->pixelInfo->Z
            );
        } else if( strcmp( state->pixelInfo->dimOrder, "XYCZT" ) == 0 ) {
            increment_plane_indexes(
                &( state->pixelInfo->theC ),
                &( state->pixelInfo->theZ ),
                &( state->pixelInfo->theT ),
                state->pixelInfo->C,
                state->pixelInfo->Z,
                state->pixelInfo->T
            );
        } else if( strcmp( state->pixelInfo->dimOrder, "XYCTZ" ) == 0 ) {
            increment_plane_indexes(
                &( state->pixelInfo->theC ),
                &( state->pixelInfo->theT ),
                &( state->pixelInfo->theZ ),
                state->pixelInfo->C,
                state->pixelInfo->T,
                state->pixelInfo->Z
            );
        }


        /* cleanup */
        b64z_decode_end( state->binDataInfo->strm );
        free( state->binDataInfo->strm );
        state->binDataInfo->strm = NULL;

        if( state->binDataInfo->compression ) free( state->binDataInfo->compression );
        state->binDataInfo->compression = NULL;

        break;
    /*
    * END 'Process <BinData> inside of <Pixels>'
    *
    **************************************************************************/


    case IN_PIXELS:
        state->state = PARSER_START;

        /* get SHA1, print SHA1 attribute  */
        if (get_md_from_fd (state->pixelInfo->pixWriter->fd_rep, state->pixelInfo->pixWriter->head->sha1) < 0) {
            fprintf(stderr, "Unable to retrieve SHA1.");
            assert(0);
        }
        fprintf( stdout,  " FileSHA1 = \"" );
        print_md( state->pixelInfo->pixWriter->head->sha1 );
        fprintf( stdout,  "\"" );

        /* close pixelsRep object; get ImageServerID from FinishPixels */
        if ( (ImageServerID = FinishPixels( state->pixelInfo->pixWriter, 0 )) == 0 ) {
            if (errno)
                fprintf (stderr,"%s\n",strerror( errno ) );
            else
                fprintf(stderr, "Access control error - check error log for details.\n");
            assert(0);
        }

        /* set ImageServerID */
        fprintf( stdout, " ImageServerID = \"%llu\" ", (unsigned long long)ImageServerID );

        /* cleanup */
        freePixelsRep (state->pixelInfo->pixWriter);
        free( state->pixelInfo->binDataBuf );
        free( state->pixelInfo->dimOrder );
        free( state->pixelInfo->pixelType );
        free( state->pixelInfo );
        state->pixelInfo = NULL;

    /* DO NOT "break;" Go on to default action of stack cleanup and
    / element closure.
    */

    default:
        /* Stack maintence */
        if( state->elementInfo != NULL ) {
            elementInfo = state->elementInfo;
            state->elementInfo = elementInfo->prev;
            if( elementInfo->hasContent == 0 ) {
                fprintf( stdout, "/>" );
            } else {
                fprintf( stdout, "</%s>", name );
            }
            free( elementInfo );
        }
    }


} /* END OME_EndElement */
Exemplo n.º 17
0
/// This is our compute-routine
int coReadSTP3::compute(const char *)
{
    char buf[1024];

    const char *path = pbrVolumeFile->getValue();
    FILE *fp = fopen(path, "rb");
    if (!fp)
    {
        sprintf(buf, "Failed to open file %s", path);
        sendInfo(buf);

        return STOP_PIPELINE;
    }

    float ignore_value = pfsIgnoreValue->getValue();

    int32_t image_type;
    if (fread(&image_type, sizeof(image_type), 1, fp) != sizeof(image_type))
    {
        fprintf(stderr, "fread_1 failed in ReadSTP3.cpp");
    }
    byteSwap(image_type);
    int32_t series_header;
    if (fread(&series_header, sizeof(series_header), 1, fp) != sizeof(series_header))
    {
        fprintf(stderr, "fread_2 failed in ReadSTP3.cpp");
    }
    byteSwap(series_header);
    int32_t image_header;
    if (fread(&image_header, sizeof(image_header), 1, fp) != sizeof(image_header))
    {
        fprintf(stderr, "fread_3 failed in ReadSTP3.cpp");
    }
    byteSwap(image_header);
    int32_t image_length;
    if (fread(&image_length, sizeof(image_length), 1, fp) != sizeof(image_length))
    {
        fprintf(stderr, "fread_4 failed in ReadSTP3.cpp");
    }
    byteSwap(image_length);
    char patient_name[81];
    if (fread(patient_name, 1, 80, fp) != 1)
    {
        fprintf(stderr, "fread_5 failed in ReadSTP3.cpp");
    }
    patient_name[80] = '\0';
    char comment[81];
    if (fread(comment, 1, 80, fp) != 1)
    {
        fprintf(stderr, "fread_6 failed in ReadSTP3.cpp");
    }
    comment[80] = '\0';
    if (fread(&resolution, sizeof(resolution), 1, fp) != sizeof(resolution))
    {
        fprintf(stderr, "fread_7 failed in ReadSTP3.cpp");
    }
    byteSwap(resolution);
    int32_t byte_per_voxel;
    if (fread(&byte_per_voxel, sizeof(byte_per_voxel), 1, fp) != sizeof(byte_per_voxel))
    {
        fprintf(stderr, "fread_8 failed in ReadSTP3.cpp");
    }
    byteSwap(byte_per_voxel);
    if (fread(&num_slices, sizeof(num_slices), 1, fp) != sizeof(num_slices))
    {
        fprintf(stderr, "fread_9 failed in ReadSTP3.cpp");
    }
    byteSwap(num_slices);
    double psiz;
    if (fread(&psiz, sizeof(psiz), 1, fp) != sizeof(psiz))
    {
        fprintf(stderr, "fread_10 failed in ReadSTP3.cpp");
    }
    byteSwap(psiz);
    pixel_size = (float)psiz;
    char date[81];
    if (fread(date, 1, 80, fp) != 1)
    {
        fprintf(stderr, "fread_11 failed in ReadSTP3.cpp");
    }
    date[80] = '\0';

    char *image_type_desc = "(unknown)";
    switch (image_type)
    {
    case 1:
    case 100:
        image_type = 1;
        image_type_desc = "CT";
        break;
    case 2:
    case 200:
        image_type = 2;
        image_type_desc = "MR";
        break;
    case 3:
    case 410:
        image_type = 3;
        image_type_desc = "PET";
        break;
    }

    sprintf(buf, "Reading %s: %s image, %dx%d pixels, %d slices, %d byte/voxel",
            path, image_type_desc, (int)resolution, (int)resolution, (int)num_slices, (int)byte_per_voxel);
    sendInfo(buf);
    sprintf(buf, "Patient: %s", patient_name);
    sendInfo(buf);
    sprintf(buf, "Comment: %s", comment);
    sendInfo(buf);
    //sprintf(buf, "Date:    %s", date);
    //sendInfo(buf);

    slice_z = new float[num_slices];

    FILE *vfp = NULL;
    int32_t voi_header;
    bool read_voi = pboUseVoi->getValue();
    voi_total_no = 0;
    if (read_voi)
    {
        char *voiPath = new char[strlen(path) + 5];
        strcpy(voiPath, path);
        char *ext = strrchr(voiPath, '.');
        if (ext)
        {
            strcpy(ext, ".vois");
        }
        else
        {
            strcat(voiPath, ".vois");
        }

        vfp = fopen(voiPath, "rb");
        if (!vfp)
        {
            sprintf(buf, "Failed to open voi file %s", voiPath);
            sendInfo(buf);

            read_voi = false;
        }
        else
        {
            int32_t voi_version_number;
            if (fread(&voi_version_number, sizeof(voi_version_number), 1, vfp) != sizeof(voi_version_number))
            {
                fprintf(stderr, "fread_12 failed in ReadSTP3.cpp");
            } // 340
            byteSwap(voi_version_number);

            if (fread(&voi_header, sizeof(voi_header), 1, vfp) != sizeof(voi_header))
            {
                fprintf(stderr, "fread_13 failed in ReadSTP3.cpp");
            } // 2048
            byteSwap(voi_header);
            //fprintf(stderr, "voi_header=%d\n", voi_header);

            char voi_patient_name[81];
            if (fread(voi_patient_name, 1, 80, vfp) != 1)
            {
                fprintf(stderr, "fread_14 failed in ReadSTP3.cpp");
            }
            voi_patient_name[80] = '\0';
            char dummy_name[81];
            if (fread(dummy_name, 1, 80, vfp) != 1)
            {
                fprintf(stderr, "fread_15 failed in ReadSTP3.cpp");
            } // empty

            if (fread(&voi_total_no, sizeof(voi_total_no), 1, vfp) != sizeof(voi_total_no))
            {
                fprintf(stderr, "fread_16 failed in ReadSTP3.cpp");
            } // 20
            byteSwap(voi_total_no);

            int32_t voi_slices;
            if (fread(&voi_slices, sizeof(voi_slices), 1, vfp) != sizeof(voi_slices))
            {
                fprintf(stderr, "fread_17 failed in ReadSTP3.cpp");
            }
            byteSwap(voi_slices);

            sprintf(buf, "VOI Patient: %s", voi_patient_name);
            sendInfo(buf);

            sprintf(buf, "No. of vois: %d, no. of slices for vois: %d",
                    voi_total_no, voi_slices);
            sendInfo(buf);
        }
    }

    int voi_num = pisVoiNo->getValue();
    int32_t voi_property, voi_first_slice, voi_last_slice, voi_color;
    char voi_name[41];
    if (read_voi && voi_num < MAX_VOIS && voi_num < voi_total_no)
    {
        fseek(vfp, voi_header + VOI_DESC_SIZE * voi_num, SEEK_SET);
        if (fread(&voi_property, sizeof(voi_property), 1, vfp) != sizeof(voi_property))
        {
            fprintf(stderr, "fread_18 failed in ReadSTP3.cpp");
        }
        byteSwap(voi_property);
        if (fread(voi_name, 40, 1, vfp) != 40)
        {
            fprintf(stderr, "fread_19 failed in ReadSTP3.cpp");
        }
        voi_name[40] = '\0';
        if (fread(&voi_first_slice, sizeof(voi_first_slice), 1, vfp) != sizeof(voi_first_slice))
        {
            fprintf(stderr, "fread_20 failed in ReadSTP3.cpp");
        }
        byteSwap(voi_first_slice);
        if (fread(&voi_last_slice, sizeof(voi_last_slice), 1, vfp) != sizeof(voi_last_slice))
        {
            fprintf(stderr, "fread_21 failed in ReadSTP3.cpp");
        }
        byteSwap(voi_last_slice);
        if (fread(&voi_color, sizeof(voi_color), 1, vfp) != sizeof(voi_color))
        {
            fprintf(stderr, "fread_22 failed in ReadSTP3.cpp");
        }
        byteSwap(voi_color);
        fprintf(stderr, "voi name: %s, first=%d, last=%d\n", voi_name, voi_first_slice, voi_last_slice);
    }
    else
    {
        read_voi = false;
    }

    if (read_voi)
    {
        voi_first_slice--;
        voi_last_slice--;
    }
    else
    {
        voi_first_slice = 0;
        voi_last_slice = num_slices - 1;
    }

    coDoFloat *dataOut = new coDoFloat(poVolume->getObjName(),
                                       resolution * resolution * num_slices);
    float *data = NULL;
    dataOut->getAddress(&data);
    size_t slice_size = resolution * resolution * byte_per_voxel;
    unsigned char *slice = new unsigned char[slice_size];
    float minZ = -1.0, maxZ = 1.0;
    for (int i = 0; i < num_slices; i++)
    {
        long fpos = series_header + i * image_header + i * image_length;
        fseek(fp, fpos, SEEK_SET);
        int32_t image_type;
        if (fread(&image_type, sizeof(image_type), 1, fp) != sizeof(image_type))
        {
            fprintf(stderr, "fread_23 failed in ReadSTP3.cpp");
        }
        byteSwap(image_type);

        double z_pos;
        if (fread(&z_pos, sizeof(double), 1, fp) != sizeof(double))
        {
            fprintf(stderr, "fread_24 failed in ReadSTP3.cpp");
        }
        byteSwap(z_pos);
        slice_z[i] = z_pos;
        float z_position = (float)z_pos;
        double gantry;
        if (fread(&gantry, sizeof(double), 1, fp) != sizeof(double))
        {
            fprintf(stderr, "fread_25 failed in ReadSTP3.cpp");
        }
        byteSwap(gantry);
        //float gantry_tilt = (float)gantry;

        if (i == 0)
        {
            minZ = z_position;
        }
        else if (i == num_slices - 1)
        {
            maxZ = z_position;
        }
    }

    if (read_voi)
    {
        fseek(vfp, voi_header + VOI_DESC_SIZE * MAX_VOIS, SEEK_SET);
        //fprintf(stderr, "pos=%d\n", voi_header+VOI_DESC_SIZE*MAX_VOIS);
    }

    for (int i = 0; i < num_slices; i++)
    {
        vector<float> p_x, p_y;
        readVoiSlice(vfp, voi_num, &p_x, &p_y);

        long fpos = series_header + (i + 1) * image_header + i * image_length;
#if 0
      if(minZ > maxZ)
      {
         fpos = series_header + (num_slices-1-i-1)*image_header + (num_slices-1-i)*image_length;
      }
#endif
        fseek(fp, fpos, SEEK_SET);
        if (fread(slice, slice_size, 1, fp) != slice_size)
        {
            fprintf(stderr, "fread_26 failed in ReadSTP3.cpp");
        }

        for (int y = 0; y < resolution; y++)
        {
            vector<float> i_x;
            computeIntersections(y, p_x, p_y, &i_x);

            int no_isect = 0;
            for (int x = 0; x < resolution; x++)
            {
                while (no_isect < i_x.size() && i_x[no_isect] < x)
                    no_isect++;

                int j = x * resolution + y;
                int k = ((y * resolution) + x) * num_slices + i;
                if (byte_per_voxel == 1)
                {
                    data[k] = slice[j] / 255.f;
                }
                else if (byte_per_voxel == 2)
                {
                    data[k] = (256.f * slice[j * 2] + slice[j * 2 + 1]) / 65535.f;
                }
                else
                {
                    data[k] = 0.f;
                }
                if (read_voi && no_isect % 2 == 0)
                {
                    data[k] = ignore_value;
                }
            }
        }

        p_x.clear();
        p_y.clear();
    }
    if (fp)
        fclose(fp);

    coDoFloat *voiOut[NO_VOIS];
    for (int v = 0; v < NO_VOIS; v++)
    {
        if (!poVoi[v]->isConnected())
        {
            voiOut[v] = NULL;
            continue;
        }

        voiOut[v] = new coDoFloat(poVoi[v]->getObjName(),
                                  resolution * resolution * num_slices);
        float *data = NULL;
        voiOut[v]->getAddress(&data);

        voi_num = pisVolumeFromVoi[v]->getValue();

        if (read_voi && voi_num < MAX_VOIS && voi_num < voi_total_no)
        {
            fseek(vfp, voi_header + VOI_DESC_SIZE * voi_num, SEEK_SET);
            if (fread(&voi_property, sizeof(voi_property), 1, vfp) != sizeof(voi_property))
            {
                fprintf(stderr, "fread_27 failed in ReadSTP3.cpp");
            }
            byteSwap(voi_property);
            if (fread(voi_name, 40, 1, vfp) != 40)
            {
                fprintf(stderr, "fread_28 failed in ReadSTP3.cpp");
            }
            voi_name[40] = '\0';
            if (fread(&voi_first_slice, sizeof(voi_first_slice), 1, vfp) != sizeof(voi_first_slice))
            {
                fprintf(stderr, "fread_29 failed in ReadSTP3.cpp");
            }
            byteSwap(voi_first_slice);
            if (fread(&voi_last_slice, sizeof(voi_last_slice), 1, vfp) != sizeof(voi_last_slice))
            {
                fprintf(stderr, "fread_30 failed in ReadSTP3.cpp");
            }
            byteSwap(voi_last_slice);
            if (fread(&voi_color, sizeof(voi_color), 1, vfp) != sizeof(voi_color))
            {
                fprintf(stderr, "fread_31 failed in ReadSTP3.cpp");
            }
            byteSwap(voi_color);
            fprintf(stderr, "voi name: %s, first=%d, last=%d\n", voi_name, voi_first_slice, voi_last_slice);

            fseek(vfp, voi_header + VOI_DESC_SIZE * MAX_VOIS, SEEK_SET);

            for (int i = 0; i < num_slices; i++)
            {

                vector<float> p_x, p_y;
                readVoiSlice(vfp, voi_num, &p_x, &p_y);

                for (int y = 0; y < resolution; y++)
                {
                    vector<float> i_x;
                    computeIntersections(y, p_x, p_y, &i_x);
                    int no_isect = 0;
                    for (int x = 0; x < resolution; x++)
                    {
                        while (no_isect < i_x.size() && i_x[no_isect] < x)
                            no_isect++;

                        int k = ((y * resolution) + x) * num_slices + i;
                        if (no_isect % 2 == 0)
                        {
                            data[k] = ignore_value;
                        }
                        else
                        {
                            data[k] = 1.f;
                        }
                    }
                }
            }
        }
    }

    if (vfp)
        fclose(vfp);
    delete[] slice;

    float maxX = pixel_size * resolution / 2.f;
    float minX = -maxX;
    float maxY = maxX;
    float minY = -maxY;
#if 0
   if(minZ > maxZ)
   {
      float temp = minZ;
      minZ = maxZ;
      maxZ = temp;
   }
#endif

    coDoUniformGrid *gridOut = new coDoUniformGrid(poGrid->getObjName(),
                                                   resolution, resolution, num_slices, //voi_last_slice-voi_first_slice+1,
                                                   minX, maxX,
                                                   minY, maxY,
                                                   //minZ + ((maxZ-minZ)*voi_first_slice)/num_slices, minZ + ((maxZ-minZ)*voi_last_slice)/num_slices);
                                                   minZ, maxZ);

    char *matPath = new char[strlen(path) + 5];
    strcpy(matPath, path);
    char *ext = strrchr(matPath, '.');
    if (ext)
    {
        strcpy(ext, ".tra");
    }
    else
    {
        strcat(matPath, ".tra");
    }

    double mat[4][4], inv[4][4];
    if (getTransformation(matPath, &mat[0][0], &inv[0][0]) >= 0)
    {
        char transMat[64 * 16];
        char *p = transMat;
        for (int i = 0; i < 4; i++)
        {
            for (int j = 0; j < 4; j++)
            {
                int sz = sprintf(p, "%f ", mat[j][i]);
                p += sz;
            }
        }
        gridOut->addAttribute("Transformation", transMat);
        fprintf(stderr, "attached Transformation: %s\n", transMat);
    }
    else
    {
        char buf[1024];
        sprintf(buf, "failed to read transformation data from %s", matPath);
        sendInfo(matPath);
    }

    poGrid->setCurrentObject(gridOut);
    poVolume->setCurrentObject(dataOut);

    sprintf(buf, "Volume data loaded: (%f, %f, %f) - (%f, %f %f)",
            minX, minY, minZ, maxX, maxY, maxZ);
    sendInfo(buf);

    return CONTINUE_PIPELINE;
}
Exemplo n.º 18
0
int coReadSTP3::getTransformation(const char *filename, double *mat, double *inv)
{
#if 0
   FILE *fp = fopen(filename, "rb");

   if(!fp)
   {
      fprintf(stderr, "failed to open %s\n", filename);
      return -1;
   }

   // read transformation header
   uint32_t file_type;
   if (fread(&file_type,sizeof(file_type),  1, fp)!=sizeof(file_type))
   {
      fprintf(stderr,"fread_32 failed in ReadSTP3.cpp");
   }
   byteSwap(file_type);
   uint32_t ser_head_len;
   if (fread(&ser_head_len,sizeof(ser_head_len),  1, fp)!=sizeof(ser_head_len))
   {
      fprintf(stderr,"fread_33 failed in ReadSTP3.cpp");
   }
   byteSwap(ser_head_len);
   uint32_t block_len;
   if (fread(&block_len,sizeof(block_len),  1, fp)!=sizeof(block_len))
   {
      fprintf(stderr,"fread_34 failed in ReadSTP3.cpp");
   }
   byteSwap(block_len);
   fprintf(stderr, "blocklen=%d, serheadlen=%d\n", block_len, ser_head_len);
   char patient_name[81];
   if (fread(patient_name, 1, 80, fp)!= 1)
   {
      fprintf(stderr,"fread_35 failed in ReadSTP3.cpp");
   }
   patient_name[80] = '\0';
   char comm[81];
   if (fread(comm, 1, 80, fp)!= 1)
   {
      fprintf(stderr,"fread_36 failed in ReadSTP3.cpp");
   }
   comm[80] = '\0';
   char date[81];
   if (fread(date, 1, 80, fp)!= 1)
   {
      fprintf(stderr,"fread_37 failed in ReadSTP3.cpp");
   }
   date[80] = '\0';
   uint32_t serial_num;
   if (fread(&serial_num,sizeof(serial_num),  1, fp)!=sizeof(serial_num))
   {
      fprintf(stderr,"fread_38 failed in ReadSTP3.cpp");
   }
   byteSwap(serial_num);
   uint32_t num_slices;
   if (fread(&num_slices,sizeof(num_slices),  1, fp)!=sizeof(num_slices))
   {
      fprintf(stderr,"fread_39 failed in ReadSTP3.cpp");
   }
   byteSwap(num_slices);

   vector<double *> mats, invs;
   uint32_t trafo_type, is_axial;
   // read transformation for each slice
   for(int i = 0; i < num_slices; i++)
   {
      fseek(fp, block_len * (i+1) + ser_head_len, SEEK_SET);
      if (fread(&trafo_type,sizeof(trafo_type), 1, fp)!=sizeof(trafo_type))
      {
         fprintf(stderr,"fread_40 failed in ReadSTP3.cpp");
      }
      byteSwap(trafo_type);
      uint32_t calculated;
      if (fread(&calculated,sizeof(calculated), 1, fp)!=sizeof(calculated))
      {
         fprintf(stderr,"fread_41 failed in ReadSTP3.cpp");
      }
      byteSwap(calculated);
      if (fread(&is_axial,sizeof(is_axial), 1, fp)!=sizeof(is_axial))
      {
         fprintf(stderr,"fread_42 failed in ReadSTP3.cpp");
      }
      byteSwap(is_axial);
      double    marker[12][2];
      if (fread(marker,sizeof(marker), 1, fp)!=sizeof(marker))
      {
         fprintf(stderr,"fread_43 failed in ReadSTP3.cpp");
      }
      double    plate[16][2];
      if (fread(plate,sizeof(plate), 1, fp)!=sizeof(plate))
      {
         fprintf(stderr,"fread_44 failed in ReadSTP3.cpp");
      }
      uint32_t missing;
      if (fread(&missing,sizeof(missing), 1, fp)!=sizeof(missing))
      {
         fprintf(stderr,"fread_45 failed in ReadSTP3.cpp");
      }
      byteSwap(missing);
      double *m= new double[16];
      if (fread(m,sizeof(*m)*16, 1, fp)!=sizeof(*m)*16)
      {
         fprintf(stderr,"fread_46 failed in ReadSTP3.cpp");
      }
      byteSwapM(m, 16);
      mats.push_back(m);
      m = new double[16];
      if (fread(m,sizeof(*m)*16, 1, fp)!=sizeof(*m)*16)
      {
         fprintf(stderr,"fread_47 failed in ReadSTP3.cpp");
      }
      byteSwapM(m, 16);
      invs.push_back(m);
   }
   fclose(fp);

   memcpy(mat, mats[num_slices/2],sizeof(double)*16);
   memcpy(inv, invs[num_slices/2],sizeof(double)*16);

   for(int i=0; i<mats.size(); i++)
   {
      delete[] mats[i];
      delete[] invs[i];
   }

   return 0;
#endif

    struct patient_struct patient;
    strcpy(patient.Tra_File, filename);
    patient.Resolution = resolution;
    patient.No_Slices = num_slices;
    patient.Pixel_size = pixel_size;
    for (int i = 0; i < num_slices; i++)
    {
        patient.Z_Table[i] = slice_z[i];
    }
    QString result;

    int ret = read_ct_tran(&patient, &result);

    memcpy(mat, &patient.Global_Tra_Matrix[0][0], sizeof(double) * 16);
    memcpy(inv, &patient.Rev_Global_Tra_Matrix[0][0], sizeof(double) * 16);

    mat[14] -= 100.;
    //inv[14] += 100.;

    cerr << result.latin1() << endl;

    return ret;
}
Exemplo n.º 19
0
void AIFFDecoder::header()
{
  if(!fd) return;
  aIffHeader hdr;
  char cname[5];
  cname[4]=0;
  fseek(fd,8,SEEK_SET);
  fread(cname,4,1,fd);
  DEBUG_OUT<<"IFF "<<cname<<" format.\n";
  tchunkOffset=24;  // probably should be 12?
  if(!strcmp(cname,"ANIM")) {
    fseek(fd,20,SEEK_SET);
    fread(cname,4,1,fd);
    DEBUG_OUT<<"IFF ANIM ("<<cname<<"), reading only key frame.\n";
    if(!strcmp(cname,"PBM ")) isPBM=true;
  } else
  if(!strcmp(cname,"ILBM")) tchunkOffset=12; else
  if(!strcmp(cname,"PBM ")) {
    tchunkOffset=12;  isPBM=true;
    DEBUG_OUT<<"(PC-DPaint packed pixels)\n";
  }
  else {
    DEBUG_OUT<<"Don't know what that format is, giving up...\n";
    /*errorFlag=true;*/  return;
  }
  if(!iffFindChunk(tchunkOffset,(char *)"BMHD",true)) {
    DEBUG_OUT<<"Couldn't find BMHD!\n";  /*errorFlag=true;*/  return;
  }
  fread((void *)&hdr,sizeof(aIffHeader),1,fd);
  if(littleEndian) {
    byteSwap(&hdr.width);  byteSwap(&hdr.height);
  }
  depth=hdr.depth;  width=hdr.width;  height=hdr.height;
  if(!isPBM) nPlanes=depth; else nPlanes=1;
  // FIXME: See IFF39 doc about rounding...
  // FIXME: See IFF39 doc about interleaved bitplanes...
  lineBytes=calcBPL(2);
  bytesPerLine=calcBPL(4);
  DEBUG_OUT<<"IFF: lineBytes="<<lineBytes<<" BPL="<<bytesPerLine<<"\n";
  //bytesPerLine=lineBytes;
  iffChunk=0; iffViewModes=0;
  if(iffFindChunk(tchunkOffset,(char *)"CAMG",true)) {
    uint32_t camg;
    fread((void *)&camg,4,1,fd);
    if(littleEndian) byteSwap(&camg);
    iffViewModes=camg;
  }
  DEBUG_OUT<<"Picture aspect is "<<(int)hdr.aspectX<<" : "<<(int)hdr.aspectY<<"\n";
  // FIXME: don't read the bits out of CAMG if you can't help it!
  if(iffViewModes&0x800) {
    switch(depth) {
      case 6:
        DEBUG_OUT<<"Amiga HAM6 Mode...\n";  depth=12;  break;
      case 8:
        DEBUG_OUT<<"Amiga HAM8 Mode...\n";  depth=24;  break;
      default:
        //DEBUG_OUT.warning(" Ham, but neither 6 nor 8 planes!\n");
        break;
    }
    isHam=true;
  }
  switch(hdr.compression) {
    case 0: compressed=false; break;
    case 1: compressed=true; break;
    default: DEBUG_OUT<<"Unknown compression method!\n"; break;
  }
  if(hdr.masking==1) hasMask=true;
  // FIXME: handle "CMAP has all 8 bits" flag here...
  DEBUG_OUT<<"Searching for dynamic mode chunks...\n";
  if(iffFindChunk(tchunkOffset,(char *)"CTBL",true)) isDynamic=true; else // DigiView Gold dynamic mode
  if(iffFindChunk(tchunkOffset,(char *)"PCHG",true)) isDynamic=true; else // HamLab et al palette change mode
  if(iffFindChunk(tchunkOffset,(char *)"SHAM",true)) isDynamic=true;      // Sliced-HAM mode
  if(isDynamic) DEBUG_OUT<<"Image changes palette dynamically.\n";
  //DEBUG_OUT<<"Page: "<<hdr.pwidth<<"x"<<hdr.pheight<<"\n";
  needsRGBReorder=false;
  if((!isHam)&&(depth==24)) needsRGBReorder=true;
}
Exemplo n.º 20
0
bool StarComponent::loadStaticData()
{
    // We break from Qt / KDE API and use traditional file handling here, to obtain speed.
    // We also avoid C++ constructors for the same reason.
    KStarsData* data = KStarsData::Instance();
    FILE *dataFile, *nameFile;
    bool swapBytes = false;
    BinFileHelper dataReader, nameReader;
    QString name, gname, visibleName;
    StarObject *star;

    if(starsLoaded)
        return true;

    // prepare to index stars to this date
    m_skyMesh->setKSNumbers( &m_reindexNum );

    /* Open the data files */
    // TODO: Maybe we don't want to hardcode the filename?
    if((dataFile = dataReader.openFile("namedstars.dat")) == NULL) {
        qDebug() << "Could not open data file namedstars.dat" << endl;
        return false;
    }

    if(!(nameFile = nameReader.openFile("starnames.dat"))) {
        qDebug() << "Could not open data file starnames.dat" << endl;
        return false;
    }

    if(!dataReader.readHeader()) {
        qDebug() << "Error reading namedstars.dat header : " << dataReader.getErrorNumber() << " : " << dataReader.getError() << endl;
        return false;
    }

    if(!nameReader.readHeader()) {
        qDebug() << "Error reading starnames.dat header : " << nameReader.getErrorNumber() << " : " << nameReader.getError() << endl;
        return false;
    }
    //KDE_fseek(nameFile, nameReader.getDataOffset(), SEEK_SET);
    QT_FSEEK(nameFile, nameReader.getDataOffset(), SEEK_SET);
    swapBytes = dataReader.getByteSwap();

    long int nstars = 0;

    //KDE_fseek(dataFile, dataReader.getDataOffset(), SEEK_SET);
    QT_FSEEK(dataFile, dataReader.getDataOffset(), SEEK_SET);

    qint16 faintmag;
    quint8 htm_level;
    quint16 t_MSpT;

    fread( &faintmag, 2, 1, dataFile );
    if( swapBytes )
        faintmag = bswap_16( faintmag );
    fread( &htm_level, 1, 1, dataFile );
    fread( &t_MSpT, 2, 1, dataFile ); // Unused
    if( swapBytes )
        faintmag = bswap_16( faintmag );


    if( faintmag / 100.0 > m_FaintMagnitude )
        m_FaintMagnitude = faintmag / 100.0;

    if( htm_level != m_skyMesh->level() )
        qDebug() << "WARNING: HTM Level in shallow star data file and HTM Level in m_skyMesh do not match. EXPECT TROUBLE" << endl;

    for(int i = 0; i < m_skyMesh -> size(); ++i) {

        Trixel trixel = i;// = ( ( i >= 256 ) ? ( i - 256 ) : ( i + 256 ) );
        for(unsigned long j = 0; j < (unsigned long)dataReader.getRecordCount(i); ++j) {
            if(!fread(&stardata, sizeof(starData), 1, dataFile)){
                qDebug() << "FILE FORMAT ERROR: Could not read starData structure for star #" << j << " under trixel #" << trixel << endl;
            }

            /* Swap Bytes when required */
            if(swapBytes)
                byteSwap( &stardata );

            if(stardata.flags & 0x01) {
                /* Named Star - Read the nameFile */
                visibleName = "";
                if(!fread(&starname, sizeof( starName ), 1, nameFile))
                    qDebug() << "ERROR: fread() call on nameFile failed in trixel " << trixel << " star " << j << endl;
                name = QByteArray(starname.longName, 32);
                gname = QByteArray(starname.bayerName, 8);
                if ( ! gname.isEmpty() && gname.at(0) != '.')
                    visibleName = gname;
                if(! name.isEmpty() ) {
                    // HEV: look up star name in internationalization filesource
                    name = i18nc("star name", name.toLocal8Bit().data());
                } else {
                    name = i18n("star");
                }
            }
            else
                qDebug() << "ERROR: Named star file contains unnamed stars! Expect trouble." << endl;

            /* Create the new StarObject */
            star = new StarObject;
            star->init( &stardata );
            if( star->getHDIndex() != 0 && name == i18n("star"))
                name = QString("HD %1").arg(star->getHDIndex());

            star->setNames( name, visibleName );
            star->EquatorialToHorizontal( data->lst(), data->geo()->lat() );
            ++nstars;

            if ( ! gname.isEmpty() ) m_genName.insert( gname, star );

            if ( ! name.isEmpty() && name != i18n("star")) {
                objectNames(SkyObject::STAR).append( name );
            }
            if ( ! visibleName.isEmpty() && gname != name ) {
                objectNames(SkyObject::STAR).append( star -> gname(false) );
            }

            m_ObjectList.append( star );

            m_starIndex->at( trixel )->append( star );
            double pm = star->pmMagnitude();
            for (int j = 0; j < m_highPMStars.size(); j++ ) {
                HighPMStarList* list = m_highPMStars.at( j );
                if ( list->append( trixel, star, pm ) ) break;
            }

            if( star->getHDIndex() != 0 )
                m_HDHash.insert( star->getHDIndex(), star );

        }

    }

    dataReader.closeFile();
    nameReader.closeFile();

    starsLoaded = true;
    return true;

}