コード例 #1
0
        public static InputElement[] GetStreamOutputLayout(this EffectPass pass, out int vertexsize)
        {
            vertexsize = 0;
            if (pass.GeometryShaderDescription.Variable == null)
            {
                return new InputElement[0];
            }
            else
            {
                EffectShaderVariable gs = pass.GeometryShaderDescription.Variable;
                int outputcount = gs.GetShaderDescription(0).OutputParameterCount;

                InputElement[] elems = new InputElement[outputcount];

                int offset = 0;

                for (int vip = 0; vip < outputcount; vip++)
                {
                    ShaderParameterDescription sd = gs.GetOutputParameterDescription(0, vip);
                    int componentcount = 0;

                    if (sd.UsageMask.HasFlag(RegisterComponentMaskFlags.ComponentX)) { componentcount++; }
                    if (sd.UsageMask.HasFlag(RegisterComponentMaskFlags.ComponentY)) { componentcount++; }
                    if (sd.UsageMask.HasFlag(RegisterComponentMaskFlags.ComponentZ)) { componentcount++; }
                    if (sd.UsageMask.HasFlag(RegisterComponentMaskFlags.ComponentW)) { componentcount++; }

                    int vsize = 4 * componentcount;

                    string fmt = "";
                    if (componentcount == 1) { fmt = "R32_"; }
                    if (componentcount == 2) { fmt = "R32G32_"; }
                    if (componentcount == 3) { fmt = "R32G32B32_"; }
                    if (componentcount == 4) { fmt = "R32G32B32A32_"; }

                    switch (sd.ComponentType)
                    {
                        case RegisterComponentType.Float32:
                            fmt += "Float";
                            break;
                        case RegisterComponentType.SInt32:
                            fmt += "SInt";
                            break;
                        case RegisterComponentType.UInt32:
                            fmt += "UInt";
                            break;
                    }

                    Format f = (Format)Enum.Parse(typeof(Format), fmt);

                    InputElement elem = new InputElement(sd.SemanticName, (int)sd.SemanticIndex, f, offset, 0);

                    elems[vip] = elem;

                    offset += vsize;
                    vertexsize += vsize;
                }

                return elems;
            }
        }
コード例 #2
0
        public void Evaluate(int SpreadMax)
        {
            if (this.FInLayoutType.IsChanged || this.FInFormat.IsChanged || this.FAutoIndex.IsChanged)
            {
                this.FOutput.SliceCount = SpreadMax;
                int offset = 0;

                InputElement[] elements = new InputElement[SpreadMax];

                for (int i = 0; i < SpreadMax; i++)
                {
                    Format fmt= (Format)Enum.Parse(typeof(Format), this.FInFormat[i].Name);
                    elements[i] = InputLayoutFactory.GetInputElement(this.FInLayoutType[i],fmt,0,offset);
                    offset += FormatHelper.Instance.GetSize(fmt);
                }

                if (this.FAutoIndex[0])
                {
                    InputLayoutFactory.AutoIndex(elements);
                }

                this.FOutput.AssignFrom(elements);

            }
        }
コード例 #3
0
ファイル: ShaderQuad.cs プロジェクト: treytomes/DirectCanvas
        /// <summary>
        /// Creates the input elements that describe the vertices to the GPU
        /// </summary>
        private static InputElement[] CreateInputElements()
        {
            var layoutInstanced = new InputElement[2];

            layoutInstanced[0] = new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0, InputClassification.PerVertexData, 0);
            layoutInstanced[1] = new InputElement("TEXCOORD", 0, Format.R32G32_Float, InputElement.AppendAligned, 0, InputClassification.PerVertexData, 0);

            return layoutInstanced;
        }
コード例 #4
0
		public WatermarkExtender(InputElement el, string watermark)
		{
			this.el = el;
			this.watermark = watermark;
			DomEvent.AddHandler(el, "focus", OnFocus);
			DomEvent.AddHandler(el, "blur", OnBlur);
			((Dictionary)(object)el)["readOnly"] = null;
			
			
			
		}
コード例 #5
0
		public MultiSelectorBehaviour(DOMElement container, HtmlAutoCompleteBehaviour htmlAutoComplete, InputElement hiddenOutput)
		{
			this.container = container;
			this.hiddenOutput = hiddenOutput;
			this.HtmlAutoComplete = htmlAutoComplete;
			this.HtmlAutoComplete.ItemChosen = htmlAutoComplete_ItemChosen;
			selections = new PairListField(hiddenOutput);
			InitialiseInitialSelections();
			DomEvent.AddHandler(this.container, "click", this.OnClick);
			
		}
コード例 #6
0
ファイル: Controller.cs プロジェクト: davelondon/dontstayin
		public static bool WhenLoggedInButtonNoValidation(InputElement element)
		{
			PageImplementation.WhenLoggedIn(
				new Action(
					delegate()
					{
						Script.Eval("__doPostBack(\"" + element.ID.Replace(new RegularExpression("_", "g"), "$") + "\",'');");
					}
				)
			);
			return false;
		}
コード例 #7
0
ファイル: Controller.cs プロジェクト: davelondon/dontstayin
		public static bool WhenLoggedInButtonValidator(InputElement element, string validators)
		{
			PageImplementation.WhenLoggedIn(
				new Action(
					delegate()
					{
						Script.Eval("WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(\"" + element.ID.Replace(new RegularExpression("_", "g"), "$") + "\", \"\", true, \"" + validators + "\", \"\", false, true));");
					}
				)
			);
			return false;
		}
コード例 #8
0
ファイル: BloomEffect.cs プロジェクト: RugCode/drg-pt
		public override void LoadResources()
		{
			if (m_Disposed == true)
			{
				m_Effect = new Effect(GameEnvironment.Device, Bytecode); // Helper.ResolvePath(m_ShaderLocation), "fx_4_0", ShaderFlags.None, EffectFlags.None, null, null);
				m_Technique = m_Effect.GetTechniqueByName("BlurBilinear");

				m_Pass_Gaussian = m_Technique.GetPassByName("Gaussian");

				m_SourceTex = m_Effect.GetVariableByName("g_SourceTex").AsResource();
				m_GWeights = m_Effect.GetVariableByName("g_GWeights").AsScalar();

				//m_ElementCount = 1 + GAUSSIAN_MAX_SAMPLES;
				m_DataStride = Marshal.SizeOf(typeof(Vector2)) * (1 + GAUSSIAN_MAX_SAMPLES);

				InputElement[] IADesc = new InputElement[1 + (GAUSSIAN_MAX_SAMPLES / 2)];

				IADesc[0] = new InputElement()
				{
					SemanticName = "POSITION",
					SemanticIndex = 0,
					AlignedByteOffset = 0,
					Slot = 0,
					Classification = InputClassification.PerVertexData,
					Format = Format.R32G32_Float
				};


				for (int i = 1; i < 1 + (GAUSSIAN_MAX_SAMPLES / 2); i++)
				{
					IADesc[i] = new InputElement()
					{
						SemanticName = "TEXCOORD",
						SemanticIndex = i - 1,
						AlignedByteOffset = 8 + (i - 1) * 16,
						Slot = 0,
						Classification = InputClassification.PerVertexData,
						Format = Format.R32G32B32A32_Float
					};
				}

				// Real number of "sematinc based" elements
				//m_ElementCount = 1 + GAUSSIAN_MAX_SAMPLES / 2;

				EffectPassDescription PassDesc = m_Pass_Gaussian.Description;
				m_Layout = new InputLayout(GameEnvironment.Device, PassDesc.Signature, IADesc);

				m_Disposed = false;
			}
		}
