コード例 #1
0
        /// <summary>
        /// Function to return an interpolated point from the spline.
        /// </summary>
        /// <param name="startPointIndex">Index in the point list to start from.</param>
        /// <param name="delta">Delta value to interpolate.</param>
        /// <returns>The interpolated value at <paramref name="delta"/>.</returns>
        /// <exception cref="ArgumentOutOfRangeException">Thrown when the <paramref name="startPointIndex"/> parameter is less than 0, or greater than/equal to the number of points in the spline minus 1.</exception>
        /// <remarks>
        /// <para>
        /// The <paramref name="delta"/> parameter is a unit value where 0 is the first point in the spline (relative to <paramref name="startPointIndex"/>) and 1 is the next point from the <paramref name="startPointIndex"/> in the spline.
        /// </para>
        /// <para>
        /// If the <paramref name="delta"/> is less than 0, or greater than 1, the value will be wrapped to fit within the 0..1 range.
        /// </para>
        /// </remarks>
        /// <exception cref="ArgumentOutOfRangeException"><c>[Debug only]</c> Thrown when the <paramref name="startPointIndex"/> is less than 0, or greater than/equal to the number of points - 1 in the <see cref="IGorgonSpline.Points"/> parameter.</exception>
        public DX.Vector4 GetInterpolatedValue(int startPointIndex, float delta)
        {
            DX.Matrix calculations = DX.Matrix.Identity;

            startPointIndex.ValidateRange(nameof(startPointIndex), 0, Points.Count - 1);

            if (delta.EqualsEpsilon(0.0f))
            {
                return(Points[startPointIndex]);
            }

            if (delta.EqualsEpsilon(1.0f))
            {
                return(Points[startPointIndex + 1]);
            }

            var deltaCubeSquare = new DX.Vector4(delta * delta * delta, delta * delta, delta * delta, 1.0f);

            DX.Vector4 startPoint     = Points[startPointIndex];
            DX.Vector4 startPointNext = Points[startPointIndex + 1];
            DX.Vector4 tangent        = _tangents[startPointIndex];
            DX.Vector4 tangentNext    = _tangents[startPointIndex + 1];

            calculations.Row1 = startPoint;
            calculations.Row2 = startPointNext;
            calculations.Row3 = tangent;
            calculations.Row4 = tangentNext;

            DX.Matrix.Multiply(ref _coefficients, ref calculations, out DX.Matrix calcResult);
            DX.Vector4.Transform(ref deltaCubeSquare, ref calcResult, out DX.Vector4 result);

            return(result);
        }
コード例 #2
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MiniTriVertex"/> struct.
 /// </summary>
 /// <param name="position">The position of the vertex in object space.</param>
 /// <param name="color">The color of the vertex.</param>
 public MiniTriVertex(DX.Vector3 position, GorgonColor color)
 {
     // Note that we're passing a 3D vector, but storing a 4D vector. We need the W coordinate set to 1.0f to indicate that the coordinates are normalized.
     // For more information about the W component, go to http://www.tomdalling.com/blog/modern-opengl/explaining-homogenous-coordinates-and-projective-geometry/
     Position = new DX.Vector4(position, 1.0f);
     Color    = color;
 }
コード例 #3
0
 public TransformedColoredTextured(Vector4 value, int c, float u, float v)
 {
     this.Position = value;
     this.Tu       = u;
     this.Tv       = v;
     this.Color    = c;
 }
コード例 #4
0
        /// <summary>
        /// Function to build up the renderable vertices.
        /// </summary>
        /// <param name="bounds">The bounds of the renderable.</param>
        /// <param name="anchor">The anchor point for the renderable.</param>
        /// <param name="corners">The corners of the sprite.</param>
        private static void BuildRenderable(ref DX.RectangleF bounds, ref DX.Vector2 anchor, ref DX.Vector4 corners)
        {
            if (anchor.IsZero)
            {
                return;
            }

            var anchorProjected = new DX.Vector2(anchor.X * bounds.Width, anchor.Y * bounds.Height);

            corners = new DX.Vector4(-anchorProjected.X, -anchorProjected.Y, bounds.Width, bounds.Height);
        }
