Esempio n. 1
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DepthStencilValue"/> struct.
 /// </summary>
 /// <param name="format">
 /// The format of the commonly cleared color follows the same validation rules as a view/ descriptor creation.
 /// In general, the format of the clear color can be any format in the same typeless group that the resource format belongs to.
 /// </param>
 /// <param name="color">Specifies a RGBA clear color.</param>
 public ClearValue(Format format, RawColor4 color)
 {
     Format       = format;
     Color        = color;
     DepthStencil = default;
 }
Esempio n. 2
0
 public Vertex(Vector4 pos, RawColor4 color, Vector4 normal)
 {
     Position = pos;
     Color    = color;
     Normal   = normal;
 }
Esempio n. 3
0
        //static ComPtr<ID3D11Texture2D> CreateTexture2D(UINT width, UINT height, UINT mipLevels, UINT arraySize, DXGI_FORMAT format, UINT sampleCount, UINT sampleQuality, D3D11_USAGE usage, UINT bindFlags, UINT cpuAccessFlags, UINT miscFlags, const void* data, const string& name)
        //{
        //    D3D11_TEXTURE2D_DESC td;
        //    td.Width = width;
        //    td.Height = height;
        //    td.MipLevels = mipLevels;
        //    td.ArraySize = arraySize;
        //    td.Format = format;
        //    td.SampleDesc.Count = sampleCount;
        //    td.SampleDesc.Quality = sampleQuality;
        //    td.Usage = usage;
        //    td.BindFlags = bindFlags;
        //    td.CPUAccessFlags = cpuAccessFlags;
        //    td.MiscFlags = miscFlags;
        //    D3D11_SUBRESOURCE_DATA srd;
        //    srd.pSysMem = data;
        //    srd.SysMemPitch = 1;
        //    srd.SysMemSlicePitch = 0;
        //    ComPtr<ID3D11Texture2D> t;
        //    Try(DXManager::GetDevice()->CreateTexture2D(&td, data != nullptr ? &srd : nullptr, &t), name);
        //    DXManager::AddVramUsage(ElementSize(format) * width * height * arraySize);
        //    return t;
        //}


        public static SamplerState CreateSamplerState(Device device, TextureAddressMode addressU, TextureAddressMode addressV, TextureAddressMode addressW, RawColor4 border, Comparison comparisonFunc, Filter filter, int maxAnisotropy, float maxLOD, float minLOD, float mipLODBias)
        {
            SamplerStateDescription smpDesc = new SamplerStateDescription();

            smpDesc.AddressU           = addressU;
            smpDesc.AddressV           = addressV;
            smpDesc.AddressW           = addressW;
            smpDesc.BorderColor        = border;
            smpDesc.ComparisonFunction = comparisonFunc;
            smpDesc.Filter             = filter;
            smpDesc.MaximumAnisotropy  = maxAnisotropy;
            smpDesc.MaximumLod         = maxLOD;
            smpDesc.MinimumLod         = minLOD;
            smpDesc.MipLodBias         = mipLODBias;
            SamplerState smp = new SamplerState(device, smpDesc);

            return(smp);
        }
Esempio n. 4
0
 private SolidColorBrush CreateBrush(RawColor4 color)
 {
     return(new SolidColorBrush(_device, color));
 }
Esempio n. 5
0
 /// <summary>
 /// Draw formatted text at the specified position.
 /// </summary>
 /// <param name="sprite">Reference to an ID3DX10Sprite object that contains the string you wish to draw. Can be NULL, in which case Direct3D will render the string with its own sprite object. To improve efficiency, a sprite object should be specified if ID3DX10Font::DrawText is to be called more than once in a row.</param>
 /// <param name="text">Pointer to a string to draw. If UNICODE is defined, this parameter type resolves to an LPCWSTR, otherwise, the type resolves to an LPCSTR. If the Count parameter is -1, the string must be NULL terminated.</param>
 /// <param name="x">The x.</param>
 /// <param name="y">The y.</param>
 /// <param name="color">Color of the text. See <see cref="RawColor4"/>.</param>
 /// <returns>
 /// If the function succeeds, the return value is the height of the text in logical units. If DT_VCENTER or DT_BOTTOM is specified, the return value is the offset from pRect (top to the bottom) of the drawn text. If the function fails, the return value is zero.
 /// </returns>
 /// <unmanaged>int ID3DX10Font::DrawTextW([None] LPD3DX10SPRITE pSprite,[None] const wchar_t* pString,[None] int Count,[None] RECT* pRect,[None] int Format,[None] D3DXCOLOR Color)</unmanaged>
 /// <remarks>
 /// The parameters of this method are very similar to those of the {{GDI DrawText}} function. This method supports both ANSI and Unicode strings. Unless the DT_NOCLIP format is used, this method clips the text so that it does not appear outside the specified rectangle. All formatting is assumed to have multiple lines unless the DT_SINGLELINE format is specified. If the selected font is too large for the rectangle, this method does not attempt to substitute a smaller font. This method supports only fonts whose escapement and orientation are both zero.
 /// </remarks>
 /// <unmanaged>int ID3DX10Font::DrawTextW([In] ID3DX10Sprite* pSprite,[In] const wchar_t* pString,[In] int Count,[In] RECT* pRect,[In] unsigned int Format,[In] D3DXCOLOR Color)</unmanaged>
 public int DrawText(Sprite sprite, string text, int x, int y, RawColor4 color)
 {
     return(DrawText(sprite, text, new RawRectangle(x, y, 0, 0), FontDrawFlags.NoClip, color));
 }
Esempio n. 6
0
 /// <summary>
 /// Creates a new <see cref="SharpDX.Direct2D1.SolidColorBrush"/> that has the specified color and opacity.
 /// </summary>
 /// <param name="renderTarget">an instance of <see cref = "SharpDX.Direct2D1.RenderTarget" /></param>
 /// <param name="color">The red, green, blue, and alpha values of the brush's color.</param>
 /// <param name="brushProperties">The base opacity of the brush.</param>
 public SolidColorBrush(RenderTarget renderTarget, RawColor4 color, SharpDX.Direct2D1.BrushProperties?brushProperties)
     : base(IntPtr.Zero)
 {
     renderTarget.CreateSolidColorBrush(color, brushProperties, this);
 }