コード例 #9
0
ファイル: Base.cs プロジェクト: vokac/F2B
        public BaseInput(InputElement input, SelectorElement selector, EventQueue queue)
            : base()
        {
            InputName = input.Name;
            InputType = input.Type;
            SelectorName = selector.Name;
            Processor = selector.Processor;

            switch (selector.Login)
            {
                case "success": Login = LoginStatus.SUCCESS; break;
                case "failure": Login = LoginStatus.FAILURE; break;
                default: Login = LoginStatus.UNKNOWN; break;
            }

            equeue = queue;
        }
コード例 #10
0
ファイル: ChatElement.cs プロジェクト: nezbo/Descent
        /// <summary>
        /// Creates a new Chat for the given Game.
        /// </summary>
        /// <param name="game">The current Game object.</param>
        public ChatElement(Game game)
            : base(game, "chat", (int)(game.GraphicsDevice.Viewport.Width * (3 / 4.0)), (Player.Instance.NumberOfPlayers - 1) * 100, game.GraphicsDevice.Viewport.Width / 4, game.GraphicsDevice.Viewport.Height - (Player.Instance.NumberOfPlayers - 1) * 100)
        {
            InputElement input = new InputElement(game, "chatInput", Bound.X + 10, Bound.Y + Bound.Height - 40, Bound.Width - 18, 30);
            AddChild(input);

            messages = new LinkedList<string>();

            AddDrawable(this.Name, new Image(game.Content.Load<Texture2D>("chatbg")),
                        new Rectangle(Bound.X, Bound.Y + Bound.Height - 50, Bound.Width, 50));

            // external events
            manager.ChatMessageEvent += new ChatMessageHandler(GetMessage);
            manager.GiveEquipmentEvent += new GiveEquipmentHandler(GiveEquipment);

            this.SetDrawBackground(true);
            this.SetBackground("chatbg");
        }
コード例 #11
0
        private void CreatePSO(InputElement[] inputElementDescs,ShaderBytecode vertexShader,ShaderBytecode pixelShader)
        {
            // Describe and create the graphics pipeline state object (PSO).
            var psoDesc = new GraphicsPipelineStateDescription()
            {
                InputLayout = new InputLayoutDescription(inputElementDescs),
                RootSignature = rootSignature,
                VertexShader = vertexShader,
                PixelShader = pixelShader,
                RasterizerState = RasterizerStateDescription.Default(),
                BlendState = BlendStateDescription.Default(),
                DepthStencilFormat = SharpDX.DXGI.Format.D32_Float,
                DepthStencilState = new DepthStencilStateDescription()
                {
                    IsDepthEnabled = true,
                    DepthComparison = Comparison.LessEqual,
                    DepthWriteMask = DepthWriteMask.All,
                    IsStencilEnabled = false
                },
                SampleMask = int.MaxValue,
                PrimitiveTopologyType = PrimitiveTopologyType.Triangle,
                RenderTargetCount = 1,
                Flags = PipelineStateFlags.None,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                StreamOutput = new StreamOutputDescription()
            };
            psoDesc.RenderTargetFormats[0] = SharpDX.DXGI.Format.R8G8B8A8_UNorm;

            pipelineState = device.CreateGraphicsPipelineState(psoDesc);

            commandList = device.CreateCommandList(CommandListType.Direct, commandAllocator, pipelineState);
            commandList.Close();
        }
コード例 #12
0
        internal void ChangeStylusCapture(IInputElement stylusCapture, CaptureMode captureMode, int timestamp)
        {
            // if the capture changed...
            if (stylusCapture != _stylusCapture)
            {
                // Actually change the capture first.  Invalidate the properties,
                // and then send the events.
                IInputElement oldStylusCapture = _stylusCapture;

                _stylusCapture = stylusCapture;
                _captureMode   = captureMode;

                // We also need to figure out ahead of time if any plugincollections on this captured element (or a parent)
                // for the penthread hittesting code.
                _stylusCapturePlugInCollection = null;

                if (stylusCapture != null)
                {
                    UIElement uiElement = InputElement.GetContainingUIElement(stylusCapture as DependencyObject) as UIElement;
                    if (uiElement != null)
                    {
                        PresentationSource source = PresentationSource.CriticalFromVisual(uiElement as Visual);

                        if (source != null)
                        {
                            PointerStylusPlugInManager manager;

                            if (_pointerLogic.PlugInManagers.TryGetValue(source, out manager))
                            {
                                _stylusCapturePlugInCollection = manager.FindPlugInCollection(uiElement);
                            }
                        }
                    }
                }

                _pointerLogic.UpdateStylusCapture(this, oldStylusCapture, _stylusCapture, timestamp);

                // Send the LostStylusCapture and GotStylusCapture events.
                if (oldStylusCapture != null)
                {
                    StylusEventArgs lostCapture = new StylusEventArgs(StylusDevice, timestamp);
                    lostCapture.RoutedEvent = Stylus.LostStylusCaptureEvent;
                    lostCapture.Source      = oldStylusCapture;
                    InputManager.UnsecureCurrent.ProcessInput(lostCapture);
                }
                if (_stylusCapture != null)
                {
                    StylusEventArgs gotCapture = new StylusEventArgs(StylusDevice, timestamp);
                    gotCapture.RoutedEvent = Stylus.GotStylusCaptureEvent;
                    gotCapture.Source      = _stylusCapture;
                    InputManager.UnsecureCurrent.ProcessInput(gotCapture);
                }

                // Now update the stylus over state (only if this is the current stylus and
                // it is inrange).
                if (_pointerLogic.CurrentStylusDevice == this || InRange)
                {
                    if (_stylusCapture != null)
                    {
                        IInputElement inputElementHit = _stylusCapture;

                        // See if we need to update over for subtree mode.
                        if (CapturedMode == CaptureMode.SubTree && _inputSource != null && _inputSource.Value != null)
                        {
                            Point pt = _pointerLogic.DeviceUnitsFromMeasureUnits(GetPosition(null));
                            inputElementHit = FindTarget(_inputSource.Value, pt);
                        }

                        ChangeStylusOver(inputElementHit);
                    }
                    else
                    {
                        // Only try to update over if we have a valid input source.
                        if (_inputSource != null && _inputSource.Value != null)
                        {
                            Point pt = GetPosition(null);                       // relative to window (root element)
                            pt = _pointerLogic.DeviceUnitsFromMeasureUnits(pt); // change back to device coords.
                            IInputElement currentOver = Input.StylusDevice.GlobalHitTest(_inputSource.Value, pt);
                            ChangeStylusOver(currentOver);
                        }
                    }
                }

                // For Mouse StylusDevice we want to make sure Mouse capture is set up the same.
                if (Mouse.Captured != _stylusCapture || Mouse.CapturedMode != _captureMode)
                {
                    Mouse.Capture(_stylusCapture, _captureMode);
                }
            }
        }
コード例 #13
0
 public virtual InputLayout CreateLayout(InputElement[] elements)
 {
     return new InputLayout(Device, bcVertex, elements);
 }
