//>>> _using
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SharpDX;
using SharpDX.Direct3D11;
using SharpDX.Windows;
//<<< _using
using Framefield.Core.OperatorPartTraits;
using Framefield.Core.Rendering;
using Buffer = SharpDX.Direct3D11.Buffer;
using SharpDX.Direct3D;

namespace Framefield.Core.IDa788172e_e9ec_4892_b384_93c64695e4e6
{
    public class Class_WaveDistortAxis : FXSourceCodeFunction, IFXSceneSourceCode, IMeshSupplier
    {
        //>>> _inputids
        private enum InputId
        {
            Code = 0,
            Scene = 1,
            LengthPrimary = 2,
            LengthSecondary = 3,
            AmplitudePrimary = 4,
            AmplitudeSecondary = 5,
            PhasePrimary = 6,
            PhaseSecondary = 7,
            AxisX = 8,
            AxisY = 9,
            AxisZ = 10,
            DisplaceX = 11,
            DisplaceY = 12,
            DisplaceZ = 13,
            RegionMinPosition = 14,
            RegionMinSmooth = 15,
            RegionMaxPosition = 16,
            RegionMaxBlend = 17,
            NormalSmoothing = 18
        }
        //<<< _inputids

        public Class_WaveDistortAxis()
        {
            _meshCollector = new MeshCollector(this);
        }

        public override void Dispose() 
        {
            Utilities.DisposeObj(ref _mesh);
            base.Dispose();
        }

        public void AddMeshesTo(ICollection<Mesh> meshes)
        {
            UpdateMesh(new OperatorPartContext(), OperatorPart.Connections);
            if (_mesh != null)
                meshes.Add(_mesh);
        }

        public override OperatorPartContext Eval(OperatorPartContext context, List<OperatorPart> inputs, int outputIdx)
        {
            try
            {
                UpdateMesh(context, inputs);

                if (_mesh.Vertices != null)
                {
                    // render stream output to screen or whatever target is set
                    context.Renderer.SetupEffect(context);
                    context.Renderer.Render(_mesh, context);
                }
            }
            catch (Exception exception)
            {
                Logger.Error(this, "Load Effect error: {0}", exception.Message);
            }

            return context;
        }

