Exemple #1
0
void makeTexture()
{
  glGenTextures(6, texName);
	
	Bitmap* bm0 = new Bitmap();
	loadBitmap(bm0, "../../bmp/disk4.bmp");
	makeTexImage(bm0);
	setColorMap(0);
	makeNormalMap(bm0);
	setNormalMap(0);

	loadBitmap(bm0, "../../bmp/brick2.bmp");
	makeTexImage(bm0);
	setColorMap(1);
	makeNormalMap(bm0);
	setNormalMap(1);

	loadBitmap(bm0, "../../bmp/stones1.bmp");
	makeTexImage(bm0);
	setColorMap(2);
	makeNormalMap(bm0);
	setNormalMap(2);
}
void BasicNormalMethod::copyFrom(ShadingMethodBase* method)
{
	setNormalMap(((BasicNormalMethod*)method)->getNormalMap());
}
int main(int argc, char *argv[])
{
    MyAssertHandler assertHandler;
    MyMessageHandler messageHandler;

    bool alpha = false;
    bool normal = false;
    bool color2normal = false;
    bool linear = false;
    bool wrapRepeat = false;
    bool noMipmaps = false;
    bool fast = false;
    bool nocuda = false;
    bool bc1n = false;
    bool luminance = false;
    nvtt::Format format = nvtt::Format_BC1;
    bool fillHoles = false;
    bool countEmptyRows = false;
    bool outProvided = false;
    bool premultiplyAlpha = false;
    nvtt::MipmapFilter mipmapFilter = nvtt::MipmapFilter_Box;
    bool loadAsFloat = false;
    bool rgbm = false;
    bool rangescale = false;

    const char * externalCompressor = NULL;

    bool silent = false;
    bool dds10 = false;

    nv::Path input;
    nv::Path output;


    // Parse arguments.
    for (int i = 1; i < argc; i++)
    {
        // Input options.
        if (strcmp("-color", argv[i]) == 0)
        {
        }
        else if (strcmp("-alpha", argv[i]) == 0)
        {
            alpha = true;
        }
        else if (strcmp("-normal", argv[i]) == 0)
        {
            normal = true;
        }
        else if (strcmp("-tonormal", argv[i]) == 0)
        {
            color2normal = true;
        }
		else if (strcmp("-linear", argv[i]) == 0)
		{
			linear = true;
		}
        else if (strcmp("-clamp", argv[i]) == 0)
        {
        }
        else if (strcmp("-repeat", argv[i]) == 0)
        {
            wrapRepeat = true;
        }
        else if (strcmp("-nomips", argv[i]) == 0)
        {
            noMipmaps = true;
        }
        else if (strcmp("-fillholes", argv[i]) == 0)
        {
            fillHoles = true;
        }
        else if (strcmp("-countempty", argv[i]) == 0)
        {
            countEmptyRows = true;
        }
        else if (strcmp("-premula", argv[i]) == 0)
        {
            premultiplyAlpha = true;
        }
        else if (strcmp("-mipfilter", argv[i]) == 0)
        {
            if (i+1 == argc) break;
            i++;

            if (strcmp("box", argv[i]) == 0) mipmapFilter = nvtt::MipmapFilter_Box;
            else if (strcmp("triangle", argv[i]) == 0) mipmapFilter = nvtt::MipmapFilter_Triangle;
            else if (strcmp("kaiser", argv[i]) == 0) mipmapFilter = nvtt::MipmapFilter_Kaiser;
        }
        else if (strcmp("-float", argv[i]) == 0)
        {
            loadAsFloat = true;
        }
        else if (strcmp("-rgbm", argv[i]) == 0)
        {
            rgbm = true;
        }
        else if (strcmp("-rangescale", argv[i]) == 0)
        {
            rangescale = true;
        }


        // Compression options.
        else if (strcmp("-fast", argv[i]) == 0)
        {
            fast = true;
        }
        else if (strcmp("-nocuda", argv[i]) == 0)
        {
            nocuda = true;
        }
        else if (strcmp("-rgb", argv[i]) == 0)
        {
            format = nvtt::Format_RGB;
        }
        else if (strcmp("-lumi", argv[i]) == 0)
        {
            luminance = true;
            format = nvtt::Format_RGB;
        }
        else if (strcmp("-bc1", argv[i]) == 0)
        {
            format = nvtt::Format_BC1;
        }
        else if (strcmp("-bc1n", argv[i]) == 0)
        {
            format = nvtt::Format_BC1;
            bc1n = true;
        }
        else if (strcmp("-bc1a", argv[i]) == 0)
        {
            format = nvtt::Format_BC1a;
        }
        else if (strcmp("-bc2", argv[i]) == 0)
        {
            format = nvtt::Format_BC2;
        }
        else if (strcmp("-bc3", argv[i]) == 0)
        {
            format = nvtt::Format_BC3;
        }
        else if (strcmp("-bc3n", argv[i]) == 0)
        {
            format = nvtt::Format_BC3n;
        }
        else if (strcmp("-bc4", argv[i]) == 0)
        {
            format = nvtt::Format_BC4;
        }
        else if (strcmp("-bc5", argv[i]) == 0)
        {
            format = nvtt::Format_BC5;
        }
        else if (strcmp("-bc6", argv[i]) == 0)
        {
            format = nvtt::Format_BC6;
        }
        else if (strcmp("-bc7", argv[i]) == 0)
        {
            format = nvtt::Format_BC7;
        }
        else if (strcmp("-bc3_rgbm", argv[i]) == 0)
        {
            format = nvtt::Format_BC3_RGBM;
            rgbm = true;
        }

        // Undocumented option. Mainly used for testing.
        else if (strcmp("-ext", argv[i]) == 0)
        {
            if (i+1 < argc && argv[i+1][0] != '-') {
                externalCompressor = argv[i+1];
                i++;
            }
        }
        else if (strcmp("-pause", argv[i]) == 0)
        {
            printf("Press ENTER\n"); fflush(stdout);
            getchar();
        }

        // Output options
        else if (strcmp("-silent", argv[i]) == 0)
        {
            silent = true;
        }
        else if (strcmp("-dds10", argv[i]) == 0)
        {
            dds10 = true;
        }

        else if (argv[i][0] != '-')
        {
            input = argv[i];

            if (i+1 < argc && argv[i+1][0] != '-') {
                output = argv[i+1];
                if(output.endsWith("\\") || output.endsWith("/")) {
                    //only path specified
                    output.append(input.fileName());
				    output.stripExtension();
				    output.append(".dds");
               }
               else
                   outProvided = true;
            }
            else
            {
                output.copy(input.str());
                output.stripExtension();
                output.append(".dds");
            }

            break;
        }
		else
		{
			printf("Warning: unrecognized option \"%s\"\n", argv[i]);
		}
    }

    const uint version = nvtt::version();
    const uint major = version / 100 / 100;
    const uint minor = (version / 100) % 100;
    const uint rev = version % 100;


    if (!silent)
    {
        printf("NVIDIA Texture Tools %u.%u.%u - Copyright NVIDIA Corporation 2007\n\n", major, minor, rev);
    }

    if (input.isNull())
    {
        printf("usage: nvcompress [options] infile [outfile.dds]\n\n");

        printf("Input options:\n");
        printf("  -color        The input image is a color map (default).\n");
        printf("  -alpha        The input image has an alpha channel used for transparency.\n");
        printf("  -normal       The input image is a normal map.\n");
        printf("  -linear       The input is in linear color space.\n");
        printf("  -tonormal     Convert input to normal map.\n");
        printf("  -clamp        Clamp wrapping mode (default).\n");
        printf("  -repeat       Repeat wrapping mode.\n");
        printf("  -nomips       Disable mipmap generation.\n");
        printf("  -premula      Premultiply alpha into color channel.\n");
        printf("  -mipfilter    Mipmap filter. One of the following: box, triangle, kaiser.\n");
        printf("  -float        Load as floating point image.\n\n");
        printf("  -rgbm         Transform input to RGBM.\n\n");
        printf("  -rangescale   Scale image to use entire color range.\n\n");
        printf("  -fillholes    Fill transparent areas with nearby color. Note: adds transparent upper height into output file name in case the outfile was not specified, and infile was in form #.####.xxx.ext\n\n");

        printf("Compression options:\n");
        printf("  -fast         Fast compression.\n");
        printf("  -nocuda       Do not use cuda compressor.\n");
        printf("  -rgb          RGBA format\n");
        printf("  -lumi         LUMINANCE format\n");
        printf("  -bc1          BC1 format (DXT1)\n");
        printf("  -bc1n         BC1 normal map format (DXT1nm)\n");
        printf("  -bc1a         BC1 format with binary alpha (DXT1a)\n");
        printf("  -bc2          BC2 format (DXT3)\n");
        printf("  -bc3          BC3 format (DXT5)\n");
        printf("  -bc3n         BC3 normal map format (DXT5nm)\n");
        printf("  -bc4          BC4 format (ATI1)\n");
        printf("  -bc5          BC5 format (3Dc/ATI2)\n");
        printf("  -bc6          BC6 format\n");
        printf("  -bc7          BC7 format\n\n");
        printf("  -bc3_rgbm     BC3-rgbm format\n\n");

        printf("Output options:\n");
        printf("  -silent  \tDo not output progress messages\n");
        printf("  -dds10   \tUse DirectX 10 DDS format (enabled by default for BC6/7)\n\n");

        return EXIT_FAILURE;
    }

    // Make sure input file exists.
    if (!nv::FileSystem::exists(input.str()))
    {
        fprintf(stderr, "The file '%s' does not exist.\n", input.str());
        return 1;
    }

    // Set input options.
    nvtt::InputOptions inputOptions;

    bool useSurface = false;    // @@ use Surface API in all cases!
    nvtt::Surface image;

    if (format == nvtt::Format_Unknown && nv::strCaseDiff(input.extension(), ".dds") == 0)
    {
        // Load surface.
        nv::DirectDrawSurface dds(input.str());
        if (!dds.isValid())
        {
            fprintf(stderr, "The file '%s' is not a valid DDS file.\n", input.str());
            return EXIT_FAILURE;
        }

        if (!dds.isSupported())
        {
            fprintf(stderr, "The file '%s' is not a supported DDS file.\n", input.str());
            return EXIT_FAILURE;
        }

        //if format not specified, get from dds
        if (dds.isRGB())
            format = nvtt::Format_RGB;
        else if (dds.isLuminance()) {
            luminance = true;
            format = nvtt::Format_RGB;
        }
        else {
            uint cc = dds.fourcc();
            switch(cc) {
            case nv::FOURCC_DXT1:   format = nvtt::Format_DXT1; break;
            case nv::FOURCC_DXT3:   format = nvtt::Format_DXT3; break;
            case nv::FOURCC_DXT5:   format = nvtt::Format_DXT5; break;
            case nv::FOURCC_RXGB:   format = nvtt::Format_BC3n; break;
            case nv::FOURCC_ATI1:   format = nvtt::Format_BC4; break;
            case nv::FOURCC_ATI2:   format = nvtt::Format_BC5; break;
            }
        }

        alpha = dds.hasAlpha();
    }


    if (format == nvtt::Format_BC3_RGBM || rgbm) {
        useSurface = true;

        if (!image.load(input.str())) {
            fprintf(stderr, "Error opening input file '%s'.\n", input.str());
            return EXIT_FAILURE;
        }

        if (rangescale) {
            // get color range
            float min_color[3], max_color[3];
            image.range(0, &min_color[0], &max_color[0]);
            image.range(1, &min_color[1], &max_color[1]);
            image.range(2, &min_color[2], &max_color[2]);

            //printf("Color range = %.2f %.2f %.2f\n", max_color[0], max_color[1], max_color[2]);

            float color_range = nv::max3(max_color[0], max_color[1], max_color[2]);
            const float max_color_range = 16.0f;

            if (color_range > max_color_range) {
                //Log::print("Clamping color range %f to %f\n", color_range, max_color_range);
                color_range = max_color_range;
            }
            //color_range = max_color_range;  // Use a fixed color range for now.

            for (int i = 0; i < 3; i++) {
                image.scaleBias(i, 1.0f / color_range, 0.0f);
            }
            image.toneMap(nvtt::ToneMapper_Linear, /*parameters=*/NULL); // Clamp without changing the hue.

            // Clamp alpha.
            image.clamp(3);
        }

        if (alpha) {
            image.setAlphaMode(nvtt::AlphaMode_Transparency);
        }

        // To gamma.
        image.toGamma(2);

        if (format != nvtt::Format_BC3_RGBM) {
            image.setAlphaMode(nvtt::AlphaMode_None);
            image.toRGBM(1, 0.15f);
        }
    }
    else if (format == nvtt::Format_BC6) {
        //format = nvtt::Format_BC1;
        //fprintf(stderr, "BLABLABLA.\n");
        useSurface = true;

        if (!image.load(input.str())) {
            fprintf(stderr, "Error opening input file '%s'.\n", input.str());
            return EXIT_FAILURE;
        }

        image.setAlphaMode(nvtt::AlphaMode_Transparency);
    }
    else {
        if (nv::strCaseDiff(input.extension(), ".dds") == 0)
        {
            // Load surface.
            nv::DirectDrawSurface dds(input.str());
            if (!dds.isValid())
            {
                fprintf(stderr, "The file '%s' is not a valid DDS file.\n", input.str());
                return EXIT_FAILURE;
            }

            if (!dds.isSupported())
            {
                fprintf(stderr, "The file '%s' is not a supported DDS file.\n", input.str());
                return EXIT_FAILURE;
            }

            uint faceCount;
            if (dds.isTexture2D())
            {
                inputOptions.setTextureLayout(nvtt::TextureType_2D, dds.width(), dds.height());
                faceCount = 1;
            }
            else if (dds.isTexture3D())
            {
                inputOptions.setTextureLayout(nvtt::TextureType_3D, dds.width(), dds.height(), dds.depth());
                faceCount = 1;

                nvDebugBreak();
            }
            else if (dds.isTextureCube()) {
                inputOptions.setTextureLayout(nvtt::TextureType_Cube, dds.width(), dds.height());
                faceCount = 6;
            } else {
                nvDebugCheck(dds.isTextureArray());
                inputOptions.setTextureLayout(nvtt::TextureType_Array, dds.width(), dds.height(), 1, dds.arraySize());
                faceCount = dds.arraySize();
                dds10 = true;
            }

            uint mipmapCount = dds.mipmapCount();

            nv::Image mipmap;

            for (uint f = 0; f < faceCount; f++)
            {
                for (uint m = 0; m < mipmapCount; m++)
                {
                    dds.mipmap(&mipmap, f, m); // @@ Load as float.

                    inputOptions.setMipmapData(mipmap.pixels(), mipmap.width(), mipmap.height(), mipmap.depth(), f, m);
                }
            }
        }
        else
        {
            if (nv::strCaseDiff(input.extension(), ".exr") == 0 || nv::strCaseDiff(input.extension(), ".hdr") == 0)
            {
                loadAsFloat = true;
            }

            if (loadAsFloat)
            {
                nv::AutoPtr<nv::FloatImage> image(nv::ImageIO::loadFloat(input.str()));

                if (image == NULL)
                {
                    fprintf(stderr, "The file '%s' is not a supported image type.\n", input.str());
                    return EXIT_FAILURE;
                }

                inputOptions.setFormat(nvtt::InputFormat_RGBA_32F);
                inputOptions.setTextureLayout(nvtt::TextureType_2D, image->width(), image->height());

                /*for (uint i = 0; i < image->componentNum(); i++)
                {
                    inputOptions.setMipmapChannelData(image->channel(i), i, image->width(), image->height());
                }*/
            }
            else
            {
                // Regular image.
                nv::Image image;
                if (!image.load(input.str()))
                {
                    fprintf(stderr, "The file '%s' is not a supported image type.\n", input.str());
                    return 1;
                }

                if(countEmptyRows)
                {
                    //count empty rows & append to the file name
                    const int w = image.width();
                    const int h = image.height();
                    int ytr = 0;   //height of the transparent part

                    if(image.format() == image.Format_ARGB) {
                        for(int y=0; y<h; ++y) {
                            for(int x=0; x<w; ++x) {
                                if(image.pixel(x,y).a >= 128) {
                                    ytr = y;
                                    y = h;
                                    break;
                                }
                            }
                        }
                    }

                    //change outfile
                    output.stripExtension();
                    output.appendFormat(".%04i.dds", ytr);
                }

                if(fillHoles) {
                    nv::FloatImage fimage(&image);

                    // create feature mask
                    nv::BitMap bmp(image.width(),image.height());
                    bmp.clearAll();
                    const int w=image.width();
                    const int h=image.height();
                    int ytr = h;   //height of the transparent part
                    for(int y=0; y<h; ++y)
                        for(int x=0; x<w; ++x) 
                            if(fimage.pixel(3,x,y,0) >= 0.5f) {
                                bmp.setBitAt(x,y);
                                if(y < ytr) ytr = y;
                            }


                    // fill holes
                    nv::fillVoronoi(&fimage,&bmp);

                    // do blur passes
                    for(int i=0; i<8; ++i)
                        nv::fillBlur(&fimage,&bmp);

                    nv::AutoPtr<nv::Image> img(fimage.createImage(0));

                    inputOptions.setTextureLayout(nvtt::TextureType_2D, img->width(), img->height());
                    inputOptions.setMipmapData(img->pixels(), img->width(), img->height());
                }
                else {
                    inputOptions.setTextureLayout(nvtt::TextureType_2D, image.width(), image.height());
                    inputOptions.setMipmapData(image.pixels(), image.width(), image.height());
                }
            }

        }


        if (format == nvtt::Format_Unknown)
            format = nvtt::Format_BC1;


        if (wrapRepeat)
        {
            inputOptions.setWrapMode(nvtt::WrapMode_Repeat);
        }
        else
        {
            inputOptions.setWrapMode(nvtt::WrapMode_Clamp);
        }

        if (alpha)
        {
            inputOptions.setAlphaMode(nvtt::AlphaMode_Transparency);
        }
        else
        {
            inputOptions.setAlphaMode(nvtt::AlphaMode_None);
        }

        // Block compressed textures with mipmaps must be powers of two.
        if (!noMipmaps && format != nvtt::Format_RGB)
        {
            //inputOptions.setRoundMode(nvtt::RoundMode_ToPreviousPowerOfTwo);
        }

        if (linear)
        {
            setLinearMap(inputOptions);
        }
        else if (normal)
        {
            setNormalMap(inputOptions);
        }
        else if (color2normal)
        {
            setColorToNormalMap(inputOptions);
        }
        else
        {
            setColorMap(inputOptions);
        }

        if (noMipmaps)
        {
            inputOptions.setMipmapGeneration(false);
        }

        /*if (premultiplyAlpha)
        {
            inputOptions.setPremultiplyAlpha(true);
            inputOptions.setAlphaMode(nvtt::AlphaMode_Premultiplied);
        }*/

        inputOptions.setMipmapFilter(mipmapFilter);
    }



    nvtt::CompressionOptions compressionOptions;
    compressionOptions.setFormat(format);

    //compressionOptions.setQuantization(/*color dithering*/true, /*alpha dithering*/false, /*binary alpha*/false);

    if (format == nvtt::Format_BC2) {
        // Dither alpha when using BC2.
        compressionOptions.setQuantization(/*color dithering*/false, /*alpha dithering*/true, /*binary alpha*/false);
    }
    else if (format == nvtt::Format_BC1a) {
        // Binary alpha when using BC1a.
        compressionOptions.setQuantization(/*color dithering*/false, /*alpha dithering*/true, /*binary alpha*/true, 127);
    }
    else if (format == nvtt::Format_RGBA)
    {
        if (luminance)
        {
            compressionOptions.setPixelFormat(8, 0xff, 0, 0, 0);
        }
        else {
            // @@ Edit this to choose the desired pixel format:
            // compressionOptions.setPixelType(nvtt::PixelType_Float);
            // compressionOptions.setPixelFormat(16, 16, 16, 16);
            // compressionOptions.setPixelType(nvtt::PixelType_UnsignedNorm);
            // compressionOptions.setPixelFormat(16, 0, 0, 0);

            //compressionOptions.setQuantization(/*color dithering*/true, /*alpha dithering*/false, /*binary alpha*/false);
            //compressionOptions.setPixelType(nvtt::PixelType_UnsignedNorm);
            //compressionOptions.setPixelFormat(5, 6, 5, 0);
            //compressionOptions.setPixelFormat(8, 8, 8, 8);

            // A4R4G4B4
            //compressionOptions.setPixelFormat(16, 0xF00, 0xF0, 0xF, 0xF000);

            //compressionOptions.setPixelFormat(32, 0xFF0000, 0xFF00, 0xFF, 0xFF000000);

            // R10B20G10A2
            //compressionOptions.setPixelFormat(10, 10, 10, 2);

            // DXGI_FORMAT_R11G11B10_FLOAT
            //compressionOptions.setPixelType(nvtt::PixelType_Float);
            //compressionOptions.setPixelFormat(11, 11, 10, 0);
        }
    }
    else if (format == nvtt::Format_BC6)
    {
        compressionOptions.setPixelType(nvtt::PixelType_UnsignedFloat);
    }

    if (fast)
    {
        compressionOptions.setQuality(nvtt::Quality_Fastest);
    }
    else
    {
        compressionOptions.setQuality(nvtt::Quality_Normal);
        //compressionOptions.setQuality(nvtt::Quality_Production);
        //compressionOptions.setQuality(nvtt::Quality_Highest);
    }

    if (bc1n)
    {
        compressionOptions.setColorWeights(1, 1, 0);
    }

    
    //compressionOptions.setColorWeights(0.2126, 0.7152, 0.0722);
    //compressionOptions.setColorWeights(0.299, 0.587, 0.114);
    //compressionOptions.setColorWeights(3, 4, 2);

    if (externalCompressor != NULL)
    {
        compressionOptions.setExternalCompressor(externalCompressor);
    }


    MyErrorHandler errorHandler;
    MyOutputHandler outputHandler(output.str());
    if (outputHandler.stream->isError())
    {
        fprintf(stderr, "Error opening '%s' for writting\n", output.str());
        return EXIT_FAILURE;
    }

    nvtt::Context context;
    context.enableCudaAcceleration(!nocuda);

    if (!silent) 
    {
        printf("CUDA acceleration ");
        if (context.isCudaAccelerationEnabled())
        {
            printf("ENABLED\n\n");
        }
        else
        {
            printf("DISABLED\n\n");
        }
    }

    int outputSize = 0;
    if (useSurface) {
        outputSize = context.estimateSize(image, 1, compressionOptions);
    }
    else {
        outputSize = context.estimateSize(inputOptions, compressionOptions);
    }

    outputHandler.setTotal(outputSize);
    outputHandler.setDisplayProgress(!silent);

    nvtt::OutputOptions outputOptions;
    //outputOptions.setFileName(output);
    outputOptions.setOutputHandler(&outputHandler);
    outputOptions.setErrorHandler(&errorHandler);

	// Automatically use dds10 if compressing to BC6 or BC7
	if (format == nvtt::Format_BC6 || format == nvtt::Format_BC7)
	{
		dds10 = true;
	}

    if (dds10)
    {
        outputOptions.setContainer(nvtt::Container_DDS10);
    }

    // printf("Press ENTER.\n");
    // fflush(stdout);
    // getchar();

    nv::Timer timer;
    timer.start();

    if (useSurface) {
        if (!context.outputHeader(image, 1, compressionOptions, outputOptions)) {
            fprintf(stderr, "Error writing file header.\n");
            return EXIT_FAILURE;
        }
        if (!context.compress(image, 0, 0, compressionOptions, outputOptions)) {
            fprintf(stderr, "Error compressing file.\n");
            return EXIT_FAILURE;
        } 
    }
    else {
        if (!context.process(inputOptions, compressionOptions, outputOptions)) {
            return EXIT_FAILURE;
        }
    }

    timer.stop();

    if (!silent) {
        printf("\rtime taken: %.3f seconds\n", timer.elapsed());
    }

    return EXIT_SUCCESS;
}
Exemple #4
0
void PlatformDemoState::buildTerrain()
{
    m_shaderResource.preload(PlatformShaderId::SpecularSmooth2D, xy::Shader::NormalMapped::vertex, NORMAL_FRAGMENT_TEXTURED);
    m_textureResource.setFallbackColour({ 127, 127, 255 });
    const auto& normalTexture = m_textureResource.get("normalFallback");

    auto background = xy::Component::create<Plat::Background>(m_messageBus, m_textureResource);
    background->setAmbientColour(m_scene.getAmbientColour());
    auto entity = xy::Entity::create(m_messageBus);
    entity->addComponent(background);
    m_scene.addEntity(entity, xy::Scene::Layer::BackRear);

    auto drawable = xy::Component::create<xy::AnimatedDrawable>(m_messageBus);
    drawable->setTexture(m_textureResource.get("assets/images/platform/left_edge.png"));
    drawable->setNormalMap(normalTexture);
    drawable->setShader(m_shaderResource.get(PlatformShaderId::SpecularSmooth2D));

    entity = xy::Entity::create(m_messageBus);
    entity->addComponent(drawable);

    m_scene.addEntity(entity, xy::Scene::Layer::BackFront);
    //-------------------------
    drawable = xy::Component::create<xy::AnimatedDrawable>(m_messageBus);
    drawable->setTexture(m_textureResource.get("assets/images/platform/ground_section.png"));
    drawable->setNormalMap(normalTexture);
    drawable->setShader(m_shaderResource.get(PlatformShaderId::SpecularSmooth2D));

    entity = xy::Entity::create(m_messageBus);
    entity->setPosition(256.f, 1080.f - 128.f);
    entity->addComponent(drawable);

    m_scene.addEntity(entity, xy::Scene::Layer::BackFront);
    //-------------------------
    drawable = xy::Component::create<xy::AnimatedDrawable>(m_messageBus);
    drawable->setTexture(m_textureResource.get("assets/images/platform/ground_section.png"));
    drawable->setNormalMap(normalTexture);
    drawable->setShader(m_shaderResource.get(PlatformShaderId::SpecularSmooth2D));

    entity = xy::Entity::create(m_messageBus);
    entity->setPosition(1024.f, 1080.f - 128.f);
    entity->addComponent(drawable);

    m_scene.addEntity(entity, xy::Scene::Layer::BackFront);
    //-------------------------
    drawable = xy::Component::create<xy::AnimatedDrawable>(m_messageBus);
    drawable->setTexture(m_textureResource.get("assets/images/platform/ground_section.png"));
    drawable->setNormalMap(normalTexture);
    drawable->setShader(m_shaderResource.get(PlatformShaderId::SpecularSmooth2D));

    entity = xy::Entity::create(m_messageBus);
    entity->setPosition(1792.f, 1080.f - 128.f);
    entity->addComponent(drawable);

    m_scene.addEntity(entity, xy::Scene::Layer::BackFront);
    //-------------------------
    drawable = xy::Component::create<xy::AnimatedDrawable>(m_messageBus);
    drawable->setTexture(m_textureResource.get("assets/images/platform/right_edge.png"));
    drawable->setNormalMap(normalTexture);
    drawable->setShader(m_shaderResource.get(PlatformShaderId::SpecularSmooth2D));

    entity = xy::Entity::create(m_messageBus);
    entity->setPosition(2560.f, 0.f);
    entity->addComponent(drawable);

    m_scene.addEntity(entity, xy::Scene::Layer::BackFront);
    //-------------------------
    auto model = m_meshRenderer.createModel(MeshID::Platform, m_messageBus);
    model->rotate(xy::Model::Axis::X, 90.f);
    model->rotate(xy::Model::Axis::Z, 180.f);
    model->setPosition({ 384.f, 158.f, 0.f });
    model->setBaseMaterial(m_meshRenderer.getMaterial(MatId::Platform01));

    entity = xy::Entity::create(m_messageBus);
    entity->setPosition(400.f, 700.f);
    entity->addComponent(model);

    m_scene.addEntity(entity, xy::Scene::Layer::BackFront);
    //-------------------------
    drawable = xy::Component::create<xy::AnimatedDrawable>(m_messageBus);
    drawable->setTexture(m_textureResource.get("assets/images/platform/plat_03.png"));
    drawable->setNormalMap(normalTexture);
    drawable->setShader(m_shaderResource.get(PlatformShaderId::SpecularSmooth2D));

    entity = xy::Entity::create(m_messageBus);
    entity->setPosition(2000.f, 550.f);
    entity->addComponent(drawable);

    m_scene.addEntity(entity, xy::Scene::Layer::BackFront);
    //-------------------------
    drawable = xy::Component::create<xy::AnimatedDrawable>(m_messageBus);
    drawable->setTexture(m_textureResource.get("assets/images/platform/plat_02.png"));
    drawable->setNormalMap(normalTexture);
    drawable->setShader(m_shaderResource.get(PlatformShaderId::SpecularSmooth2D));

    entity = xy::Entity::create(m_messageBus);
    entity->setPosition(1670.f, 450.f);
    entity->addComponent(drawable);

    m_scene.addEntity(entity, xy::Scene::Layer::BackFront);
    //-------------------------

    model = m_meshRenderer.createModel(MeshID::Platform, m_messageBus);
    model->rotate(xy::Model::Axis::X, 90.f);
    model->rotate(xy::Model::Axis::Z, 180.f);
    model->setPosition({ 384.f, 158.f, 0.f });
    model->setBaseMaterial(m_meshRenderer.getMaterial(MatId::Platform04));

    entity = xy::Entity::create(m_messageBus);
    entity->setPosition(1210.f, 600.f);
    entity->addComponent(model);

    m_scene.addEntity(entity, xy::Scene::Layer::BackFront);

    //------some shadow receivers-------//
    model = m_meshRenderer.createModel(MeshID::Quad, m_messageBus);
    model->setPosition({ 0.f, 0.f, -250.f });

    entity = xy::Entity::create(m_messageBus);
    entity->setPosition(1000.f, 702.f);
    entity->addComponent(model);
    m_scene.addEntity(entity, xy::Scene::Layer::BackFront);

    model = m_meshRenderer.createModel(MeshID::Quad, m_messageBus);
    model->rotate(xy::Model::Axis::X, 90.f);

    entity = xy::Entity::create(m_messageBus);
    entity->setPosition(1000.f, 952.f);
    entity->addComponent(model);
    m_scene.addEntity(entity, xy::Scene::Layer::BackFront);
}
Exemple #5
0
int main(int argc, char *argv[])
{
	MyAssertHandler assertHandler;
	MyMessageHandler messageHandler;

	bool alpha = false;
	bool normal = false;
	bool color2normal = false;
	bool wrapRepeat = false;
	bool noMipmaps = false;
	bool fast = false;
	bool nocuda = false;
	bool silent = false;
	bool bc1n = false;
	nvtt::Format format = nvtt::Format_BC1;

	const char * externalCompressor = NULL;

	nv::Path input;
	nv::Path output;


	// Parse arguments.
	for (int i = 1; i < argc; i++)
	{
		// Input options.
		if (strcmp("-color", argv[i]) == 0)
		{
		}
		else if (strcmp("-alpha", argv[i]) == 0)
		{
			alpha = true;
		}
		else if (strcmp("-normal", argv[i]) == 0)
		{
			normal = true;
		}
		else if (strcmp("-tonormal", argv[i]) == 0)
		{
			color2normal = true;
		}
		else if (strcmp("-clamp", argv[i]) == 0)
		{
		}
		else if (strcmp("-repeat", argv[i]) == 0)
		{
			wrapRepeat = true;
		}
		else if (strcmp("-nomips", argv[i]) == 0)
		{
			noMipmaps = true;
		}

		// Compression options.
		else if (strcmp("-fast", argv[i]) == 0)
		{
			fast = true;
		}
		else if (strcmp("-nocuda", argv[i]) == 0)
		{
			nocuda = true;
		}
		else if (strcmp("-rgb", argv[i]) == 0)
		{
			format = nvtt::Format_RGB;
		}
		else if (strcmp("-bc1", argv[i]) == 0)
		{
			format = nvtt::Format_BC1;
		}
		else if (strcmp("-bc1n", argv[i]) == 0)
		{
			format = nvtt::Format_BC1;
			bc1n = true;
		}
		else if (strcmp("-bc1a", argv[i]) == 0)
		{
			format = nvtt::Format_BC1a;
		}
		else if (strcmp("-bc2", argv[i]) == 0)
		{
			format = nvtt::Format_BC2;
		}
		else if (strcmp("-bc3", argv[i]) == 0)
		{
			format = nvtt::Format_BC3;
		}
		else if (strcmp("-bc3n", argv[i]) == 0)
		{
			format = nvtt::Format_BC3n;
		}
		else if (strcmp("-bc4", argv[i]) == 0)
		{
			format = nvtt::Format_BC4;
		}
		else if (strcmp("-bc5", argv[i]) == 0)
		{
			format = nvtt::Format_BC5;
		}

		// Undocumented option. Mainly used for testing.
		else if (strcmp("-ext", argv[i]) == 0)
		{
			if (i+1 < argc && argv[i+1][0] != '-') {
				externalCompressor = argv[i+1];
				i++;
			}
		}

		// Misc options
		else if (strcmp("-silent", argv[i]) == 0)
		{
			silent = true;
		}

		else if (argv[i][0] != '-')
		{
			input = argv[i];

			if (i+1 < argc && argv[i+1][0] != '-') {
				output = argv[i+1];
			}
			else
			{
				output.copy(input.str());
				output.stripExtension();
				output.append(".dds");
			}

			break;
		}
	}

	const uint version = nvtt::version();
	const uint major = version / 100;
	const uint minor = version % 100;
	

	printf("NVIDIA Texture Tools %u.%u - Copyright NVIDIA Corporation 2007\n\n", major, minor);

	if (input.isNull())
	{
		printf("usage: nvcompress [options] infile [outfile]\n\n");
		
		printf("Input options:\n");
		printf("  -color   \tThe input image is a color map (default).\n");
		printf("  -alpha     \tThe input image has an alpha channel used for transparency.\n");		
		printf("  -normal  \tThe input image is a normal map.\n");
		printf("  -tonormal\tConvert input to normal map.\n");
		printf("  -clamp   \tClamp wrapping mode (default).\n");
		printf("  -repeat  \tRepeat wrapping mode.\n");
		printf("  -nomips  \tDisable mipmap generation.\n\n");

		printf("Compression options:\n");
		printf("  -fast    \tFast compression.\n");
		printf("  -nocuda  \tDo not use cuda compressor.\n");
		printf("  -rgb     \tRGBA format\n");
		printf("  -bc1     \tBC1 format (DXT1)\n");
		printf("  -bc1n    \tBC1 normal map format (DXT1nm)\n");
		printf("  -bc1a    \tBC1 format with binary alpha (DXT1a)\n");
		printf("  -bc2     \tBC2 format (DXT3)\n");
		printf("  -bc3     \tBC3 format (DXT5)\n");
		printf("  -bc3n    \tBC3 normal map format (DXT5nm)\n");
		printf("  -bc4     \tBC4 format (ATI1)\n");
		printf("  -bc5     \tBC5 format (3Dc/ATI2)\n\n");
		
		return EXIT_FAILURE;
	}

	// @@ Make sure input file exists.
	
	// Set input options.
	nvtt::InputOptions inputOptions;
	
	if (nv::strCaseCmp(input.extension(), ".dds") == 0)
	{
		// Load surface.
		nv::DirectDrawSurface dds(input);
		if (!dds.isValid())
		{
			fprintf(stderr, "The file '%s' is not a valid DDS file.\n", input.str());
			return EXIT_FAILURE;
		}
		
		if (!dds.isSupported() || dds.isTexture3D())
		{
			fprintf(stderr, "The file '%s' is not a supported DDS file.\n", input.str());
			return EXIT_FAILURE;
		}
		
		uint faceCount;
		if (dds.isTexture2D())
		{
			inputOptions.setTextureLayout(nvtt::TextureType_2D, dds.width(), dds.height());
			faceCount = 1;
		}
		else 
		{
			nvDebugCheck(dds.isTextureCube());
			inputOptions.setTextureLayout(nvtt::TextureType_Cube, dds.width(), dds.height());
			faceCount = 6;
		}
		
		uint mipmapCount = dds.mipmapCount();
		
		nv::Image mipmap;
		
		for (uint f = 0; f < faceCount; f++)
		{
			for (uint m = 0; m < mipmapCount; m++)
			{
				dds.mipmap(&mipmap, f, m);
				
				inputOptions.setMipmapData(mipmap.pixels(), mipmap.width(), mipmap.height(), 1, f, m);
			}
		}
	}
	else
	{
		// Regular image.
		nv::Image image;
		if (!image.load(input))
		{
			fprintf(stderr, "The file '%s' is not a supported image type.\n", input.str());
			return EXIT_FAILURE;
		}
		
		inputOptions.setTextureLayout(nvtt::TextureType_2D, image.width(), image.height());
		inputOptions.setMipmapData(image.pixels(), image.width(), image.height());
	}

	if (wrapRepeat)
	{
		inputOptions.setWrapMode(nvtt::WrapMode_Repeat);
	}
	else
	{
		inputOptions.setWrapMode(nvtt::WrapMode_Clamp);
	}

	if (alpha)
	{
		inputOptions.setAlphaMode(nvtt::AlphaMode_Transparency);
	}
	else
	{
		inputOptions.setAlphaMode(nvtt::AlphaMode_None);
	}

	if (normal)
	{
		setNormalMap(inputOptions);
	}
	else if (color2normal)
	{
		setColorToNormalMap(inputOptions);
	}
	else
	{
		setColorMap(inputOptions);
	}
	
	if (noMipmaps)
	{
		inputOptions.setMipmapGeneration(false);
	}

	nvtt::CompressionOptions compressionOptions;
	compressionOptions.setFormat(format);
	if (fast)
	{
		compressionOptions.setQuality(nvtt::Quality_Fastest);
	}
	else
	{
		compressionOptions.setQuality(nvtt::Quality_Normal);
		//compressionOptions.setQuality(nvtt::Quality_Production);
		//compressionOptions.setQuality(nvtt::Quality_Highest);
	}

	if (bc1n)
	{
		compressionOptions.setColorWeights(1, 1, 0);
	}

	if (externalCompressor != NULL)
	{
		compressionOptions.setExternalCompressor(externalCompressor);
	}

	
	MyErrorHandler errorHandler;
	MyOutputHandler outputHandler(output);
	if (outputHandler.stream->isError())
	{
		fprintf(stderr, "Error opening '%s' for writting\n", output.str());
		return EXIT_FAILURE;
	}

	nvtt::Compressor compressor;
	compressor.enableCudaAcceleration(!nocuda);

	printf("CUDA acceleration ");
	if (compressor.isCudaAccelerationEnabled())
	{
		printf("ENABLED\n\n");
	}
	else
	{
		printf("DISABLED\n\n");
	}
	
	outputHandler.setTotal(compressor.estimateSize(inputOptions, compressionOptions));
	outputHandler.setDisplayProgress(!silent);

	nvtt::OutputOptions outputOptions;
	//outputOptions.setFileName(output);
	outputOptions.setOutputHandler(&outputHandler);
	outputOptions.setErrorHandler(&errorHandler);
	
//	printf("Press ENTER.\n");
//	fflush(stdout);
//	getchar();

	clock_t start = clock();
	
	if (!compressor.process(inputOptions, compressionOptions, outputOptions))
	{
		return EXIT_FAILURE;
	}

	clock_t end = clock();
	printf("\rtime taken: %.3f seconds\n", float(end-start) / CLOCKS_PER_SEC);
	
	return EXIT_SUCCESS;
}
int main(int argc, char *argv[])
{
    MyAssertHandler assertHandler;
    MyMessageHandler messageHandler;

    bool alpha = false;
    bool normal = false;
    bool color2normal = false;
    bool wrapRepeat = false;
    bool noMipmaps = false;
    bool fast = false;
    bool nocuda = false;
    bool bc1n = false;
    bool luminance = false;
    nvtt::Format format = nvtt::Format_BC1;
    bool premultiplyAlpha = false;
    nvtt::MipmapFilter mipmapFilter = nvtt::MipmapFilter_Box;
    bool loadAsFloat = false;
    uint bitCount = 0, rmask = 0, gmask = 0, bmask = 0, amask = 0;
    bool fmtSet;
    const char * externalCompressor = NULL;
    
    bool silent = false;
    bool dds10 = false;

    nv::Path input;
    nv::Path output;


    // Parse arguments.
    for (int i = 1; i < argc; i++)
    {
        // Input options.
        if (strcmp("-color", argv[i]) == 0)
        {
        }
        else if (strcmp("-alpha", argv[i]) == 0)
        {
            alpha = true;
        }
        else if (strcmp("-normal", argv[i]) == 0)
        {
            normal = true;
        }
        else if (strcmp("-tonormal", argv[i]) == 0)
        {
            color2normal = true;
        }
        else if (strcmp("-clamp", argv[i]) == 0)
        {
        }
        else if (strcmp("-repeat", argv[i]) == 0)
        {
            wrapRepeat = true;
        }
        else if (strcmp("-nomips", argv[i]) == 0)
        {
            noMipmaps = true;
        }
        else if (strcmp("-premula", argv[i]) == 0)
        {
            premultiplyAlpha = true;
        }
        else if (strcmp("-mipfilter", argv[i]) == 0)
        {
            if (i+1 == argc) break;
            i++;

            if (strcmp("box", argv[i]) == 0) mipmapFilter = nvtt::MipmapFilter_Box;
            else if (strcmp("triangle", argv[i]) == 0) mipmapFilter = nvtt::MipmapFilter_Triangle;
            else if (strcmp("kaiser", argv[i]) == 0) mipmapFilter = nvtt::MipmapFilter_Kaiser;
        }
        else if (strcmp("-float", argv[i]) == 0)
        {
            loadAsFloat = true;
        }

        // Compression options.
        else if (strcmp("-fast", argv[i]) == 0)
        {
            fast = true;
        }
        else if (strcmp("-nocuda", argv[i]) == 0)
        {
            nocuda = true;
        }
        else if (strcmp("-rgb", argv[i]) == 0)
        {
            format = nvtt::Format_RGB;
        }
        else if (strcmp("-lumi", argv[i]) == 0)
        {
            luminance = true;
            format = nvtt::Format_RGB;
        }
        else if (strcmp("-bc1", argv[i]) == 0)
        {
            format = nvtt::Format_BC1;
        }
        else if (strcmp("-bc1n", argv[i]) == 0)
        {
            format = nvtt::Format_BC1;
            bc1n = true;
        }
        else if (strcmp("-bc1a", argv[i]) == 0)
        {
            format = nvtt::Format_BC1a;
        }
        else if (strcmp("-bc2", argv[i]) == 0)
        {
            format = nvtt::Format_BC2;
        }
        else if (strcmp("-bc3", argv[i]) == 0)
        {
            format = nvtt::Format_BC3;
        }
        else if (strcmp("-bc3n", argv[i]) == 0)
        {
            format = nvtt::Format_BC3n;
        }
        else if (strcmp("-bc4", argv[i]) == 0)
        {
            format = nvtt::Format_BC4;
        }
        else if (strcmp("-bc5", argv[i]) == 0)
        {
            format = nvtt::Format_BC5;
        }
        else if (strcmp("-fmt", argv[i]) == 0)
        {
            if (i+1 == argc) break;
            i++;
            if (strcmp("rgba8", argv[i]) == 0)
            {
                format = nvtt::Format_RGB;
                fmtSet = true;
                bitCount = 32;
                amask = 0xFF000000;
                rmask = 0x00FF0000;
                gmask = 0x0000FF00;
                bmask = 0x000000FF;
            }
            else if (strcmp("bgra8", argv[i]) == 0)
            {
                format = nvtt::Format_RGBA;
                fmtSet = true;
                bitCount = 32;
                amask = 0xFF000000;
                rmask = 0x000000FF;
                gmask = 0x0000FF00;
                bmask = 0x00FF0000;
            }
            else if (strcmp("rgb8", argv[i]) == 0)
            {
                format = nvtt::Format_RGB;
                fmtSet = true;
                bitCount = 24;
                amask = 0x00000000;
                rmask = 0x00FF0000;
                gmask = 0x0000FF00;
                bmask = 0x000000FF;
            }
            else if (strcmp("bgr8", argv[i]) == 0)
            {
                format = nvtt::Format_RGB;
                fmtSet = true;
                bitCount = 24;
                amask = 0x00000000;
                rmask = 0x000000FF;
                gmask = 0x0000FF00;
                bmask = 0x00FF0000;
            }
        }

        // Undocumented option. Mainly used for testing.
        else if (strcmp("-ext", argv[i]) == 0)
        {
            if (i+1 < argc && argv[i+1][0] != '-') {
                externalCompressor = argv[i+1];
                i++;
            }
        }
        else if (strcmp("-pause", argv[i]) == 0)
        {
            printf("Press ENTER\n"); fflush(stdout);
            getchar();
        }

        // Output options
        else if (strcmp("-silent", argv[i]) == 0)
        {
            silent = true;
        }
        else if (strcmp("-dds10", argv[i]) == 0)
        {
            dds10 = true;
        }

        else if (argv[i][0] != '-')
        {
            input = argv[i];

            if (i+1 < argc && argv[i+1][0] != '-') {
                output = argv[i+1];
            }
            else
            {
                output.copy(input.str());
                output.stripExtension();
                output.append(".dds");
            }

            break;
        }
    }

    const uint version = nvtt::version();
    const uint major = version / 100 / 100;
    const uint minor = (version / 100) % 100;
    const uint rev = version % 100;


    printf("NVIDIA Texture Tools %u.%u.%u - Copyright NVIDIA Corporation 2007\n\n", major, minor, rev);

    if (input.isNull())
    {
        printf("usage: nvcompress [options] infile [outfile]\n\n");

        printf("Input options:\n");
        printf("  -color     \tThe input image is a color map (default).\n");
        printf("  -alpha     \tThe input image has an alpha channel used for transparency.\n");
        printf("  -normal    \tThe input image is a normal map.\n");
        printf("  -tonormal  \tConvert input to normal map.\n");
        printf("  -clamp     \tClamp wrapping mode (default).\n");
        printf("  -repeat    \tRepeat wrapping mode.\n");
        printf("  -nomips    \tDisable mipmap generation.\n");
        printf("  -premula   \tPremultiply alpha into color channel.\n");
        printf("  -mipfilter \tMipmap filter. One of the following: box, triangle, kaiser.\n");
        printf("  -float     \tLoad as floating point image.\n\n");

        printf("Compression options:\n");
        printf("  -fast    \tFast compression.\n");
        printf("  -nocuda  \tDo not use cuda compressor.\n");
        printf("  -rgb     \tRGBA format\n");
        printf("  -lumi    \tLUMINANCE format\n");
        printf("  -bc1     \tBC1 format (DXT1)\n");
        printf("  -bc1n    \tBC1 normal map format (DXT1nm)\n");
        printf("  -bc1a    \tBC1 format with binary alpha (DXT1a)\n");
        printf("  -bc2     \tBC2 format (DXT3)\n");
        printf("  -bc3     \tBC3 format (DXT5)\n");
        printf("  -bc3n    \tBC3 normal map format (DXT5nm)\n");
        printf("  -bc4     \tBC4 format (ATI1)\n");
        printf("  -bc5     \tBC5 format (3Dc/ATI2)\n\n");

        printf("Output options:\n");
        printf("  -silent  \tDo not output progress messages\n");
        printf("  -dds10   \tUse DirectX 10 DDS format\n\n");

        return EXIT_FAILURE;
    }

    // Make sure input file exists.
    if (!nv::FileSystem::exists(input.str()))
    {
        fprintf(stderr, "The file '%s' does not exist.\n", input.str());
        return 1;
    }

    // Set input options.
    nvtt::InputOptions inputOptions;

    if (nv::strCaseCmp(input.extension(), ".dds") == 0)
    {
        // Load surface.
        nv::DirectDrawSurface dds(input.str());
        if (!dds.isValid())
        {
            fprintf(stderr, "The file '%s' is not a valid DDS file.\n", input.str());
            return EXIT_FAILURE;
        }

        if (!dds.isSupported() || dds.isTexture3D())
        {
            fprintf(stderr, "The file '%s' is not a supported DDS file.\n", input.str());
            return EXIT_FAILURE;
        }

        uint faceCount;
        if (dds.isTexture2D())
        {
            inputOptions.setTextureLayout(nvtt::TextureType_2D, dds.width(), dds.height());
            faceCount = 1;
        }
        else 
        {
            nvDebugCheck(dds.isTextureCube());
            inputOptions.setTextureLayout(nvtt::TextureType_Cube, dds.width(), dds.height());
            faceCount = 6;
        }

        uint mipmapCount = dds.mipmapCount();

        nv::Image mipmap;

        for (uint f = 0; f < faceCount; f++)
        {
            for (uint m = 0; m < mipmapCount; m++)
            {
                dds.mipmap(&mipmap, f, m); // @@ Load as float.

                inputOptions.setMipmapData(mipmap.pixels(), mipmap.width(), mipmap.height(), 1, f, m);
            }
        }
    }
    else
    {
        if (nv::strCaseCmp(input.extension(), ".exr") == 0 || nv::strCaseCmp(input.extension(), ".hdr") == 0)
        {
            loadAsFloat = true;
        }

        if (loadAsFloat)
        {
            nv::AutoPtr<nv::FloatImage> image(nv::ImageIO::loadFloat(input.str()));

            if (image == NULL)
            {
                fprintf(stderr, "The file '%s' is not a supported image type.\n", input.str());
                return EXIT_FAILURE;
            }

            inputOptions.setFormat(nvtt::InputFormat_RGBA_32F);
            inputOptions.setTextureLayout(nvtt::TextureType_2D, image->width(), image->height());

            /*for (uint i = 0; i < image->componentNum(); i++)
            {
                inputOptions.setMipmapChannelData(image->channel(i), i, image->width(), image->height());
            }*/
        }
        else
        {
            // Regular image.
            nv::Image image;
            if (!image.load(input.str()))
            {
                fprintf(stderr, "The file '%s' is not a supported image type.\n", input.str());
                return 1;
            }

            inputOptions.setTextureLayout(nvtt::TextureType_2D, image.width(), image.height());
            inputOptions.setMipmapData(image.pixels(), image.width(), image.height());
        }
    }

    if (wrapRepeat)
    {
        inputOptions.setWrapMode(nvtt::WrapMode_Repeat);
    }
    else
    {
        inputOptions.setWrapMode(nvtt::WrapMode_Clamp);
    }

    if (alpha)
    {
        inputOptions.setAlphaMode(nvtt::AlphaMode_Transparency);
    }
    else
    {
        inputOptions.setAlphaMode(nvtt::AlphaMode_None);
    }

    // Block compressed textures with mipmaps must be powers of two.
    if (!noMipmaps && format != nvtt::Format_RGB)
    {
        inputOptions.setRoundMode(nvtt::RoundMode_ToPreviousPowerOfTwo);
    }

    if (normal)
    {
        setNormalMap(inputOptions);
    }
    else if (color2normal)
    {
        setColorToNormalMap(inputOptions);
    }
    else
    {
        setColorMap(inputOptions);
    }

    if (noMipmaps)
    {
        inputOptions.setMipmapGeneration(false);
    }

    /*if (premultiplyAlpha)
    {
        inputOptions.setPremultiplyAlpha(true);
        inputOptions.setAlphaMode(nvtt::AlphaMode_Premultiplied);
    }*/

    inputOptions.setMipmapFilter(mipmapFilter);

    nvtt::CompressionOptions compressionOptions;
    compressionOptions.setFormat(format);

    if (format == nvtt::Format_BC2) {
        // Dither alpha when using BC2.
        compressionOptions.setQuantization(/*color dithering*/false, /*alpha dithering*/true, /*binary alpha*/false);
    }
    else if (format == nvtt::Format_BC1a) {
        // Binary alpha when using BC1a.
        compressionOptions.setQuantization(/*color dithering*/false, /*alpha dithering*/true, /*binary alpha*/true, 127);
    }
    else if (format == nvtt::Format_RGBA)
    {
        if (fmtSet)
        {
            compressionOptions.setPixelFormat(bitCount, rmask, gmask, bmask, amask);
        }
        else if (luminance)
        {
            compressionOptions.setPixelFormat(8, 0xff, 0, 0, 0);
        }
        else {
            // @@ Edit this to choose the desired pixel format:
            // compressionOptions.setPixelType(nvtt::PixelType_Float);
            // compressionOptions.setPixelFormat(16, 16, 16, 16);
            // compressionOptions.setPixelType(nvtt::PixelType_UnsignedNorm);
            // compressionOptions.setPixelFormat(16, 0, 0, 0);
        }
    }

    if (fast)
    {
        compressionOptions.setQuality(nvtt::Quality_Fastest);
    }
    else
    {
        compressionOptions.setQuality(nvtt::Quality_Normal);
        //compressionOptions.setQuality(nvtt::Quality_Production);
        //compressionOptions.setQuality(nvtt::Quality_Highest);
    }

    if (bc1n)
    {
        compressionOptions.setColorWeights(1, 1, 0);
    }

    
    //compressionOptions.setColorWeights(0.2126, 0.7152, 0.0722);
    //compressionOptions.setColorWeights(0.299, 0.587, 0.114);
    //compressionOptions.setColorWeights(3, 4, 2);

    if (externalCompressor != NULL)
    {
        compressionOptions.setExternalCompressor(externalCompressor);
    }


    MyErrorHandler errorHandler;
    MyOutputHandler outputHandler(output.str());
    if (outputHandler.stream->isError())
    {
        fprintf(stderr, "Error opening '%s' for writting\n", output.str());
        return EXIT_FAILURE;
    }

    nvtt::Context context;
    context.enableCudaAcceleration(!nocuda);

    printf("CUDA acceleration ");
    if (context.isCudaAccelerationEnabled())
    {
        printf("ENABLED\n\n");
    }
    else
    {
        printf("DISABLED\n\n");
    }

    outputHandler.setTotal(context.estimateSize(inputOptions, compressionOptions));
    outputHandler.setDisplayProgress(!silent);

    nvtt::OutputOptions outputOptions;
    //outputOptions.setFileName(output);
    outputOptions.setOutputHandler(&outputHandler);
    outputOptions.setErrorHandler(&errorHandler);

    if (dds10)
    {
        outputOptions.setContainer(nvtt::Container_DDS10);
    }

    // printf("Press ENTER.\n");
    // fflush(stdout);
    // getchar();

    nv::Timer timer;
    timer.start();

    if (!context.process(inputOptions, compressionOptions, outputOptions))
    {
        return EXIT_FAILURE;
    }
    timer.stop();

    printf("\rtime taken: %.3f seconds\n", timer.elapsed());

    return EXIT_SUCCESS;
}
void NormalMappingDelegate::onInit()
{
    scene = new Scene();
    this->move_forward=false;
    this->move_backward=false;
    this->move_left=false;
    this->move_right=false;
    this->move_up = false;
    this->move_down = false;
    scene->setRenderType (DEFERRED_SHADING);

    AmbientLight * ambient = scene->getAmbientLight ();
    ambient->setColor (QVector3D(1,1,1));
    ambient->setIntensity (0.5);

    auto sprite = new Sprite();
    sprite->setTexture (TexturePool::getInstance ()->createOrGetTexture ("./res/texture/mygame/fps/cross_hair.png"));
    sprite->setCamera (scene->guiCamera ());
    sprite->setPos (QVector3D(1024/2-sprite->texture ()->width ()/2,768/2-sprite->texture ()->height ()/2,0));
    scene->root ()->addChild (sprite);

    scene->setCamera (&camera);

    //set this scene as current scene
    scene->setAsCurrentScene();
    scene->root ()->addChild (&camera);

    //create a box
    auto the_head = new Entity("./res/model/scan_head/Infinite-Level_02.obj",Entity::LoadPolicy::LoadFromLoader);
    the_head->setShaderProgram (ShaderPool::getInstance ()->get ("deferred"));
    the_head->scale (30,30,30);
    //set it's normal map
    auto material = the_head->getMesh (0)->getMaterial ();
    material->setNormalMap (TexturePool::getInstance ()->createOrGetTexture ("./res/model/scan_head/Infinite-Level_02_Tangent_SmoothUV.jpg"));
    the_head->setCamera (&camera);
    //this sample we don't use shadow
    the_head->setIsEnableShadow (false);

        //bob
        auto the_bob2 = new Entity("./res/model/bob/boblampclean.md5mesh",Entity::LoadPolicy::LoadFromLoader);
        the_bob2->setShaderProgram (ShaderPool::getInstance ()->get ("deferred"));
        the_bob2->setCamera (&camera);
        the_bob2->setPos (QVector3D(-2,0,-10));
        the_bob2->setRotation (QVector3D(-90,0,0));
        scene->root ()->addChild (the_bob2);
        the_bob2->setIsEnableShadow (false);
        the_bob2->scale (0.05,0.05,0.05);
        the_bob2->getSkeleton ()->getEntityNodeRoot ()->findNode ("lamp")->addChild (the_head);
        //this sample we don't use shadow
        the_bob2->setIsEnableShadow (false);
        the_bob2->onRender = [](Entity * self, float dt){
            self->playAnimate (0,self->animateTime ()+ 0.02);
        };



        auto the_orc = new Entity("./res/model/orc/orc.FBX",Entity::LoadPolicy::LoadFromLoader);
        the_orc->setShaderProgram (ShaderPool::getInstance ()->get ("deferred"));
        the_orc->setCamera (&camera);
        the_orc->setRotation (QVector3D(0,180,0));
        the_orc->setScalling (QVector3D(0.1,0.1,0.1));
        the_orc->setPos (QVector3D(0,0,-10));

        scene->root ()->addChild (the_orc);
        the_orc->onRender = [](Entity * self, float dt){
            self->playAnimate (0,self->animateTime () + 0.02);
        };

        auto the_orc_axe = new Entity("./res/model/orc/axe.FBX",Entity::LoadPolicy::LoadFromLoader);
        the_orc_axe->setShaderProgram (ShaderPool::getInstance ()->get ("deferred"));
        the_orc_axe->setCamera (&camera);
        the_orc->getSkeleton ()->getEntityNodeRoot ()->findNode ("Bip001 R Hand")->addChild (the_orc_axe);

        //then add  a Directional light
        auto directional_light = scene->getDirectionalLight ();
        directional_light->setIntensity (1);
        directional_light->setColor (QVector3D(1,1,1));
        directional_light->setDirection (QVector3D(0,0,-1));
}
 void Ex_004_ShadowMapping::run() {
     const string path = "/Users/saburookita/Personal Projects/Three.cpp Rev.2/examples/assets/";
     
     ForwardRenderer renderer;
     renderer.init( "Ex 004: Shadow Mapping", 1600 * 2 / 4, 900 * 2 / 4 );
     renderer.setCameraControl(Arcball::create(2.0f));
     
     
     /* Create scene */
     auto scene = Scene::create();
     scene->setFog(Fog::create( 0x72645b / 2, 2.0, 15.0 ));
     scene->setViewport( 0.0, 0.0, renderer.getWidth(), renderer.getHeight() );
     scene->setShadowMapType( SHADOW_MAP::PCF_SOFT );
     
     /* Create camera */
     auto camera = PerspectiveCamera::create( 50.0, renderer.getAspectRatio(), 0.001, 100.0 );
     camera->translate(0.0, 1.5, 5.5);
     camera->lookAt( 0.0, 0.0, 0.0 );
     
     /* Create our objects */
     auto sphere = Mesh::create( SphereGeometry::create(30, 20, 0.66f ),
                                PhongMaterial::create(0x777777, 0x0, 0x0, 0x999999, 30, true) );
     
     sphere->setNormalMap( TextureUtils::loadAsNormalMap  ( path, "tutorial_normals07.gif" ) );
     sphere->translate(-2.0, 0.66f, 0.0);
     sphere->castShadow = true;
     sphere->receiveShadow = true;
     
     auto cube = Mesh::create( CubeGeometry::create(1.0, 10),
                              PhongMaterial::create(0x777777, 0x0, 0x0, 0x0, 30, false) );
     cube->setTexture( TextureUtils::loadAsTexture( path, "four_shapes_color.tga" ) );
     cube->translate(0.0, 0.5, 0.0);
     cube->castShadow = true;
     cube->receiveShadow = true;
     
     auto cylinder = Mesh::create( CylinderGeometry::create(0.5, 0.5, 1.0, 30, 5, true),
                                  PhongMaterial::create( 0xCCCCCC, 0x0, 0x0, 0x111111, 150.0, false ) );
     cylinder->getMaterial()->setSide( SIDE::DOUBLE_SIDE );
     cylinder->castShadow = true;
     cylinder->receiveShadow = true;
     cylinder->setTexture  ( TextureUtils::loadAsTexture   ( path, "rock_color.tga" ) );
     cylinder->setNormalMap( TextureUtils::loadAsNormalMap ( path, "rock_normal.tga" ) );
     cylinder->translate(+2.0f, 0.5f, -2.0f);
     
     scene->add( cylinder );
     scene->add( cube );
     scene->add( sphere );
     
     /* And the ground plane */
     auto plane = Mesh::create( PlaneGeometry::create(20.0f),
                               PhongMaterial::create(0x777777, 0x777777, 0x0, 0x999999, 30) );
     plane->name = "plane";
     plane->rotateX(-90.0f);
     plane->translate(0.0, 0.0, 0.0);
     plane->receiveShadow = true;
     scene->add( plane );
     
     /* Cubemap */
     auto env = Mesh::create( CubeGeometry::create(20.0f), MeshCubeMapMaterial::create() );
     env->setTexture( TextureUtils::loadAsEnvMap( path + "cube/pisa",
                                               "nx.png", "ny.png", "nz.png",
                                               "px.png", "py.png", "pz.png"));
     
     sphere->setEnvMap( downcast(env->getTexture(), EnvMap) );
     scene->add( env );
     
     
     /* Create a (rotating) directional light */
     auto dir_light = DirectionalLight::create(0x99CCFF, 1.35, glm::vec3( 3.0, 1.0, 3.0 ) );
     dir_light->castShadow       = true;
     dir_light->shadowBias       = -0.0005;
     dir_light->shadowMapSize    = glm::vec2(512);
     scene->add( dir_light );
     
     /* Create a spotlight, the shadow should be casted no the left hand side */
     auto spot_light = SpotLight::create(0x99CCFF, 1.0, 20.0, 50.0, 1.0 );
     spot_light->position = glm::vec3(3.0, 2.0, 3.0);
     spot_light->castShadow = true;
     scene->add( spot_light );
     
     /* Create an ambient light */
     scene->add( AmbientLight::create(0x777777));
     
     /* Create a post render callback for objects rotation */
     bool rotate_objects = false;
     float light_rotation_1 = 0.0;
     renderer.setPostRenderCallbackHandler( [&](){
         dir_light->position.x = ( 3.0 * cosf( light_rotation_1 ) );
         dir_light->position.z = ( 3.0 * sinf( light_rotation_1 ) );
         
         light_rotation_1 += 0.01;
         
         if( rotate_objects ) {
             cube->rotateX(-1.0f);
             cylinder->rotateX(1.0f);
         }
     });
     
     /* Override key callback handler */
     renderer.setKeyCallbackHandler([&](GLFWwindow *window, int key, int scancode, int action, int mod) {
         if( action == GLFW_PRESS ) {
             switch ( key) {
                 case GLFW_KEY_R: /* Toggle rotation */
                     rotate_objects = !rotate_objects;
                     break;
                     
                 default:
                     break;
             }
         }
     });
     
     renderer.setGamma( true, true );
     
     renderer.setClearColor( scene->getFog()->getColor() );
     renderer.render(scene, camera );
 }
    void Ex_008_FontStashIntegration::run() {
//        const string path = "/Users/saburookita/Personal Projects/Three.cpp Rev.2/examples/assets/";
        const string path = "../examples/assets/";
        
        ForwardRenderer renderer;
        renderer.init( "Ex 008: FontStash integration test", 1600 * 2 / 4, 900 * 2 / 4 );
        renderer.setCameraControl(Arcball::create(2.0f));
        
        
        /* First load the fonts */
        renderer.addFont("droid-regular",   path + "fonts/DroidSerif-Regular.ttf");
        renderer.addFont("droid-italic",    path + "fonts/DroidSerif-Italic.ttf");
        renderer.addFont("droid-bold",      path + "fonts/DroidSerif-Bold.ttf");
        renderer.addFont("droid-japanese",  path + "fonts/DroidSansJapanese.ttf");
        
        /*Then write on screen*/
        renderer.addText( "Test FontStash",     100, 100, "droid-regular", 0x0, 32.0f );
        renderer.addText( "writing in italic",  100, 130, "droid-italic", 0x00FF00, 24.0f );
        renderer.addText( "... or bold",        250, 130, "droid-bold", 0xFF0000, 24.0f );
        
        renderer.addText( "éßüä",               400, 90, "droid-regular", 0x0000FF, 24.0f );
        renderer.addText( "日本語もできます。",    400, 120, "droid-japanese", 0xFFFFFF, 24.0f );
        
        renderer.addText( "spacing = 1.0",   100, 200, "droid-italic", 0x00FF00, 20.0f, 1.0f );
        renderer.addText( "spacing = 5.0",   100, 225, "droid-italic", 0xFFFF00, 20.0f, 5.0f );
        renderer.addText( "spacing = 10.0",  100, 250, "droid-italic", 0x00FFFF, 20.0f, 10.0f );
        
        renderer.addText( "blur = 1.0",   400, 200, "droid-bold", 0x99CCFF, 30.0f, 0.0f, 1.0f );
        renderer.addText( "blur = 5.0",   400, 240, "droid-bold", 0xFFCC99, 30.0f, 0.0f, 5.0f );
        renderer.addText( "blur = 10.0",  400, 280, "droid-bold", 0xCCFF99, 30.0f, 0.0f, 10.0f );
        
        int cursor_pos_text = renderer.addText( "Cursor Position: ", 80, 400, "droid-regular", 0xFFFFFF, 20.0f );
        
        /* Create scene */
        auto scene = Scene::create();
        scene->setFog(Fog::create( 0x72645b, 2.0, 15.0 ));
        scene->setViewport( 0.0, 0.0, renderer.getWidth(), renderer.getHeight() );
        scene->setShadowMapType( SHADOW_MAP::PCF );
        
        /* Create camera */
        auto camera = PerspectiveCamera::create( 50.0, renderer.getAspectRatio(), 0.001, 100.0 );
        camera->translate(0.0, 1.5, 5.5);
        camera->lookAt( 0.0, 1.0, 0.0 );
        
        /* Load our ply models */
        float x_offset = -1.0;
        auto statue = Loader::loadPLY(path + "/ply models/", "happy_vrip_res3.ply",
                                      aiProcess_JoinIdenticalVertices |
                                      aiProcess_GenSmoothNormals | aiProcess_FlipWindingOrder );
        
        statue->setMaterial(PhongMaterial::create(0x777777, 0x0, 0x777777, 0x0, 0, true));
        statue->getGeometry()->setScale(10.f);
        statue->castShadow      = true;
        statue->receiveShadow   = true;
        
        auto bounding_box = statue->computeBoundingBox();
        glm::vec3 size    = bounding_box->size();
        glm::vec3 center  = bounding_box->center();
        statue->translate(x_offset, -(center.y - size.y * 0.5), 0.0);
        
        x_offset += 2.0f;
        scene->add( statue );
     
        
        /* A sphere, cube, and cylinder walk into a pub */
        auto sphere = Mesh::create( SphereGeometry::create(30, 20, 0.66f ),
                                   PhongMaterial::create( 0xCCCCCC, 0x0, 0x0, 0x222222, 130.0, true ) );
        
        sphere->setTexture      ( TextureUtils::loadAsTexture    ( path + "planets", "earth_atmos_2048.jpg") );
        sphere->setNormalMap    ( TextureUtils::loadAsNormalMap  ( path + "planets", "earth_normal_2048.jpg" ) );
        sphere->setSpecularMap  ( TextureUtils::loadAsSpecularMap( path + "planets", "earth_specular_2048.jpg" ) );
        sphere->receiveShadow = true;
        sphere->castShadow    = true;
        sphere->translate( x_offset, 0.66f, 0.0f );
        scene->add( sphere );
        
        
        auto plane = Mesh::create( PlaneGeometry::create(20.0f),
                                   PhongMaterial::create(0x777777, 0x777777, 0x0, 0x999999, 30) );
        plane->name = "plane";
        plane->rotateX(-90.0f);
        plane->receiveShadow = true;
        scene->add( plane );
        
        /* Cubemap */
        auto env = Mesh::create( CubeGeometry::create(50.0f), MeshCubeMapMaterial::create() );
        env->setTexture( TextureUtils::loadAsEnvMap( path + "cube/pisa",
                                                    "nx.png", "ny.png", "nz.png",
                                                    "px.png", "py.png", "pz.png"));
        statue->setEnvMap( env->getTexture() );
        scene->add( env );
        
        
        /* Create a (rotating) directional light */
        auto dir_light = DirectionalLight::create(0x99CCFF, 1.35, glm::vec3( 3.0, 1.0, 3.0 ) );
        dir_light->castShadow       = true;
        dir_light->shadowBias       = -0.001;
        dir_light->shadowCameraNear = -10.0;
        dir_light->shadowCameraFar  =  10.0;
        scene->add( dir_light );
        
        /* Create a spotlight, the shadow should be casted no the left hand side */
        auto spot_light = SpotLight::create(0x99CCFF, 1.0, 20.0, 50.0, 1.0 );
        spot_light->position = glm::vec3(3.0, 2.0, 3.0);
        spot_light->castShadow = true;
        scene->add( spot_light );
        
        /* Create an ambient light */
        scene->add( AmbientLight::create(0x777777));
        
        /* Create a post render callback for objects rotation */
        bool rotate_objects = false;
        float light_rotation_1 = 0.0;
        renderer.setPostRenderCallbackHandler( [&](){
            dir_light->position.x = ( 3.0 * cosf( light_rotation_1 ) );
            dir_light->position.z = ( 3.0 * sinf( light_rotation_1 ) );
            
            light_rotation_1 += 0.01;
            
            if( rotate_objects ) {
                statue->rotateY(1.0f);
                sphere->rotateY(-1.0f);
            }
        });
        
        renderer.setCursorCallbackHandler([&](GLFWwindow *, double x, double y){
            stringstream ss;
            ss.precision(4);
            ss << "Cursor Position: (" << x << ", " << y << ")";
            renderer.setText(cursor_pos_text, ss.str() );
        });
        
        /* Override key callback handler */
        renderer.setKeyCallbackHandler([&](GLFWwindow *window, int key, int scancode, int action, int mod) {
            if( action == GLFW_PRESS ) {
                switch ( key) {
                    case GLFW_KEY_R: /* Toggle rotation */
                        rotate_objects = !rotate_objects;
                        break;
                        
                    default:
                        break;
                }
            }
        });
        
        
        renderer.setGamma( true, true );
        
        renderer.setClearColor( scene->getFog()->getColor() );
        renderer.render(scene, camera );
    }