コード例 #14
0
        private void LoadAssets()
        {
            DescriptorRange[] ranges = new DescriptorRange[] { new DescriptorRange() { RangeType = DescriptorRangeType.ShaderResourceView, DescriptorCount = 1, OffsetInDescriptorsFromTableStart = int.MinValue, BaseShaderRegister = 0 } };

            StaticSamplerDescription sampler = new StaticSamplerDescription()
            {
                Filter = Filter.MinimumMinMagMipPoint,
                AddressU = TextureAddressMode.Border,
                AddressV = TextureAddressMode.Border,
                AddressW = TextureAddressMode.Border,
                MipLODBias = 0,
                MaxAnisotropy = 0,
                ComparisonFunc = Comparison.Never,
                BorderColor = StaticBorderColor.TransparentBlack,
                MinLOD = 0.0f,
                MaxLOD = float.MaxValue,
                ShaderRegister = 0,
                RegisterSpace = 0,
                ShaderVisibility = ShaderVisibility.Pixel,
            };

            RootParameter[] rootParameters = new RootParameter[] { new RootParameter(ShaderVisibility.Pixel, ranges) };

            RootSignatureDescription rootSignatureDesc = new RootSignatureDescription(RootSignatureFlags.AllowInputAssemblerInputLayout, rootParameters, new StaticSamplerDescription[] { sampler });
            rootSignature = device.CreateRootSignature(0, rootSignatureDesc.Serialize());

            // Create the pipeline state, which includes compiling and loading shaders.
            #if DEBUG
            var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "VSMain", "vs_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug));
            #else
            var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "VSMain", "vs_5_0"));
            #endif

            #if DEBUG
            var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "PSMain", "ps_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug));
            #else
            var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "PSMain", "ps_5_0"));
            #endif

            // Define the vertex input layout.
            InputElement[] inputElementDescs = new InputElement[]
            {
                    new InputElement("POSITION",0,Format.R32G32B32_Float,0,0),
                    new InputElement("TEXCOORD",0,Format.R32G32_Float,12,0)
            };

            // Describe and create the graphics pipeline state object (PSO).
            GraphicsPipelineStateDescription psoDesc = new GraphicsPipelineStateDescription()
            {
                InputLayout = new InputLayoutDescription(inputElementDescs),
                RootSignature = rootSignature,
                VertexShader = vertexShader,
                PixelShader = pixelShader,
                RasterizerState = RasterizerStateDescription.Default(),
                BlendState = BlendStateDescription.Default(),
                DepthStencilFormat = SharpDX.DXGI.Format.D32_Float,
                DepthStencilState = new DepthStencilStateDescription() { IsDepthEnabled = false, IsStencilEnabled = false },
                SampleMask = int.MaxValue,
                PrimitiveTopologyType = PrimitiveTopologyType.Triangle,
                RenderTargetCount = 1,
                Flags = PipelineStateFlags.None,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                StreamOutput = new StreamOutputDescription()
            };
            psoDesc.RenderTargetFormats[0] = SharpDX.DXGI.Format.R8G8B8A8_UNorm;

            pipelineState = device.CreateGraphicsPipelineState(psoDesc);

            // Create the command list.
            commandList = device.CreateCommandList(CommandListType.Direct, commandAllocator, pipelineState);

            // Create the vertex buffer.
            float aspectRatio = viewport.Width / viewport.Height;

            // Define the geometry for a triangle.
            Vertex[] triangleVertices = new Vertex[]
            {
                    new Vertex() {position=new Vector3(0.0f, 0.25f * aspectRatio, 0.0f ),uv=new Vector2(0.5f, 0.0f) },
                    new Vertex() {position=new Vector3(0.25f, -0.25f * aspectRatio, 0.0f),uv=new Vector2(1.0f, 1.0f) },
                    new Vertex() {position=new Vector3(-0.25f, -0.25f * aspectRatio, 0.0f),uv=new Vector2(0.0f, 1.0f) },
            };

            int vertexBufferSize = Utilities.SizeOf(triangleVertices);

            // Note: using upload heaps to transfer static data like vert buffers is not
            // recommended. Every time the GPU needs it, the upload heap will be marshalled
            // over. Please read up on Default Heap usage. An upload heap is used here for
            // code simplicity and because there are very few verts to actually transfer.
            vertexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(vertexBufferSize), ResourceStates.GenericRead);

            // Copy the triangle data to the vertex buffer.
            IntPtr pVertexDataBegin = vertexBuffer.Map(0);
            Utilities.Write(pVertexDataBegin, triangleVertices, 0, triangleVertices.Length);
            vertexBuffer.Unmap(0);

            // Initialize the vertex buffer view.
            vertexBufferView = new VertexBufferView();
            vertexBufferView.BufferLocation = vertexBuffer.GPUVirtualAddress;
            vertexBufferView.StrideInBytes = Utilities.SizeOf<Vertex>();
            vertexBufferView.SizeInBytes = vertexBufferSize;

            Resource textureUploadHeap;

            // Create the texture.
            // Describe and create a Texture2D.
            ResourceDescription textureDesc = ResourceDescription.Texture2D(Format.R8G8B8A8_UNorm, TextureWidth, TextureHeight);
            texture = device.CreateCommittedResource(new HeapProperties(HeapType.Default), HeapFlags.None, textureDesc, ResourceStates.CopyDestination);

            long uploadBufferSize = GetRequiredIntermediateSize(this.texture, 0, 1);

            // Create the GPU upload buffer.
            textureUploadHeap = device.CreateCommittedResource(new HeapProperties(CpuPageProperty.WriteBack, MemoryPool.L0), HeapFlags.None, ResourceDescription.Texture2D(Format.R8G8B8A8_UNorm, TextureWidth, TextureHeight), ResourceStates.GenericRead);

            // Copy data to the intermediate upload heap and then schedule a copy
            // from the upload heap to the Texture2D.
            byte[] textureData = GenerateTextureData();

            GCHandle handle = GCHandle.Alloc(textureData, GCHandleType.Pinned);
            IntPtr ptr = Marshal.UnsafeAddrOfPinnedArrayElement(textureData, 0);
            textureUploadHeap.WriteToSubresource(0, null, ptr, TexturePixelSize * TextureWidth, textureData.Length);
            handle.Free();

            commandList.CopyTextureRegion(new TextureCopyLocation(texture, 0), 0, 0, 0, new TextureCopyLocation(textureUploadHeap, 0), null);

            commandList.ResourceBarrierTransition(this.texture, ResourceStates.CopyDestination, ResourceStates.PixelShaderResource);

            // Describe and create a SRV for the texture.
            ShaderResourceViewDescription srvDesc = new ShaderResourceViewDescription()
            {
                Shader4ComponentMapping = D3DXUtilities.DefaultComponentMapping(),
                Format = textureDesc.Format,
                Dimension = ShaderResourceViewDimension.Texture2D,
            };
            srvDesc.Texture2D.MipLevels = 1;

            device.CreateShaderResourceView(this.texture, srvDesc, shaderRenderViewHeap.CPUDescriptorHandleForHeapStart);

            // Command lists are created in the recording state, but there is nothing
            // to record yet. The main loop expects it to be closed, so close it now.
            commandList.Close();

            commandQueue.ExecuteCommandList(commandList);

            // Create synchronization objects.
            fence = device.CreateFence(0, FenceFlags.None);
            fenceValue = 1;

            // Create an event handle to use for frame synchronization.
            fenceEvent = new AutoResetEvent(false);

            WaitForPreviousFrame();

            //release temp texture
            textureUploadHeap.Dispose();
        }
