CharacterStateWindow::CharacterStateWindow()
: CeGuiWindow("characterstatewindow.xml", WND_SHOW, false),
	mCharacter(NULL)
{
	mLP = getProgressBar("CharacterStateWindow/LP");
	mAP = getProgressBar("CharacterStateWindow/AP");
	mAU = getProgressBar("CharacterStateWindow/AU");
	mName = getStaticText("CharacterStateWindow/Name");
}
Beispiel #2
0
VolumeList* Synth2DReader::read(const std::string &fileName) throw (tgt::FileException, std::bad_alloc) {
    RawVolumeReader rawReader(getProgressBar());

    FILE* fin = fopen(fileName.c_str(), "rb");
    char buf[4096];
    fread(buf, 4096, 1, fin);
    fclose(fin);

    Synth2DVolumeHeader* header = (Synth2DVolumeHeader *)buf;
    if ((header->magic[0] != 'V') || (header->magic[1] != 'O') || (header->magic[2] != 'L') || (header->magic[3] != 'U') || (header->version != 4)
            || (header->bytesPerChannel != 1) || (header->numChannels != 1 && header->numChannels != 3 && header->numChannels != 4))
        throw tgt::CorruptedFileException("error while reading data", fileName);

    std::string om("I");
    if(header->numChannels == 3)
        om = std::string("RGB");
    else if(header->numChannels == 4)
        om = std::string("RGBA");

    ivec3 dims(header->volSize);
    rawReader.setReadHints(dims,                     // dimensions of the volume
                           ivec3(1, 1, 1),           // thickness of one slice
                           om,                       // intensity, rgb or rgba image
                           "UCHAR",                  // one unsigned char per voxel
                           1,                        // number of time frames
                           4096);                    // header skip

    VolumeList* volumeList = rawReader.read(fileName);

    return volumeList;
}
 CharacterSelectionWindow::Element::Element(CharacterSelectionWindow* parent)
 :  AbstractWindow("characterselectionwindow_character.xml", WIT_NONE, false), 
    mParent(parent),
    mCreature(NULL),
    mTextName(NULL)
 {
     mTextName = getWindow("CharacterSelectionWindow/Character/Name");
     mPortrait = getWindow("CharacterSelectionWindow/Character/Picture");
     mLP = getProgressBar("CharacterSelectionWindow/Character/LP");
 }
