//>>> _using
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SharpDX;
using SharpDX.Direct3D11;
using SharpDX.Windows;
//<<< _using
using System.IO;

namespace Framefield.Core.IDd50105bb_2cb1_40e4_995a_e0a0f8840660
{
    public class Class_GenerateMipMap : OperatorPart.Function
    {
        //>>> _inputids
        private enum InputId
        {
            Image = 0
        }
        //<<< _inputids

        public override void Dispose()
        {
            Utilities.DisposeObj(ref _mipMappedImage);
            Utilities.DisposeObj(ref _mipMappedImageSRV);
        }

        public override OperatorPartContext Eval(OperatorPartContext context, List<OperatorPart> inputs, int outputIdx) 
        {
            //>>> _params
            var Image = inputs[(int)InputId.Image].Eval(context).Image; // Needs to be checked for null!
            //<<< _params

            if (Image == null)
            {
                context.Image = null;
                return context;
            }


            if (_mipMappedImage == null || Changed)
            {
                Dispose();
                var device = context.D3DDevice;
                var description = Image.Description;
                description.OptionFlags |= ResourceOptionFlags.GenerateMipMaps;
                description.MipLevels = 1 + (int)Math.Log(Math.Max(description.Width, description.Height), 2);
                _mipMappedImage = new Texture2D(device, description);               
                _mipMappedImageSRV = new ShaderResourceView(device, _mipMappedImage);

                device.ImmediateContext.CopySubresourceRegion(Image, 0, null, _mipMappedImage, 0);
                device.ImmediateContext.GenerateMips(_mipMappedImageSRV);

                // debug info
                //Logger.Info("width: {0}  height: {1}  mip levels: {2}", description.Width, description.Height, description.MipLevels);
                //Texture2D.ToFile(device.ImmediateContext, _mipMappedImage, ImageFileFormat.Dds, "MipMapTest.dds");
 
                Changed = false;
            }

            context.Image = _mipMappedImage;

            return context;
        }

        //ImageResource _imageResource;
        Texture2D _mipMappedImage;
        ShaderResourceView _mipMappedImageSRV;
    }
}