コード例 #5
0
        void SetSceneConstants()
        {
            FreeLook freelook    = Demo.FreeLook;
            Vector3  up          = MathHelper.Convert(freelook.Up);
            Vector3  eye         = MathHelper.Convert(freelook.Eye);
            Vector4  eyePosition = new Vector4(eye, 1);

            sceneConstants.View = Matrix.LookAtLH(eye, MathHelper.Convert(freelook.Target), up);
            Matrix.PerspectiveFovLH(FieldOfView, AspectRatio, _nearPlane, FarPlane, out sceneConstants.Projection);
            Matrix.Invert(ref sceneConstants.View, out sceneConstants.ViewInverse);

            Texture2DDescription depthBuffer = lightDepthTexture.Description;
            Vector3 lightPosition            = sunLightDirection * -60;
            Matrix  lightView = Matrix.LookAtLH(lightPosition, Vector3.Zero, up);
            //Matrix lightProjection = Matrix.OrthoLH(depthBuffer.Width / 8.0f, depthBuffer.Height / 8.0f, _nearPlane, FarPlane);
            Matrix lightProjection = Matrix.PerspectiveFovLH(FieldOfView, (float)depthBuffer.Width / (float)depthBuffer.Height, _nearPlane, FarPlane);

            sceneConstants.LightViewProjection = lightView * lightProjection;

            DataStream data;

            _immediateContext.MapSubresource(sceneConstantsBuffer, MapMode.WriteDiscard, SharpDX.Direct3D11.MapFlags.None, out data);
            Marshal.StructureToPtr(sceneConstants, data.DataPointer, false);
            _immediateContext.UnmapSubresource(sceneConstantsBuffer, 0);
            data.Dispose();

            sunLightDirectionVar.Set(new Vector4(sunLightDirection, 1));

            Matrix overlayMatrix = Matrix.Scaling(info.Width / _width, info.Height / _height, 1.0f);

            overlayMatrix *= Matrix.Translation(-(_width - info.Width) / _width, (_height - info.Height) / _height, 0.0f);
            overlayViewProjectionVar.SetMatrix(overlayMatrix);


            lightProjectionVar.SetMatrixTranspose(ref sceneConstants.Projection);
            lightViewVar.SetMatrixTranspose(ref sceneConstants.View);
            lightViewInverseVar.SetMatrix(ref sceneConstants.ViewInverse);
            lightViewportWidthVar.Set(_width);
            lightViewportHeightVar.Set(_height);
            lightEyePositionVar.Set(ref eyePosition);

            float   tanHalfFovY    = (float)Math.Tan(FieldOfView * 0.5f);
            float   tanHalfFovX    = tanHalfFovY * AspectRatio;
            float   projectionA    = FarPlane / (FarPlane - _nearPlane);
            float   projectionB    = -projectionA * _nearPlane;
            Vector4 viewParameters = new Vector4(tanHalfFovX, tanHalfFovY, projectionA, projectionB);

            lightViewParametersVar.Set(ref viewParameters);


            viewportWidthVar.Set(_width);
            viewportHeightVar.Set(_height);
            viewParametersVar.Set(ref viewParameters);
        }
コード例 #6
0
        /// <summary>Function called prior to rendering a pass.</summary>
        /// <param name="passIndex">The index of the pass to render.</param>
        /// <param name="output">The final render target that will receive the rendering from the effect.</param>
        /// <param name="camera">The currently active camera.</param>
        /// <returns>A <see cref="PassContinuationState"/> to instruct the effect on how to proceed.</returns>
        /// <remarks>Applications can use this to set up per-pass states and other configuration settings prior to executing a single render pass.</remarks>
        /// <seealso cref="PassContinuationState" />
        protected override PassContinuationState OnBeforeRenderPass(int passIndex, GorgonRenderTargetView output, IGorgon2DCamera camera)
        {
            DX.Vector2 intensity = FullScreen ? new DX.Vector2((Intensity * 16) * (1.0f / output.Width), (Intensity * 16) * (1.0f / output.Height))
                : new DX.Vector2(Intensity * 0.05f, 0);
            var settings = new DX.Vector4(intensity, output.Width, output.Height);

            _settings.Buffer.SetData(ref settings);

            Graphics.SetRenderTarget(output);

            return(PassContinuationState.Continue);
        }
コード例 #7
0
ファイル: SpriteTransformer.cs プロジェクト: ishkang/Gorgon
        /// <summary>
        /// Function to build up the renderable vertices.
        /// </summary>
        /// <param name="bounds">The bounds of the renderable.</param>
        /// <param name="anchor">The anchor point for the renderable.</param>
        /// <param name="corners">The corners of the renderable.</param>
        private static void BuildRenderable(ref DX.RectangleF bounds, ref DX.Vector2 anchor, out DX.Vector4 corners)
        {
            var vectorSize = new DX.Vector2(bounds.Size.Width, bounds.Size.Height);
            DX.Vector2 axisOffset = default;

            if (!anchor.IsZero)
            {
                DX.Vector2.Multiply(ref anchor, ref vectorSize, out axisOffset);
            }

            corners = new DX.Vector4(-axisOffset.X, -axisOffset.Y, vectorSize.X - axisOffset.X, vectorSize.Y - axisOffset.Y);
        }
コード例 #8
0
ファイル: Program.cs プロジェクト: hammerforgegames/Gorgon
        /// <summary>
        /// Function to update the world project matrix.
        /// </summary>
        private static void UpdatedWorldProjection()
        {
            // Update the animated offset for the center point.  We need to put this into a Vector4 because our data needs to be
            // aligned to a 16 byte boundary for constant buffers.
            var offset = new DX.Vector4(_heightOffset, 0, 0, 0);

            DX.Matrix.RotationY(_angle.ToRadians(), out _worldMatrix);
            _worldMatrix.Row4 = new DX.Vector4(0, 0, 2.0f, 1.0f);

            // We've put our world matrix and center point offset inside of the same buffer since they're both updated once per
            // frame.
            _vsConstants.Buffer.SetData(ref _worldMatrix, 64, CopyMode.NoOverwrite);
            _vsConstants.Buffer.SetData(ref offset, 128, CopyMode.NoOverwrite);
        }
コード例 #9
0
ファイル: Paint.cs プロジェクト: still-scene/Operators
        private Vector3 PointFromMousePos(EvaluationContext context, Vector2 mousePos)
        {
            const float offsetFromCamPlane = 0.98f;
            var         posInClipSpace     = new SharpDX.Vector4((mousePos.X - 0.5f) * 2, (-mousePos.Y + 0.5f) * 2, offsetFromCamPlane, 1);
            Matrix      clipSpaceToCamera  = context.CameraToClipSpace;

            clipSpaceToCamera.Invert();
            Matrix cameraToWorld = context.WorldToCamera;

            cameraToWorld.Invert();
            Matrix worldToObject = context.ObjectToWorld;

            worldToObject.Invert();

            var clipSpaceToWorld = Matrix.Multiply(clipSpaceToCamera, cameraToWorld);
            var m = Matrix.Multiply(cameraToWorld, clipSpaceToCamera);

            m.Invert();
            var p = SharpDX.Vector4.Transform(posInClipSpace, clipSpaceToWorld);

            return(new Vector3(p.X, p.Y, p.Z) / p.W);
        }