Esempio n. 7
0
        private void TxtView_D2DPaint(D2DGraphics g)
        {
            if (!string.IsNullOrWhiteSpace(BackGroundText) && !isHideBackGroundText)
            {
                g.RenderTarget.AntialiasMode = AntialiasMode.PerPrimitive;
                SolidColorBrush brush      = new SolidColorBrush(g.RenderTarget, GDIDataD2DUtils.TransToRawColor4(BackGroundTextColor));
                TextFormat      textFormat = new TextFormat(D2DGraphics.dwriteFactory, foreFont.FamilyName, foreFont.Weight, foreFont.Style, foreFont.Size)
                {
                    TextAlignment = TextAlignment.Leading, ParagraphAlignment = ParagraphAlignment.Center
                };

                textFormat.WordWrapping = WordWrapping.Wrap;

                SharpDX.RectangleF textRegionRect =
                    new SharpDX.RectangleF(0, 0, Width - 1, Height - 1);

                g.RenderTarget.DrawText(BackGroundText, textFormat, textRegionRect, brush, DrawTextOptions.Clip);
            }


            if (metricsList != null)
            {
                g.RenderTarget.AntialiasMode = AntialiasMode.Aliased;


                SharpDX.Direct2D1.Brush brush = new SolidColorBrush(g.RenderTarget, SharpDX.Color.SkyBlue);

                foreach (HitTestMetrics m in metricsList)
                {
                    SharpDX.RectangleF textRegionRect =
                        new SharpDX.RectangleF((float)Math.Ceiling(m.Left), (float)Math.Ceiling(m.Top), (float)Math.Ceiling(m.Width), (float)Math.Ceiling(m.Height));

                    g.RenderTarget.FillRectangle(textRegionRect, brush);
                }
            }

            g.RenderTarget.AntialiasMode = AntialiasMode.PerPrimitive;

            if (CurrentTextLayout != null && scTextRenderer != null)
            {
                CurrentTextLayout.Draw(scTextRenderer, 0, 0);
            }


            if (cursorState == 1)
            {
                g.RenderTarget.AntialiasMode = AntialiasMode.Aliased;

                RawRectangleF rect =
                    new RawRectangleF(
                        hitTestMetrics[cursorIdx].Left,
                        hitTestMetrics[cursorIdx].Top,
                        hitTestMetrics[cursorIdx].Left + hitTestMetrics[cursorIdx].Width,
                        hitTestMetrics[cursorIdx].Top + hitTestMetrics[cursorIdx].Height);

                RawVector2 pt0;
                RawVector2 pt1;

                if (isTrailingHit[cursorIdx] == false)
                {
                    pt0 = new RawVector2((float)Math.Ceiling(rect.Left), (float)Math.Ceiling(rect.Top));
                    pt1 = new RawVector2((float)Math.Ceiling(rect.Left), (float)Math.Ceiling(rect.Bottom));
                }
                else
                {
                    pt0 = new RawVector2((float)Math.Ceiling(rect.Right), (float)Math.Ceiling(rect.Top));
                    pt1 = new RawVector2((float)Math.Ceiling(rect.Right), (float)Math.Ceiling(rect.Bottom));
                }

                RawColor4 color = GDIDataD2DUtils.TransToRawColor4(Color.FromArgb(255, 255, 0, 0));
                SharpDX.Direct2D1.Brush brushx = new SolidColorBrush(g.RenderTarget, color);

                if (pt0.X == 0 && pt1.X == 0)
                {
                    pt1.X = pt0.X = 1;
                }

                g.RenderTarget.DrawLine(pt0, pt1, brushx);
            }
        }
        protected override void OnPaint(PaintEventArgs e)
        {
            lock (bufferLock)
            {
                try
                {
                    var gifEmotesOnScreen = new List <GifEmoteState>();

                    if (buffer == null)
                    {
                        buffer = context.Allocate(e.Graphics, ClientRectangle);
                    }

                    var g = buffer.Graphics;

                    g.Clear((App.ColorScheme.ChatBackground as SolidBrush).Color);

                    var borderPen = Selected ? App.ColorScheme.ChatBorderFocused : App.ColorScheme.ChatBorder;

                    g.SmoothingMode = SmoothingMode.AntiAlias;

                    // DRAW MESSAGES
                    var M = GetMessagesClone();

                    if (M != null && M.Length > 0)
                    {
                        var startIndex = Math.Max(0, (int)_scroll.Value);
                        if (startIndex < M.Length)
                        {
                            var yStart = MessagePadding.Top - (int)(M[startIndex].Height * (_scroll.Value % 1));
                            var h      = Height - MessagePadding.Top - MessagePadding.Bottom;

                            if (startIndex < M.Length)
                            {
                                var y = yStart;

                                //for (int i = 0; i < startIndex; i++)
                                //{
                                //    M[i].IsVisible = false;
                                //}

                                for (var i = startIndex; i < M.Length; i++)
                                {
                                    var msg = M[i];
                                    //msg.IsVisible = true;

                                    MessageRenderer.DrawMessage(g, msg, MessagePadding.Left, y, selection, i, !App.UseDirectX, gifEmotesOnScreen, allowMessageSeperator: AllowMessageSeperator);

                                    if (y - msg.Height > h)
                                    {
                                        //for (; i < M.Length; i++)
                                        //{
                                        //    M[i].IsVisible = false;
                                        //}

                                        break;
                                    }

                                    y += msg.Height;

                                    if (AppSettings.ChatShowLastReadMessageIndicator && LastReadMessage == msg && i != M.Length - 1)
                                    {
                                        g.FillRectangle(lastReadMessageBrush, 0, y, Width, 1);
                                    }
                                }

                                GifEmotesOnScreen = gifEmotesOnScreen;
                            }

                            if (App.UseDirectX)
                            {
                                SharpDX.Direct2D1.DeviceContextRenderTarget renderTarget = null;
                                var dc = g.GetHdc();

                                renderTarget = new SharpDX.Direct2D1.DeviceContextRenderTarget(MessageRenderer.D2D1Factory, MessageRenderer.RenderTargetProperties);

                                renderTarget.BindDeviceContext(dc, new RawRectangle(0, 0, Width, Height));

                                renderTarget.BeginDraw();

                                //renderTarget.TextRenderingParams = new SharpDX.DirectWrite.RenderingParams(Fonts.Factory, 1, 1, 1, SharpDX.DirectWrite.PixelGeometry.Flat, SharpDX.DirectWrite.RenderingMode.CleartypeGdiClassic);
                                renderTarget.TextAntialiasMode = SharpDX.Direct2D1.TextAntialiasMode.Grayscale;

                                var y = yStart;

                                var brushes = new Dictionary <RawColor4, SCB>();

                                var textColor = App.ColorScheme.Text;
                                var textBrush = new SCB(renderTarget, new RawColor4(textColor.R / 255f, textColor.G / 255f, textColor.B / 255f, 1));

                                for (var i = startIndex; i < M.Length; i++)
                                {
                                    var msg = M[i];

                                    foreach (var word in msg.Words)
                                    {
                                        if (word.Type == SpanType.Text)
                                        {
                                            SCB brush;

                                            if (word.Color == null)
                                            {
                                                brush = textBrush;
                                            }
                                            else
                                            {
                                                var hsl = word.Color.Value;

                                                if (App.ColorScheme.IsLightTheme)
                                                {
                                                    if (hsl.Saturation > 0.4f)
                                                    {
                                                        hsl = hsl.WithSaturation(0.4f);
                                                    }
                                                    if (hsl.Luminosity > 0.5f)
                                                    {
                                                        hsl = hsl.WithLuminosity(0.5f);
                                                    }
                                                }
                                                else
                                                {
                                                    if (hsl.Luminosity < 0.5f)
                                                    {
                                                        hsl = hsl.WithLuminosity(0.5f);
                                                    }

                                                    if (hsl.Luminosity < 0.6f && hsl.Hue > 0.54444 && hsl.Hue < 0.8333)
                                                    {
                                                        hsl = hsl.WithLuminosity(hsl.Luminosity + (float)Math.Sin((hsl.Hue - 0.54444) / (0.8333 - 0.54444) * Math.PI) * hsl.Saturation * 0.2f);
                                                    }

                                                    if (hsl.Luminosity < 0.8f && (hsl.Hue < 0.06 || hsl.Hue > 0.92))
                                                    {
                                                        hsl = hsl.WithLuminosity(hsl.Luminosity + (msg.HasAnyHighlightType(HighlightType.Highlighted) ? 0.27f : 0.1f) * hsl.Saturation);
                                                    }
                                                }

                                                if (hsl.Luminosity >= 0.95f)
                                                {
                                                    hsl = hsl.WithLuminosity(0.95f);
                                                }

                                                float r, _g, b;
                                                hsl.ToRGB(out r, out _g, out b);
                                                var color = new RawColor4(r, _g, b, 1f);

                                                if (!brushes.TryGetValue(color, out brush))
                                                {
                                                    brushes[color] = brush = new SCB(renderTarget, color);
                                                }
                                            }

                                            if (word.SplitSegments == null)
                                            {
                                                renderTarget.DrawText((string)word.Value, Fonts.GetTextFormat(word.Font), new RawRectangleF(MessagePadding.Left + word.X, y + word.Y, 10000, 10000), brush);
                                            }
                                            else
                                            {
                                                foreach (var split in word.SplitSegments)
                                                {
                                                    renderTarget.DrawText(split.Item1, Fonts.GetTextFormat(word.Font), new RawRectangleF(MessagePadding.Left + split.Item2.X, y + split.Item2.Y, 10000, 10000), brush);
                                                }
                                            }
                                        }
                                    }

                                    if (y - msg.Height > h)
                                    {
                                        break;
                                    }

                                    y += msg.Height;
                                }

                                foreach (var b in brushes.Values)
                                {
                                    b.Dispose();
                                }

                                renderTarget.EndDraw();

                                textBrush.Dispose();
                                g.ReleaseHdc(dc);
                                renderTarget.Dispose();
                            }

                            {
                                var y = yStart;

                                Brush disabledBrush = new SolidBrush(Color.FromArgb(172, (App.ColorScheme.ChatBackground as SolidBrush)?.Color ?? Color.Black));
                                for (var i = startIndex; i < M.Length; i++)
                                {
                                    var msg = M[i];

                                    if (msg.Disabled)
                                    {
                                        g.SmoothingMode = SmoothingMode.None;

                                        g.FillRectangle(disabledBrush, 0, y + 1, Width, msg.Height - 1);
                                    }

                                    if (y - msg.Height > h)
                                    {
                                        break;
                                    }

                                    y += msg.Height;
                                }
                                disabledBrush.Dispose();
                            }
                        }
                    }

                    g.DrawRectangle(borderPen, 0, 0, Width - 1, Height - 1);

                    OnPaintOnBuffer(g);

                    buffer.Render(e.Graphics);
                }
                catch (Exception exc)
                {
                    exc.Log("graphics");
                }
            }
        }
Esempio n. 9
0
 /// <summary>
 /// Sets the named property to the given value.
 /// </summary>
 /// <param name="name">Name of the property</param>
 /// <param name="value">Value of the property</param>
 /// <unmanaged>HRESULT ID2D1Properties::SetValueByName([In] const wchar_t* name,[In] D2D1_PROPERTY_TYPE type,[In, Buffer] const void* data,[In] unsigned int dataSize)</unmanaged>
 public unsafe void SetValueByName(string name, RawColor4 value)
 {
     SetValueByName(name, PropertyType.Vector4, new IntPtr(&value), sizeof(RawColor4));
 }
 private void BeginScene(RawColor4 givenColour)
 {
     DeviceContext.ClearDepthStencilView(DepthStencilView, DepthStencilClearFlags.Depth, 1, 0);
     DeviceContext.ClearRenderTargetView(RenderTargetView, givenColour);
 }
 public ID3D11BlendState OMGetBlendState(out RawColor4 blendFactor, out int sampleMask)
 {
     OMGetBlendState(out var blendState, out blendFactor, out sampleMask);
     return(blendState);
 }
Esempio n. 12
0
 /// <summary>
 /// Return a blackstart dimming color
 /// </summary>
 /// <param name="InColor"></param>
 /// <returns></returns>
 public RawColor4 BlackstartDim(RawColor4 InColor)
 {
     //return Color.FromArgb(BlackstartDimmingFactor , InColor);
     return(new RawColor4((InColor.R * BlackstartDimmingFactor) / 100, (InColor.G * BlackstartDimmingFactor) / 100, (InColor.B * BlackstartDimmingFactor) / 100, InColor.A));
 }
Esempio n. 13
0
 /// <summary>
 /// Function to convert a SharpDX raw color 4 type to a <see cref="GorgonColor"/>.
 /// </summary>
 /// <param name="color">The SharpDX raw color 4 type to convert.</param>
 /// <returns>A new <see cref="GorgonColor"/>.</returns>
 public static GorgonColor ToGorgonColor(this RawColor4 color) => new GorgonColor(color.R, color.G, color.B, color.A);
Esempio n. 14
0
        public void Draw(RawRectangle destinationRectangle, RawRectangle sourceRectangle, RawColor4 color, Single scale = 1.0f, Single angle = 0f, Single z = 0f)
        {
            Sprite sprite = new Sprite(sourceRectangle, destinationRectangle, color)
            {
                Scale = scale,
                Angle = angle,
                Z     = z
            };

            this.SpriteList.Add(sprite);
        }
 public static Color ToColor(this RawColor4 color)
 {
     return(new Color(color.R, color.G, color.B, color.A));
 }
Esempio n. 16
0
 /// <summary>
 /// Sets the named property to the given value.
 /// </summary>
 /// <param name="index">Index of the property</param>
 /// <param name="value">Value of the property</param>
 /// <unmanaged>HRESULT ID2D1Properties::SetValue([In] const wchar_t* name,[In] D2D1_PROPERTY_TYPE type,[In, Buffer] const void* data,[In] unsigned int dataSize)</unmanaged>
 public unsafe void SetValue(int index, RawColor4 value)
 {
     SetValue(index, PropertyType.Vector4, new IntPtr(&value), sizeof(RawColor4));
 }
Esempio n. 17
0
 /// <summary>
 /// Creates a new <see cref="SharpDX.Direct2D1.SolidColorBrush"/> that has the specified color and opacity.
 /// </summary>
 /// <param name="renderTarget">an instance of <see cref = "SharpDX.Direct2D1.RenderTarget" /></param>
 /// <param name="color">The red, green, blue, and alpha values of the brush's color.</param>
 public SolidColorBrush(RenderTarget renderTarget, RawColor4 color) : this(renderTarget, color, null)
 {
 }
Esempio n. 18
0
 public unsafe static Color4 Convert(RawColor4 color)
 {
     return(*(Color4 *)&color);
 }
Esempio n. 19
0
        private void InitTextFormatLayout()
        {
            if (d2d == null)
            {
                return;
            }

            TextMetrics metrics;
            SizeF       minSize;

            CurrentTextFormat = new TextFormat(D2DGraphics.dwriteFactory, foreFont.FamilyName, foreFont.Size);
            //{ TextAlignment = TextAlignment.Center, ParagraphAlignment = ParagraphAlignment.Center};

            CurrentTextFormat.WordWrapping = WordWrapping.NoWrap;

            CurrentTextLayout = new TextLayout(D2DGraphics.dwriteFactory, txt, CurrentTextFormat, 0, 0);

            metrics = CurrentTextLayout.Metrics;
            minSize = new SizeF(metrics.WidthIncludingTrailingWhitespace, metrics.Height);

            float w = (float)Math.Ceiling(minSize.Width);

            if (w > boxWidth)
            {
                Width = w;
            }
            else
            {
                Width = boxWidth;
            }

            Height = (float)Math.Ceiling(minSize.Height);



            RawColor4 rawColor = GDIDataD2DUtils.TransToRawColor4(foreColor);
            //RedDrawingeffect = new ColorDrawingEffect(rawColor);
            //CurrentTextLayout.SetDrawingEffect(RedDrawingeffect, new TextRange(0, txt.Count() - 1));

            SolidColorBrush brush = new SolidColorBrush(d2d.renderTarget, rawColor);

            CurrentTextLayout.SetDrawingEffect(brush, new TextRange(0, txt.Count()));



            //BlueDrawingEffect = new ColorDrawingEffect(SharpDX.Color.Blue);
            //GreenDrawingEffect = new ColorDrawingEffect(SharpDX.Color.Green);

            //CurrentTextLayout.SetFontSize(10.0f, new TextRange(6, 14));

            //CurrentTextLayout.SetDrawingEffect(BlueDrawingEffect, new TextRange(14, 7));
            //CurrentTextLayout.SetDrawingEffect(GreenDrawingEffect, new TextRange(21, 8));
            //CurrentTextLayout.SetUnderline(true, new TextRange(0, 20));
            //CurrentTextLayout.SetStrikethrough(true, new TextRange(22, 7));


            //SolidColorBrush greenBrush = new SolidColorBrush(d2d.renderTarget, SharpDX.Color.Black);
            //CurrentTextLayout.SetDrawingEffect(greenBrush, new TextRange(10, 1));

            /*
             * // Set a stylistic typography
             * using (var typo = new Typography(d2d.dwriteFactory))
             * {
             *  typo.AddFontFeature(new FontFeature(FontFeatureTag.StylisticSet7, 1));
             *  CurrentTextLayout.SetTypography(typo, CurrentTextRange);
             * }
             */
        }