void VolumeURLListProperty::loadVolume(const std::string& url, bool invalidateUI /*=true*/)
        throw (tgt::FileException, std::bad_alloc) {

    if (!containsURL(url)) {
        LWARNING("loadVolume(): passed URL not contained by this property: " << url);
        return;
    }

    // delete volume, if already loaded and owned by the property
    if (getVolume(url) && isOwner(url))
        delete getVolume(url);
    handleMap_.erase(url);
    ownerMap_.erase(url);

    ProgressBar* progressBar = getProgressBar();
    if (progressBar) {
        progressBar->setTitle("Loading volume");
        progressBar->setProgressMessage("Loading volume ...");
    }

    VolumeSerializerPopulator serializerPopulator(progressBar);
    VolumeBase* handle = serializerPopulator.getVolumeSerializer()->read(VolumeURL(url));

    if (progressBar)
        progressBar->hide();

    if (handle) {
        // url may have been altered by loading routine
        if (url != handle->getOrigin().getURL()) {
            bool selected = isSelected(url);
            selectionMap_.erase(url);
            selectionMap_[handle->getOrigin().getURL()] = selected;

            for (size_t i=0; i<value_.size(); i++) {
                if (value_[i] == url) {
                    value_[i] = handle->getOrigin().getURL();
                    break;

                }
            }
        }

        handleMap_[handle->getOrigin().getURL()] = handle;
        ownerMap_[handle->getOrigin().getURL()] = true;
    }

    if(invalidateUI)
        invalidate();
}
void SMActionVideoNative::positionChanged(qint64 position)
{
    qint64 percent = (100 * position) / mediaDuration;
    getProgressBar()->setValue((int)percent);
    if (position >= mediaDuration)
    {
//        qInfo() << "END " << repeat() << " " << _repeat;
//        if (repeat() > 0 && _repeated < repeat())
//        {
//            _repeated ++;
//            mediaPlayer->setPosition(0);
//            mediaPlayer->play();
//            qInfo() << "repeat";
//        }
//        else
            emit end(this);
    }
}
void MoleculeURLListProperty::loadMolecule(const std::string& url)
        throw (tgt::FileException, std::bad_alloc) {

    if (!containsURL(url)) {
        LWARNING("loadMolecule(): passed URL not contained by this property: " << url);
        return;
    }

    // delete molecule, if already loaded and owned by the property
    if (getMolecule(url) && isOwner(url))
        delete getMolecule(url);
    handleMap_.erase(url);
    ownerMap_.erase(url);

    ProgressBar* progressBar = getProgressBar();
    if (progressBar) {
        progressBar->setTitle("Loading molecule");
        progressBar->setMessage("Loading molecule ...");
    }

    Molecule* handle = MoleculeIO::read(MoleculeURL(url));

    if (handle) {
        // url may have been altered by loading routine
        if (url != handle->getOrigin().getURL()) {
            bool selected = isSelected(url);
            selectionMap_.erase(url);
            selectionMap_[handle->getOrigin().getURL()] = selected;

            for (size_t i=0; i<value_.size(); i++) {
                if (value_[i] == url) {
                    value_[i] = handle->getOrigin().getURL();
                    break;

                }
            }
        }

        handleMap_[handle->getOrigin().getURL()] = handle;
        ownerMap_[handle->getOrigin().getURL()] = true;
    }

    invalidate();
}
void SMActionVideoVLC::slotTimeout(void)
{
    if (getStatus() != STATUS_PLAY)
        return;

    // It's possible that the vlc doesn't play anything
    // so check before
    libvlc_media_t *curMedia = libvlc_media_player_get_media (_mp);
    if (curMedia == NULL)
        return;

    float pos=libvlc_media_player_get_position (_mp);

    qint64 percent = 100 * pos;
    getProgressBar()->setValue((int)percent);
    if (pos >= 1.0)
    {

    }
}
Beispiel #8
0
SurfaceExtraction::SurfaceExtraction()
    : Processor()
    , volume_("volume")
    , outport_("mesh")
    , isoValue_("iso", "ISO Value", 0.5f, 0.0f, 1.0f, 0.01f)
    , method_("method", "Method")
    , colors_("meshColors", "Mesh Colors")
    , dirty_(false) {
    addPort(volume_);
    addPort(outport_);

    addProperty(method_);
    addProperty(isoValue_);
    addProperty(colors_);

    getProgressBar().hide();

    method_.addOption("marchingtetrahedra", "Marching Tetrahedra", TETRA);
    volume_.onChange(this, &SurfaceExtraction::updateColors);
    volume_.onChange(this, &SurfaceExtraction::setMinMax);
    method_.setCurrentStateAsDefault();
}
Beispiel #9
0
void VolumeURLProperty::loadVolume() throw (tgt::FileException, std::bad_alloc){

    std::string url = get();
    if (url.empty()) {
        LWARNING("loadVolume(): empty URL");
        return;
    }

    ProgressBar* progressBar = getProgressBar();
    if (progressBar) {
        progressBar->setTitle("Loading volume");
        progressBar->setProgressMessage("Loading volume ...");
    }
    VolumeSerializerPopulator serializerPopulator(progressBar);
    VolumeList* volumeList = serializerPopulator.getVolumeSerializer()->read(url);

    if (progressBar)
        progressBar->hide();

    if (volumeList && !volumeList->empty()) {
        VolumeBase* handle = volumeList->first();
        tgtAssert(handle, "No handle");
        setVolume(static_cast<Volume*>(handle));

        // delete superfluous volumes
        if (volumeList->size() > 1) {
            LWARNING("More than one volume loaded from file: " + url + ". Discarding surplus volumes!");
                for (size_t i=1; i<volumeList->size(); i++)
                    delete volumeList->at(i);
        }

        // property does take ownership of loaded handles
        volumeOwner_ = true;
    }

    delete volumeList;
}
Beispiel #10
0
VolumeFlow3D* FlowReader::readConvert(const tgt::ivec3& dimensions, const BYTE orientation,
                                      std::fstream& ifs)
{
    tgt::ivec3 permutation = Flow3D::getAxisPermutation(orientation);
    switch (orientation) {
        case Flow3D::XZY:
            LINFO("voxel order: XZY (code = " << static_cast<int>(orientation) << ")");
            LINFO("changing voxel order from XZY to XYZ...");
            break;
        case Flow3D::YXZ:
            LINFO("voxel order: YXZ (code = " << static_cast<int>(orientation) << ")");
            LINFO("changing voxel order from YXZ to XYZ...");
            break;
        case Flow3D::YZX:
            LINFO("voxel order: YZX (code = " << static_cast<int>(orientation) << ")");
            LINFO("changing voxel order from YZX to XYZ...");
            break;
        case Flow3D::ZXY:
            LINFO("voxel order: ZXY (code = " << static_cast<int>(orientation) << ")");
            LINFO("changing voxel order from ZXY to XYZ...");
            break;
        case Flow3D::ZYX:
            LINFO("voxel order: ZYX (code = " << static_cast<int>(orientation) << ")");
            LINFO("changing voxel order from ZYX to XYZ...");
            break;
        case Flow3D::XYZ:
            LINFO("voxel order: XYZ (code = " << static_cast<int>(orientation) << ")");
            LINFO("no conversion of voxel order required.");
            break;
        default:
            LINFO("voxel order: unknown (code = " << static_cast<int>(orientation) << ")");
            LINFO("further processing not possible! canceling");
            return 0;
    }

    const size_t numVoxels = dimensions.x * dimensions.y * dimensions.z;
    const size_t byteSize = numVoxels * sizeof(tgt::vec3);

    tgt::vec3* voxels = 0;
    try {
        voxels = new tgt::vec3[numVoxels];
    } catch (std::bad_alloc) {
        throw;
    }

    const tgt::ivec3 xyz(0, 1, 2);  // target voxel order is XYZ
    const int max = tgt::max(dimensions);

    // no remainder possible because getNumBytes is a multiple of max
    //
    const size_t bufferByteSize = byteSize / static_cast<size_t>(max);
    const size_t numBufferElements = bufferByteSize / sizeof(tgt::vec3);
    tgt::vec3* buffer = new tgt::vec3[numBufferElements];
    memset(buffer, 0, bufferByteSize);

    ProgressBar* progress = getProgressBar();

    tgt::ivec3 pos(0, 0, 0);
    float maxValue = std::numeric_limits<float>::min();
    float minValue = std::numeric_limits<float>::max();
    float maxMagnitude = 0.0f;

    for (size_t i = 0; i < size_t(max); ++i) {
        ifs.read(reinterpret_cast<char*>(buffer), bufferByteSize);
        if (progress)
            progress->setProgress(static_cast<float>(i) / static_cast<float>(max));

        for (size_t j = 0; j < numBufferElements; ++j) {
            // get the number of the voxel in current data orientation
            //
            size_t voxelNumber = j + (i * numBufferElements);

            if (orientation != Flow3D::XYZ) {
                // convert the number into the position within the voxel
                // ((x, y, z)-coordinates in volume's bounding box)
                //
                pos = Flow3D::voxelNumberToPos(voxelNumber, permutation, dimensions);

                // re-calculate the number of the voxel for the desired
                // data orientation
                //
                size_t newNumber = Flow3D::posToVoxelNumber(pos, xyz, dimensions);
                voxels[newNumber] = buffer[j];
            } else
                voxels[voxelNumber] = buffer[j];

            // calculate max and min of current voxel and dataset's min and max.
            //
            float voxelMax = tgt::max(buffer[j]);
            float voxelMin = tgt::min(buffer[j]);
            float magnitude = tgt::length(buffer[j]);

            if (voxelMax > maxValue)
                maxValue = voxelMax;
            if (voxelMin < minValue)
                minValue = voxelMin;
            if (magnitude > maxMagnitude)
                maxMagnitude = magnitude;
        }
    }

    progress->setProgress(1.f);

    delete [] buffer;

    LINFO("min. among all components of all voxels: " << minValue);
    LINFO("max. among all components of all voxels: " << maxValue);
    LINFO("max. magnitude among all  voxels: " << maxMagnitude);

    return new VolumeFlow3D(voxels, dimensions, minValue, maxValue, maxMagnitude);
}
Beispiel #11
0
VolumeList* ECAT7VolumeReader::read(const std::string &url, int volumeId)
    throw(tgt::CorruptedFileException, tgt::IOException, std::bad_alloc)
{
    LINFO("Loading dataset " << url << " vid: " << volumeId);

    VolumeURL origin(url);
    std::string fileName = origin.getPath();
    FILE* fin = fopen(fileName.c_str(), "rb");

    if(!fin) {
        throw tgt::FileNotFoundException("ECAT7: File not found", fileName);
    }

    ECAT7VolumeReader::ECAT7Structure s = readStructure(fileName);

    VolumeList* vc = new VolumeList();

    for(size_t i=0; i<s.subVolumes_.size(); i++) {
        fseek(fin, s.subVolumes_[i].de_.startBlock_ * 512, SEEK_SET);
        fseek(fin, 512, SEEK_CUR); //skip past header (already read)

        tgt::svec3 dimensions = s.subVolumes_[i].getDimensions();
        //tgt::mat4 m = s.subVolumes_[i].getTransformation();
        tgt::vec3 spacing = s.subVolumes_[i].getSpacing();
        tgt::vec3 offset  = s.subVolumes_[i].getOffset();

        if(volumeId != -1) {
            if(volumeId != s.subVolumes_[i].getId())
                continue;
        }

        if(s.subVolumes_[i].ih_.num_dimensions != 3)
            continue;

        if (getProgressBar()) {
            getProgressBar()->setTitle("Loading Volume");
            getProgressBar()->setProgressMessage("Loading volume: " + fileName);
        }

        VolumeRAM* vol;
        RealWorldMapping denormalize;
        if(s.h_.file_type == 6) {
            vol = new VolumeRAM_UInt8(dimensions);
            denormalize = RealWorldMapping::createDenormalizingMapping<uint8_t>();
        }
        else if(s.h_.file_type == 7) {
            vol = new VolumeRAM_UInt16(dimensions);
            denormalize = RealWorldMapping::createDenormalizingMapping<uint16_t>();
        }
        else {
            LERROR("Unknown file format detected.");
            return 0;
        }

        float scale = s.subVolumes_[i].ih_.scale_factor * s.h_.ecat_calibration_factor;
        RealWorldMapping rwm(scale, 0.0f, s.h_.data_units);

        VolumeReader::read(vol, fin);

        // Assume that the pixel size values given in the ecat header are in cm.  Multiply spacing and offset
        // with 0.1 to convert to mm.
        Volume* vh = new Volume(vol, spacing * 0.1f, offset * 0.1f);
        vh->setRealWorldMapping(RealWorldMapping::combine(denormalize, rwm));

        if(s.swapEndianness_)
            VolumeOperatorSwapEndianness::APPLY_OP(vh);

        // TODO: This must depend on some parameter in the headers, figure out which and how
        bool mirrorZ = true;
        if(mirrorZ)
        {
            Volume* mirrored = VolumeOperatorMirrorZ::APPLY_OP(vh);
            delete vh;
            vh = mirrored;
        }

        VolumeURL o("ecat7", fileName);
        o.addSearchParameter("volumeId", itos(s.subVolumes_[i].de_.id_));
        vh->setOrigin(o);

        s.transformMetaData(vh->getMetaDataContainer(), static_cast<int>(i));

        if(length(offset) == 0.f)
            centerVolume(vh);

        vc->add(vh);

        if (getProgressBar())
            getProgressBar()->hide();
    }

    fclose(fin);
    return vc;
}
VolumeCollection* AnalyzeVolumeReader::readAnalyze(const std::string &fileName)
    throw (tgt::FileException, std::bad_alloc)
{
    LWARNING("Loading analyze file " << fileName);
    LWARNING("Related img file: " << getRelatedImgFileName(fileName));

    std::ifstream file(fileName.c_str(), std::ios::in | std::ios::binary);
    if(!file) {
        throw tgt::FileNotFoundException("Failed to open file: ", fileName);
    }

    file.seekg(0, std::ios::end);
    std::streamoff fileSize = file.tellg();
    file.seekg(0, std::ios::beg);

    if(fileSize != 348)
        LWARNING("Filesize != 348");

    header_key header;
    if (!file.read((char*)&header, sizeof(header))) {
        throw tgt::CorruptedFileException("Failed to read header!", fileName);
    }

    image_dimension dimension;
    if (!file.read((char*)&dimension, sizeof(dimension))) {
        throw tgt::CorruptedFileException("Failed to read dimensions!", fileName);
    }

    data_history history;
    if (!file.read((char*)&history, sizeof(history))) {
        throw tgt::CorruptedFileException("Failed to read history!", fileName);
    }

    bool bigEndian = false;
    //check if swap is necessary:
    if((dimension.dim[0] < 0) || (dimension.dim[0] > 15)) {
        bigEndian = true;
        header.swapEndianess();
        dimension.swapEndianess();
        history.swapEndianess();
    }

    RawVolumeReader::ReadHints h;

    h.dimensions_.x = dimension.dim[1];
    h.dimensions_.y = dimension.dim[2];
    h.dimensions_.z = dimension.dim[3];
    LINFO("Resolution: " << h.dimensions_);

    if (hor(lessThanEqual(h.dimensions_, ivec3(0)))) {
        LERROR("Invalid resolution or resolution not specified: " << h.dimensions_);
        throw tgt::CorruptedFileException("error while reading data", fileName);
    }

    h.spacing_.x = dimension.pixdim[1];
    h.spacing_.y = dimension.pixdim[2];
    h.spacing_.z = dimension.pixdim[3];
    LINFO("Spacing: " << h.spacing_);

    LINFO("Datatype: " << dimension.datatype);

    switch(dimension.datatype) {
        case DT_UNSIGNED_CHAR:
            h.format_ = "UCHAR";
            h.objectModel_ = "I";
            break;
        case DT_SIGNED_SHORT:
            h.format_ = "SHORT";
            h.objectModel_ = "I";
            break;
        case DT_SIGNED_INT:
            h.format_ = "INT";
            h.objectModel_ = "I";
            break;
        case DT_FLOAT:
            h.format_ = "FLOAT";
            h.objectModel_ = "I";
            break;
        case DT_DOUBLE:
            h.format_ = "DOUBLE";
            h.objectModel_ = "I";
            break;
        case DT_RGB:
            h.format_ = "UCHAR";
            h.objectModel_ = "RGB";
            break;
        case DT_ALL:
        case DT_COMPLEX:
        case 0: //DT_NONE/DT_UNKNOWN
        case DT_BINARY:
        default:
            throw tgt::UnsupportedFormatException("Unsupported datatype!");
    }

    h.bigEndianByteOrder_ = bigEndian;

    std::string objectType;
    std::string gridType;

    RawVolumeReader rawReader(getProgressBar());
    rawReader.setReadHints(h);

    VolumeCollection* volumeCollection = rawReader.read(getRelatedImgFileName(fileName));

    if (!volumeCollection->empty()) {
        static_cast<VolumeHandle*>(volumeCollection->first())->setOrigin(VolumeOrigin(fileName));
        oldVolumePosition(static_cast<VolumeHandle*>(volumeCollection->first()));
    }

    return volumeCollection;
}
VolumeCollection* AnalyzeVolumeReader::readNifti(const std::string &fileName, bool standalone)
    throw (tgt::FileException, std::bad_alloc)
{
    LINFO("Loading nifti file " << fileName);

    std::ifstream file(fileName.c_str(), std::ios::in | std::ios::binary);
    if(!file) {
        throw tgt::FileNotFoundException("Failed to open file: ", fileName);
    }

    //file.seekg(0, std::ios::end);
    //int fileSize = file.tellg();
    //file.seekg(0, std::ios::beg);

    nifti_1_header header;
    if (!file.read((char*)&header, sizeof(header))) {
        throw tgt::CorruptedFileException("Failed to read header!", fileName);
    }

    file.close();

    bool bigEndian = false;
    //check if swap is necessary:
    if((header.dim[0] < 0) || (header.dim[0] > 15)) {
        bigEndian = true;
        header.swapEndianess();
    }

    if(header.sizeof_hdr != 348) {
        throw tgt::CorruptedFileException("Invalid header.sizeof_hdr", fileName);
    }

    if(!( (header.magic[0] == 'n') && (header.magic[2] == '1') && (header.magic[3] == 0) ))
        throw tgt::CorruptedFileException("Not a Nifti header!", fileName);

    if(header.magic[1] == '+') {
        if(!standalone)
            LWARNING("Tried to read standalone Nifti as hdr+img!");
        standalone = true;
    }
    else if(header.magic[1] == 'i') {
        if(!standalone)
            LWARNING("Tried to hdr+img Nifti as standalone!");
        standalone = false;
    }
    else
        throw tgt::CorruptedFileException("Not a Nifti header!", fileName);

    RawVolumeReader::ReadHints h;

    h.dimensions_.x = header.dim[1];
    h.dimensions_.y = header.dim[2];
    h.dimensions_.z = header.dim[3];
    LINFO("Resolution: " << h.dimensions_);

    if (hor(lessThanEqual(h.dimensions_, ivec3(0)))) {
        LERROR("Invalid resolution or resolution not specified: " << h.dimensions_);
        throw tgt::CorruptedFileException("error while reading data", fileName);
    }

    h.spacing_.x = header.pixdim[1];
    h.spacing_.y = header.pixdim[2];
    h.spacing_.z = header.pixdim[3];
    LINFO("Spacing: " << h.spacing_);

    LINFO("Datatype: " << header.datatype);

    //TODO: support more datatypes
    if(header.datatype > 128) {
        header.datatype -= 128;
        h.objectModel_ = "RGB";
    }
    else
        h.objectModel_ = "I";


    switch(header.datatype) {
        case DT_UNSIGNED_CHAR:
            h.format_ = "UCHAR";
            h.objectModel_ = "I";
            break;
        case DT_SIGNED_SHORT:
            h.format_ = "SHORT";
            h.objectModel_ = "I";
            break;
        case DT_SIGNED_INT:
            h.format_ = "INT";
            h.objectModel_ = "I";
            break;
        case DT_FLOAT:
            h.format_ = "FLOAT";
            h.objectModel_ = "I";
            break;
        case DT_DOUBLE:
            h.format_ = "DOUBLE";
            h.objectModel_ = "I";
            break;
        case DT_RGB:
            h.format_ = "UCHAR";
            h.objectModel_ = "RGB";
            break;
        case DT_RGBA32:         /* 4 byte RGBA (32 bits/voxel)  */
            h.format_ = "UCHAR";
            h.objectModel_ = "RGBA";
            break;
        case DT_INT8:           /* signed char (8 bits)         */
            h.format_ = "CHAR";
            h.objectModel_ = "I";
            break;
        case DT_UINT16:         /* unsigned short (16 bits)     */
            h.format_ = "USHORT";
            h.objectModel_ = "I";
            break;
        case DT_UINT32:         /* unsigned int (32 bits)       */
            h.format_ = "UINT";
            h.objectModel_ = "I";
            break;
        case DT_INT64:          /* long long (64 bits)          */
        case DT_UINT64:         /* unsigned long long (64 bits) */
        case DT_FLOAT128:       /* long double (128 bits)       */
        case DT_COMPLEX128:     /* double pair (128 bits)       */
        case DT_COMPLEX256:     /* long double pair (256 bits)  */
        case DT_ALL:
        case DT_COMPLEX:
        case 0: //DT_NONE/DT_UNKNOWN
        case DT_BINARY:
        default:
            throw tgt::UnsupportedFormatException("Unsupported datatype!");
    }

    if (header.intent_code == IC_INTENT_SYMMATRIX) {
        h.objectModel_ = "TENSOR_FUSION_LOW";
    }

    h.bigEndianByteOrder_ = bigEndian;

    //std::string objectType;
    //std::string gridType;
        //} else if (type == "ObjectType:") {
            //args >> objectType;
            //LDEBUG(type << " " << objectType);
        //} else if (type == "GridType:") {
            //args >> gridType;
            //LDEBUG(type << " " << gridType);
        //} else if (type == "BitsStored:") {
            //args >> h.bitsStored_;
            //LDEBUG(type << " " << h.bitsStored_);
        //} else if (type == "Unit:") {
            //args >> h.unit_;
            //LDEBUG(type << " " << h.unit_);

    if (standalone)
        h.headerskip_ = static_cast<uint16_t>(header.vox_offset);

    RawVolumeReader rawReader(getProgressBar());
    rawReader.setReadHints(h);

    VolumeCollection* volumeCollection = 0;
    if(standalone)
        volumeCollection = rawReader.read(fileName);
    else
        volumeCollection = rawReader.read(getRelatedImgFileName(fileName));

    if (!volumeCollection->empty()) {
        static_cast<VolumeHandle*>(volumeCollection->first())->setOrigin(VolumeOrigin(fileName));
        oldVolumePosition(static_cast<VolumeHandle*>(volumeCollection->first()));
    }

    return volumeCollection;
}
VolumeList* AmiraMeshReader::readMetaFile(const std::string &fileName, size_t firstSlice, size_t lastSlice, int timeframe)
    throw (tgt::FileException, std::bad_alloc)
{
	bool error = false;
	const char* FileName = fileName.c_str();
	FILE* fp = fopen(FileName, "rb");
    if (!fp)
    {
        LERROR("Could not find :" << FileName);
        error = true;
		goto K;
    }

    char buffer[2048];
    fread(buffer, sizeof(char), 2047, fp);
    buffer[2047] = '\0'; //The following string routines prefer null-terminated strings

    if (!strstr(buffer, "# AmiraMesh BINARY-LITTLE-ENDIAN 2.1") && !strstr(buffer, "# AmiraMesh 3D BINARY 2.0"))
    {
        LERROR("Not a proper AmiraMesh file.");
        fclose(fp);
        error = true;
		goto K;
    }

    //Find the Lattice definition, i.e., the dimensions of the uniform grid
    int xDim(0), yDim(0), zDim(0);
    sscanf(FindAndJump(buffer, "define Lattice"), "%d %d %d", &xDim, &yDim, &zDim);
	LDEBUG("Grid Dimensions: " << xDim << " " << yDim << " " << zDim);

    //Find the BoundingBox
    float xmin(1.0f), ymin(1.0f), zmin(1.0f);
    float xmax(-1.0f), ymax(-1.0f), zmax(-1.0f);
    sscanf(FindAndJump(buffer, "BoundingBox"), "%g %g %g %g %g %g", &xmin, &xmax, &ymin, &ymax, &zmin, &zmax);
    LDEBUG("BoundingBox in x-Direction: [" << xmin << " " << xmax << "]");
	LDEBUG("BoundingBox in x-Direction: [" << ymin << " " << ymax << "]");
	LDEBUG("BoundingBox in x-Direction: [" << zmin << " " << zmax << "]");
	
    //Is it a uniform grid? We need this only for the sanity check below.
    const bool bIsUniform = (strstr(buffer, "CoordType \"uniform\"") != NULL);
    LDEBUG("GridType: " << bIsUniform ? "uniform" : "UNKNOWN");

    //Type of the field: scalar, vector
    int NumComponents(0);
    if (strstr(buffer, "Lattice { float Data }"))
    {
        //Scalar field
        NumComponents = 1;
    }
    else
    {
        //A field with more than one component, i.e., a vector field
        sscanf(FindAndJump(buffer, "Lattice { float["), "%d", &NumComponents);
    }
    LDEBUG("Number of Components: " << NumComponents);

    //Sanity check
    if (xDim <= 0 || yDim <= 0 || zDim <= 0
        || xmin > xmax || ymin > ymax || zmin > zmax
        || !bIsUniform || NumComponents <= 0)
    {
        printf("Something went wrong\n");
        fclose(fp);
        error = true;
		goto K;
    }


	K : RawVolumeReader::ReadHints h;
	std::string objectFilename = fileName;

	h.headerskip_ = strstr(buffer, "# Data section follows") - buffer;
    //Set the file pointer to the beginning of "# Data section follows"
	fseek(fp, h.headerskip_, SEEK_SET);
    //Consume this line, which is "# Data section follows"
	char buf1[2048];
	fgets(buf1, 2047, fp);
	int l1 = strlen(buf1);

    //Consume the next line, which is "@1"
	char buf2[2048];
    fgets(buf2, 2047, fp);
	int l2 = strlen(buf2);

    vec3 sliceThickness = vec3(1.f, 1.f, 1.f);
    int numFrames = NumComponents;
	
	h.dimensions_.x = xDim;
	h.dimensions_.y = yDim;
	h.dimensions_.z = zDim;
	
	h.format_ = "FLOAT";
	h.objectModel_ = "I";
	h.bigEndianByteOrder_ = false;
	h.headerskip_ += (l1 + l2);
	LDEBUG("Header size : " << h.headerskip_);

    if (hor(lessThanEqual(h.dimensions_, ivec3(0)))) {
        LERROR("Invalid resolution or resolution not specified: " << h.dimensions_);
        error = true;
    }

    h.spacing_ = sliceThickness;
	h.timeStep_ = 0;

	if (!error) {
        RawVolumeReader rawReader(getProgressBar());

        // do we have a relative path?
        if ((objectFilename.substr(0, 1) != "/")  && (objectFilename.substr(0, 1) != "\\") &&
            (objectFilename.substr(1, 2) != ":/") && (objectFilename.substr(1, 2) != ":\\"))
        {
            size_t p = fileName.find_last_of("\\/");
            // construct path relative to dat file
            objectFilename = fileName.substr(0, p + 1) + objectFilename;
        }

        int start = 0;
        int end = numFrames;
        if (timeframe != -1) {
            if (timeframe >= numFrames)
                throw tgt::FileException("Specified time frame not in volume", fileName);

            start = timeframe;
            end = timeframe+1;
        }

        VolumeList* toReturn = new VolumeList();
        for (int frame = start; frame < end; ++frame) {
            h.timeframe_ = frame;
            rawReader.setReadHints(h);

            VolumeList* volumeList = rawReader.readSlices(objectFilename, firstSlice, lastSlice);
            if (!volumeList->empty()) {
                VolumeURL origin(fileName);
                origin.addSearchParameter("timeframe", itos(frame));

                Volume* vh = static_cast<Volume*>(volumeList->first());
                vh->setOrigin(origin);
                vh->setTimestep(static_cast<float>(frame));

                oldVolumePosition(vh);

                if(!h.hash_.empty())
                    vh->setHash(h.hash_);

                toReturn->add(volumeList->first());
            }
            delete volumeList;
        }
        return toReturn;
    }
    else {
        throw tgt::CorruptedFileException("error while reading data", fileName);
    }
}
Beispiel #15
0
        bool downloadUpdates( const char* downloadWebsite, const std::list<EvidyonUpdateFile>& filesAndSizes )
        {
            // Hide the combo box, show the progress bar
            ComboBox_Enable( getDisplayModeCombo(), FALSE );
            ShowWindow( getProgressBar(), SW_SHOWDEFAULT );

            std::vector<std::pair<std::string,std::string>> tempFilesToLocalFiles;

            // Initialize the progress bar.  All files are scaled to 65535 since the 32-bit range
            // doesn't seem to be working correctly.
            Progress_SetRange( getProgressBar(), 0, 65535 );

            // Repeat for each of the files
            for (std::list<EvidyonUpdateFile>::const_iterator p = filesAndSizes.begin(); p != filesAndSizes.end(); ++p)
            {
                // Update the display window
                {
                    // Get the number of bytes
                    char bytes[16];
                    if( p->file_size > 1000 )
                    {
                        sprintf_s( bytes, "%lu KB", p->file_size / 1000 );
                    } else if( p->file_size > 1000000 )
                    {
                        sprintf_s( bytes, "%lu MB", p->file_size / 1000000 );

                    } else
                    {
                        sprintf_s( bytes, "%lu bytes", p->file_size );
                    }

                    std::string text = "Downloading ";
                    text.append( p->file_name );
                    text.append( " - " );
                    text.append( bytes );
                    appendStatusLine( text.c_str() );
                }

                // Get the file's name on the website
                std::string fileUrl = downloadWebsite;
                fileUrl.append( p->file_name );

                // Get the file's local name
                std::string fileLocalName = "~";
                fileLocalName.append( p->file_name );

                // Open the local file
                HANDLE hDestination;
                hDestination = CreateFile( fileLocalName.c_str(),
                                           GENERIC_WRITE,
                                           FILE_SHARE_READ,
                                           NULL,
                                           CREATE_ALWAYS,
                                           FILE_FLAG_WRITE_THROUGH | 
                                           FILE_FLAG_SEQUENTIAL_SCAN,
                                           NULL );
                CONFIRM( hDestination ) else return false;

                // Add to the list of local files
                tempFilesToLocalFiles.push_back( std::pair<std::string,std::string>( fileLocalName, p->file_name ) );

                // Download this file
                dcx::dcxWin32InternetStream reader;
                if( !reader.open( "EvidyonClient", fileUrl.c_str() ) )
                {
                    CloseHandle( hDestination );
                    return false;
                }

                // Reset the progress bar
                Progress_SetPos( getProgressBar(), 0 );

                char buffer[512];
                size_t bytesRead = 0;
                size_t bytes;
                while( reader.scan( buffer, sizeof(buffer), &bytes ) && !reader.end() )
                {
                    // Write this data into the output file
                    DWORD bytesWritten;
                    BOOL success = WriteFile( hDestination,
                                              buffer,
                                              bytes,
                                             &bytesWritten,
                                              NULL );

                    // Exit if the data couldn't be written or the user exited the launcher
                    if( !dcx::dcxWin32StdMessagePump( myMainWindow ) ||
                        APP_WARNING( !success || !bytesWritten )( "Couldn't write data to temporary file" ) )
                        break;

                    // Add to the number of bytes that were read
                    bytesRead += bytes;

                    // Update the progress bar
                    Progress_SetPos( getProgressBar(), (WORD)(((double)bytesRead / (double)p->file_size) * 65535) );
                }

                bool completed = reader.end();

                // Get rid of the output file and internet connection
                reader.close();
                CloseHandle( hDestination );

                // If we didn't finish the download, fail
                if( APP_ERROR( !completed )( "Didn't complete download of %s", fileUrl.c_str() ) )
                    return false;
            }

            // Delete original files and copy files over
            for( std::vector<std::pair<std::string,std::string>>::iterator i  = tempFilesToLocalFiles.begin();
                                                                           i != tempFilesToLocalFiles.end(); ++i )
            {
                // Copy over the existing file
                if (CopyFile( i->first.c_str(), i->second.c_str(), FALSE )) {
                  // Erase the temporary file
                  DeleteFile( i->first.c_str() );
                }
            }

            // Max out the bar
            Progress_SetPos( getProgressBar(), 65535 );

            // Success
            return true;
        }