コード例 #10
0
ファイル: VolumeRenderer.cs プロジェクト: ishkang/Gorgon
        /// <summary>
        /// Function to assign the volume texture to render.
        /// </summary>
        /// <param name="texture">The volume texture to render.</param>
        public void AssignTexture(GorgonTexture3DView texture)
        {
            _textureView = texture;

            var   size      = new DX.Vector3(texture.Width, texture.Height, texture.Depth);
            float maxSize   = texture.Width.Max(texture.Height).Max(texture.Depth);
            var   volParams = new VolumeRayParameters
            {
                Steps = new DX.Vector3(1.0f / texture.Width,
                                       1.0f / texture.Height,
                                       1.0f / texture.Depth) * 0.5f,
                Iterations = (int)(maxSize * 2.0f)
            };

            _volumeRayParams.SetData(ref volParams);

            var scaleFactor = new DX.Vector4(1.0f, 1.0f, 1.0f / (maxSize / size.Z), 1.0f);

            _volumeScaleFactor.SetData(ref scaleFactor);

            RebuildVolumeData();
        }
コード例 #11
0
ファイル: RenderModel.cs プロジェクト: ousttrue/ModelMotionIO
        public void UpdateVertexBuffer(MMIO.Node<NodeContent> node)
        {
            var gray = new SharpDX.Vector4(0.5f, 0.5f, 0.5f, 0.5f);
            var white = new SharpDX.Vector4(1.0f, 1.0f, 1.0f, 1.0f);
            var red = new SharpDX.Vector4(1.0f, 0, 0, 1.0f);

            var vertices = node.TraversePair()
                .Select(x =>
                {
                    if (x.Item2.Content.IsSelected.Value)
                    {
                        return new { line = x, color = red };
                    }
                    else if (x.Item2.Content.KeyFrame.Value == Transform.Identity)
                    {
                        return new { line = x, color = gray };
                    }
                    else
                    {
                        return new { line = x, color = white };
                    }
                })
                .SelectMany(x => new SharpDX.Vector4[] {
                    new SharpDX.Vector4(x.line.Item1.Content.WorldTransform.Translation, 1.0f), x.color
                    , new SharpDX.Vector4(x.line.Item2.Content.WorldTransform.Translation, 1.0f), x.color
                })
                .SelectMany(x => new Single[] { x.X, x.Y, x.Z, x.W })
                .ToArray()
                ;

            if (!vertices.Any()) return;

            // ToDO: Meshごとにシェーダーを見るべし
            // ToDo: 解放されている?
            var ptr = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(float)) * vertices.Length);
            Marshal.Copy(vertices, 0, ptr, vertices.Length);

            VertexBufferUpdate = VertexBufferUpdateCommand.Create(VertexBuffer, ptr);
        }
コード例 #12
0
ファイル: TrackKeyProcessor.cs プロジェクト: ishkang/Gorgon
        /// <summary>
        /// Function to update the rectangle boundaries of the object that the animation is being applied to.
        /// </summary>
        /// <param name="animationLength">The length, in seconds, of the animation.</param>
        /// <param name="track">The track to evaluate.</param>
        /// <param name="time">The current time for the animation.</param>
        /// <param name="result">The result value to apply to the object bounds.</param>
        /// <returns><b>true</b> if there's a value to update, <b>false</b> if not.</returns>
        public static bool TryUpdateRectBounds(float animationLength, IGorgonTrack <GorgonKeyRectangle> track, float time, out DX.RectangleF result)
        {
            switch (track.KeyFrames.Count)
            {
            case 0:
                result = DX.RectangleF.Empty;
                return(false);

            case 1:
                result = track.KeyFrames[0].Value;
                return(true);
            }

            (GorgonKeyRectangle prev, GorgonKeyRectangle next, int prevKeyIndex, float deltaTime) = TweenKey.GetNearestKeys(track, time, animationLength);

            switch (track.InterpolationMode)
            {
            case TrackInterpolationMode.Linear:
                result = new DX.RectangleF(prev.Value.X + ((next.Value.X - prev.Value.X) * deltaTime),
                                           prev.Value.Y + ((next.Value.Y - prev.Value.Y) * deltaTime),
                                           prev.Value.Width + ((next.Value.Width - prev.Value.Width) * deltaTime),
                                           prev.Value.Height + ((next.Value.Height - prev.Value.Height) * deltaTime));
                break;

            case TrackInterpolationMode.Spline:
                DX.Vector4 splineResult = track.SplineController.GetInterpolatedValue(prevKeyIndex, deltaTime);
                result = new DX.RectangleF(splineResult.X, splineResult.Y, splineResult.Z, splineResult.W);
                break;

            default:
                result = next.Value;
                break;
            }

            return(true);
        }
コード例 #13
0
 public static SharpDX.Vector3 ToVector3(this SharpDX.Vector4 vector4)
 {
     return(new SharpDX.Vector3(vector4.X, vector4.Y, vector4.Z));
 }