        bool _firstEval = true;
        private void UpdateMesh(OperatorPartContext context, List<OperatorPart> inputs)
        {
            if (_firstEval)
            {
                for (int i = 0; i < NumCodes(); ++i)
                    Compile(i);
                _firstEval = false;
                Changed = true;
            }

            if (!Changed && _mesh.Vertices != null)
                return;

            //>>> _params
            var Code = inputs[(int)InputId.Code].Eval(context).Text;
            var Scene = inputs[(int)InputId.Scene];
            var LengthPrimary = inputs[(int)InputId.LengthPrimary].Eval(context).Value;
            var LengthSecondary = inputs[(int)InputId.LengthSecondary].Eval(context).Value;
            var Length = new Vector2(LengthPrimary, LengthSecondary);
            var AmplitudePrimary = inputs[(int)InputId.AmplitudePrimary].Eval(context).Value;
            var AmplitudeSecondary = inputs[(int)InputId.AmplitudeSecondary].Eval(context).Value;
            var Amplitude = new Vector2(AmplitudePrimary, AmplitudeSecondary);
            var PhasePrimary = inputs[(int)InputId.PhasePrimary].Eval(context).Value;
            var PhaseSecondary = inputs[(int)InputId.PhaseSecondary].Eval(context).Value;
            var Phase = new Vector2(PhasePrimary, PhaseSecondary);
            var AxisX = inputs[(int)InputId.AxisX].Eval(context).Value;
            var AxisY = inputs[(int)InputId.AxisY].Eval(context).Value;
            var AxisZ = inputs[(int)InputId.AxisZ].Eval(context).Value;
            var Axis = new Vector3(AxisX, AxisY, AxisZ);
            var DisplaceX = inputs[(int)InputId.DisplaceX].Eval(context).Value;
            var DisplaceY = inputs[(int)InputId.DisplaceY].Eval(context).Value;
            var DisplaceZ = inputs[(int)InputId.DisplaceZ].Eval(context).Value;
            var Displace = new Vector3(DisplaceX, DisplaceY, DisplaceZ);
            var RegionMinPosition = inputs[(int)InputId.RegionMinPosition].Eval(context).Value;
            var RegionMinSmooth = inputs[(int)InputId.RegionMinSmooth].Eval(context).Value;
            var RegionMin = new Vector2(RegionMinPosition, RegionMinSmooth);
            var RegionMaxPosition = inputs[(int)InputId.RegionMaxPosition].Eval(context).Value;
            var RegionMaxBlend = inputs[(int)InputId.RegionMaxBlend].Eval(context).Value;
            var RegionMax = new Vector2(RegionMaxPosition, RegionMaxBlend);
            var NormalSmoothing = inputs[(int)InputId.NormalSmoothing].Eval(context).Value;
            //<<< _params

            if (Scene.Func.Changed || _mesh.Vertices == null)
            {
                //Logger.Info(this, "collect meshes");
                _meshCollector.Collect(Scene);
                Scene.Func.Changed = false;
            }

            var inputMesh = _meshCollector.FirstMeshOrDefault;
            if (inputMesh == null)
                return;

            _mesh.AttributesSize = inputMesh.AttributesSize;
            _mesh.NumTriangles = inputMesh.NumTriangles;
            _mesh.InputElements = inputMesh.InputElements;
            if (_mesh.Vertices == null || _mesh.Vertices.Description.SizeInBytes != inputMesh.Vertices.Description.SizeInBytes)
            {
                if (_mesh.Vertices != null)
                    _mesh.Vertices.Dispose();

                _mesh.Vertices = new Buffer(D3DDevice.Device, new BufferDescription()
                                                                    {
                                                                        BindFlags = BindFlags.StreamOutput | BindFlags.VertexBuffer,
                                                                        CpuAccessFlags = CpuAccessFlags.None,
                                                                        OptionFlags = ResourceOptionFlags.None,
                                                                        SizeInBytes = _mesh.NumTriangles*inputMesh.AttributesSize*3,
                                                                        Usage = ResourceUsage.Default
                                                                    });
            }

            _effect.GetVariableByName("Length").AsVector().Set(Length);
            _effect.GetVariableByName("Amplitude").AsVector().Set(Amplitude);
            _effect.GetVariableByName("Phase").AsVector().Set(Phase);
            _effect.GetVariableByName("Axis").AsVector().Set(Axis);
            _effect.GetVariableByName("Displace").AsVector().Set(Displace);
            _effect.GetVariableByName("RegionMin").AsVector().Set(RegionMin);
            _effect.GetVariableByName("RegionMax").AsVector().Set(RegionMax);
            _effect.GetVariableByName("NormalSmoothing").AsScalar().Set(NormalSmoothing);
            

            context.D3DDevice.ImmediateContext.StreamOutput.SetTargets(new [] { new StreamOutputBufferBinding(_mesh.Vertices, 0) });
            context.D3DDevice.ImmediateContext.OutputMerger.DepthStencilState = new DepthStencilState(context.D3DDevice,
                                                                                                        new DepthStencilStateDescription()
                                                                                                            {
                                                                                                                IsDepthEnabled = false,
                                                                                                                IsStencilEnabled = false
                                                                                                            });
            context.D3DDevice.ImmediateContext.InputAssembler.InputLayout = context.InputLayout;
            context.D3DDevice.ImmediateContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
            context.D3DDevice.ImmediateContext.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(inputMesh.Vertices, inputMesh.AttributesSize, 0));
            var technique = _effect.GetTechniqueByIndex(0);
            technique.GetPassByIndex(0).Apply(context.D3DDevice.ImmediateContext);
            context.D3DDevice.ImmediateContext.Draw(_mesh.NumTriangles*3, 0);
            context.D3DDevice.ImmediateContext.StreamOutput.SetTargets(new [] { new StreamOutputBufferBinding(null, 0) });

            Changed = false;
        }

        private Mesh _mesh = new Mesh();
        private MeshCollector _meshCollector;
    }
}