Esempio n. 20
0
        void FillItemGeometry(D2DGraphics g)
        {
            g.RenderTarget.AntialiasMode = AntialiasMode.PerPrimitive;

            RawRectangleF    rect        = new RawRectangleF(1, 1, Width - 1, Height - 1);
            RoundedRectangle roundedRect = new RoundedRectangle()
            {
                RadiusX = this.RadiusX,
                RadiusY = this.RadiusY,
                Rect    = rect
            };

            GradientStop[] gradientStops = new GradientStop[5];

            gradientStops[0].Color    = GDIDataD2DUtils.TransToRawColor4(colors[0]);
            gradientStops[0].Position = 0f;

            gradientStops[1].Color    = GDIDataD2DUtils.TransToRawColor4(colors[1]);
            gradientStops[1].Position = 0.4f;

            gradientStops[2].Color    = GDIDataD2DUtils.TransToRawColor4(colors[2]);
            gradientStops[2].Position = 0.5f;

            gradientStops[3].Color    = GDIDataD2DUtils.TransToRawColor4(colors[1]);
            gradientStops[3].Position = 0.6f;

            gradientStops[4].Color    = GDIDataD2DUtils.TransToRawColor4(colors[0]);
            gradientStops[4].Position = 1f;

            //
            GradientStopCollection gradientStopCollection = new GradientStopCollection(g.RenderTarget, gradientStops, Gamma.StandardRgb, ExtendMode.Clamp);

            //
            LinearGradientBrushProperties props = new LinearGradientBrushProperties()
            {
                StartPoint = new RawVector2(rect.Left, rect.Top),
                EndPoint   = new RawVector2(rect.Left, rect.Bottom)
            };

            SharpDX.Direct2D1.LinearGradientBrush linearGradientBrush = new SharpDX.Direct2D1.LinearGradientBrush(g.RenderTarget, props, gradientStopCollection);
            g.RenderTarget.FillRoundedRectangle(roundedRect, linearGradientBrush);

            //
            gradientStops = new GradientStop[5];

            gradientStops[0].Color    = GDIDataD2DUtils.TransToRawColor4(colors[2]);
            gradientStops[0].Position = 0f;

            gradientStops[1].Color    = GDIDataD2DUtils.TransToRawColor4(colors[1]);
            gradientStops[1].Position = 0.1f;

            gradientStops[2].Color    = GDIDataD2DUtils.TransToRawColor4(colors[0]);
            gradientStops[2].Position = 0.5f;

            gradientStops[3].Color    = GDIDataD2DUtils.TransToRawColor4(colors[1]);
            gradientStops[3].Position = 0.9f;


            gradientStops[4].Color    = GDIDataD2DUtils.TransToRawColor4(colors[2]);
            gradientStops[4].Position = 1f;

            //
            gradientStopCollection = new GradientStopCollection(g.RenderTarget, gradientStops, Gamma.StandardRgb, ExtendMode.Clamp);

            //
            props = new LinearGradientBrushProperties()
            {
                StartPoint = new RawVector2(rect.Left, rect.Top),
                EndPoint   = new RawVector2(rect.Right, rect.Top)
            };

            linearGradientBrush = new SharpDX.Direct2D1.LinearGradientBrush(g.RenderTarget, props, gradientStopCollection);
            g.RenderTarget.FillRoundedRectangle(roundedRect, linearGradientBrush);



            RawColor4       rawColor = GDIDataD2DUtils.TransToRawColor4(Color.FromArgb(SideShadowAlpha, 0, 0, 0));
            SolidColorBrush brush    = new SolidColorBrush(g.RenderTarget, rawColor);

            g.RenderTarget.DrawRoundedRectangle(roundedRect, brush);
        }
Esempio n. 21
0
 //---------------------------------------------------------------------------------------------------------
 /// <summary>
 /// Сериализация цветового значения в строку
 /// </summary>
 /// <param name="color">Цветовое значение</param>
 /// <returns>Строка</returns>
 //---------------------------------------------------------------------------------------------------------
 public static String Serialize(this RawColor4 color)
 {
     return(String.Format("{0},{1},{2},{3}", color.R, color.G, color.B, color.A));
 }
