Exemplo n.º 1
0
Bitmap *loadFromData(void const *data, size_t size, std::string const &fmt)
{
    ilGetError();
    ILenum ilFormat = IL_RAW;
    ilFormat = get_bitmap_ext_fmt(fmt);
    bitmap_init();
    int img = ilGenImage();
    ilBindImage(img);
    ilEnable(IL_ORIGIN_SET);
    ilOriginFunc(IL_ORIGIN_LOWER_LEFT);
    ilEnable(IL_CONV_PAL);
    ilLoadL(ilFormat, data, size);
    int err = ilGetError();
    if (err != IL_NO_ERROR)
    {
        ilDeleteImage(img);
        char errStr[256];
        _snprintf_s(errStr, 256, "Error 0x%x", err);
        errStr[255] = 0;
        throw std::runtime_error(std::string("Error loading image format: ") + fmt
            + "\n" + errStr);
    }
    return new ILBitmap(img);
}
Exemplo n.º 2
0
Arquivo: test.cpp Projeto: abma/ResIL
void testSavers(const TCHAR* sourceFN, const TCHAR* targetFN)
{
	testHeap();
	ilInit();
	testHeap();
	ILuint handle = ilGenImage();
	testHeap();
	ilBindImage(handle);
	testHeap();
	if (!ilLoadImage(sourceFN)) {
		printf("Failed to load %S using ilLoadImage\n", sourceFN);
		++errors;
		return;
	}
	testHeap();

	// gif, ico: no save support...
	// todo: psd, pcx, tga, tif
	testSavers2(IL_BMP, targetFN, L"bmp");
	testSavers2(IL_JPG, targetFN, L"jpg");
	testSavers2(IL_PNG, targetFN, L"png");
	testSavers2(IL_PSD, targetFN, L"psd");
	testSavers2(IL_PCX, targetFN, L"pcx");
	testSavers2(IL_TGA, targetFN, L"tga");
	testSavers2(IL_TIF, targetFN, L"tif");
	testSavers2(IL_TGA, targetFN, L"tga");
	testSavers2(IL_PCX, targetFN, L"pcx");
	testSavers2(IL_PNM, targetFN, L"pnm");
	testSavers2(IL_SGI, targetFN, L"sgi");
	testSavers2(IL_WBMP, targetFN, L"wbmp");
	testSavers2(IL_MNG, targetFN, L"mng");
	testSavers2(IL_VTF, targetFN, L"vtf");

	testHeap();
	ilDeleteImage(handle);
}
std::tr1::shared_ptr<ATexture> ATextureLoader::LoadFile(const std::string& path)
{
	// try to retrieve the texture from the cache, if it exists
	std::tr1::shared_ptr<ATexture> texture_sp = ATextureCache::GetInstance()->Get(path);
	if(texture_sp != nullptr){
		return texture_sp;
	}

	unsigned int width, contentWidth, height, contentHeight;

	ILuint imageID = ilGenImage();
	ilBindImage(imageID);

	if(!ilLoadImage(path.c_str())){
		std::string error = "Fail to load file: " + path;
		throw std::exception(error.c_str());
		return nullptr;
	}

	// The content in
	width = contentWidth = ilGetInteger(IL_IMAGE_WIDTH);
	height = contentHeight = ilGetInteger(IL_IMAGE_HEIGHT);
	ILint bpp = ilGetInteger(IL_IMAGE_BYTES_PER_PIXEL);

	// Actual texture  size padded with extra pixels, ensure width and height are power of two.
	if(!isPowerOfTwo(contentWidth))
		width = nextPowerOfTwo(contentWidth);
	if(!isPowerOfTwo(contentHeight))
		height = nextPowerOfTwo(contentHeight);

	// default background colour will be solid black
	ilClearColour(0.0f, 0.0f, 0.0f, 1.0f);

	// TODO: there is still some confusion here.......
	// flip texture problem is mentioned here: http://www.gamedev.net/topic/308200-devil-textures-upside-down/

	// Together with the ilOriginFunc in the graphics_engine.h initialize function, and followed by iLuFlipImage(). 
	// They ensure the image data will be correctly loaded and place on top left corner. And the data will be always stored from top left corner.
	iluImageParameter(ILU_PLACEMENT, ILU_UPPER_LEFT);
	// bitmap image seems like storing data upside down, its origin is on the lower left.
	// jpg, png data seems like using upper left as the origin.
	if (ilGetInteger(IL_IMAGE_ORIGIN) == IL_ORIGIN_UPPER_LEFT){
		// This is for fixing the loaded image upside down in OpenGL...
		iluFlipImage();
	}

	// set the canvas size.
	iluEnlargeCanvas(width, height, bpp);

	// Allocate the memory for the image data.
	GLubyte* buffer = new GLubyte[width * height * bpp];
	// Copy the loaded image data into the texture data depending on how many bytes per pixel
	if(bpp == 4){
		ilCopyPixels(0, 0, 0, width, height, 1, IL_RGBA, GL_UNSIGNED_BYTE, buffer);
	}
	else if(bpp == 3){
		ilCopyPixels(0, 0, 0, width, height, 1, IL_RGB, GL_UNSIGNED_BYTE, buffer);
	}
	else{
		std::string error = "Loading process, byte per pixel error, bpp: "+bpp;
		throw std::exception(error.c_str());	
	}

	// Delete the devIL image data
	ilDeleteImage(imageID);

	// create a brand new texture to use
	// put the texture into the texture cache.
	texture_sp = ATextureCache::GetInstance()->Cache(path, new ATexture(buffer, contentWidth, contentHeight, width, height, GL_RGBA, bpp));

	// after texture is created, the buffer data will be uploaded to OpenGL, so no long needed.
	delete[] buffer;

	// This is a pointer to the loaded image data
	return texture_sp;
}
Exemplo n.º 4
0
ofxTexture::~ofxTexture()
{
    glDeleteTextures(1, &m_TextureId);
    ilDeleteImage(m_ImageId);
}
Exemplo n.º 5
0
/*----------------------------------
ofxTexture::Lock()
------------------------------------
- store texture data at GPU
- save alot of RAM
- a texture locked can't be manipulated or used as material to manipulate other textures
- only used for render
----------------------------------*/
void ofxTexture::Lock()
{
    m_Locked = true;
    ilDeleteImage(m_ImageId);
}
Exemplo n.º 6
0
	//------------------------------------------------------------------------------------
	// Destructor
	//------------------------------------------------------------------------------------
	Image::~Image()
	{
		ilDeleteImage(m_iImgID);
		Device::GetSingletonPtr()->GetImageManager()->RemoveResource(this);
	}