コード例 #15
0
ファイル: Controller.cs プロジェクト: davelondon/dontstayin
		public static bool WhenLoggedInRadio(InputElement element)
		{
			PageImplementation.WhenLoggedIn(
				new Action(
					delegate()
					{
						Script.Eval("setTimeout('__doPostBack(\\'" + element.ID.Replace(new RegularExpression("_", "g"), "$") + "\\',\\'\\')', 0);");
					}
				)
			);
			return true;
		}
コード例 #16
0
        private bool InitializeShader(Device device, IntPtr hwnd, string vsFileName, string psFileName)
        {
            try
            {
                // Setup full pathes
                vsFileName = DSystemConfiguration.ShaderFilePath + vsFileName;
                psFileName = DSystemConfiguration.ShaderFilePath + psFileName;

                // Compile the Vertex & Pixel Shader code.
                ShaderBytecode vertexShaderByteCode = ShaderBytecode.CompileFromFile(vsFileName, "SkyDomeVertexShader", DSystemConfiguration.VertexShaderProfile, ShaderFlags.None, EffectFlags.None);
                ShaderBytecode pixelShaderByteCode  = ShaderBytecode.CompileFromFile(psFileName, "SkyDomePixelShader", DSystemConfiguration.PixelShaderProfile, ShaderFlags.None, EffectFlags.None);

                // Create the Vertex & Pixel Shader from the buffer.
                VertexShader = new VertexShader(device, vertexShaderByteCode);
                PixelShader  = new PixelShader(device, pixelShaderByteCode);

                // Create the vertex input layout description.
                InputElement[] inputElements = new InputElement[]
                {
                    new InputElement()
                    {
                        SemanticName         = "POSITION",
                        SemanticIndex        = 0,
                        Format               = SharpDX.DXGI.Format.R32G32B32_Float,
                        Slot                 = 0,
                        AlignedByteOffset    = 0,
                        Classification       = InputClassification.PerVertexData,
                        InstanceDataStepRate = 0
                    }
                };

                // Create the vertex input the layout.
                Layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), inputElements);

                // Release the vertex and pixel shader buffers, since they are no longer needed.
                vertexShaderByteCode.Dispose();
                pixelShaderByteCode.Dispose();

                // Setup the description of the dynamic matrix constant buffer that is in the vertex shader.
                BufferDescription matrixBufferDesc = new BufferDescription()
                {
                    Usage               = ResourceUsage.Dynamic,
                    SizeInBytes         = Utilities.SizeOf <DMatrixBuffer>(),
                    BindFlags           = BindFlags.ConstantBuffer,
                    CpuAccessFlags      = CpuAccessFlags.Write,
                    OptionFlags         = ResourceOptionFlags.None,
                    StructureByteStride = 0
                };

                // Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class.
                ConstantMatrixBuffer = new SharpDX.Direct3D11.Buffer(device, matrixBufferDesc);

                // Setup the description of the gradient constant buffer that is in the pixel shader.
                BufferDescription gradientBufferDesc = new BufferDescription()
                {
                    Usage               = ResourceUsage.Dynamic,
                    SizeInBytes         = Utilities.SizeOf <DGradientBuffer>(),
                    BindFlags           = BindFlags.ConstantBuffer,
                    CpuAccessFlags      = CpuAccessFlags.Write,
                    OptionFlags         = ResourceOptionFlags.None,
                    StructureByteStride = 0
                };

                // Create the constant buffer pointer so we can access the pixel shader constant buffer from within this class.
                ConstantGradientBuffer = new SharpDX.Direct3D11.Buffer(device, gradientBufferDesc);

                return(true);
            }
            catch
            {
                return(false);
            }
        }
コード例 #17
0
        public static InputElement[] GetStreamOutputLayout(this EffectPass pass, out int vertexsize)
        {
            vertexsize = 0;
            if (pass.GeometryShaderDescription.Variable == null)
            {
                return(new InputElement[0]);
            }
            else
            {
                EffectShaderVariable gs = pass.GeometryShaderDescription.Variable;
                int outputcount         = gs.GetShaderDescription(0).OutputParameterCount;

                InputElement[] elems = new InputElement[outputcount];

                int offset = 0;

                for (int vip = 0; vip < outputcount; vip++)
                {
                    ShaderParameterDescription sd = gs.GetOutputSignatureElementDescription(0, vip);
                    int componentcount            = 0;

                    if (sd.UsageMask.HasFlag(RegisterComponentMaskFlags.ComponentX))
                    {
                        componentcount++;
                    }
                    if (sd.UsageMask.HasFlag(RegisterComponentMaskFlags.ComponentY))
                    {
                        componentcount++;
                    }
                    if (sd.UsageMask.HasFlag(RegisterComponentMaskFlags.ComponentZ))
                    {
                        componentcount++;
                    }
                    if (sd.UsageMask.HasFlag(RegisterComponentMaskFlags.ComponentW))
                    {
                        componentcount++;
                    }

                    int vsize = 4 * componentcount;

                    string fmt = "";
                    if (componentcount == 1)
                    {
                        fmt = "R32_";
                    }
                    if (componentcount == 2)
                    {
                        fmt = "R32G32_";
                    }
                    if (componentcount == 3)
                    {
                        fmt = "R32G32B32_";
                    }
                    if (componentcount == 4)
                    {
                        fmt = "R32G32B32A32_";
                    }

                    switch (sd.ComponentType)
                    {
                    case RegisterComponentType.Float32:
                        fmt += "Float";
                        break;

                    case RegisterComponentType.SInt32:
                        fmt += "SInt";
                        break;

                    case RegisterComponentType.UInt32:
                        fmt += "UInt";
                        break;
                    }

                    Format       f    = (Format)Enum.Parse(typeof(Format), fmt);
                    InputElement elem = new InputElement(sd.SemanticName, (int)sd.SemanticIndex, f, offset, 0);
                    elems[vip]  = elem;
                    offset     += vsize;
                    vertexsize += vsize;
                }

                return(elems);
            }
        }
コード例 #18
0
        /// <summary>
        ///     Captures the stylus to a particular element.
        /// </summary>
        internal override bool Capture(IInputElement element, CaptureMode captureMode)
        {
            int timeStamp = Environment.TickCount;

            VerifyAccess();

            if (!(captureMode == CaptureMode.None || captureMode == CaptureMode.Element || captureMode == CaptureMode.SubTree))
            {
                throw new System.ComponentModel.InvalidEnumArgumentException("captureMode", (int)captureMode, typeof(CaptureMode));
            }

            if (element == null)
            {
                captureMode = CaptureMode.None;
            }

            if (captureMode == CaptureMode.None)
            {
                element = null;
            }

            // Validate that element is either a UIElement or a ContentElement
            DependencyObject doStylusCapture = element as DependencyObject;

            if (doStylusCapture != null && !InputElement.IsValid(element))
            {
                throw new InvalidOperationException(SR.Get(SRID.Invalid_IInputElement, doStylusCapture.GetType()));
            }

            doStylusCapture?.VerifyAccess();

            bool success = false;

            // The element we are capturing to must be both enabled and visible.
            UIElement e = element as UIElement;

            if ((e?.IsVisible ?? false) || (e?.IsEnabled ?? false))
            {
                success = true;
            }
            else
            {
                ContentElement ce = element as ContentElement;

                if (ce?.IsEnabled ?? false)
                {
                    success = true;
                }
                else
                {
                    // Setting capture to null.
                    success = true;
                }
            }

            if (success)
            {
                ChangeStylusCapture(element, captureMode, timeStamp);
            }

            return(success);
        }