Esempio n. 22
0
        static void Main()
        {
            var initError = EVRInitError.None;

            system = OpenVR.Init(ref initError);

            if (initError != EVRInitError.None)
            {
                return;
            }

            compositor = OpenVR.Compositor;

            compositor.CompositorBringToFront();
            compositor.FadeGrid(5.0f, false);

            count = OpenVR.k_unMaxTrackedDeviceCount;

            currentPoses = new TrackedDevicePose_t[count];
            nextPoses    = new TrackedDevicePose_t[count];

            controllers                    = new List <uint>();
            controllerModels               = new RenderModel_t[count];
            controllerTextures             = new RenderModel_TextureMap_t[count];
            controllerTextureViews         = new ShaderResourceView[count];
            controllerVertexBuffers        = new SharpDX.Direct3D11.Buffer[count];
            controllerIndexBuffers         = new SharpDX.Direct3D11.Buffer[count];
            controllerVertexBufferBindings = new VertexBufferBinding[count];

            for (uint device = 0; device < count; device++)
            {
                var deviceClass = system.GetTrackedDeviceClass(device);

                switch (deviceClass)
                {
                case ETrackedDeviceClass.HMD:
                    headset = device;
                    break;

                case ETrackedDeviceClass.Controller:
                    controllers.Add(device);
                    break;
                }
            }

            uint width  = 0;
            uint height = 0;

            system.GetRecommendedRenderTargetSize(ref width, ref height);

            headsetSize = new Size((int)width, (int)height);
            windowSize  = new Size(960, 540);

            var leftEyeProjection  = Convert(system.GetProjectionMatrix(EVREye.Eye_Left, 0.01f, 1000.0f));
            var rightEyeProjection = Convert(system.GetProjectionMatrix(EVREye.Eye_Right, 0.01f, 1000.0f));

            var leftEyeView  = Convert(system.GetEyeToHeadTransform(EVREye.Eye_Left));
            var rightEyeView = Convert(system.GetEyeToHeadTransform(EVREye.Eye_Right));

            foreach (var controller in controllers)
            {
                var modelName     = new StringBuilder(255, 255);
                var propertyError = ETrackedPropertyError.TrackedProp_Success;

                var length = system.GetStringTrackedDeviceProperty(controller, ETrackedDeviceProperty.Prop_RenderModelName_String, modelName, 255, ref propertyError);

                if (propertyError == ETrackedPropertyError.TrackedProp_Success)
                {
                    var modelName2 = modelName.ToString();

                    while (true)
                    {
                        var pointer    = IntPtr.Zero;
                        var modelError = EVRRenderModelError.None;

                        modelError = OpenVR.RenderModels.LoadRenderModel_Async(modelName2, ref pointer);

                        if (modelError == EVRRenderModelError.Loading)
                        {
                            continue;
                        }

                        if (modelError == EVRRenderModelError.None)
                        {
                            var renderModel = System.Runtime.InteropServices.Marshal.PtrToStructure <RenderModel_t>(pointer);

                            controllerModels[controller] = renderModel;
                            break;
                        }
                    }

                    while (true)
                    {
                        var pointer      = IntPtr.Zero;
                        var textureError = EVRRenderModelError.None;

                        textureError = OpenVR.RenderModels.LoadTexture_Async(controllerModels[controller].diffuseTextureId, ref pointer);

                        if (textureError == EVRRenderModelError.Loading)
                        {
                            continue;
                        }

                        if (textureError == EVRRenderModelError.None)
                        {
                            var texture = System.Runtime.InteropServices.Marshal.PtrToStructure <RenderModel_TextureMap_t>(pointer);

                            controllerTextures[controller] = texture;
                            break;
                        }
                    }
                }
            }

            int adapterIndex = 0;

            system.GetDXGIOutputInfo(ref adapterIndex);

            using (var form = new Form())
                using (var factory = new Factory4())
                {
                    form.ClientSize = windowSize;

                    var adapter = factory.GetAdapter(adapterIndex);

                    var swapChainDescription = new SwapChainDescription
                    {
                        BufferCount     = 1,
                        Flags           = SwapChainFlags.None,
                        IsWindowed      = true,
                        ModeDescription = new ModeDescription
                        {
                            Format      = Format.B8G8R8A8_UNorm,
                            Width       = form.ClientSize.Width,
                            Height      = form.ClientSize.Height,
                            RefreshRate = new Rational(60, 1)
                        },
                        OutputHandle      = form.Handle,
                        SampleDescription = new SampleDescription(1, 0),
                        SwapEffect        = SwapEffect.Discard,
                        Usage             = Usage.RenderTargetOutput
                    };

                    SharpDX.Direct3D11.Device.CreateWithSwapChain(adapter, DeviceCreationFlags.None, swapChainDescription, out device, out swapChain);

                    factory.MakeWindowAssociation(form.Handle, WindowAssociationFlags.None);

                    context = device.ImmediateContext;

                    using (var backBuffer = swapChain.GetBackBuffer <Texture2D>(0))
                        backBufferView = new RenderTargetView(device, backBuffer);

                    var depthBufferDescription = new Texture2DDescription
                    {
                        Format            = Format.D16_UNorm,
                        ArraySize         = 1,
                        MipLevels         = 1,
                        Width             = form.ClientSize.Width,
                        Height            = form.ClientSize.Height,
                        SampleDescription = new SampleDescription(1, 0),
                        Usage             = ResourceUsage.Default,
                        BindFlags         = BindFlags.DepthStencil,
                        CpuAccessFlags    = CpuAccessFlags.None,
                        OptionFlags       = ResourceOptionFlags.None
                    };

                    using (var depthBuffer = new Texture2D(device, depthBufferDescription))
                        depthStencilView = new DepthStencilView(device, depthBuffer);

                    // Create Eye Textures
                    var eyeTextureDescription = new Texture2DDescription
                    {
                        ArraySize         = 1,
                        BindFlags         = BindFlags.RenderTarget,
                        CpuAccessFlags    = CpuAccessFlags.None,
                        Format            = Format.B8G8R8A8_UNorm,
                        Width             = headsetSize.Width,
                        Height            = headsetSize.Height,
                        MipLevels         = 1,
                        OptionFlags       = ResourceOptionFlags.None,
                        SampleDescription = new SampleDescription(1, 0),
                        Usage             = ResourceUsage.Default
                    };

                    var leftEyeTexture  = new Texture2D(device, eyeTextureDescription);
                    var rightEyeTexture = new Texture2D(device, eyeTextureDescription);

                    var leftEyeTextureView  = new RenderTargetView(device, leftEyeTexture);
                    var rightEyeTextureView = new RenderTargetView(device, rightEyeTexture);

                    // Create Eye Depth Buffer
                    eyeTextureDescription.BindFlags = BindFlags.DepthStencil;
                    eyeTextureDescription.Format    = Format.D32_Float;

                    var eyeDepth     = new Texture2D(device, eyeTextureDescription);
                    var eyeDepthView = new DepthStencilView(device, eyeDepth);

                    Shapes.Cube.Load(device);
                    Shapes.Sphere.Load(device);
                    Shaders.Position.Load(device);
                    Shaders.Normal.Load(device);
                    Shaders.NormalTexture.Load(device);

                    // Load Controller Models
                    foreach (var controller in controllers)
                    {
                        var model = controllerModels[controller];

                        controllerVertexBuffers[controller] = new SharpDX.Direct3D11.Buffer(device, model.rVertexData, new BufferDescription
                        {
                            BindFlags   = BindFlags.VertexBuffer,
                            SizeInBytes = (int)model.unVertexCount * 32
                        });

                        controllerVertexBufferBindings[controller] = new VertexBufferBinding(controllerVertexBuffers[controller], 32, 0);

                        controllerIndexBuffers[controller] = new SharpDX.Direct3D11.Buffer(device, model.rIndexData, new BufferDescription
                        {
                            BindFlags   = BindFlags.IndexBuffer,
                            SizeInBytes = (int)model.unTriangleCount * 3 * 2
                        });

                        var texture = controllerTextures[controller];

                        using (var texture2d = new Texture2D(device, new Texture2DDescription
                        {
                            ArraySize = 1,
                            BindFlags = BindFlags.ShaderResource,
                            Format = Format.R8G8B8A8_UNorm,
                            Width = texture.unWidth,
                            Height = texture.unHeight,
                            MipLevels = 1,
                            SampleDescription = new SampleDescription(1, 0)
                        }, new DataRectangle(texture.rubTextureMapData, texture.unWidth * 4)))
                            controllerTextureViews[controller] = new ShaderResourceView(device, texture2d);
                    }

                    worldViewProjectionBuffer = new SharpDX.Direct3D11.Buffer(device, Utilities.SizeOf <Matrix>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);

                    var rasterizerStateDescription = RasterizerStateDescription.Default();
                    //rasterizerStateDescription.FillMode = FillMode.Wireframe;
                    rasterizerStateDescription.IsFrontCounterClockwise = true;
                    //rasterizerStateDescription.CullMode = CullMode.None;

                    rasterizerState = new RasterizerState(device, rasterizerStateDescription);

                    var blendStateDescription = BlendStateDescription.Default();

                    blendStateDescription.RenderTarget[0].BlendOperation   = BlendOperation.Add;
                    blendStateDescription.RenderTarget[0].SourceBlend      = BlendOption.SourceAlpha;
                    blendStateDescription.RenderTarget[0].DestinationBlend = BlendOption.InverseSourceAlpha;

                    blendStateDescription.RenderTarget[0].IsBlendEnabled = false;

                    blendState = new BlendState(device, blendStateDescription);

                    var depthStateDescription = DepthStencilStateDescription.Default();

                    depthStateDescription.DepthComparison  = Comparison.LessEqual;
                    depthStateDescription.IsDepthEnabled   = true;
                    depthStateDescription.IsStencilEnabled = false;

                    depthStencilState = new DepthStencilState(device, depthStateDescription);

                    var samplerStateDescription = SamplerStateDescription.Default();

                    samplerStateDescription.Filter   = Filter.MinMagMipLinear;
                    samplerStateDescription.AddressU = TextureAddressMode.Wrap;
                    samplerStateDescription.AddressV = TextureAddressMode.Wrap;

                    samplerState = new SamplerState(device, samplerStateDescription);

                    startTime  = DateTime.Now;
                    frame      = 0;
                    windowSize = form.ClientSize;

                    backgroundColor = new RawColor4(0.1f, 0.1f, 0.1f, 1);

                    var vrEvent   = new VREvent_t();
                    var eventSize = (uint)Utilities.SizeOf <VREvent_t>();

                    head = Matrix.Identity;

                    // Initialize Audio
                    var audioSamples = 1024;

                    var audioDevices = DirectSoundCapture.GetDevices();

                    //var audioCapture = new DirectSoundCapture(devices.OrderByDescending(d => d.Description.Contains("Mic")).First().DriverGuid);
                    var audioCapture = new DirectSoundCapture(audioDevices.OrderByDescending(d => d.Description.Contains("Mix")).First().DriverGuid);

                    var audioFormat = new WaveFormat();
                    var audioLength = audioFormat.ConvertLatencyToByteSize(24);

                    var audioData     = new byte[audioLength];
                    var audioPosition = 0;

                    var leftWaveForm  = new float[1024 * 8];
                    var rightWaveForm = new float[1024 * 8];

                    for (var sample = 0; sample < 1024; sample++)
                    {
                        leftWaveForm[(sample * 8) + 0]  = -1.0f + ((float)sample / 512.0f);
                        rightWaveForm[(sample * 8) + 0] = -1.0f + ((float)sample / 512.0f);
                    }

                    var audioBuffer = new CaptureBuffer(audioCapture, new CaptureBufferDescription
                    {
                        BufferBytes = audioLength,
                        Format      = audioFormat
                    });

                    audioBuffer.Start(true);

                    var waveFormBufferDescription = new BufferDescription
                    {
                        BindFlags      = BindFlags.VertexBuffer,
                        SizeInBytes    = leftWaveForm.Length * sizeof(float),
                        CpuAccessFlags = CpuAccessFlags.Write,
                        Usage          = ResourceUsage.Dynamic
                    };

                    var leftWaveFormVertexBuffer  = SharpDX.Direct3D11.Buffer.Create(device, leftWaveForm, waveFormBufferDescription);
                    var rightWaveFormVertexBuffer = SharpDX.Direct3D11.Buffer.Create(device, rightWaveForm, waveFormBufferDescription);

                    var leftWaveFormVertexBufferBinding  = new VertexBufferBinding(leftWaveFormVertexBuffer, 8 * sizeof(float), 0);
                    var rightWaveFormVertexBufferBinding = new VertexBufferBinding(rightWaveFormVertexBuffer, 8 * sizeof(float), 0);

                    RenderLoop.Run(form, () =>
                    {
                        if (audioBuffer.CurrentCapturePosition != audioBuffer.CurrentRealPosition)
                        {
                            audioBuffer.Read(audioData, 0, audioData.Length, 0, LockFlags.None);

                            for (var sample = 0; sample < 1024; sample++)
                            {
                                leftWaveForm[(sample * 8) + 1]  = -BitConverter.ToInt16(audioData, sample * 4) / (float)short.MinValue;
                                rightWaveForm[(sample * 8) + 1] = -BitConverter.ToInt16(audioData, (sample * 4) + 2) / (float)short.MinValue;
                            }

                            DataStream stream;

                            context.MapSubresource(leftWaveFormVertexBuffer, 0, MapMode.WriteDiscard, SharpDX.Direct3D11.MapFlags.None, out stream);

                            stream.WriteRange(leftWaveForm);

                            context.UnmapSubresource(leftWaveFormVertexBuffer, 0);

                            stream.Dispose();

                            context.MapSubresource(rightWaveFormVertexBuffer, 0, MapMode.WriteDiscard, SharpDX.Direct3D11.MapFlags.None, out stream);

                            stream.WriteRange(rightWaveForm);

                            context.UnmapSubresource(rightWaveFormVertexBuffer, 0);

                            stream.Dispose();
                        }

                        audioPosition += 8;

                        if (audioPosition >= leftWaveForm.Length)
                        {
                            audioPosition = 0;
                        }

                        while (system.PollNextEvent(ref vrEvent, eventSize))
                        {
                            switch ((EVREventType)vrEvent.eventType)
                            {
                            case EVREventType.VREvent_TrackedDeviceActivated:
                                var controller = vrEvent.trackedDeviceIndex;

                                controllers.Add(controller);

                                var modelName     = new StringBuilder(255, 255);
                                var propertyError = ETrackedPropertyError.TrackedProp_Success;

                                var length = system.GetStringTrackedDeviceProperty(controller, ETrackedDeviceProperty.Prop_RenderModelName_String, modelName, 255, ref propertyError);

                                if (propertyError == ETrackedPropertyError.TrackedProp_Success)
                                {
                                    var modelName2 = modelName.ToString();

                                    while (true)
                                    {
                                        var pointer    = IntPtr.Zero;
                                        var modelError = EVRRenderModelError.None;

                                        modelError = OpenVR.RenderModels.LoadRenderModel_Async(modelName2, ref pointer);

                                        if (modelError == EVRRenderModelError.Loading)
                                        {
                                            continue;
                                        }

                                        if (modelError == EVRRenderModelError.None)
                                        {
                                            var renderModel = System.Runtime.InteropServices.Marshal.PtrToStructure <RenderModel_t>(pointer);

                                            controllerModels[controller] = renderModel;

                                            // Load Controller Model
                                            var model = controllerModels[controller];

                                            controllerVertexBuffers[controller] = new SharpDX.Direct3D11.Buffer(device, model.rVertexData, new BufferDescription
                                            {
                                                BindFlags   = BindFlags.VertexBuffer,
                                                SizeInBytes = (int)model.unVertexCount * 32
                                            });

                                            controllerVertexBufferBindings[controller] = new VertexBufferBinding(controllerVertexBuffers[controller], 32, 0);

                                            controllerIndexBuffers[controller] = new SharpDX.Direct3D11.Buffer(device, model.rIndexData, new BufferDescription
                                            {
                                                BindFlags   = BindFlags.IndexBuffer,
                                                SizeInBytes = (int)model.unTriangleCount * 3 * 2
                                            });

                                            break;
                                        }
                                    }

                                    while (true)
                                    {
                                        var pointer      = IntPtr.Zero;
                                        var textureError = EVRRenderModelError.None;

                                        textureError = OpenVR.RenderModels.LoadTexture_Async(controllerModels[controller].diffuseTextureId, ref pointer);

                                        if (textureError == EVRRenderModelError.Loading)
                                        {
                                            continue;
                                        }

                                        if (textureError == EVRRenderModelError.None)
                                        {
                                            var textureMap = System.Runtime.InteropServices.Marshal.PtrToStructure <RenderModel_TextureMap_t>(pointer);

                                            controllerTextures[controller] = textureMap;

                                            using (var texture2d = new Texture2D(device, new Texture2DDescription
                                            {
                                                ArraySize = 1,
                                                BindFlags = BindFlags.ShaderResource,
                                                Format = Format.R8G8B8A8_UNorm,
                                                Width = textureMap.unWidth,
                                                Height = textureMap.unHeight,
                                                MipLevels = 1,
                                                SampleDescription = new SampleDescription(1, 0)
                                            }, new DataRectangle(textureMap.rubTextureMapData, textureMap.unWidth * 4)))
                                                controllerTextureViews[controller] = new ShaderResourceView(device, texture2d);

                                            break;
                                        }
                                    }
                                }
                                break;

                            case EVREventType.VREvent_TrackedDeviceDeactivated:
                                controllers.RemoveAll(c => c == vrEvent.trackedDeviceIndex);
                                break;

                            default:
                                System.Diagnostics.Debug.WriteLine((EVREventType)vrEvent.eventType);
                                break;
                            }
                        }

                        if (form.ClientSize != windowSize)
                        {
                            Utilities.Dispose(ref backBufferView);

                            if (form.ClientSize.Width != 0 && form.ClientSize.Height != 0)
                            {
                                swapChain.ResizeBuffers(1, form.ClientSize.Width, form.ClientSize.Height, Format.B8G8R8A8_UNorm, SwapChainFlags.None);

                                using (var backBuffer = swapChain.GetBackBuffer <Texture2D>(0))
                                    backBufferView = new RenderTargetView(device, backBuffer);
                            }

                            windowSize = form.ClientSize;
                        }

                        // Update Device Tracking
                        compositor.WaitGetPoses(currentPoses, nextPoses);

                        if (currentPoses[headset].bPoseIsValid)
                        {
                            Convert(ref currentPoses[headset].mDeviceToAbsoluteTracking, ref head);
                        }

                        foreach (var controller in controllers)
                        {
                            var controllerMatrix = Matrix.Identity;

                            Convert(ref currentPoses[controller].mDeviceToAbsoluteTracking, ref controllerMatrix);
                        }

                        // Render Left Eye
                        context.Rasterizer.SetViewport(0, 0, headsetSize.Width, headsetSize.Height);
                        context.OutputMerger.SetTargets(eyeDepthView, leftEyeTextureView);
                        context.OutputMerger.SetDepthStencilState(depthStencilState);

                        context.ClearRenderTargetView(leftEyeTextureView, backgroundColor);
                        context.ClearDepthStencilView(eyeDepthView, DepthStencilClearFlags.Depth, 1.0f, 0);

                        Shaders.Normal.Apply(context);

                        context.Rasterizer.State = rasterizerState;

                        context.OutputMerger.SetBlendState(blendState);
                        context.OutputMerger.SetDepthStencilState(depthStencilState);

                        context.PixelShader.SetSampler(0, samplerState);

                        var ratio = (float)headsetSize.Width / (float)headsetSize.Height;

                        var projection = leftEyeProjection;
                        var view       = Matrix.Invert(leftEyeView * head);
                        var world      = Matrix.Scaling(1.0f + (Math.Abs(leftWaveForm[audioPosition + 1]) * 0.1f)) * Matrix.Translation(0, 1.0f, 0);

                        worldViewProjection = world * view * projection;

                        context.UpdateSubresource(ref worldViewProjection, worldViewProjectionBuffer);

                        context.VertexShader.SetConstantBuffer(0, worldViewProjectionBuffer);

                        //Shapes.Cube.Begin(context);
                        //Shapes.Cube.Draw(context);

                        Shapes.Sphere.Begin(context);
                        Shapes.Sphere.Draw(context);

                        // Draw Controllers
                        context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;

                        Shaders.NormalTexture.Apply(context);

                        context.PixelShader.SetSampler(0, samplerState);

                        foreach (var controller in controllers)
                        {
                            context.InputAssembler.SetVertexBuffers(0, controllerVertexBufferBindings[controller]);
                            context.InputAssembler.SetIndexBuffer(controllerIndexBuffers[controller], Format.R16_UInt, 0);

                            context.PixelShader.SetShaderResource(0, controllerTextureViews[controller]);

                            Convert(ref currentPoses[controller].mDeviceToAbsoluteTracking, ref world);

                            world = Matrix.Scaling(1.0f + (Math.Abs(leftWaveForm[audioPosition + 1]) * 0.5f)) * world;

                            worldViewProjection = world * view * projection;

                            context.UpdateSubresource(ref worldViewProjection, worldViewProjectionBuffer);

                            context.VertexShader.SetConstantBuffer(0, worldViewProjectionBuffer);

                            context.DrawIndexed((int)controllerModels[controller].unTriangleCount * 3 * 4, 0, 0);
                        }

                        // Draw Waveforms
                        Shaders.Position.Apply(context);

                        world = Matrix.Scaling(100, 2.5f, 1) * Matrix.Translation(0, 1, 1);

                        worldViewProjection = world * view * projection;

                        context.UpdateSubresource(ref worldViewProjection, worldViewProjectionBuffer);

                        context.InputAssembler.PrimitiveTopology = PrimitiveTopology.LineStrip;

                        context.InputAssembler.SetVertexBuffers(0, leftWaveFormVertexBufferBinding);

                        context.Draw(1024, 0);

                        world = Matrix.Scaling(100, 2.5f, 1) * Matrix.Translation(0, 1, -1);

                        worldViewProjection = world * view * projection;

                        context.UpdateSubresource(ref worldViewProjection, worldViewProjectionBuffer);

                        context.InputAssembler.SetVertexBuffers(0, rightWaveFormVertexBufferBinding);

                        context.Draw(1024, 0);

                        // Present Left Eye
                        var texture = new Texture_t
                        {
                            eType       = ETextureType.DirectX,
                            eColorSpace = EColorSpace.Gamma,
                            handle      = leftEyeTextureView.Resource.NativePointer
                        };

                        var bounds = new VRTextureBounds_t
                        {
                            uMin = 0.0f,
                            uMax = 1.0f,
                            vMin = 0.0f,
                            vMax = 1.0f,
                        };

                        var submitError = compositor.Submit(EVREye.Eye_Left, ref texture, ref bounds, EVRSubmitFlags.Submit_Default);

                        if (submitError != EVRCompositorError.None)
                        {
                            System.Diagnostics.Debug.WriteLine(submitError);
                        }

                        // Render Right Eye
                        context.Rasterizer.SetViewport(0, 0, headsetSize.Width, headsetSize.Height);
                        context.OutputMerger.SetTargets(eyeDepthView, rightEyeTextureView);
                        context.OutputMerger.SetDepthStencilState(depthStencilState);

                        context.ClearRenderTargetView(rightEyeTextureView, backgroundColor);
                        context.ClearDepthStencilView(eyeDepthView, DepthStencilClearFlags.Depth, 1.0f, 0);

                        Shaders.Normal.Apply(context);

                        context.Rasterizer.State = rasterizerState;

                        context.OutputMerger.SetBlendState(blendState);
                        context.OutputMerger.SetDepthStencilState(depthStencilState);

                        context.PixelShader.SetSampler(0, samplerState);

                        projection = rightEyeProjection;
                        view       = Matrix.Invert(rightEyeView * head);
                        world      = Matrix.Scaling(1.0f + (Math.Abs(leftWaveForm[audioPosition + 1]) * 0.1f)) * Matrix.Translation(0, 1.0f, 0);

                        worldViewProjection = world * view * projection;

                        context.UpdateSubresource(ref worldViewProjection, worldViewProjectionBuffer);

                        context.VertexShader.SetConstantBuffer(0, worldViewProjectionBuffer);

                        //Shapes.Cube.Begin(context);
                        //Shapes.Cube.Draw(context);

                        Shapes.Sphere.Begin(context);
                        Shapes.Sphere.Draw(context);

                        // Draw Controllers
                        context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;

                        Shaders.NormalTexture.Apply(context);

                        context.PixelShader.SetSampler(0, samplerState);

                        foreach (var controller in controllers)
                        {
                            context.InputAssembler.SetVertexBuffers(0, controllerVertexBufferBindings[controller]);
                            context.InputAssembler.SetIndexBuffer(controllerIndexBuffers[controller], Format.R16_UInt, 0);

                            context.PixelShader.SetShaderResource(0, controllerTextureViews[controller]);

                            Convert(ref currentPoses[controller].mDeviceToAbsoluteTracking, ref world);

                            world = Matrix.Scaling(1.0f + (Math.Abs(leftWaveForm[audioPosition + 1]) * 0.5f)) * world;

                            worldViewProjection = world * view * projection;

                            context.UpdateSubresource(ref worldViewProjection, worldViewProjectionBuffer);

                            context.VertexShader.SetConstantBuffer(0, worldViewProjectionBuffer);

                            context.DrawIndexed((int)controllerModels[controller].unTriangleCount * 3 * 4, 0, 0);
                        }

                        // Draw Waveforms
                        Shaders.Position.Apply(context);

                        world = Matrix.Scaling(100, 2.5f, 1) * Matrix.Translation(0, 1, 1);

                        worldViewProjection = world * view * projection;

                        context.UpdateSubresource(ref worldViewProjection, worldViewProjectionBuffer);

                        context.InputAssembler.PrimitiveTopology = PrimitiveTopology.LineStrip;

                        context.InputAssembler.SetVertexBuffers(0, leftWaveFormVertexBufferBinding);

                        context.Draw(1024, 0);

                        world = Matrix.Scaling(100, 2.5f, 1) * Matrix.Translation(0, 1, -1);

                        worldViewProjection = world * view * projection;

                        context.UpdateSubresource(ref worldViewProjection, worldViewProjectionBuffer);

                        context.InputAssembler.SetVertexBuffers(0, rightWaveFormVertexBufferBinding);

                        context.Draw(1024, 0);

                        // Present Right Eye
                        texture.handle = rightEyeTextureView.Resource.NativePointer;

                        submitError = compositor.Submit(EVREye.Eye_Right, ref texture, ref bounds, EVRSubmitFlags.Submit_Default);

                        if (submitError != EVRCompositorError.None)
                        {
                            System.Diagnostics.Debug.WriteLine(submitError);
                        }

                        // Render Window
                        context.Rasterizer.SetViewport(0, 0, windowSize.Width, windowSize.Height);

                        context.OutputMerger.SetTargets(depthStencilView, backBufferView);
                        context.OutputMerger.SetDepthStencilState(depthStencilState);

                        context.ClearRenderTargetView(backBufferView, backgroundColor);
                        context.ClearDepthStencilView(depthStencilView, DepthStencilClearFlags.Depth, 1.0f, 0);

                        Shaders.Normal.Apply(context);

                        context.Rasterizer.State = rasterizerState;

                        context.OutputMerger.SetBlendState(blendState);
                        context.OutputMerger.SetDepthStencilState(depthStencilState);

                        context.PixelShader.SetSampler(0, samplerState);

                        ratio = (float)form.ClientSize.Width / (float)form.ClientSize.Height;

                        projection = Matrix.PerspectiveFovRH(3.14f / 3.0f, ratio, 0.01f, 1000);
                        view       = Matrix.Invert(head);
                        world      = Matrix.Scaling(1.0f + (Math.Abs(leftWaveForm[audioPosition + 1]) * 0.1f)) * Matrix.Translation(0, 1.0f, 0);

                        worldViewProjection = world * view * projection;

                        context.UpdateSubresource(ref worldViewProjection, worldViewProjectionBuffer);

                        context.VertexShader.SetConstantBuffer(0, worldViewProjectionBuffer);

                        //Shapes.Cube.Begin(context);
                        //Shapes.Cube.Draw(context);

                        Shapes.Sphere.Begin(context);
                        Shapes.Sphere.Draw(context);

                        // Draw Controllers
                        context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;

                        Shaders.NormalTexture.Apply(context);

                        context.PixelShader.SetSampler(0, samplerState);

                        foreach (var controller in controllers)
                        {
                            context.InputAssembler.SetVertexBuffers(0, controllerVertexBufferBindings[controller]);
                            context.InputAssembler.SetIndexBuffer(controllerIndexBuffers[controller], Format.R16_UInt, 0);

                            Convert(ref currentPoses[controller].mDeviceToAbsoluteTracking, ref world);

                            world = Matrix.Scaling(1.0f + (Math.Abs(leftWaveForm[audioPosition + 1]) * 0.5f)) * world;

                            worldViewProjection = world * view * projection;

                            context.UpdateSubresource(ref worldViewProjection, worldViewProjectionBuffer);

                            context.VertexShader.SetConstantBuffer(0, worldViewProjectionBuffer);

                            context.DrawIndexed((int)controllerModels[controller].unTriangleCount * 3 * 4, 0, 0);
                        }

                        // Draw Waveforms
                        Shaders.Position.Apply(context);

                        world = Matrix.Scaling(100, 2.5f, 1) * Matrix.Translation(0, 1, 1);

                        worldViewProjection = world * view * projection;

                        context.UpdateSubresource(ref worldViewProjection, worldViewProjectionBuffer);

                        context.InputAssembler.PrimitiveTopology = PrimitiveTopology.LineStrip;

                        context.InputAssembler.SetVertexBuffers(0, leftWaveFormVertexBufferBinding);

                        context.Draw(1024, 0);

                        world = Matrix.Scaling(100, 2.5f, 1) * Matrix.Translation(0, 1, -1);

                        worldViewProjection = world * view * projection;

                        context.UpdateSubresource(ref worldViewProjection, worldViewProjectionBuffer);

                        context.InputAssembler.SetVertexBuffers(0, rightWaveFormVertexBufferBinding);

                        context.Draw(1024, 0);

                        // Show Backbuffer
                        swapChain.Present(0, PresentFlags.None);
                    });
                }
        }