コード例 #14
0
 public FTransform(SharpDX.Vector4 rot, SharpDX.Vector3 translation, SharpDX.Vector3 scale)
 {
     Rotation    = rot;
     Translation = translation;
     Scale3D     = scale;
 }
コード例 #15
0
 /// <summary>
 /// Function to clear the unordered access value with the specified values.
 /// </summary>
 /// <param name="values">Values used to clear.</param>
 /// <remarks>
 /// <para>
 /// This method will copy the lower n[i] bits (where n is the number of bits in a channel, i is the index of the channel) to the proper channel.
 /// </para>
 /// <para>
 /// This method works on any unordered access view that does not require format conversion.  Unordered access views for raw/structured buffers only use the first value in the vector.
 /// </para>
 /// </remarks>
 public void Clear(DX.Vector4 values) => Resource.Graphics.D3DDeviceContext.ClearUnorderedAccessView(Native, new DX.Vector4(values.X, values.Y, values.Z, values.W));
コード例 #16
0
ファイル: Render.cs プロジェクト: gvdexile9/Get-Chaos-Value
        private void PropheccyDisplay()
        {
            if (!Settings.ProphecyPrices)
            {
                return;
            }

            try
            {
                var UIHover = GameController.Game.IngameState.UIHover;
                var newBox  = new RectangleF(lastProphWindowPos.X, lastProphWindowPos.Y, lastProphWindowSize.X, lastProphWindowSize.Y);

                if (!StashPanel.IsVisible)
                {
                    return;
                }
                var refBool = true;

                if (!UIHover.Tooltip.GetClientRect().Intersects(newBox))
                {
                    var menuOpacity = ImGui.GetStyle().GetColor(ColorTarget.WindowBg).W;
                    if (Settings.ProphecyOverrideColors)
                    {
                        var tempColor = new SharpDX.Vector4(Settings.ProphecyBackground.Value.R / 255.0f, Settings.ProphecyBackground.Value.G / 255.0f,
                                                            Settings.ProphecyBackground.Value.B / 255.0f, Settings.ProphecyBackground.Value.A / 255.0f);
                        ImGui.PushStyleColor(ColorTarget.WindowBg, ToImVector4(tempColor));
                        menuOpacity = ImGui.GetStyle().GetColor(ColorTarget.WindowBg).W;
                    }

                    ImGui.BeginWindow("Poe.NinjaProphs", ref refBool, new System.Numerics.Vector2(200, 150), menuOpacity, Settings.ProphecyLocked ? WindowFlags.NoCollapse | WindowFlags.NoScrollbar | WindowFlags.NoMove | WindowFlags.NoResize | WindowFlags.NoInputs | WindowFlags.NoBringToFrontOnFocus | WindowFlags.NoTitleBar | WindowFlags.NoFocusOnAppearing : WindowFlags.Default | WindowFlags.NoTitleBar | WindowFlags.ResizeFromAnySide);

                    if (Settings.ProphecyOverrideColors)
                    {
                        ImGui.PopStyleColor();
                    }


                    var prophystringlist = new List <string>();
                    var propicies        = GameController.Player.GetComponent <Player>().Prophecies;
                    foreach (var prophecyDat in propicies)
                    {
                        //var text = $"{GetProphecyValues(prophecyDat.Name)}c - {prophecyDat.Name}({prophecyDat.SealCost})";
                        var text = $"{{{HexConverter(Settings.ProphecyChaosValue)}}}{GetProphecyValues(prophecyDat.Name)}c {{}}- {{{HexConverter(Settings.ProphecyProecyName)}}}{prophecyDat.Name} {{{HexConverter(Settings.ProphecyProecySealColor)}}}({prophecyDat.SealCost}){{}}";
                        if (prophystringlist.Any(x => Equals(x, text)))
                        {
                            continue;
                        }
                        prophystringlist.Add(text);
                    }

                    foreach (var proph in prophystringlist)
                    {
                        //ImGui.Text(VARIABLE);
                        Coloredtext(proph);
                    }

                    lastProphWindowSize = new Vector2(ImGui.GetWindowSize().X, ImGui.GetWindowSize().Y);
                    lastProphWindowPos  = new Vector2(ImGui.GetWindowPosition().X, ImGui.GetWindowPosition().Y);
                    ImGui.EndWindow();
                }
            }
            catch
            {
                ImGui.EndWindow();
            }
        }
コード例 #17
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Settings"/> struct.
 /// </summary>
 /// <param name="linecolor">The linecolor.</param>
 /// <param name="texelSize">Size of the texel.</param>
 /// <param name="threshold">The threshold.</param>
 public Settings(GorgonColor linecolor, DX.Vector2 texelSize, float threshold)
 {
     LineColor       = linecolor;
     _texelThreshold = new DX.Vector4(texelSize, threshold, 0);
 }