Beispiel #16
0
        void execute( HINSTANCE hInstance, dcx::dcxCPUFeatures* cpuFeatures ) {
            myMainWindow = createMainDialog( hInstance );

            dcx::dcxIniFileWriter ini_file_writer;
            DisplayModeList display_mode_list;
            {
              dcx::dcxIniFileReader ini_file_reader;
              ini_file_reader.read("config.ini");
              ini_file_writer.scan(&ini_file_reader);
              DWORD current_display_mode_index = 
                EnumDisplayModes(ini_file_reader.getSetting("Graphics", "ResolutionX", 0),
                                 ini_file_reader.getSetting("Graphics", "ResolutionY", 0),
                                 ini_file_reader.getSetting("Graphics", "ColorDepth", 0),
                                 ini_file_reader.getSetting("Graphics", "Fullscreen", 0) == 0, display_mode_list);

              { // re-sort
                DisplayMode current;
                if (current_display_mode_index < display_mode_list.size()) current = display_mode_list.at(current_display_mode_index);
                qsort(&display_mode_list.at(0), display_mode_list.size(), sizeof(DisplayModeList::value_type), CompareDisplayMode);
                DWORD index = 0;
                for (DisplayModeList::iterator i = display_mode_list.begin(); i != display_mode_list.end(); ++i, ++index) {
                  DisplayMode& dm = *i;
                  if (dm.width == current.width &&
                      dm.height == current.height &&
                      dm.windowed == current.windowed &&
                      (current.windowed == true || dm.bpp == current.bpp)) {
                    current_display_mode_index = index; break;
                  }
                }
              }


              HWND hDisplayModeCombo = getDisplayModeCombo();
              DWORD index = 0;
              for (DisplayModeList::iterator i = display_mode_list.begin(); i != display_mode_list.end(); ++i, ++index) {
                int k = ComboBox_AddString(hDisplayModeCombo, i->text.c_str());
                ComboBox_SetItemData(hDisplayModeCombo, k, index);
              }
              ComboBox_SetCurSel(hDisplayModeCombo, current_display_mode_index);
            }

            Evidyon::UpdateFile update_file;
            std::list<EvidyonUpdateFile> files_to_update;
            if (!Evidyon::DownloadUpdateFile(Evidyon::ONLINE_CLIENT_UPDATE_FILE, &update_file)) {
                errorMessageBox( "Couldn't contact the update server; please try again later" );
                goto EXIT;
            }

            if (update_file.major != MAJOR_VERSION) {
              // download the full installer
              MessageBox(myMainWindow, "The game has been significantly updated and you\n"
                                       "should re-download from www.unseenstudios.com", "Major Update!", MB_OK);
              goto EXIT;
            } else {
              ShowWindow( getEditboxStatus(), SW_SHOW);
              for (std::map<std::string, Evidyon::UpdateFileData>::const_iterator i = update_file.files.begin();
                   i != update_file.files.end(); ++i) {
                const std::string& filename = i->first;
                md5wrapper wrappy;
                std::string local_md5 = wrappy.getHashFromFile(filename);
                if (local_md5.compare(i->second.md5) != 0) {  // this file needs to be updated
                  EvidyonUpdateFile file;
                  file.file_name = filename;
                  file.file_size = i->second.file_bytes;
                  files_to_update.push_back(file);
                }
              }
            }
            // Update the client
            bool allowGameStart = false;
            if (files_to_update.size() > 0) {
              if (downloadUpdates(Evidyon::ONLINE_CLIENT_UPDATE_FOLDER, files_to_update)) {
                allowGameStart = true;
              } else {
                appendStatusLine( "ERROR!  Unable to download updates at this time.  If you are running Vista, this could "\
                                  "be due to the permissions for the directory in which Evidyon is installed being set to read-only." );
              }
            }
            else
                allowGameStart = true;

            // Add the update text to the output
            {
              //dc::dcFileStream fs;
              //if (fs.open("notes.txt", STREAM_TEXT)) {
              //  std::string notes;
              //  size_t len = fs.size();
              //  char text = new char[len+1];
              //  fs.read(text, len);
              //  text[len] = '\0';
              //  fs.close();
              //  appendStatusLine(text);
              //  delete[] text;
              //}
            }


            if (allowGameStart) {
                // Re-enable the "launch" button
                Button_Enable( getStartgameButton(), TRUE );
            }

            ShowWindow(getStartgameButton(), SW_SHOW);
            ShowWindow(getProgressBar(), SW_HIDE);

            // Wait for the user to do something
            myLaunchGameFlag = false;
            ComboBox_Enable(getDisplayModeCombo(), TRUE);
            while( dcx::dcxWin32StdMessagePump( myMainWindow ) && !myLaunchGameFlag );

            // Get the display mode selection
            int current_sel = ComboBox_GetCurSel(getDisplayModeCombo());
            current_sel = min(current_sel, display_mode_list.size() - 1);
            current_sel = max(current_sel, 0);
            DisplayMode& dm = display_mode_list.at(current_sel);
            ini_file_writer.setSetting("Graphics", "ResolutionX", dm.width),
            ini_file_writer.setSetting("Graphics", "ResolutionY", dm.height),
            ini_file_writer.setSetting("Graphics", "ColorDepth", dm.bpp),
            ini_file_writer.setSetting("Graphics", "Fullscreen", dm.windowed ? 0 : 1);
            {
              dc::dcFileStream ini_fs;
              ini_fs.open("config.ini", STREAM_OVERWRITE|STREAM_TEXT);
              ini_file_writer.write(&ini_fs);
              ini_fs.close();
            }

            // Close the window
            if( IsWindow( myMainWindow ) )
            {
                EndDialog( myMainWindow, 0 );
                DestroyWindow( myMainWindow );
                dcx::dcxWin32StdMessagePump( 0 );

                // Launch the client
                std::string exeFile = "evidyon";

                STARTUPINFO startupInfo;
                ZeroMemory( &startupInfo, sizeof(startupInfo) );

                PROCESS_INFORMATION processInfo;
                /*
                // Build the version to run based on the computer's capabilities
                if( cpuFeatures->sse2 ) {
                    exeFile.append( "_sse2" );
                }
                else if( cpuFeatures->sse ) {
                    exeFile.append( "_sse" );
                }*/

                exeFile.append( ".exe" );
                
                // Start the server
                if( !CreateProcessA( exeFile.c_str(), NULL, NULL, NULL, FALSE, CREATE_NEW_CONSOLE|ABOVE_NORMAL_PRIORITY_CLASS,
                                     NULL, NULL, &startupInfo, &processInfo ) )
                {
                    DWORD error = GetLastError();
                    MessageBox( NULL, "Failed to launch Evidyon", "Error", MB_OK );
                    goto EXIT;
                }

                // Run the client
                WaitForSingleObject( processInfo.hProcess, INFINITE );

                // Free the process and exit
                CloseHandle( processInfo.hProcess );
                CloseHandle( processInfo.hThread );
            }

EXIT:
            DestroyWindow( myMainWindow );
        }