Esempio n. 23
0
 public void ClearRenderTargetView(RenderTargetView view, RawColor4 color)
 {
     context.ClearRenderTargetView(view, color);
 }
Esempio n. 24
0
        static void Main()
        {
            var initError = EVRInitError.None;

            system = OpenVR.Init(ref initError);

            if (initError != EVRInitError.None)
            {
                return;
            }

            compositor = OpenVR.Compositor;

            compositor.CompositorBringToFront();
            compositor.FadeGrid(5.0f, false);

            count = OpenVR.k_unMaxTrackedDeviceCount;

            currentPoses = new TrackedDevicePose_t[count];
            nextPoses    = new TrackedDevicePose_t[count];

            controllers                    = new List <uint>();
            controllerModels               = new RenderModel_t[count];
            controllerTextures             = new RenderModel_TextureMap_t[count];
            controllerTextureViews         = new ShaderResourceView[count];
            controllerVertexBuffers        = new SharpDX.Direct3D11.Buffer[count];
            controllerIndexBuffers         = new SharpDX.Direct3D11.Buffer[count];
            controllerVertexBufferBindings = new VertexBufferBinding[count];
            controllerEmitters             = new Emitter[count];
            controllerVoices               = new SourceVoice[count];

            for (uint device = 0; device < count; device++)
            {
                var deviceClass = system.GetTrackedDeviceClass(device);

                switch (deviceClass)
                {
                case ETrackedDeviceClass.HMD:
                    headset = device;
                    break;

                case ETrackedDeviceClass.Controller:
                    controllers.Add(device);
                    break;
                }
            }

            uint width  = 0;
            uint height = 0;

            system.GetRecommendedRenderTargetSize(ref width, ref height);

            headsetSize = new Size((int)width, (int)height);
            windowSize  = new Size(960, 540);

            var leftEyeProjection  = Convert(system.GetProjectionMatrix(EVREye.Eye_Left, 0.01f, 1000.0f));
            var rightEyeProjection = Convert(system.GetProjectionMatrix(EVREye.Eye_Right, 0.01f, 1000.0f));

            var leftEyeView  = Convert(system.GetEyeToHeadTransform(EVREye.Eye_Left));
            var rightEyeView = Convert(system.GetEyeToHeadTransform(EVREye.Eye_Right));

            foreach (var controller in controllers)
            {
                var modelName     = new StringBuilder(255, 255);
                var propertyError = ETrackedPropertyError.TrackedProp_Success;

                var length = system.GetStringTrackedDeviceProperty(controller, ETrackedDeviceProperty.Prop_RenderModelName_String, modelName, 255, ref propertyError);

                if (propertyError == ETrackedPropertyError.TrackedProp_Success)
                {
                    var modelName2 = modelName.ToString();

                    while (true)
                    {
                        var pointer    = IntPtr.Zero;
                        var modelError = EVRRenderModelError.None;

                        modelError = OpenVR.RenderModels.LoadRenderModel_Async(modelName2, ref pointer);

                        if (modelError == EVRRenderModelError.Loading)
                        {
                            continue;
                        }

                        if (modelError == EVRRenderModelError.None)
                        {
                            var renderModel = System.Runtime.InteropServices.Marshal.PtrToStructure <RenderModel_t>(pointer);

                            controllerModels[controller] = renderModel;
                            break;
                        }
                    }

                    while (true)
                    {
                        var pointer      = IntPtr.Zero;
                        var textureError = EVRRenderModelError.None;

                        textureError = OpenVR.RenderModels.LoadTexture_Async(controllerModels[controller].diffuseTextureId, ref pointer);

                        if (textureError == EVRRenderModelError.Loading)
                        {
                            continue;
                        }

                        if (textureError == EVRRenderModelError.None)
                        {
                            var texture = System.Runtime.InteropServices.Marshal.PtrToStructure <RenderModel_TextureMap_t>(pointer);

                            controllerTextures[controller] = texture;
                            break;
                        }
                    }
                }
            }

            int adapterIndex = 0;

            system.GetDXGIOutputInfo(ref adapterIndex);

            using (var form = new Form())
                using (var factory = new Factory4())
                {
                    form.ClientSize = windowSize;

                    var adapter = factory.GetAdapter(adapterIndex);

                    var swapChainDescription = new SwapChainDescription
                    {
                        BufferCount     = 1,
                        Flags           = SwapChainFlags.None,
                        IsWindowed      = true,
                        ModeDescription = new ModeDescription
                        {
                            Format      = Format.B8G8R8A8_UNorm,
                            Width       = form.ClientSize.Width,
                            Height      = form.ClientSize.Height,
                            RefreshRate = new Rational(60, 1)
                        },
                        OutputHandle      = form.Handle,
                        SampleDescription = new SampleDescription(1, 0),
                        SwapEffect        = SwapEffect.Discard,
                        Usage             = Usage.RenderTargetOutput
                    };

                    SharpDX.Direct3D11.Device.CreateWithSwapChain(adapter, DeviceCreationFlags.None, swapChainDescription, out device, out swapChain);

                    factory.MakeWindowAssociation(form.Handle, WindowAssociationFlags.None);

                    context = device.ImmediateContext;

                    using (var backBuffer = swapChain.GetBackBuffer <Texture2D>(0))
                        backBufferView = new RenderTargetView(device, backBuffer);

                    var depthBufferDescription = new Texture2DDescription
                    {
                        Format            = Format.D16_UNorm,
                        ArraySize         = 1,
                        MipLevels         = 1,
                        Width             = form.ClientSize.Width,
                        Height            = form.ClientSize.Height,
                        SampleDescription = new SampleDescription(1, 0),
                        Usage             = ResourceUsage.Default,
                        BindFlags         = BindFlags.DepthStencil,
                        CpuAccessFlags    = CpuAccessFlags.None,
                        OptionFlags       = ResourceOptionFlags.None
                    };

                    using (var depthBuffer = new Texture2D(device, depthBufferDescription))
                        depthStencilView = new DepthStencilView(device, depthBuffer);

                    // Create Eye Textures
                    var eyeTextureDescription = new Texture2DDescription
                    {
                        ArraySize         = 1,
                        BindFlags         = BindFlags.RenderTarget,
                        CpuAccessFlags    = CpuAccessFlags.None,
                        Format            = Format.B8G8R8A8_UNorm,
                        Width             = headsetSize.Width,
                        Height            = headsetSize.Height,
                        MipLevels         = 1,
                        OptionFlags       = ResourceOptionFlags.None,
                        SampleDescription = new SampleDescription(1, 0),
                        Usage             = ResourceUsage.Default
                    };

                    var leftEyeTexture  = new Texture2D(device, eyeTextureDescription);
                    var rightEyeTexture = new Texture2D(device, eyeTextureDescription);

                    var leftEyeTextureView  = new RenderTargetView(device, leftEyeTexture);
                    var rightEyeTextureView = new RenderTargetView(device, rightEyeTexture);

                    // Create Eye Depth Buffer
                    eyeTextureDescription.BindFlags = BindFlags.DepthStencil;
                    eyeTextureDescription.Format    = Format.D32_Float;

                    var eyeDepth     = new Texture2D(device, eyeTextureDescription);
                    var eyeDepthView = new DepthStencilView(device, eyeDepth);

                    Shapes.Cube.Load(device);
                    Shapes.Sphere.Load(device);
                    Shaders.Load(device);

                    // Load Controller Models
                    foreach (var controller in controllers)
                    {
                        var model = controllerModels[controller];

                        controllerVertexBuffers[controller] = new SharpDX.Direct3D11.Buffer(device, model.rVertexData, new BufferDescription
                        {
                            BindFlags   = BindFlags.VertexBuffer,
                            SizeInBytes = (int)model.unVertexCount * 32
                        });

                        controllerVertexBufferBindings[controller] = new VertexBufferBinding(controllerVertexBuffers[controller], 32, 0);

                        controllerIndexBuffers[controller] = new SharpDX.Direct3D11.Buffer(device, model.rIndexData, new BufferDescription
                        {
                            BindFlags   = BindFlags.IndexBuffer,
                            SizeInBytes = (int)model.unTriangleCount * 3 * 2
                        });

                        var texture = controllerTextures[controller];

                        using (var texture2d = new Texture2D(device, new Texture2DDescription
                        {
                            ArraySize = 1,
                            BindFlags = BindFlags.ShaderResource,
                            Format = Format.R8G8B8A8_UNorm,
                            Width = texture.unWidth,
                            Height = texture.unHeight,
                            MipLevels = 1,
                            SampleDescription = new SampleDescription(1, 0)
                        }, new DataRectangle(texture.rubTextureMapData, texture.unWidth * 4)))
                            controllerTextureViews[controller] = new ShaderResourceView(device, texture2d);
                    }

                    var controllerVertexShaderByteCode = SharpDX.D3DCompiler.ShaderBytecode.Compile(Properties.Resources.NormalTextureShader, "VS", "vs_5_0");
                    controllerVertexShader = new VertexShader(device, controllerVertexShaderByteCode);
                    controllerPixelShader  = new PixelShader(device, SharpDX.D3DCompiler.ShaderBytecode.Compile(Properties.Resources.NormalTextureShader, "PS", "ps_5_0"));

                    var controllerLayout = new InputLayout(device, SharpDX.D3DCompiler.ShaderSignature.GetInputSignature(controllerVertexShaderByteCode), new InputElement[]
                    {
                        new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0),
                        new InputElement("NORMAL", 0, Format.R32G32B32_Float, 12, 0),
                        new InputElement("TEXCOORD", 0, Format.R32G32_Float, 24, 0)
                    });

                    worldViewProjectionBuffer = new SharpDX.Direct3D11.Buffer(device, Utilities.SizeOf <Matrix>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);

                    var rasterizerStateDescription = RasterizerStateDescription.Default();
                    //rasterizerStateDescription.FillMode = FillMode.Wireframe;
                    rasterizerStateDescription.IsFrontCounterClockwise = true;
                    //rasterizerStateDescription.CullMode = CullMode.None;

                    rasterizerState = new RasterizerState(device, rasterizerStateDescription);

                    var blendStateDescription = BlendStateDescription.Default();

                    blendStateDescription.RenderTarget[0].BlendOperation   = BlendOperation.Add;
                    blendStateDescription.RenderTarget[0].SourceBlend      = BlendOption.SourceAlpha;
                    blendStateDescription.RenderTarget[0].DestinationBlend = BlendOption.InverseSourceAlpha;

                    blendStateDescription.RenderTarget[0].IsBlendEnabled = false;

                    blendState = new BlendState(device, blendStateDescription);

                    var depthStateDescription = DepthStencilStateDescription.Default();

                    depthStateDescription.DepthComparison  = Comparison.LessEqual;
                    depthStateDescription.IsDepthEnabled   = true;
                    depthStateDescription.IsStencilEnabled = false;

                    depthStencilState = new DepthStencilState(device, depthStateDescription);

                    var samplerStateDescription = SamplerStateDescription.Default();

                    samplerStateDescription.Filter   = Filter.MinMagMipLinear;
                    samplerStateDescription.AddressU = TextureAddressMode.Wrap;
                    samplerStateDescription.AddressV = TextureAddressMode.Wrap;

                    samplerState = new SamplerState(device, samplerStateDescription);

                    startTime  = DateTime.Now;
                    frame      = 0;
                    windowSize = form.ClientSize;

                    backgroundColor = new RawColor4(0.1f, 0.1f, 0.1f, 1);

                    var vrEvent   = new VREvent_t();
                    var eventSize = (uint)Utilities.SizeOf <VREvent_t>();

                    head = Matrix.Identity;

                    // Initialize Audio
                    audio = new XAudio2();
                    var voice = new MasteringVoice(audio);
                    audio3d = new X3DAudio(Speakers.Stereo);

                    foreach (var controller in controllers)
                    {
                        controllerEmitters[controller] = new Emitter
                        {
                            ChannelCount        = 1,
                            CurveDistanceScaler = 0.15f,
                            OrientFront         = Vector3.ForwardLH,
                            OrientTop           = Vector3.Up,
                            Position            = new Vector3(0, 0, 1000),
                            //Velocity = Vector3.Zero
                        };
                    }

                    listener = new Listener
                    {
                        OrientFront = Vector3.ForwardLH,
                        OrientTop   = Vector3.Up,
                        Position    = new Vector3(0, 0, 1000)
                    };

                    var audioFormat = new WaveFormat(44100, 32, 1);
                    //var audioSource = new SourceVoice(audio, audioFormat);
                    var audioBufferSize = audioFormat.ConvertLatencyToByteSize(1000);
                    var audioStream     = new DataStream(audioBufferSize, true, true);
                    var audioSamples    = audioBufferSize / audioFormat.BlockAlign;

                    var random = new Random();

                    for (var sample = 0; sample < audioSamples; sample++)
                    {
                        audioStream.Write((float)random.NextFloat(-1, 1));
                    }

                    audioStream.Position = 0;

                    var audioBuffer = new AudioBuffer
                    {
                        Stream     = audioStream,
                        AudioBytes = audioBufferSize,
                        LoopCount  = 255
                    };

                    var audioSettings = new DspSettings(1, 2);

                    foreach (var controller in controllers)
                    {
                        var audioSource = new SourceVoice(audio, audioFormat);

                        audioSource.SubmitSourceBuffer(audioBuffer, null);

                        audio3d.Calculate(listener, controllerEmitters[controller], CalculateFlags.Matrix, audioSettings);

                        audioSource.SetOutputMatrix(1, 2, audioSettings.MatrixCoefficients);

                        audioSource.Start();

                        controllerVoices[controller] = audioSource;
                    }

                    RenderLoop.Run(form, () =>
                    {
                        while (system.PollNextEvent(ref vrEvent, eventSize))
                        {
                            switch ((EVREventType)vrEvent.eventType)
                            {
                            case EVREventType.VREvent_TrackedDeviceActivated:
                                var controller = vrEvent.trackedDeviceIndex;

                                controllers.Add(controller);

                                var modelName     = new StringBuilder(255, 255);
                                var propertyError = ETrackedPropertyError.TrackedProp_Success;

                                var length = system.GetStringTrackedDeviceProperty(controller, ETrackedDeviceProperty.Prop_RenderModelName_String, modelName, 255, ref propertyError);

                                if (propertyError == ETrackedPropertyError.TrackedProp_Success)
                                {
                                    var modelName2 = modelName.ToString();

                                    while (true)
                                    {
                                        var pointer    = IntPtr.Zero;
                                        var modelError = EVRRenderModelError.None;

                                        modelError = OpenVR.RenderModels.LoadRenderModel_Async(modelName2, ref pointer);

                                        if (modelError == EVRRenderModelError.Loading)
                                        {
                                            continue;
                                        }

                                        if (modelError == EVRRenderModelError.None)
                                        {
                                            var renderModel = System.Runtime.InteropServices.Marshal.PtrToStructure <RenderModel_t>(pointer);

                                            controllerModels[controller] = renderModel;

                                            // Load Controller Model
                                            var model = controllerModels[controller];

                                            controllerVertexBuffers[controller] = new SharpDX.Direct3D11.Buffer(device, model.rVertexData, new BufferDescription
                                            {
                                                BindFlags   = BindFlags.VertexBuffer,
                                                SizeInBytes = (int)model.unVertexCount * 32
                                            });

                                            controllerVertexBufferBindings[controller] = new VertexBufferBinding(controllerVertexBuffers[controller], 32, 0);

                                            controllerIndexBuffers[controller] = new SharpDX.Direct3D11.Buffer(device, model.rIndexData, new BufferDescription
                                            {
                                                BindFlags   = BindFlags.IndexBuffer,
                                                SizeInBytes = (int)model.unTriangleCount * 3 * 2
                                            });

                                            break;
                                        }
                                    }

                                    while (true)
                                    {
                                        var pointer      = IntPtr.Zero;
                                        var textureError = EVRRenderModelError.None;

                                        textureError = OpenVR.RenderModels.LoadTexture_Async(controllerModels[controller].diffuseTextureId, ref pointer);

                                        if (textureError == EVRRenderModelError.Loading)
                                        {
                                            continue;
                                        }

                                        if (textureError == EVRRenderModelError.None)
                                        {
                                            var textureMap = System.Runtime.InteropServices.Marshal.PtrToStructure <RenderModel_TextureMap_t>(pointer);

                                            controllerTextures[controller] = textureMap;

                                            using (var texture2d = new Texture2D(device, new Texture2DDescription
                                            {
                                                ArraySize = 1,
                                                BindFlags = BindFlags.ShaderResource,
                                                Format = Format.R8G8B8A8_UNorm,
                                                Width = textureMap.unWidth,
                                                Height = textureMap.unHeight,
                                                MipLevels = 1,
                                                SampleDescription = new SampleDescription(1, 0)
                                            }, new DataRectangle(textureMap.rubTextureMapData, textureMap.unWidth * 4)))
                                                controllerTextureViews[controller] = new ShaderResourceView(device, texture2d);

                                            break;
                                        }
                                    }

                                    controllerEmitters[controller] = new Emitter
                                    {
                                        ChannelCount        = 1,
                                        CurveDistanceScaler = 0.15f,
                                        OrientFront         = Vector3.ForwardLH,
                                        OrientTop           = Vector3.Up,
                                        Position            = new Vector3(0, 0, 1000),
                                        //Velocity = Vector3.Zero
                                    };

                                    var audioSource = new SourceVoice(audio, audioFormat);

                                    audioSource.SubmitSourceBuffer(audioBuffer, null);

                                    audio3d.Calculate(listener, controllerEmitters[controller], CalculateFlags.Matrix, audioSettings);

                                    audioSource.SetOutputMatrix(1, 2, audioSettings.MatrixCoefficients);

                                    audioSource.Start();

                                    controllerVoices[controller] = audioSource;
                                }
                                break;

                            case EVREventType.VREvent_TrackedDeviceDeactivated:
                                controllers.RemoveAll(c => c == vrEvent.trackedDeviceIndex);
                                break;

                            default:
                                System.Diagnostics.Debug.WriteLine((EVREventType)vrEvent.eventType);
                                break;
                            }
                        }

                        if (form.ClientSize != windowSize)
                        {
                            Utilities.Dispose(ref backBufferView);

                            if (form.ClientSize.Width != 0 && form.ClientSize.Height != 0)
                            {
                                swapChain.ResizeBuffers(1, form.ClientSize.Width, form.ClientSize.Height, Format.B8G8R8A8_UNorm, SwapChainFlags.None);

                                using (var backBuffer = swapChain.GetBackBuffer <Texture2D>(0))
                                    backBufferView = new RenderTargetView(device, backBuffer);
                            }

                            windowSize = form.ClientSize;
                        }

                        // Update Device Tracking
                        compositor.WaitGetPoses(currentPoses, nextPoses);

                        if (currentPoses[headset].bPoseIsValid)
                        {
                            Convert(ref currentPoses[headset].mDeviceToAbsoluteTracking, ref head);

                            // Update Audio Listener
                            listener.Position    = head.TranslationVector * new Vector3(1, 1, -1);
                            listener.OrientFront = head.Forward * new Vector3(1, 1, -1);
                            listener.OrientTop   = head.Up * new Vector3(1, 1, -1);
                        }

                        foreach (var controller in controllers)
                        {
                            var controllerMatrix = Matrix.Identity;

                            Convert(ref currentPoses[controller].mDeviceToAbsoluteTracking, ref controllerMatrix);

                            var position = controllerMatrix.TranslationVector * new Vector3(1, 1, -1);

                            controllerEmitters[controller].Position = position;

                            audio3d.Calculate(listener, controllerEmitters[controller], CalculateFlags.Matrix, audioSettings);

                            controllerVoices[controller].SetOutputMatrix(1, 2, audioSettings.MatrixCoefficients);
                        }

                        // Render Left Eye
                        context.Rasterizer.SetViewport(0, 0, headsetSize.Width, headsetSize.Height);
                        context.OutputMerger.SetTargets(eyeDepthView, leftEyeTextureView);
                        context.OutputMerger.SetDepthStencilState(depthStencilState);

                        context.ClearRenderTargetView(leftEyeTextureView, backgroundColor);
                        context.ClearDepthStencilView(eyeDepthView, DepthStencilClearFlags.Depth, 1.0f, 0);

                        Shaders.Apply(context);

                        context.Rasterizer.State = rasterizerState;

                        context.OutputMerger.SetBlendState(blendState);
                        context.OutputMerger.SetDepthStencilState(depthStencilState);

                        context.PixelShader.SetSampler(0, samplerState);

                        var ratio = (float)headsetSize.Width / (float)headsetSize.Height;

                        var projection = leftEyeProjection;
                        var view       = Matrix.Invert(leftEyeView * head);
                        var world      = Matrix.Scaling(0.5f) * Matrix.Translation(0, 1.0f, 0);

                        worldViewProjection = world * view * projection;

                        context.UpdateSubresource(ref worldViewProjection, worldViewProjectionBuffer);

                        context.VertexShader.SetConstantBuffer(0, worldViewProjectionBuffer);

                        //Shapes.Cube.Begin(context);
                        //Shapes.Cube.Draw(context);

                        Shapes.Sphere.Begin(context);
                        Shapes.Sphere.Draw(context);

                        // Draw Controllers
                        context.InputAssembler.InputLayout       = controllerLayout;
                        context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;

                        context.VertexShader.Set(controllerVertexShader);
                        context.PixelShader.Set(controllerPixelShader);
                        context.GeometryShader.Set(null);
                        context.DomainShader.Set(null);
                        context.HullShader.Set(null);

                        context.PixelShader.SetSampler(0, samplerState);

                        foreach (var controller in controllers)
                        {
                            context.InputAssembler.SetVertexBuffers(0, controllerVertexBufferBindings[controller]);
                            context.InputAssembler.SetIndexBuffer(controllerIndexBuffers[controller], Format.R16_UInt, 0);

                            context.PixelShader.SetShaderResource(0, controllerTextureViews[controller]);

                            Convert(ref currentPoses[controller].mDeviceToAbsoluteTracking, ref world);

                            worldViewProjection = world * view * projection;

                            context.UpdateSubresource(ref worldViewProjection, worldViewProjectionBuffer);

                            context.VertexShader.SetConstantBuffer(0, worldViewProjectionBuffer);

                            context.DrawIndexed((int)controllerModels[controller].unTriangleCount * 3 * 4, 0, 0);
                        }

                        var texture = new Texture_t
                        {
                            eType       = ETextureType.DirectX,
                            eColorSpace = EColorSpace.Gamma,
                            handle      = leftEyeTextureView.Resource.NativePointer
                        };

                        var bounds = new VRTextureBounds_t
                        {
                            uMin = 0.0f,
                            uMax = 1.0f,
                            vMin = 0.0f,
                            vMax = 1.0f,
                        };

                        var submitError = compositor.Submit(EVREye.Eye_Left, ref texture, ref bounds, EVRSubmitFlags.Submit_Default);

                        if (submitError != EVRCompositorError.None)
                        {
                            System.Diagnostics.Debug.WriteLine(submitError);
                        }

                        // Render Right Eye
                        context.Rasterizer.SetViewport(0, 0, headsetSize.Width, headsetSize.Height);
                        context.OutputMerger.SetTargets(eyeDepthView, rightEyeTextureView);
                        context.OutputMerger.SetDepthStencilState(depthStencilState);

                        context.ClearRenderTargetView(rightEyeTextureView, backgroundColor);
                        context.ClearDepthStencilView(eyeDepthView, DepthStencilClearFlags.Depth, 1.0f, 0);

                        Shaders.Apply(context);

                        context.Rasterizer.State = rasterizerState;

                        context.OutputMerger.SetBlendState(blendState);
                        context.OutputMerger.SetDepthStencilState(depthStencilState);

                        context.PixelShader.SetSampler(0, samplerState);

                        projection = rightEyeProjection;
                        view       = Matrix.Invert(rightEyeView * head);
                        world      = Matrix.Scaling(0.5f) * Matrix.Translation(0, 1.0f, 0);

                        worldViewProjection = world * view * projection;

                        context.UpdateSubresource(ref worldViewProjection, worldViewProjectionBuffer);

                        context.VertexShader.SetConstantBuffer(0, worldViewProjectionBuffer);

                        //Shapes.Cube.Begin(context);
                        //Shapes.Cube.Draw(context);

                        Shapes.Sphere.Begin(context);
                        Shapes.Sphere.Draw(context);

                        // Draw Controllers
                        context.InputAssembler.InputLayout       = controllerLayout;
                        context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;

                        context.VertexShader.Set(controllerVertexShader);
                        context.PixelShader.Set(controllerPixelShader);
                        context.GeometryShader.Set(null);
                        context.DomainShader.Set(null);
                        context.HullShader.Set(null);

                        context.PixelShader.SetSampler(0, samplerState);

                        foreach (var controller in controllers)
                        {
                            context.InputAssembler.SetVertexBuffers(0, controllerVertexBufferBindings[controller]);
                            context.InputAssembler.SetIndexBuffer(controllerIndexBuffers[controller], Format.R16_UInt, 0);

                            context.PixelShader.SetShaderResource(0, controllerTextureViews[controller]);

                            Convert(ref currentPoses[controller].mDeviceToAbsoluteTracking, ref world);

                            worldViewProjection = world * view * projection;

                            context.UpdateSubresource(ref worldViewProjection, worldViewProjectionBuffer);

                            context.VertexShader.SetConstantBuffer(0, worldViewProjectionBuffer);

                            context.DrawIndexed((int)controllerModels[controller].unTriangleCount * 3 * 4, 0, 0);
                        }

                        texture.handle = rightEyeTextureView.Resource.NativePointer;

                        submitError = compositor.Submit(EVREye.Eye_Right, ref texture, ref bounds, EVRSubmitFlags.Submit_Default);

                        if (submitError != EVRCompositorError.None)
                        {
                            System.Diagnostics.Debug.WriteLine(submitError);
                        }

                        // Render Window
                        context.Rasterizer.SetViewport(0, 0, windowSize.Width, windowSize.Height);

                        context.OutputMerger.SetTargets(depthStencilView, backBufferView);
                        context.OutputMerger.SetDepthStencilState(depthStencilState);

                        context.ClearRenderTargetView(backBufferView, backgroundColor);
                        context.ClearDepthStencilView(depthStencilView, DepthStencilClearFlags.Depth, 1.0f, 0);

                        Shaders.Apply(context);

                        context.Rasterizer.State = rasterizerState;

                        context.OutputMerger.SetBlendState(blendState);
                        context.OutputMerger.SetDepthStencilState(depthStencilState);

                        context.PixelShader.SetSampler(0, samplerState);

                        ratio = (float)form.ClientSize.Width / (float)form.ClientSize.Height;

                        projection = Matrix.PerspectiveFovRH(3.14F / 3.0F, ratio, 0.01f, 1000);
                        view       = Matrix.Invert(head);
                        world      = Matrix.Scaling(0.5f) * Matrix.Translation(0, 1.0f, 0);

                        worldViewProjection = world * view * projection;

                        context.UpdateSubresource(ref worldViewProjection, worldViewProjectionBuffer);

                        context.VertexShader.SetConstantBuffer(0, worldViewProjectionBuffer);

                        //Shapes.Cube.Begin(context);
                        //Shapes.Cube.Draw(context);

                        Shapes.Sphere.Begin(context);
                        Shapes.Sphere.Draw(context);

                        // Draw Controllers
                        context.InputAssembler.InputLayout       = controllerLayout;
                        context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;

                        context.VertexShader.Set(controllerVertexShader);
                        context.PixelShader.Set(controllerPixelShader);
                        context.GeometryShader.Set(null);
                        context.DomainShader.Set(null);
                        context.HullShader.Set(null);

                        context.PixelShader.SetSampler(0, samplerState);

                        foreach (var controller in controllers)
                        {
                            context.InputAssembler.SetVertexBuffers(0, controllerVertexBufferBindings[controller]);
                            context.InputAssembler.SetIndexBuffer(controllerIndexBuffers[controller], Format.R16_UInt, 0);

                            Convert(ref currentPoses[controller].mDeviceToAbsoluteTracking, ref world);

                            worldViewProjection = world * view * projection;

                            context.UpdateSubresource(ref worldViewProjection, worldViewProjectionBuffer);

                            context.VertexShader.SetConstantBuffer(0, worldViewProjectionBuffer);

                            context.DrawIndexed((int)controllerModels[controller].unTriangleCount * 3 * 4, 0, 0);
                        }

                        // Show Backbuffer
                        swapChain.Present(0, PresentFlags.None);
                    });

                    audio.Dispose();
                }
        }