コード例 #18
0
ファイル: Program.cs プロジェクト: semihguresci/kgp
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            RenderForm form = new RenderForm("Kinect RGB Joint sample");

            RenderDevice device = new RenderDevice(SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport | DeviceCreationFlags.Debug);
            RenderContext context = new RenderContext(device);
            DX11SwapChain swapChain = DX11SwapChain.FromHandle(device, form.Handle);

            //VertexShader vertexShader = ShaderCompiler.CompileFromFile<VertexShader>(device, "ColorJointView.fx", "VS");
            SharpDX.D3DCompiler.ShaderSignature signature;
            VertexShader vertexShader = ShaderCompiler.CompileFromFile(device, "ColorJointView.fx", "VS_Color", out signature);
            PixelShader pixelShader = ShaderCompiler.CompileFromFile<PixelShader>(device, "ColorJointView.fx", "PS_Color");

            DX11IndexedGeometry circle = device.Primitives.Segment(new Segment()
            {
                Resolution = 32
            });
            DX11InstancedIndexedDrawer drawer = new DX11InstancedIndexedDrawer();
            circle.AssignDrawer(drawer);

            InputLayout layout;
            var bc = new ShaderBytecode(signature);
            circle.ValidateLayout(bc, out layout);

            KinectSensor sensor = KinectSensor.GetDefault();
            sensor.Open();

            Color4[] statusColor = new Color4[]
            {
                Color.Red,
                Color.Yellow,
                Color.Green
            };

            //Note cbuffer should have a minimum size of 16 bytes, so we create verctor4 instead of vector2
            SharpDX.Vector4 jointSize = new SharpDX.Vector4(0.04f,0.07f,0.0f,1.0f);
            ConstantBuffer<SharpDX.Vector4> cbSize = new ConstantBuffer<SharpDX.Vector4>(device);
            cbSize.Update(context, ref jointSize);

            DX11StructuredBuffer colorTableBuffer = DX11StructuredBuffer.CreateImmutable<Color4>(device, statusColor);

            bool doQuit = false;
            bool doUpload = false;
            bool uploadImage = false;

            KinectBody[] bodyFrame = null;
            BodyColorPositionBuffer positionBuffer = new BodyColorPositionBuffer(device);
            BodyJointStatusBuffer statusBuffer = new BodyJointStatusBuffer(device);

            KinectSensorBodyFrameProvider provider = new KinectSensorBodyFrameProvider(sensor);
            provider.FrameReceived += (sender, args) => { bodyFrame = args.FrameData; doUpload = true; };

            ColorRGBAFrameData rgbFrame = null;
            DynamicColorRGBATexture colorTexture = new DynamicColorRGBATexture(device);
            KinectSensorColorRGBAFrameProvider colorProvider = new KinectSensorColorRGBAFrameProvider(sensor);
            colorProvider.FrameReceived += (sender, args) => { rgbFrame = args.FrameData; uploadImage = true; };

            form.KeyDown += (sender, args) => { if (args.KeyCode == Keys.Escape) { doQuit = true; } };

            RenderLoop.Run(form, () =>
            {
                if (doQuit)
                {
                    form.Dispose();
                    return;
                }

                if (doUpload)
                {
                    var tracked = bodyFrame.TrackedOnly();
                    var colorSpace = tracked.Select(kb => new ColorSpaceKinectJoints(kb, sensor.CoordinateMapper));

                    positionBuffer.Copy(context, colorSpace);
                    statusBuffer.Copy(context, tracked);
                    drawer.InstanceCount = colorSpace.Count() * Microsoft.Kinect.Body.JointCount;
                }

                if (uploadImage)
                {
                    colorTexture.Copy(context, rgbFrame);
                }

                context.RenderTargetStack.Push(swapChain);
                context.Context.ClearRenderTargetView(swapChain.RenderView, SharpDX.Color.Black);

                device.Primitives.ApplyFullTri(context, colorTexture.ShaderView);
                device.Primitives.FullScreenTriangle.Draw(context);

                circle.Bind(context, layout);

                context.Context.PixelShader.Set(pixelShader);
                context.Context.VertexShader.Set(vertexShader);
                context.Context.VertexShader.SetShaderResource(0, positionBuffer.ShaderView);
                context.Context.VertexShader.SetShaderResource(1, statusBuffer.ShaderView);
                context.Context.VertexShader.SetShaderResource(2, colorTableBuffer.ShaderView);
                context.Context.VertexShader.SetConstantBuffer(0, cbSize.Buffer);

                circle.Draw(context);

                context.RenderTargetStack.Pop();
                swapChain.Present(0, SharpDX.DXGI.PresentFlags.None);
            });

            swapChain.Dispose();
            context.Dispose();
            device.Dispose();

            colorProvider.Dispose();
            colorTexture.Dispose();

            positionBuffer.Dispose();
            statusBuffer.Dispose();
            colorTableBuffer.Dispose();

            cbSize.Dispose();

            provider.Dispose();
            circle.Dispose();
            layout.Dispose();

            pixelShader.Dispose();
            vertexShader.Dispose();

            sensor.Close();
        }
コード例 #19
0
ファイル: DirectXUtil.cs プロジェクト: gitter-badger/dEngine
 public static SharpDX.Vector4 Round(this SharpDX.Vector4 vec)
 {
     return(new SharpDX.Vector4((float)Math.Round(vec.X), (float)Math.Round(vec.Y), (float)Math.Round(vec.Z),
                                (float)Math.Round(vec.W)));
 }