コード例 #19
0
 // hooking the click event allows us to find the submit button that started this whole process
 private void Form_OnClick(DomEvent e) {
     _submitButtonClicked = FindSubmitButton(e.Target);
 }
コード例 #20
0
ファイル: FileLog.cs プロジェクト: vokac/F2B
        public FileLogInput(InputElement input, SelectorElement selector, EventQueue equeue)
            : base(input, selector, equeue)
        {
            filename = input.LogPath;
            interval = input.Interval;
            onlyWatcher = false;
            active = false;

            List<Regex> tmpMatch = new List<Regex>();
            List<Regex> tmpIgnore = new List<Regex>();
            foreach (RegexpElement ree in selector.Regexps)
            {
                Regex re = new Regex(ree.Value, RegexOptions.Singleline);
                switch (ree.Type)
                {
                    case "match": tmpMatch.Add(re); break;
                    case "ignore": tmpIgnore.Add(re); break;
                    default: throw new Exception("unknown regex type: " + ree.Type);
                }
            }
            match = tmpMatch.ToArray();
            ignore = tmpMatch.ToArray();

            if (interval <= 0)
            {
                onlyWatcher = true;
            }

            // Create a new FileSystemWatcher and set its properties.
            watcher = new FileSystemWatcher();
            watcher.Path = Path.GetDirectoryName(filename);
            watcher.Filter = Path.GetFileName(filename);
            // Watch for changes (assuming we are monitoring log file
            // where we just append data to the end of the file)
            watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.DirectoryName;

            // Add event handlers.
            watcher.Created += new FileSystemEventHandler((s, e) => FileWatcherReplaced(s, e));
            watcher.Deleted += new FileSystemEventHandler((s, e) => FileWatcherReplaced(s, e));
            watcher.Renamed += new RenamedEventHandler((s, e) => FileWatcherReplaced(s, e));

            if (onlyWatcher)
            {
                watcher.NotifyFilter |= NotifyFilters.Size;
                watcher.Changed += new FileSystemEventHandler((s, e) => FileWatcherChanged(s, e));
                // Increase size of internal buffer used to monitor all changes in given directory.
                // It can help not to loose change events in case of heavy activity in log
                // directory - it is probably better not to use this watcher for changes
                // in monitored file by setting interval to some reasonable number (e.g.
                // 1000 microseconds), because of better reliability. This buffer is using
                // non-swappable memory (be careful with its size)
                //watcher.InternalBufferSize *= 16;

                // signal used to synchronize event processing deactivation with
                // currently running ProcessLines code
                exit = new AutoResetEvent(false);
            }
            else
            {
                // signal used to interupt waiting line processing thread
                wait = new AutoResetEvent(false);
            }
        }
コード例 #21
0
ファイル: EventLog.cs プロジェクト: vokac/F2B
        public EventLogInput(InputElement input, SelectorElement selector, EventQueue equeue)
            : base(input, selector, equeue)
        {
            // Event log query with suppressed events logged by this service
            StringBuilder qstr = new StringBuilder();
            qstr.Append("<QueryList>");
            qstr.Append("<Query>");
            qstr.Append(selector.Query.Value);
            qstr.Append("<Suppress Path=\"Application\">*[System/Provider/@Name=\"F2B\"]</Suppress>");
            qstr.Append("</Query>");
            qstr.Append("</QueryList>");

            EventLogSession session = null;
            if (input.Server != string.Empty)
            {
                SecureString pw = new SecureString();
                Array.ForEach(input.Password.ToCharArray(), pw.AppendChar);
                session = new EventLogSession(input.Server, input.Domain,
                                              input.Username, pw,
                                              SessionAuthentication.Default);
                pw.Dispose();
            }

            EventLogQuery query = new EventLogQuery(null, PathType.LogName, qstr.ToString());
            if (session != null)
            {
                query.Session = session;
            }

            // create event watcher (must be enable later)
            watcher = new EventLogWatcher(query);
            watcher.EventRecordWritten +=
                new EventHandler<EventRecordWrittenEventArgs>(
                    (s, a) => EventRead(s, a));

            // event data parsers (e.g. XPath + regex to extract event data)
            // (it is important to preserve order - it is later used as array index)
            List<Tuple<string, EventDataElement>> tmp = new List<Tuple<string, EventDataElement>>();
            tmp.Add(new Tuple<string,EventDataElement>("address", selector.Address));
            tmp.Add(new Tuple<string,EventDataElement>("port", selector.Port));
            tmp.Add(new Tuple<string,EventDataElement>("username", selector.Username));
            tmp.Add(new Tuple<string,EventDataElement>("domain", selector.Domain));

            evtmap = new Dictionary<string, Tuple<int, int>>();
            evtregex = new List<Regex>();
            List<string> xPathRefs = new List<string>();

            for (int i = 0; i < tmp.Count; i++)
            {
                string evtdescr = tmp[i].Item1;
                EventDataElement evtdata = tmp[i].Item2;

                if (evtdata == null || string.IsNullOrEmpty(evtdata.XPath))
                {
                    if (evtdescr == "address")
                    {
                        throw new ArgumentException("No address in " + Name + " configuration");
                    }

                    evtmap[evtdescr] = new Tuple<int, int>(i, -1);

                    continue;
                }

                Regex regex = null;
                if (!string.IsNullOrWhiteSpace(evtdata.Value))
                {
                    string evtstr = evtdata.Value.Trim();
                    try
                    {
                        regex = new Regex(evtstr, RegexOptions.IgnoreCase | RegexOptions.Singleline);
                    }
                    catch (ArgumentException ex)
                    {
                        Log.Error("Invalid " + Name + " " + evtdescr + " regex: "
                            + evtstr + " (" + ex.Message + ")");
                        throw;
                    }
                }

                evtregex.Add(regex);
                if (xPathRefs.Contains(evtdata.XPath))
                {
                    int index = xPathRefs.IndexOf(evtdata.XPath);
                    evtmap[evtdescr] = new Tuple<int, int>(i, index);
                }
                else
                {
                    xPathRefs.Add(evtdata.XPath);
                    evtmap[evtdescr] = new Tuple<int, int>(i, xPathRefs.Count - 1);
                }
            }

            Debug.Assert(tmp.Count == evtmap.Count,
                "Invalid index map size (tmp[" + tmp.Count
                + "] != map[" + evtmap.Count + "]).");

            evtsel = new EventLogPropertySelector(xPathRefs);
        }