Esempio n. 25
0
        /// <summary>
        /// Draw formatted text.
        /// </summary>
        /// <remarks>
        /// The parameters of this method are very similar to those of the {{GDI DrawText}} function. This method supports both ANSI and Unicode strings. Unless the DT_NOCLIP format is used, this method clips the text so that it does not appear outside the specified rectangle. All formatting is assumed to have multiple lines unless the DT_SINGLELINE format is specified. If the selected font is too large for the rectangle, this method does not attempt to substitute a smaller font. This method supports only fonts whose escapement and orientation are both zero.
        /// </remarks>
        /// <param name="sprite">Reference to an ID3DX10Sprite object that contains the string you wish to draw. Can be NULL, in which case Direct3D will render the string with its own sprite object. To improve efficiency, a sprite object should be specified if ID3DX10Font::DrawText is to be called more than once in a row. </param>
        /// <param name="text">Pointer to a string to draw. If UNICODE is defined, this parameter type resolves to an LPCWSTR, otherwise, the type resolves to an LPCSTR. If the Count parameter is -1, the string must be NULL terminated. </param>
        /// <param name="rect">Pointer to a <see cref="RawRectangle"/> structure that contains the rectangle, in logical coordinates, in which the text is to be formatted. As with any RECT object, the coordinate value of the rectangle's right side must be greater than that of its left side. Likewise, the coordinate value of the bottom must be greater than that of the top. </param>
        /// <param name="drawFlags">Specify the method of formatting the text. It can be any combination of the following values:    ItemDescription  DT_BOTTOM  Justify the text to the bottom of the rectangle. This value must be combined with DT_SINGLELINE.   DT_CALCRECT  Tell DrawText to automatically calculate the width and height of the rectangle based on the length of the string you tell it to draw. If there are multiple lines of text, ID3DX10Font::DrawText uses the width of the rectangle pointed to by the pRect parameter and extends the base of the rectangle to bound the last line of text. If there is only one line of text, ID3DX10Font::DrawText modifies the right side of the rectangle so that it bounds the last character in the line. In either case, ID3DX10Font::DrawText returns the height of the formatted text but does not draw the text.   DT_CENTER  Center text horizontally in the rectangle.   DT_EXPANDTABS  Expand tab characters. The default number of characters per tab is eight.   DT_LEFT  Align text to the left.   DT_NOCLIP  Draw without clipping. ID3DX10Font::DrawText is somewhat faster when DT_NOCLIP is used.   DT_RIGHT  Align text to the right.   DT_RTLREADING  Display text in right-to-left reading order for bidirectional text when a Hebrew or Arabic font is selected. The default reading order for all text is left-to-right.   DT_SINGLELINE  Display text on a single line only. Carriage returns and line feeds do not break the line.   DT_TOP  Top-justify text.   DT_VCENTER  Center text vertically (single line only).   DT_WORDBREAK  Break words. Lines are automatically broken between words if a word would extend past the edge of the rectangle specified by the pRect parameter. A carriage return/line feed sequence also breaks the line.   ? </param>
        /// <param name="color">Color of the text. See <see cref="RawColor4"/>. </param>
        /// <returns>If the function succeeds, the return value is the height of the text in logical units. If DT_VCENTER or DT_BOTTOM is specified, the return value is the offset from pRect (top to the bottom) of the drawn text. If the function fails, the return value is zero. </returns>
        /// <unmanaged>int ID3DX10Font::DrawTextW([None] LPD3DX10SPRITE pSprite,[None] const wchar_t* pString,[None] int Count,[None] RECT* pRect,[None] int Format,[None] D3DXCOLOR Color)</unmanaged>
        public unsafe int DrawText(SharpDX.Direct3D10.Sprite sprite, string text, RawRectangle rect, FontDrawFlags drawFlags, RawColor4 color)
        {
            int value = DrawText(sprite, text, text.Length, new IntPtr(&rect), (int)drawFlags, color);

            if (value == 0)
            {
                throw new SharpDXException("Draw failed");
            }
            return(value);
        }