コード例 #20
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            RenderForm form = new RenderForm("Kinect RGB Joint sample");

            RenderDevice  device    = new RenderDevice(SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport | DeviceCreationFlags.Debug);
            RenderContext context   = new RenderContext(device);
            DX11SwapChain swapChain = DX11SwapChain.FromHandle(device, form.Handle);

            //VertexShader vertexShader = ShaderCompiler.CompileFromFile<VertexShader>(device, "ColorJointView.fx", "VS");
            SharpDX.D3DCompiler.ShaderSignature signature;
            VertexShader vertexShader = ShaderCompiler.CompileFromFile(device, "ColorJointView.fx", "VS_Color", out signature);
            PixelShader  pixelShader  = ShaderCompiler.CompileFromFile <PixelShader>(device, "ColorJointView.fx", "PS_Color");

            DX11IndexedGeometry circle = device.Primitives.Segment(new Segment()
            {
                Resolution = 32
            });
            DX11InstancedIndexedDrawer drawer = new DX11InstancedIndexedDrawer();

            circle.AssignDrawer(drawer);

            InputLayout layout;
            var         bc = new ShaderBytecode(signature);

            circle.ValidateLayout(bc, out layout);

            KinectSensor sensor = KinectSensor.GetDefault();

            sensor.Open();

            Color4[] statusColor = new Color4[]
            {
                Color.Red,
                Color.Yellow,
                Color.Green
            };

            //Note cbuffer should have a minimum size of 16 bytes, so we create verctor4 instead of vector2
            SharpDX.Vector4 jointSize = new SharpDX.Vector4(0.04f, 0.07f, 0.0f, 1.0f);
            ConstantBuffer <SharpDX.Vector4> cbSize = new ConstantBuffer <SharpDX.Vector4>(device);

            cbSize.Update(context, ref jointSize);

            DX11StructuredBuffer colorTableBuffer = DX11StructuredBuffer.CreateImmutable <Color4>(device, statusColor);

            bool doQuit      = false;
            bool doUpload    = false;
            bool uploadImage = false;


            KinectBody[]            bodyFrame      = null;
            BodyColorPositionBuffer positionBuffer = new BodyColorPositionBuffer(device);
            BodyJointStatusBuffer   statusBuffer   = new BodyJointStatusBuffer(device);

            KinectSensorBodyFrameProvider provider = new KinectSensorBodyFrameProvider(sensor);

            provider.FrameReceived += (sender, args) => { bodyFrame = args.FrameData; doUpload = true; };

            ColorRGBAFrameData                 rgbFrame      = null;
            DynamicColorRGBATexture            colorTexture  = new DynamicColorRGBATexture(device);
            KinectSensorColorRGBAFrameProvider colorProvider = new KinectSensorColorRGBAFrameProvider(sensor);

            colorProvider.FrameReceived += (sender, args) => { rgbFrame = args.FrameData; uploadImage = true; };


            form.KeyDown += (sender, args) => { if (args.KeyCode == Keys.Escape)
                                                {
                                                    doQuit = true;
                                                }
            };

            RenderLoop.Run(form, () =>
            {
                if (doQuit)
                {
                    form.Dispose();
                    return;
                }

                if (doUpload)
                {
                    var tracked    = bodyFrame.TrackedOnly();
                    var colorSpace = tracked.Select(kb => new ColorSpaceKinectJoints(kb, sensor.CoordinateMapper));

                    positionBuffer.Copy(context, colorSpace);
                    statusBuffer.Copy(context, tracked);
                    drawer.InstanceCount = colorSpace.Count() * Microsoft.Kinect.Body.JointCount;
                }

                if (uploadImage)
                {
                    colorTexture.Copy(context, rgbFrame);
                }

                context.RenderTargetStack.Push(swapChain);
                context.Context.ClearRenderTargetView(swapChain.RenderView, SharpDX.Color.Black);

                device.Primitives.ApplyFullTri(context, colorTexture.ShaderView);
                device.Primitives.FullScreenTriangle.Draw(context);

                circle.Bind(context, layout);

                context.Context.PixelShader.Set(pixelShader);
                context.Context.VertexShader.Set(vertexShader);
                context.Context.VertexShader.SetShaderResource(0, positionBuffer.ShaderView);
                context.Context.VertexShader.SetShaderResource(1, statusBuffer.ShaderView);
                context.Context.VertexShader.SetShaderResource(2, colorTableBuffer.ShaderView);
                context.Context.VertexShader.SetConstantBuffer(0, cbSize.Buffer);

                circle.Draw(context);

                context.RenderTargetStack.Pop();
                swapChain.Present(0, SharpDX.DXGI.PresentFlags.None);
            });

            swapChain.Dispose();
            context.Dispose();
            device.Dispose();

            colorProvider.Dispose();
            colorTexture.Dispose();

            positionBuffer.Dispose();
            statusBuffer.Dispose();
            colorTableBuffer.Dispose();

            cbSize.Dispose();

            provider.Dispose();
            circle.Dispose();
            layout.Dispose();



            pixelShader.Dispose();
            vertexShader.Dispose();


            sensor.Close();
        }