コード例 #22
0
ファイル: SpriteQuad.cs プロジェクト: treytomes/DirectCanvas
        /// <summary>
        /// Creates the input elements that describe the vertices to the GPU
        /// </summary>
        private InputElement[] CreateInputElements()
        {
            var layoutInstanced = new InputElement[10];

            layoutInstanced[0] = new InputElement("POSITION", 0, Format.R32G32_Float, 0, 0, InputClassification.PerVertexData, 0);
            layoutInstanced[1] = new InputElement("TEXCOORD", 0, Format.R32G32_Float, InputElement.AppendAligned, 0, InputClassification.PerVertexData, 0);
            layoutInstanced[2] = new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 0, 1, InputClassification.PerInstanceData, 1);
            layoutInstanced[3] = new InputElement("SOURCERECT", 0, Format.R32G32B32A32_Float, 16, 1, InputClassification.PerInstanceData, 1);
            layoutInstanced[4] = new InputElement("TEXTURESIZE", 0, Format.R32G32_Float, 32, 1, InputClassification.PerInstanceData, 1);
            layoutInstanced[5] = new InputElement("TEXTUREINDEX", 0, Format.R8_UInt, 40, 1, InputClassification.PerInstanceData, 1);
            layoutInstanced[6] = new InputElement("TRANSLATION", 0, Format.R32G32_Float, 44, 1, InputClassification.PerInstanceData, 1);
            layoutInstanced[7] = new InputElement("SCALEFACTOR", 0, Format.R32G32_Float, 52, 1, InputClassification.PerInstanceData, 1);
            layoutInstanced[8] = new InputElement("ROTATE", 0, Format.R32G32B32_Float, 60, 1, InputClassification.PerInstanceData, 1);
            layoutInstanced[9] = new InputElement("ROTATIONCENTER", 0, Format.R32G32_Float, 72, 1, InputClassification.PerInstanceData, 1);

            return layoutInstanced;
        }
コード例 #23
0
ファイル: Controller.cs プロジェクト: davelondon/dontstayin
		public static bool WhenLoggedInButton(InputElement element)
		{
			return WhenLoggedInButtonValidator(element, "");
		}
コード例 #24
0
ファイル: Controller.cs プロジェクト: davelondon/dontstayin
		void defaultButton(InputElement textBox, InputElement button)
		{
			DomEvent.AddHandler(textBox, "keyup", delegate(DomEvent e)
			{
				if (e.KeyCode == 13)
				{
					if (AsyncInProgress)
						return;

					button.Click();

				}
			});
		}
コード例 #25
0
		public HtmlAutoCompleteBehaviour(InputElement input, InputElement hiddenInput, DOMElement anchor, bool isSuggest, InputElement parametersHiddenField)
		{
			DOMAttribute cometAtt = input.GetAttributeNode(HtmlAutoCompleteAttributes.CometServiceUrl);

			remoteSuggestionsGetter = new WebServiceRemoteSuggestionsGetter(
				input.GetAttributeNode(HtmlAutoCompleteAttributes.WebServiceUrl).Value,
				input.GetAttributeNode(HtmlAutoCompleteAttributes.WebServiceMethod).Value
			);
			
			this.mode = isSuggest == true ? HtmlAutoCompleteMode.Suggest : HtmlAutoCompleteMode.Complete;
			this.input = input;
			this.hiddenInput = hiddenInput;
			this.anchor = anchor == null ? input : anchor;
			DomEvent.AddHandler(input, "blur", delegate(DomEvent e) { Window.SetTimeout(DoBlur, 250); });
			DomEvent.AddHandler(input, "keydown", this.HandleKeyDown);
			DomEvent.AddHandler(input, "keyup", this.HandleKeyUp);
			DomEvent.AddHandler(input, "focus", CallOnFocus);

			DOMAttribute waterMarkNode = input.GetAttributeNode(HtmlAutoCompleteAttributes.Watermark);
			if (waterMarkNode != null)
			{
				watermarker = new WatermarkExtender(input, input.GetAttributeNode(HtmlAutoCompleteAttributes.Watermark).Value);
			}
			DOMAttribute popupLeftNode = input.GetAttributeNode(HtmlAutoCompleteAttributes.PopupLeftOffset);
			popupLeftOffset = popupLeftNode == null ? 0 : int.ParseInvariant(popupLeftNode.Value);
			DOMAttribute popupTopNode = input.GetAttributeNode(HtmlAutoCompleteAttributes.PopupTopOffset);
			popupTopOffset = popupTopNode == null ? 0 : int.ParseInvariant(popupTopNode.Value);
			DOMAttribute rightAlignNode = input.GetAttributeNode(HtmlAutoCompleteAttributes.RightAlign);
			rightAlign = rightAlignNode == null ? false : bool.Parse(rightAlignNode.Value);
			
			if (input.GetAttributeNode(HtmlAutoCompleteAttributes.PopupLeftOffset) != null)
			{
				popupLeftOffset = int.ParseInvariant(input.GetAttributeNode(HtmlAutoCompleteAttributes.PopupLeftOffset).Value);
			}
			Parameters = new PairListField(parametersHiddenField);
			Suggestions.OnSuggestionsChanged = delegate() { DisplaySuggestionsInPopupMenu(); };

			this.remoteSuggestionsGetter.OnAllSuggestionsReceived = delegate() 
			{ 
				RemoveLowPrioritySuggestionsAndSetRemainingSuggestionsToLowPriority();
				HideAjaxIcon();
			};
			this.remoteSuggestionsGetter.OnSuggestionsRequested = delegate()
			                                                      {
			                                                      	ShowAjaxIcon();
			                                                      };
			
			this.remoteSuggestionsGetter.OnSuggestionReceived = delegate(Suggestion[] newSuggestions) 
			{
				Trace.Write("Received" + newSuggestions.Length + "suggestions");
				if (TransformReceivedSuggestions != null)
				{
					AddSuggestions(TransformReceivedSuggestions(newSuggestions, maxNumberOfItemsToGet));
				}
				else
				{
					AddSuggestions(newSuggestions);
				}
			};
			this.remoteSuggestionsGetter.OnAbortCurrentRequest= delegate()
			                                                      {
			                                                      	HideAjaxIcon();

			                                                      };
			

		}
コード例 #26
0
 public InputLayoutDescription(InputElement[] elements)
 {
     Elements = elements;
 }
コード例 #27
0
ファイル: Vertex.cs プロジェクト: adrianj/Direct3D-Testing
 public InputElement[] GetInputElements()
 {
     InputElement [] ret = new InputElement[]
     {
         new InputElement("POSITION",0,Format.R32G32B32_Float,0,0),
         new InputElement("NORMAL",0,Format.R32G32B32A32_Float,16,0),
         new InputElement("COLOR",0,Format.R32G32B32A32_Float,32,0)
     };
     return ret;
 }
コード例 #28
0
 public VertexLayoutD3d11(InputElement[] elems)
 {
     m_Elems = elems;
 }
コード例 #29
0
        private InputElement[] BindInputLayout(out int vertexsize)
        {
            InputElement[] inputlayout = new InputElement[this.FInLayout.SliceCount];
            vertexsize = 0;
            for (int i = 0; i < this.FInLayout.SliceCount; i++)
            {

                if (this.FInLayout.PluginIO.IsConnected && this.FInLayout[i] != null)
                {
                    inputlayout[i] = this.FInLayout[i];
                }
                else
                {
                    //Set deault, can do better here
                    inputlayout[i] = new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0);
                }
                vertexsize += FormatHelper.Instance.GetSize(inputlayout[i].Format);
            }
            InputLayoutFactory.AutoIndex(inputlayout);

            return inputlayout;
        }