Esempio n. 26
0
 public void ClearView(ID3D11View view, RawColor4 color)
 {
     ClearView(view, color);
 }
Esempio n. 27
0
 public static SamplerState CreateSamplerState(Device device, TextureAddressMode address, RawColor4 border, Comparison comparisonFunc, Filter filter, int maxAnisotropy, float maxLOD, float minLOD, float mipLODBias)
 {
     return(CreateSamplerState(device, address, address, address, border, comparisonFunc, filter, maxAnisotropy, maxLOD, minLOD, mipLODBias));
 }
Esempio n. 28
0
 public void ClearView(ID3D11View view, RawColor4 color, RawRectangle[] rects)
 {
     ClearView(view, color, rects, rects.Length);
 }
Esempio n. 29
0
        SolidColorBrush Convert(Color Color)
        {
            var color = new RawColor4(Color.R / 255f, Color.G / 255f, Color.B / 255f, Color.A / 255f);

            return(_editorSession.GetSolidColorBrush(color));
        }
Esempio n. 30
0
 private void Clear(RawColor4 color)
 {
     _deviceContext.ClearRenderTargetView(_backbufferView, color);
     _deviceContext.ClearDepthStencilView(_zbufferView, DepthStencilClearFlags.Depth, 1.0F, 0);
 }