コード例 #21
0
ファイル: Shadows.cs プロジェクト: gitter-badger/dEngine
        public static void RenderShadowMap(ref DeviceContext context, ref IWorld world, ref Camera camera)
        {
            PixHelper.BeginEvent(default(RawColorBGRA), "Shadow Rendering");
            {
                if (ShadowMapsNeedRemade)
                    CreateShadowMaps();

                var shadowMapSize = ShadowMap.Width;

                if (AreSplitsDirty || camera != _lastCamera)
                    ComputeSplits(ref camera);

                _lastCamera = camera;
                
                MakeGlobalShadowMatrix(ref camera, out ReceiverConstants.Data.ShadowMatrix);

                context.Rasterizer.SetViewport(_viewport);

                for (int cascadeIndex = 0; cascadeIndex < CascadeCount; ++cascadeIndex)
                {
                    PixHelper.BeginEvent(default(RawColorBGRA), "Cascade");
                    {
                        ResetFrustumCorners(ref _frustumCorners);

                        var prevSplitDist = cascadeIndex == 0 ? MinCascadeDistance : _cascadeSplits[cascadeIndex - 1];
                        var splitDist = _cascadeSplits[cascadeIndex];

                        for (int i = 0; i < 8; i++)
                            DxVector3.TransformCoordinate(ref _frustumCorners[i],
                                ref camera.Constants.Data.InverseViewProjection, out _frustumCorners[i]);

                        for (int i = 0; i < 4; i++)
                        {
                            DxVector3 cornerRay;
                            DxVector3 nearCornerRay;
                            DxVector3 farCornerRay;
                            DxVector3.Subtract(ref _frustumCorners[i + 4], ref _frustumCorners[i], out cornerRay);
                            DxVector3.Multiply(ref cornerRay, prevSplitDist, out nearCornerRay);
                            DxVector3.Multiply(ref cornerRay, splitDist, out farCornerRay);
                            DxVector3.Add(ref _frustumCorners[i], ref farCornerRay, out _frustumCorners[i + 4]);
                            DxVector3.Add(ref _frustumCorners[i], ref nearCornerRay, out _frustumCorners[i]);
                        }

                        var frustumCenter = DxVector3.Zero;
                        for (int i = 0; i < 8; i++)
                            DxVector3.Add(ref frustumCenter, ref _frustumCorners[i], out frustumCenter);
                        DxVector3.Multiply(ref frustumCenter, 0.125F, out frustumCenter);

                        var upDir = DxVector3.Up;

                        float sphereRadius = 0.0f;
                        for (int i = 0; i < 8; ++i)
                        {
                            DxVector3 sum;
                            DxVector3.Subtract(ref _frustumCorners[i], ref frustumCenter, out sum);
                            sphereRadius = Math.Max(sphereRadius, sum.Length());
                        }

                        sphereRadius = (float)Math.Ceiling(sphereRadius * 16.0f) / 16.0f;

                        var maxExtents = new DxVector3(sphereRadius, sphereRadius, sphereRadius);
                        DxVector3 minExtents;
                        DxVector3.Negate(ref maxExtents, out minExtents);

                        DxVector3 cascadeExtents;
                        DxVector3.Subtract(ref maxExtents, ref minExtents, out cascadeExtents);

                        // TODO: optimize
                        var shadowCameraPos = frustumCenter + Direction * -minExtents.Z;

                        Matrix viewMatrix;
                        Matrix projectionMatrix;
                        Matrix viewProjMatrix;

                        Matrix.LookAtLH(ref shadowCameraPos, ref frustumCenter, ref upDir, out viewMatrix);
                        Matrix.OrthoOffCenterLH(minExtents.X, maxExtents.X, minExtents.Y,
                            maxExtents.Y, 0.0f, cascadeExtents.Z, out projectionMatrix);
                        Matrix.Multiply(ref viewMatrix, ref projectionMatrix, out viewProjMatrix);

                        var shadowOrigin = DxVector4.UnitW;
                        DxVector4.Transform(ref shadowOrigin, ref viewProjMatrix, out shadowOrigin);
                        DxVector4.Multiply(ref shadowOrigin, shadowMapSize / 2.0f, out shadowOrigin);

                        var roundedOrigin = new DxVector4(Mathf.Round(shadowOrigin.X), Mathf.Round(shadowOrigin.Y),
                            Mathf.Round(shadowOrigin.Z), Mathf.Round(shadowOrigin.W));
                        DxVector4 roundOffset;
                        DxVector4.Subtract(ref roundedOrigin, ref shadowOrigin, out roundOffset);
                        DxVector4.Multiply(ref roundOffset, 2.0f / shadowMapSize, out roundOffset);
                        roundOffset.Z = 0.0f;
                        roundOffset.W = 0.0f;

                        projectionMatrix.Row4 += roundOffset; // R[3]
                        Matrix.Multiply(ref viewMatrix, ref projectionMatrix, out viewProjMatrix);

                        // RenderDepthCPU
                        SetupRenderDepthState(ref context, ref viewProjMatrix, cascadeIndex);
                        world.RenderObjectProvider.Draw(ref context, ref camera, true);

                        var texScaleBias = new Matrix
                        {
                            Row1 = new SharpDX.Vector4(0.5f, 0.0f, 0.0f, 0.0f),
                            Row2 = new SharpDX.Vector4(0.0f, -0.5f, 0.0f, 0.0f),
                            Row3 = new SharpDX.Vector4(0.0f, 0.0f, 1.0f, 0.0f),
                            Row4 = new SharpDX.Vector4(0.5f, 0.5f, 0.0f, 1.0f)
                        };
                        Matrix.Multiply(ref viewProjMatrix, ref texScaleBias, out viewProjMatrix);

                        var clipNear = camera.ClipNear;
                        var clipFar = camera.ClipFar;
                        var clipDist = clipFar - clipNear;
                        ReceiverConstants.Data.CascadeSplits[cascadeIndex] = clipNear + splitDist * clipDist;

                        Matrix invCascadeMatrix;
                        Matrix.Invert(ref viewProjMatrix, out invCascadeMatrix);

                        var zero = DxVector3.Zero;
                        DxVector3 cascadeCorner;
                        DxVector3.TransformCoordinate(ref zero, ref invCascadeMatrix, out cascadeCorner);
                        DxVector3.TransformCoordinate(ref cascadeCorner, ref ReceiverConstants.Data.ShadowMatrix,
                            out cascadeCorner);

                        var one = DxVector3.One;
                        DxVector3 otherCorner;
                        DxVector3.TransformCoordinate(ref one, ref invCascadeMatrix, out otherCorner);
                        DxVector3.TransformCoordinate(ref otherCorner, ref ReceiverConstants.Data.ShadowMatrix, out otherCorner);

                        var cascadeScale = DxVector3.One / (otherCorner - cascadeCorner);
                        ReceiverConstants.Data.CascadeOffsets[cascadeIndex] = new DxVector4(-cascadeCorner, 0.0f);
                        ReceiverConstants.Data.CascadeScales[cascadeIndex] = new DxVector4(cascadeScale, 1.0f);

                        if (RenderSettings.UseFilterableShadows)
                            ConvertToVsm(ref context, cascadeIndex,
                                ref ReceiverConstants.Data.CascadeSplits[cascadeIndex],
                                ref ReceiverConstants.Data.CascadeScales[0]);
                    }
                    PixHelper.EndEvent();
                }
            }
            PixHelper.EndEvent();

            DataStream stream;
            context.MapSubresource(ReceiverConstants.Buffer, MapMode.WriteDiscard, MapFlags.None, out stream);
            stream.Write(ReceiverConstants.Data.ShadowMatrix);
            stream.WriteRange(ReceiverConstants.Data.CascadeSplits, 0, 4);
            stream.WriteRange(ReceiverConstants.Data.CascadeOffsets, 0, 4);
            stream.WriteRange(ReceiverConstants.Data.CascadeScales, 0, 4);
            stream.Write(ReceiverConstants.Data.ShadowDepthBias);
            stream.Write(ReceiverConstants.Data.ShadowOffsetScale);
            stream.Write(ReceiverConstants.Data.VisualizeCascades);

            context.UnmapSubresource(ReceiverConstants.Buffer, 0);

            //ReceiverConstants.Update(ref context);
        }