コード例 #30
0
    private void _UpdateElements(IEnumerable<RawInput> inputs)
    {
        foreach (var element in _InputElements.Values)
            element.Unplugged = true;

        foreach (var input in inputs)
        {
            if (!_InputElements.ContainsKey(input.ElementType))
            {
                var inputElement = new InputElement();
                inputElement.ControlPosition = input.Position;
                inputElement.EntryTime = Time.time;
                inputElement.ElementType = input.ElementType;

                _InputElements.Add(input.ElementType, inputElement);

                if (_Prefabs.ContainsKey(input.ElementType))
                    _CreateElement(input.ElementType, input.Position);
            }

            _InputElements[input.ElementType].Unplugged = false;
        }

        var unpluggeds = _InputElements.Values.Where(e => e.Unplugged).Select(e => e.ElementType).ToList();

        foreach (var unplugged in unpluggeds)
        {
            if (_InputElements[unplugged].Fusioned)
                _TryDefuse(unplugged);
            else
                _RemoveElement(unplugged);

            _InputElements.Remove(unplugged);
        }
    }
コード例 #31
0
		public void Constructor_MessageNull_ThrowArgumentNullException()
		{
			// Arrange
			var target = new InputElement("Message", typeof(int));

		}
コード例 #32
0
        private void LoadAssets()
        {
            DescriptorRange[] ranges = new DescriptorRange[] { new DescriptorRange() { RangeType = DescriptorRangeType.ConstantBufferView, BaseShaderRegister = 0, OffsetInDescriptorsFromTableStart = int.MinValue, DescriptorCount = 1 } };
            RootParameter parameter = new RootParameter(ShaderVisibility.Vertex, ranges);

            // Create an empty root signature.
            RootSignatureDescription rootSignatureDesc = new RootSignatureDescription(RootSignatureFlags.AllowInputAssemblerInputLayout, new RootParameter[] { parameter });
            rootSignature = device.CreateRootSignature(rootSignatureDesc.Serialize());

            // Create the pipeline state, which includes compiling and loading shaders.
            #if DEBUG
            var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "VSMain", "vs_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug));
            #else
            var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "VSMain", "vs_5_0"));
            #endif

            #if DEBUG
            var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "PSMain", "ps_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug));
            #else
            var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "PSMain", "ps_5_0"));
            #endif

            // Define the vertex input layout.
            InputElement[] inputElementDescs = new InputElement[]
            {
                    new InputElement("POSITION",0,Format.R32G32B32_Float,0,0),
                    new InputElement("COLOR",0,Format.R32G32B32A32_Float,12,0)
            };

            // Describe and create the graphics pipeline state object (PSO).
            GraphicsPipelineStateDescription psoDesc = new GraphicsPipelineStateDescription()
            {
                InputLayout = new InputLayoutDescription(inputElementDescs),
                RootSignature = rootSignature,
                VertexShader = vertexShader,
                PixelShader = pixelShader,
                RasterizerState = RasterizerStateDescription.Default(),
                BlendState = BlendStateDescription.Default(),
                DepthStencilFormat = SharpDX.DXGI.Format.D32_Float,
                DepthStencilState = new DepthStencilStateDescription() { IsDepthEnabled = false, IsStencilEnabled = false },
                SampleMask = int.MaxValue,
                PrimitiveTopologyType = PrimitiveTopologyType.Triangle,
                RenderTargetCount = 1,
                Flags = PipelineStateFlags.None,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                StreamOutput = new StreamOutputDescription()
            };
            psoDesc.RenderTargetFormats[0] = SharpDX.DXGI.Format.R8G8B8A8_UNorm;

            pipelineState = device.CreateGraphicsPipelineState(psoDesc);

            // Create the command list.
            commandList = device.CreateCommandList(CommandListType.Direct, commandAllocator, pipelineState);

            // Create the vertex buffer.
            float aspectRatio = viewport.Width / viewport.Height;

            // Define the geometry for a triangle.
            Vertex[] triangleVertices = new Vertex[]
            {
                    new Vertex() {position=new Vector3(0.0f, 0.25f * aspectRatio, 0.0f ),color=new Vector4(1.0f, 0.0f, 0.0f, 1.0f ) },
                    new Vertex() {position=new Vector3(0.25f, -0.25f * aspectRatio, 0.0f),color=new Vector4(0.0f, 1.0f, 0.0f, 1.0f) },
                    new Vertex() {position=new Vector3(-0.25f, -0.25f * aspectRatio, 0.0f),color=new Vector4(0.0f, 0.0f, 1.0f, 1.0f ) },
            };

            int vertexBufferSize = Utilities.SizeOf(triangleVertices);

            // Note: using upload heaps to transfer static data like vert buffers is not
            // recommended. Every time the GPU needs it, the upload heap will be marshalled
            // over. Please read up on Default Heap usage. An upload heap is used here for
            // code simplicity and because there are very few verts to actually transfer.
            vertexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(vertexBufferSize), ResourceStates.GenericRead);

            // Copy the triangle data to the vertex buffer.
            IntPtr pVertexDataBegin = vertexBuffer.Map(0);
            Utilities.Write(pVertexDataBegin, triangleVertices, 0, triangleVertices.Length);
            vertexBuffer.Unmap(0);

            // Initialize the vertex buffer view.
            vertexBufferView = new VertexBufferView();
            vertexBufferView.BufferLocation = vertexBuffer.GPUVirtualAddress;
            vertexBufferView.StrideInBytes = Utilities.SizeOf<Vertex>();
            vertexBufferView.SizeInBytes = vertexBufferSize;

            // Command lists are created in the recording state, but there is nothing
            // to record yet. The main loop expects it to be closed, so close it now.
            commandList.Close();

            constantBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(1024 * 64), ResourceStates.GenericRead);

            //// Describe and create a constant buffer view.
            ConstantBufferViewDescription cbvDesc = new ConstantBufferViewDescription()
            {
                BufferLocation = constantBuffer.GPUVirtualAddress,
                SizeInBytes = (Utilities.SizeOf<ConstantBuffer>() + 255) & ~255
            };
            device.CreateConstantBufferView(cbvDesc, constantBufferViewHeap.CPUDescriptorHandleForHeapStart);

            // Initialize and map the constant buffers. We don't unmap this until the
            // app closes. Keeping things mapped for the lifetime of the resource is okay.
            constantBufferPointer = constantBuffer.Map(0);
            Utilities.Write(constantBufferPointer, ref constantBufferData);

            // Create synchronization objects.
            fence = device.CreateFence(0, FenceFlags.None);
            fenceValue = 1;

            // Create an event handle to use for frame synchronization.
            fenceEvent = new AutoResetEvent(false);
        }
コード例 #33
0
 private static object ValidateTextualInput(InputElement element) {
     return (!ValidationUtil.StringIsNullOrEmpty(element.Value));
 }