Exemplo n.º 7
0
FileTexture::~FileTexture()
{
	ilDeleteImage(imageHandle);
}
Exemplo n.º 8
0
bool TextureControl::GenerateComposite(string sourceName,string modName,string outputName, unsigned int destSize, unsigned int mode ) {
	
	ILuint srctex = 0;
	ILuint modtex = 0;
	ILuint canvas = 0;
		
	if(namedImages.find(modName) == namedImages.end())				// mod not selected?
		return false;
	modtex = namedImages[modName];
	ilBindImage(modtex);
	


	ILuint mW = ilGetInteger(IL_IMAGE_WIDTH);
	ILuint mH = ilGetInteger(IL_IMAGE_HEIGHT);

	if(destSize && (mW != destSize)) {		
		iluImageParameter(ILU_FILTER, ILU_SCALE_BSPLINE);
		iluScale(destSize,destSize,1);
		mW = mH = destSize;
	}

	if(namedImages.find(sourceName) == namedImages.end())				// source not selected?
		return false;
	srctex = namedImages[sourceName];
	ilBindImage(srctex);
	
	ILuint sW = ilGetInteger(IL_IMAGE_WIDTH);
	ILuint sH = ilGetInteger(IL_IMAGE_HEIGHT);

	if(destSize && (sW != destSize)) {		
		iluImageParameter(ILU_FILTER, ILU_SCALE_BSPLINE);
		iluScale(destSize,destSize,1);
		sW = sH = destSize;
	}

	if(namedImages.find(outputName) != namedImages.end())				// already have an output?  
		ilDeleteImage(namedImages[outputName]);							

	if(sW < mW) {
		ilBindImage(modtex);
		iluImageParameter(ILU_FILTER, ILU_SCALE_BSPLINE);
		iluScale(sW,sH,1);
		ilBindImage(srctex);
	} else if(sW > mW){
		iluImageParameter(ILU_FILTER, ILU_SCALE_BSPLINE);
		iluScale(mW,mH,1);
		sW=mW; sH=mH;
	}

	namedImages[outputName] = getImageHandle();
	ilTexImage(sW,sH,1,4,IL_RGBA,IL_UNSIGNED_BYTE,NULL);

	ilBlit(srctex,0,0,0,0,0,0,sW,sH,1);
	
	ilEnable(IL_BLIT_BLEND);
	ilBlit(modtex,0,0,0,0,0,0,sW,sH,1);


	return true;
}
Exemplo n.º 9
0
 ~ILBitmap()
 {
     ilDeleteImage(img_);
 }