コード例 #22
0
        void SetSceneConstants()
        {
            FreeLook freelook = Demo.Freelook;
            Vector3 up = MathHelper.Convert(freelook.Up);
            Vector3 eye = MathHelper.Convert(freelook.Eye);
            Vector4 eyePosition = new Vector4(eye, 1);

            sceneConstants.View = Matrix.LookAtLH(eye, MathHelper.Convert(freelook.Target), up);
            Matrix.PerspectiveFovLH(FieldOfView, AspectRatio, _nearPlane, FarPlane, out sceneConstants.Projection);
            Matrix.Invert(ref sceneConstants.View, out sceneConstants.ViewInverse);

            Texture2DDescription depthBuffer = lightDepthTexture.Description;
            Vector3 lightPosition = sunLightDirection * -60;
            Matrix lightView = Matrix.LookAtLH(lightPosition, Vector3.Zero, up);
            //Matrix lightProjection = Matrix.OrthoLH(depthBuffer.Width / 8.0f, depthBuffer.Height / 8.0f, _nearPlane, FarPlane);
            Matrix lightProjection = Matrix.PerspectiveFovLH(FieldOfView, (float)depthBuffer.Width / (float)depthBuffer.Height, _nearPlane, FarPlane);
            sceneConstants.LightViewProjection = lightView * lightProjection;

            SharpDX.DataStream data;
            _immediateContext.MapSubresource(sceneConstantsBuffer, MapMode.WriteDiscard, SharpDX.Direct3D11.MapFlags.None, out data);
            Marshal.StructureToPtr(sceneConstants, data.DataPointer, false);
            _immediateContext.UnmapSubresource(sceneConstantsBuffer, 0);
            data.Dispose();

            sunLightDirectionVar.Set(new Vector4(sunLightDirection, 1));

            Matrix overlayMatrix = Matrix.Scaling(info.Width / _width, info.Height / _height, 1.0f);
            overlayMatrix *= Matrix.Translation(-(_width - info.Width) / _width, (_height - info.Height) / _height, 0.0f);
            overlayViewProjectionVar.SetMatrix(overlayMatrix);


            lightProjectionVar.SetMatrixTranspose(ref sceneConstants.Projection);
            lightViewVar.SetMatrixTranspose(ref sceneConstants.View);
            lightViewInverseVar.SetMatrix(ref sceneConstants.ViewInverse);
            lightViewportWidthVar.Set(_width);
            lightViewportHeightVar.Set(_height);
            lightEyePositionVar.Set(ref eyePosition);

            float tanHalfFovY = (float)Math.Tan(FieldOfView * 0.5f);
            float tanHalfFovX = tanHalfFovY * AspectRatio;
            float projectionA = FarPlane / (FarPlane - _nearPlane);
            float projectionB = -projectionA * _nearPlane;
            Vector4 viewParameters = new Vector4(tanHalfFovX, tanHalfFovY, projectionA, projectionB);
            lightViewParametersVar.Set(ref viewParameters);


            viewportWidthVar.Set(_width);
            viewportHeightVar.Set(_height);
            viewParametersVar.Set(ref viewParameters);
        }
コード例 #23
0
ファイル: Shadows.cs プロジェクト: gitter-badger/dEngine
 private static void ConvertToVsm(ref DeviceContext context, int cascadeIndex, ref float cascadeSplit, ref DxVector4 cascadeScale)
 {
     throw new NotImplementedException();
 }
コード例 #24
-1
 public TransformedColoredTextured(float xvalue, float yvalue, float zvalue, float rhwvalue, int c, float u, float v)
 {
     this.Position = new Vector4(xvalue, yvalue, zvalue, rhwvalue);
     this.Tu       = u;
     this.Tv       = v;
     this.Color    = c;
 }