コード例 #34
0
        private void LoadAssets()
        {
            DescriptorRange[] ranges = new DescriptorRange[] { new DescriptorRange() { RangeType = DescriptorRangeType.ConstantBufferView, BaseShaderRegister = 0, DescriptorCount = 1 } };
            RootParameter parameter = new RootParameter(ShaderVisibility.Vertex, ranges);

            // Create a root signature.
            RootSignatureDescription rootSignatureDesc = new RootSignatureDescription(RootSignatureFlags.AllowInputAssemblerInputLayout, new RootParameter[] { parameter });
            rootSignature = device.CreateRootSignature(rootSignatureDesc.Serialize());

            // Create the pipeline state, which includes compiling and loading shaders.

            #if DEBUG
            var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "VSMain", "vs_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug));
            #else
            var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "VSMain", "vs_5_0"));
            #endif

            #if DEBUG
            var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "PSMain", "ps_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug));
            #else
            var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "PSMain", "ps_5_0"));
            #endif

            // Define the vertex input layout.
            InputElement[] inputElementDescs = new InputElement[]
            {
                    new InputElement("POSITION",0,Format.R32G32B32_Float,0,0),
                    new InputElement("COLOR",0,Format.R32G32B32A32_Float,12,0)
            };

            // Describe and create the graphics pipeline state object (PSO).
            GraphicsPipelineStateDescription psoDesc = new GraphicsPipelineStateDescription()
            {
                InputLayout = new InputLayoutDescription(inputElementDescs),
                RootSignature = rootSignature,
                VertexShader = vertexShader,
                PixelShader = pixelShader,
                RasterizerState = RasterizerStateDescription.Default(),
                BlendState = BlendStateDescription.Default(),
                DepthStencilFormat = SharpDX.DXGI.Format.D32_Float,
                DepthStencilState = DepthStencilStateDescription.Default(),
                SampleMask = int.MaxValue,
                PrimitiveTopologyType = PrimitiveTopologyType.Triangle,
                RenderTargetCount = 1,
                Flags = PipelineStateFlags.None,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                StreamOutput = new StreamOutputDescription()
            };
            psoDesc.RenderTargetFormats[0] = SharpDX.DXGI.Format.R8G8B8A8_UNorm;

            pipelineState = device.CreateGraphicsPipelineState(psoDesc);

            // Create the command list.
            commandList = device.CreateCommandList(CommandListType.Direct, commandAllocator, pipelineState);

            // Command lists are created in the recording state, but there is nothing
            // to record yet. The main loop expects it to be closed, so close it now.
            commandList.Close();

            // Create the vertex buffer.
            float aspectRatio = viewport.Width / viewport.Height;

            // Define the geometry for a cube.

            Vertex[] vertices = new[]
            {
                ////TOP
                new Vertex(new Vector3(-5,5,5),new Vector4(0,1,0,0)),
                new Vertex(new Vector3(5,5,5),new Vector4(0,1,0,0)),
                new Vertex(new Vector3(5,5,-5),new Vector4(0,1,0,0)),
                new Vertex(new Vector3(-5,5,-5),new Vector4(0,1,0,0)),
                //BOTTOM
                new Vertex(new Vector3(-5,-5,5),new Vector4(1,0,1,1)),
                new Vertex(new Vector3(5,-5,5),new Vector4(1,0,1,1)),
                new Vertex(new Vector3(5,-5,-5),new Vector4(1,0,1,1)),
                new Vertex(new Vector3(-5,-5,-5),new Vector4(1,0,1,1)),
                //LEFT
                new Vertex(new Vector3(-5,-5,5),new Vector4(1,0,0,1)),
                new Vertex(new Vector3(-5,5,5),new Vector4(1,0,0,1)),
                new Vertex(new Vector3(-5,5,-5),new Vector4(1,0,0,1)),
                new Vertex(new Vector3(-5,-5,-5),new Vector4(1,0,0,1)),
                //RIGHT
                new Vertex(new Vector3(5,-5,5),new Vector4(1,1,0,1)),
                new Vertex(new Vector3(5,5,5),new Vector4(1,1,0,1)),
                new Vertex(new Vector3(5,5,-5),new Vector4(1,1,0,1)),
                new Vertex(new Vector3(5,-5,-5),new Vector4(1,1,0,1)),
                //FRONT
                new Vertex(new Vector3(-5,5,5),new Vector4(0,1,1,1)),
                new Vertex(new Vector3(5,5,5),new Vector4(0,1,1,1)),
                new Vertex(new Vector3(5,-5,5),new Vector4(0,1,1,1)),
                new Vertex(new Vector3(-5,-5,5),new Vector4(0,1,1,1)),
                //BACK
                new Vertex(new Vector3(-5,5,-5),new Vector4(0,0,1,1)),
                new Vertex(new Vector3(5,5,-5),new Vector4(0,0,1,1)),
                new Vertex(new Vector3(5,-5,-5),new Vector4(0,0,1,1)),
                new Vertex(new Vector3(-5,-5,-5),new Vector4(0,0,1,1))
            };

            int vertexBufferSize = Utilities.SizeOf(vertices);

            // Note: using upload heaps to transfer static data like vert buffers is not
            // recommended. Every time the GPU needs it, the upload heap will be marshalled
            // over. Please read up on Default Heap usage. An upload heap is used here for
            // code simplicity and because there are very few verts to actually transfer.
            vertexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(vertexBufferSize), ResourceStates.GenericRead);

            // Copy the triangle data to the vertex buffer.
            IntPtr pVertexDataBegin = vertexBuffer.Map(0);
            Utilities.Write(pVertexDataBegin, vertices, 0, vertices.Length);
            vertexBuffer.Unmap(0);

            // Initialize the vertex buffer view.
            vertexBufferView = new VertexBufferView();
            vertexBufferView.BufferLocation = vertexBuffer.GPUVirtualAddress;
            vertexBufferView.StrideInBytes = Utilities.SizeOf<Vertex>();
            vertexBufferView.SizeInBytes = vertexBufferSize;

            //Create Index Buffer
            //Indices
            int[] indices = new int[]
            {
                0,1,2,0,2,3,
                4,6,5,4,7,6,
                8,9,10,8,10,11,
                12,14,13,12,15,14,
                16,18,17,16,19,18,
                20,21,22,20,22,23
            };
            int indexBufferSize = Utilities.SizeOf(indices);

            indexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(indexBufferSize), ResourceStates.GenericRead);

            // Copy the triangle data to the vertex buffer.
            IntPtr pIndexDataBegin = indexBuffer.Map(0);
            Utilities.Write(pIndexDataBegin, indices, 0, indices.Length);
            indexBuffer.Unmap(0);

            // Initialize the index buffer view.
            indexBufferView = new IndexBufferView();
            indexBufferView.BufferLocation = indexBuffer.GPUVirtualAddress;
            indexBufferView.Format = Format.R32_UInt;
            indexBufferView.SizeInBytes = indexBufferSize;

            //constant Buffer for each cubes
            constantBufferViewHeap = device.CreateDescriptorHeap(new DescriptorHeapDescription()
            {
                DescriptorCount = NumCubes,
                Type = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView,
                Flags = DescriptorHeapFlags.ShaderVisible
            });

            int constantBufferSize = (Utilities.SizeOf<Transform>() + 255) & ~255;
            constantBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(constantBufferSize * NumCubes), ResourceStates.GenericRead);
            constantBufferDescriptorSize = device.GetDescriptorHandleIncrementSize(DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView);

            //First cube
            ConstantBufferViewDescription cbvDesc = new ConstantBufferViewDescription()
            {
                BufferLocation = constantBuffer.GPUVirtualAddress,
                SizeInBytes = constantBufferSize
            };

            CpuDescriptorHandle cbHandleHeapStart = constantBufferViewHeap.CPUDescriptorHandleForHeapStart;

            for (int i = 0; i < NumCubes; i++)
            {
                device.CreateConstantBufferView(cbvDesc, cbHandleHeapStart);
                cbvDesc.BufferLocation += Utilities.SizeOf<Transform>();
                cbHandleHeapStart += constantBufferDescriptorSize;
            }

            InitBundles();
        }