Exemplo n.º 10
0
void Font::loadFontImage(const FileName &fileName)
{
	CHECK_GL_ERROR();
	
	unsigned int imageName = devil_loadImage(fileName);

	// Get image data
	unsigned char *font	= ilGetData();
	int fontWidth		= ilGetInteger(IL_IMAGE_WIDTH);
	int fontHeight		= ilGetInteger(IL_IMAGE_HEIGHT);
	int bytesPerPixel	= ilGetInteger(IL_IMAGE_BYTES_PER_PIXEL);
	bool alpha          = bytesPerPixel==4;

	ASSERT(font!=0,       "font was NULL");
	ASSERT(fontWidth>16,  "font width is too narrow");
	ASSERT(fontHeight>16, "font height is too narrow");

	// The number of columns and rows of characters contained in the font
	const int numCols = 16;
	const int numRows = 16;

	// Each character in the font has these dimensions
	const GLint width = fontWidth / 16;
	const GLint height = fontHeight / 16;

	// Create a buffer
	const size_t size = width * height * bytesPerPixel;
	unsigned char *buffer = new unsigned char[size];
	memset(buffer, 0, size);

	// Create sub textures for each character
	glEnable(GL_TEXTURE_2D);
	for(unsigned char c=0; c<255; ++c)
	{
		int charX = c % 16;
		int charY = 15 - (c - charX) / 16;
		int x = charX * fontWidth / numCols;
		int y = charY * fontHeight / numRows;

		int imgLeft=width;
		int imgRight=0;

		// Copy the character into the smaller buffer
		for(int row=0; row<height; ++row)
		{
			size_t font_row = row + y;
			size_t font_rowLength = fontWidth * bytesPerPixel;
			size_t x_offset = x * bytesPerPixel;
			size_t font_idx = font_row * font_rowLength + x_offset;

			size_t char_row = row;
			size_t char_rowLength = width * bytesPerPixel;
			size_t char_idx = char_row * char_rowLength;

			memcpy(buffer + char_idx, font + font_idx, char_rowLength);

			const int threshold = 96;

			int left=0;
			while(left < width && buffer[char_idx + left*bytesPerPixel + 3] < threshold) ++left;

			int right=width-1;
			while(right >= 0 && buffer[char_idx + right*bytesPerPixel + 3] < threshold) --right;

			imgLeft = min(imgLeft, left);
			imgRight = max(imgRight, right);
		}

		if(imgLeft >= imgRight)
		{
			characters[c].width = 0.4f;
			characters[c].left = 0.0f;
		}
		else
		{
			characters[c].width = (imgRight - imgLeft) / (float)width;
			characters[c].left = imgLeft / (float)width;
		}

		// Create a new texture object
		characters[c].charTex=0;
		glGenTextures(1, &characters[c].charTex);

		// and bind it as the present texture
		glBindTexture(GL_TEXTURE_2D, characters[c].charTex);

		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);

		// Now build mipmaps from the texture data
		gluBuild2DMipmaps(GL_TEXTURE_2D,
		                  bytesPerPixel,
		                  width,
		                  height,
		                  alpha ? GL_RGBA : GL_RGB,
		                  GL_UNSIGNED_BYTE,
		                  buffer);
	} // loop

	// Delete the buffer
	delete[] buffer;
	buffer=0;

	// Allow DevIL to free image data on its end
	ilDeleteImage(imageName);

	TRACE(string("Created font: ") + fileName.str());

	CHECK_GL_ERROR();
}
Exemplo n.º 11
0
UInt32 GUCEF_PLUGIN_CALLSPEC_PREFIX
IMGCODECPLUGIN_DecodeImage( void* pluginData      ,
                            void* codecData       ,
                            const char* codecType ,
                            TIOAccess* input      ,
                            TImage** imageOutput  ,
                            void** imageData      )
{
    UInt32 i=0, n=0, mipmapCount=0, frameCount=0;
    ILint imageID = 0, imageSize = 0;
    TImage* image = NULL;

    if ( ( NULL == codecType ) || ( NULL == input ) ) 
        return 0;
    
    /* generate an image ID and make that ID the ID of the current image */
    imageID = ilGenImage();
    ilBindImage( imageID );
    
    currentResource = input;
    
    if ( IL_TRUE == ilLoadF( ilTypeFromExt( codecType ), input ) )
    {        
        image = malloc( sizeof(TImage) );
        image->version = GUCEF_IMAGE_TIMAGE_VERSION;
        image->imageInfo.version = GUCEF_IMAGE_TIMAGEINFO_VERSION;
        frameCount = image->imageInfo.nrOfFramesInImage = (UInt32) ilGetInteger( IL_NUM_IMAGES );
        if ( frameCount == 0 )
        {
            /* DevIL returns a image count of 0 for single-image images */
            frameCount = image->imageInfo.nrOfFramesInImage = 1;
        }
        image->frames = (TImageFrame*) malloc( frameCount * sizeof( TImageFrame ) );

        /* Only 1 layer is supported atm */
        ilActiveLayer( 0 );
        
        for ( i=0; i<frameCount; ++i )
        {
            TImageFrame* imageFrame = &image->frames[ i ]; 
            imageFrame->version = GUCEF_IMAGE_TIMAGEFRAME_VERSION;

            /* activate the frame */
            ilActiveImage( i );
            
            /* init the TImageFrameInfo section */
            imageFrame->frameInfo.version = GUCEF_IMAGE_TIMAGEFRAMEINFO_VERSION;
            mipmapCount = imageFrame->frameInfo.nrOfMipmapLevels = (UInt32) ilGetInteger( IL_NUM_MIPMAPS );
            if ( mipmapCount == 0 )
            {
                /* DevIL returns a mipmap count of 0 images without mipmapping, we use 0 for the base image */
                mipmapCount = imageFrame->frameInfo.nrOfMipmapLevels = 1;
            }
            imageFrame->mipmapLevel = (TImageMipMapLevel*) malloc( mipmapCount * sizeof(TImageMipMapLevel) );
        
            for ( n=0; n<mipmapCount; ++n )
            {
                TImageMipMapLevel* mipmapLevel = &imageFrame->mipmapLevel[ n ]; 
                mipmapLevel->version = GUCEF_IMAGE_TIMAGEMIPMAPLEVEL_VERSION;
                
                /* activate the mip-map */
                ilActiveMipmap( n );
                
                // Converted paletted images
                if( ilGetInteger( IL_IMAGE_FORMAT ) == IL_COLOUR_INDEX )
                {
                    ilConvertImage( IL_BGRA, IL_UNSIGNED_BYTE );
                }
                
                /* init the TImageMipMapLevelInfo section */
                mipmapLevel->mipLevelInfo.version = GUCEF_IMAGE_TIMAGEMIPMAPLEVELINFO_VERSION;
                mipmapLevel->mipLevelInfo.pixelComponentDataType = DATATYPE_UINT8; /* DevIL only supports this type */
                mipmapLevel->mipLevelInfo.frameHeight = ilGetInteger( IL_IMAGE_HEIGHT );
                mipmapLevel->mipLevelInfo.frameWidth = ilGetInteger( IL_IMAGE_WIDTH );
                mipmapLevel->mipLevelInfo.pixelStorageFormat = ConvertILPixelFormatToGUCEFPixelFormat( ilGetInteger( IL_IMAGE_FORMAT ) );

                /* now we grab the pixel data */
                ilCompressFunc( IL_COMPRESS_NONE );
                mipmapLevel->pixelDataSizeInBytes = ilGetInteger( IL_IMAGE_SIZE_OF_DATA );
                mipmapLevel->pixelData = malloc( mipmapLevel->pixelDataSizeInBytes );
                memcpy( mipmapLevel->pixelData, ilGetData(), mipmapLevel->pixelDataSizeInBytes );
            }
        }
    }
    
    /*
     *  the image has been loaded into our GUCEF structures so we have no need for
     *  DevIL to store the data any more 
     */
    ilDeleteImage( imageID );
    
    *imageOutput = image;
    currentResource = NULL;
    
    return 1;
}
Exemplo n.º 12
0
void ilFDeleteImage_(int *Num)
{
	ilDeleteImage(*Num);
	return;
}
    void DevilImageReader::updateResult(DataContainer& data) {
        const std::string& url = p_url.getValue();
        std::string directory = cgt::FileSystem::dirName(url);
        std::string base = cgt::FileSystem::baseName(url);
        std::string ext = cgt::FileSystem::fileExtension(url);

        // check whether we open an image series
        size_t suffixPos = base.find_last_not_of("0123456789");
        if (suffixPos != std::string::npos)
            ++suffixPos;
        size_t suffixLength = (suffixPos == std::string::npos) ? 0 : base.length() - suffixPos;

        // assemble the list of files to read
        std::vector<std::string> files;
        if (suffixLength == 0 || !p_importSimilar.getValue()) {
            files.push_back(url);
        }
        else {
            std::string prefix = base.substr(0, suffixPos);
            int index = StringUtils::fromString<int>(base.substr(suffixPos));

            while (cgt::FileSystem::fileExists(directory + "/" + prefix + StringUtils::toString(index, suffixLength, '0') + "." + ext)) {
                files.push_back(directory + "/" + prefix + StringUtils::toString(index, suffixLength, '0') + "." + ext);
                ++index;
            }
        }

        if (files.empty())
            return;

        cgt::ivec3 imageSize(0, 0, static_cast<int>(files.size()));
        uint8_t* buffer = nullptr;

        ILint devilFormat = 0;
        if (p_importType.getOptionValue() == "localIntensity") 
            devilFormat = IL_LUMINANCE;
        else if (p_importType.getOptionValue() == "localIntensity3") 
            devilFormat = IL_RGB;
        else if (p_importType.getOptionValue() == "rt") 
            devilFormat = IL_RGBA;

        ILint devilDataType = 0;
        WeaklyTypedPointer::BaseType campvisDataType = WeaklyTypedPointer::UINT8;
        size_t numChannels = 1;

        // start reading
        for (size_t i = 0; i < files.size(); ++i) {
            // prepare DevIL
            ILuint img;
            ilGenImages(1, &img);
            ilBindImage(img);

            // try load file
            if (! ilLoadImage(files[i].c_str())) {
                LERROR("Could not load image: " << files[i]);
                delete [] buffer;
                return;
            }

            // prepare buffer and perform dimensions check
            if (i == 0) {
                imageSize.x = ilGetInteger(IL_IMAGE_WIDTH);
                imageSize.y = ilGetInteger(IL_IMAGE_HEIGHT);

                if (devilFormat == 0)
                    devilFormat = ilGetInteger(IL_IMAGE_FORMAT);

                switch (ilGetInteger(IL_IMAGE_TYPE)) {
                    case IL_UNSIGNED_BYTE:
                        devilDataType = IL_UNSIGNED_BYTE;
                        campvisDataType = WeaklyTypedPointer::UINT8;
                        break;
                    case IL_BYTE:
                        devilDataType = IL_BYTE;
                        campvisDataType = WeaklyTypedPointer::INT8;
                        break;
                    case IL_UNSIGNED_SHORT:
                        devilDataType = IL_UNSIGNED_SHORT;
                        campvisDataType = WeaklyTypedPointer::UINT16;
                        break;
                    case IL_SHORT:
                        devilDataType = IL_SHORT;
                        campvisDataType = WeaklyTypedPointer::INT16;
                        break;
                    case IL_UNSIGNED_INT:
                        devilDataType = IL_UNSIGNED_INT;
                        campvisDataType = WeaklyTypedPointer::UINT32;
                        break;
                    case IL_INT:
                        devilDataType = IL_INT;
                        campvisDataType = WeaklyTypedPointer::INT32;
                        break;
                    case IL_FLOAT:
                        devilDataType = IL_FLOAT;
                        campvisDataType = WeaklyTypedPointer::FLOAT;
                        break;
                    default:
                        LERROR("unsupported data type: " << ilGetInteger(IL_IMAGE_TYPE) << " (" << files[i] << ")");
                        return;
                }

                switch (devilFormat) {
                    case IL_LUMINANCE:
                        numChannels = 1;
                        break;
                    case IL_LUMINANCE_ALPHA:
                        numChannels = 2;
                        break;
                    case IL_RGB:
                        numChannels = 3;
                        break;
                    case IL_RGBA:
                        numChannels = 4;
                        break;
                    default:
                        LERROR("unsupported image format: " << devilFormat << " (" << files[i] << ")");
                        return;
                }
                buffer = new uint8_t[cgt::hmul(imageSize) * WeaklyTypedPointer::numBytes(campvisDataType, numChannels)];
            }
            else {
                if (imageSize.x != ilGetInteger(IL_IMAGE_WIDTH)) {
                    LERROR("Could not load images: widths do not match!");
                    delete [] buffer;
                    return;
                }
                if (imageSize.y != ilGetInteger(IL_IMAGE_HEIGHT)) {
                    LERROR("Could not load images: heights do not match!");
                    delete [] buffer;
                    return;
                }
            }

            // get data from image and transform to single intensity image:
            ilCopyPixels(0, 0, 0, imageSize.x, imageSize.y, 1, devilFormat, devilDataType, buffer + (WeaklyTypedPointer::numBytes(campvisDataType, numChannels) * i * imageSize.x * imageSize.y));
            ILint err = ilGetError();
            if (err != IL_NO_ERROR) {
                LERROR("Error during conversion: " << iluErrorString(err));
                delete [] buffer;
                return;
            }

            ilDeleteImage(img);
        }

        size_t dimensionality = 3;
        if (imageSize.z == 1)
            dimensionality = 2;
        if (imageSize.y == 1)
            dimensionality = 1;


        ImageData* id = new ImageData(dimensionality, imageSize, numChannels);
        WeaklyTypedPointer wtp(campvisDataType, numChannels, buffer);
        ImageRepresentationLocal::create(id, wtp);
        //id->setMappingInformation(ImageMappingInformation(imageSize, p_imageOffset.getValue(), p_voxelSize.getValue()));

        if (p_importType.getOptionValue() == "rt") {
            RenderData* rd = new RenderData();
            rd->addColorTexture(id);

            // create fake depth image
            ImageData* idDepth = new ImageData(dimensionality, imageSize, 1);
            float* ptr = new float[cgt::hmul(imageSize)];
            memset(ptr, 0, cgt::hmul(imageSize) * sizeof(float));
            WeaklyTypedPointer wtpDepth(campvisDataType, 1, ptr);
            ImageRepresentationLocal::create(idDepth, wtpDepth);
            rd->setDepthTexture(idDepth);

            data.addData(p_targetImageID.getValue(), rd);
        }
        else {
            data.addData(p_targetImageID.getValue(), id);
        }
    }