Пример #1
0
        private void DisposeResources()
        {
            DisposingResources?.Invoke(this, EventArgs.Empty);
            foreach (var technique in techniqueDict.Values.ToArray())
            {
                if (technique.IsValueCreated)
                {
                    var t = technique.Value;
                    RemoveAndDispose(ref t);
                }
            }
            techniqueDict.Clear();
            RemoveAndDispose(ref shaderPoolManager);
            DisposeAndClear();
            Initialized = false;
            global::SharpDX.Toolkit.Graphics.WICHelper.Dispose();
#if DX11_1
            Disposer.RemoveAndDispose(ref device1);
#endif
            Disposer.RemoveAndDispose(ref device);
#if DEBUGMEMORY
            ReportResources();
#endif
        }
Пример #2
0
        private void RenderHostInternal_ExceptionOccurred(object sender, RelayExceptionEventArgs e)
        {
            var bindingExpression = this.GetBindingExpression(RenderExceptionProperty);

            if (bindingExpression != null)
            {
                // If RenderExceptionProperty is bound, we assume the exception will be handled.
                this.RenderException = e.Exception;
                e.Handled            = true;
            }

            // Fire RenderExceptionOccurred event
            this.RenderExceptionOccurred?.Invoke(sender, e);

            // If the Exception is still unhandled...
            if (!e.Handled)
            {
                // ... prevent a MessageBox.Show().
                this.MessageText = e.Exception.ToString();
                e.Handled        = true;
            }
            hostPresenter.Content = null;
            Disposer.RemoveAndDispose(ref renderHostInternal);
        }
 public void Dispose()
 {
     Disposer.RemoveAndDispose(ref _model);
 }
Пример #4
0
 /// <summary>
 ///
 /// </summary>
 public virtual void Dispose()
 {
     Disposer.RemoveAndDispose(ref _mContext);
 }
 /// <summary>
 /// Must release swapchain at last after all its created resources have been released.
 /// </summary>
 public override void DisposeAndClear()
 {
     base.DisposeAndClear();
     Disposer.RemoveAndDispose(ref swapChain);
 }
Пример #6
0
 public void Dispose()
 {
     Disposer.RemoveAndDispose(ref Shape);
 }
Пример #7
0
 public void Deinitialize()
 {
     Disposer.RemoveAndDispose(ref _effect);
     Disposer.RemoveAndDispose(ref _inputLayout);
 }
Пример #8
0
        public void Attach(ISceneHost host)
        {
            Host = host;

            Device device = host.Device;

            if (device == null)
            {
                throw new Exception("Scene host device is null");
            }

            try
            {
                ShaderBytecode shaderBytes = ShaderBytecode.CompileFromFile("Shaders\\Particle.fx", "fx_4_0", ShaderFlags.None, EffectFlags.None, null, null);
                ParticleEffect = new Effect(device, shaderBytes);
            }
            catch
            { }

            try
            {
                ShaderBytecode shaderBytes = ShaderBytecode.CompileFromFile("Shaders\\Shape.fx", "fx_4_0", ShaderFlags.None, EffectFlags.None, null, null);
                ShapeEffect = new Effect(device, shaderBytes);
            }
            catch
            { }

            try
            {
                ShaderBytecode shaderBytes = ShaderBytecode.CompileFromFile("Shaders\\Line.fx", "fx_4_0", ShaderFlags.None, EffectFlags.None, null, null);
                LineEffect = new Effect(device, shaderBytes);
            }
            catch
            { }


            EffectTechnique technique = this.ParticleEffect.GetTechniqueByIndex(0);
            EffectPass      pass      = technique.GetPassByIndex(0);

            this.ParticleLayout = new InputLayout(device, pass.Description.Signature, new[] {
                new InputElement("POSITION", 0, Format.R32G32_Float, 0, 0),
                new InputElement("POSITION", 1, Format.R32G32_Float, 8, 0),
                new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0)
            });

            this.ShapeLayout = new InputLayout(device, this.ShapeEffect.GetTechniqueByIndex(0).GetPassByIndex(0).Description.Signature, new[] {
                new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0)
            });

            this.LineLayout = new InputLayout(device, this.LineEffect.GetTechniqueByIndex(0).GetPassByIndex(0).Description.Signature, new[] {
                new InputElement("POSITION", 0, Format.R32G32_Float, 0, 0)
            });

            ParticleProjection = ParticleEffect.GetVariableByName("Projection").AsVector();
            ParticleCamera     = ParticleEffect.GetVariableByName("Camera").AsVector();

            ShapeCamera     = ShapeEffect.GetVariableByName("Camera").AsVector();
            ShapeProjection = ShapeEffect.GetVariableByName("Projection").AsVector();
            ShapeColor      = ShapeEffect.GetVariableByName("Color").AsVector();
            ShapePosition   = ShapeEffect.GetVariableByName("Position").AsVector();

            ParticlePass = ParticleEffect.GetTechniqueByIndex(0).GetPassByIndex(0);
            ShapePass    = ShapeEffect.GetTechniqueByIndex(0).GetPassByIndex(0);

            DataStream lines = new DataStream(linesCount * 8, true, true);

            for (int i = 0; i < linesCount; i++)
            {
                lines.Write(new Vector2(-1.0f + (float)i / (float)linesCount * 2.0f, 0));
            }

            lines.Position = 0;

            Disposer.RemoveAndDispose(ref this.LineBuffer);

            this.LineBuffer = new Buffer(device, lines, new BufferDescription()
            {
                BindFlags      = BindFlags.VertexBuffer,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags    = ResourceOptionFlags.None,
                SizeInBytes    = linesCount * 8,
                Usage          = ResourceUsage.Default
            });

            Disposer.RemoveAndDispose(ref lines);

            device.Flush();

            Initialized = true;
        }
Пример #9
0
        /// <summary>
        /// Detaches the scene from the device it was attached to, freeing all resources associated with the formerly attached device.
        /// </summary>
        public void Detach()
        {
            // Dispose all buffers
            if (null != _nextTriangleDeviceBuffers)
            {
                for (int i = _nextTriangleDeviceBuffers.Length - 1; i >= 0; --i)
                {
                    if (null != _nextTriangleDeviceBuffers[i])
                    {
                        foreach (var ele in _nextTriangleDeviceBuffers[i])
                        {
                            ele.Dispose();
                        }
                        _nextTriangleDeviceBuffers[i] = null;
                    }
                }
            }

            if (null != _thisTriangleDeviceBuffers)
            {
                for (int i = _thisTriangleDeviceBuffers.Length - 1; i >= 0; --i)
                {
                    if (null != _thisTriangleDeviceBuffers[i])
                    {
                        foreach (var ele in _thisTriangleDeviceBuffers[i])
                        {
                            ele.Dispose();
                        }
                        _thisTriangleDeviceBuffers[i] = null;
                    }
                }
            }

            Disposer.RemoveAndDispose(ref _markerGeometryTriangleDeviceBuffer);
            Disposer.RemoveAndDispose(ref _markerGeometryLineListBuffer);
            Disposer.RemoveAndDispose(ref _overlayGeometryTriangleDeviceBuffer);
            Disposer.RemoveAndDispose(ref _overlayGeometryLineListBuffer);
            // ------- end disposing buffers -----


            // now dispose all other device dependent variables, in inverse order than in Attach()

            Disposer.RemoveAndDispose(ref _lighting);

            for (int i = 0; i < _evClipPlanes.Length; ++i)
            {
                Disposer.RemoveAndDispose(ref _evClipPlanes[i]);
            }
            Disposer.RemoveAndDispose(ref _cbClipPlanes);
            ReleaseTextureFor1DColorProviders();
            Disposer.RemoveAndDispose(ref _evMaterialMetalnessValue);
            Disposer.RemoveAndDispose(ref _evMaterialDiffuseIntensity);
            Disposer.RemoveAndDispose(ref _evMaterialSpecularIntensity);
            Disposer.RemoveAndDispose(ref _evMaterialSpecularExponent);
            Disposer.RemoveAndDispose(ref _evMaterialDiffuseColor);
            Disposer.RemoveAndDispose(ref _cbMaterial);
            Disposer.RemoveAndDispose(ref _evEyePosition);
            Disposer.RemoveAndDispose(ref _evWorldViewProj);
            Disposer.RemoveAndDispose(ref _cbViewTransformation);
            for (int i = 0; i < _renderLayouts.Length; ++i)
            {
                _renderLayouts[i]?.Dispose();
            }

            Disposer.RemoveAndDispose(ref _lightingEffect);

            _cachedDevice = null;
        }
Пример #10
0
 public void Dispose()
 {
     Disposer.RemoveAndDispose(ref buffer);
 }
Пример #11
0
        public void Update(TimeSpan timeSpan)
        {
            if (!isRunning)
            {
                return;
            }

            TimeSpan ts = (DateTime.Now - Last);

            Time.Dt = (float)ts.TotalSeconds;
            //Time.Dt = 1.0f / 60.0f;

            Last = DateTime.Now;
            double fps = 1 / ts.TotalSeconds;

            sumFps += (float)fps;

            Profiles.Current.State.Score = Math.Max((int)(PlayerShip.Instance.Position.Y / 10), Profiles.Current.State.Score);

            if (counter++ % 60 == 0)
            {
                {
                    float fa = 0.18618986725025f;
                    float fb = 210125.0f / 156.0f;
                    float fc = 31.0f / 6.0f;

                    maxEntities = (int)(fa * Math.Sqrt(fb + Profiles.Current.State.Score) + fc);
                }
                {
                    float fa = 38.0f / 9.0f;
                    float fb = 70.0f / 9.0f;
                    float fc = 200f;

                    float x = (float)Profiles.Current.State.Score / 1000.0f;
                    linesSpeed = (int)(fa * x * x + fb * x + fc);
                }
            }

            for (int i = EntityManager.Count; i < maxEntities; i++)
            {
                EntityManager.Add(Rock.Create());
            }

            EntityManager.Update();
            ParticleManager.Update();
            Profiles.Current.State.LinesPosition += linesSpeed * Time.Dt;

            if (Profiles.Current.State.LinesPosition > PlayerShip.Instance.Position.Y)
            {
                GameOver();
            }

            Device device = Host.Device;

            if (ParticleManager.particleList.Count > 0)
            {
                DataStream particles = new DataStream(ParticleManager.particleList.Count * 32, true, true);

                for (int i = 0; i < ParticleManager.particleList.Count; i++)
                {
                    var particle = ParticleManager.particleList[i];

                    Vector2 a = new Vector2(particle.Position.X, particle.Position.Y);
                    Vector2 b = new Vector2(particle.Scale.X, -particle.Orientation);

                    particles.WriteRange(new[] { a, b });
                    particles.Write(particle.Color);
                }
                particles.Position = 0;

                Disposer.RemoveAndDispose(ref this.Particles);

                this.Particles = new Buffer(device, particles, new BufferDescription()
                {
                    BindFlags      = BindFlags.VertexBuffer,
                    CpuAccessFlags = CpuAccessFlags.None,
                    OptionFlags    = ResourceOptionFlags.None,
                    SizeInBytes    = ParticleManager.particleList.Count * 32,
                    Usage          = ResourceUsage.Default
                });

                Disposer.RemoveAndDispose(ref particles);
            }
        }
Пример #12
0
 public void Dispose()
 {
     Disposer.RemoveAndDispose(ref _mesh);
 }
Пример #13
0
        public void Load(ModelType modelType,
                         IFileLocator fileLocator,
                         Device renderDevice,
                         GraphicsSettings graphicsSettings)
        {
            if (_loadCancellationTokenSource != null)
            {
                _loadCancellationTokenSource.Cancel();
            }

            _loadCancellationTokenSource = new CancellationTokenSource();

            var modelPath = this.ModelObject.GetModelPath(modelType);

            this.LoadingTask = Task.Factory.StartNew(() =>
            {
                try
                {
                    using (Diagnostics.PotentialExceptionRegion)
                    {
                        using (var visualStream = OpenVisualFile(modelPath, fileLocator))
                        {
                            this.Visual = ModelVisual.ReadFrom(visualStream);
                            foreach (var rendetSet in Visual.RenderSets)
                            {
                                foreach (var group in rendetSet.Geometry.ModelPrimitiveGroups)
                                {
                                    var material       = group.Value.Material;
                                    material.ShowArmor = modelType == ModelType.Collision;
                                    material.Armor     = this.ArmoredObject.GetArmorGroup(material.Identifier);
                                }
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    this.LogInfo("exception occurred when loading {0} visual: {1}", modelType, e.Message);
                }
            },
                                                     _loadCancellationTokenSource.Token)
                               .ContinueWith(_ =>
            {
                try
                {
                    using (Diagnostics.PotentialExceptionRegion)
                    {
                        using (var primitivesStream = OpenPrimitiveFile(modelPath, fileLocator))
                        {
                            this.Primitives = ModelPrimitive.ReadFrom(primitivesStream,
                                                                      Visual,
                                                                      modelType == ModelType.Collision);
                        }
                    }
                }
                catch (Exception e)
                {
                    this.LogInfo("exception occurred when loading {0} primitives: {1}",
                                 modelType,
                                 e.Message);
                }
            },
                                             _loadCancellationTokenSource.Token)
                               .ContinueWith(_ =>
            {
                var oldMesh = this.Mesh;
                this.Mesh   = new ModuleMesh(this, fileLocator, renderDevice, graphicsSettings);
                Disposer.RemoveAndDispose(ref oldMesh);
            },
                                             _loadCancellationTokenSource.Token);
        }
Пример #14
0
 public void Dispose()
 {
     SetRenderTargetDX10(null);
     Disposer.RemoveAndDispose(ref _renderTarget);
     DeviceService.EndD3D();
 }
Пример #15
0
        private void CreateAndBindTargets()
        {
            this.D3DSurface.SetRenderTargetDX10(null);

            Disposer.RemoveAndDispose(ref this.RenderTargetView);
            Disposer.RemoveAndDispose(ref this.RenderTarget1View);
            Disposer.RemoveAndDispose(ref this.RenderTarget2View);
            Disposer.RemoveAndDispose(ref this.OutputRenderTargetView);
            Disposer.RemoveAndDispose(ref this.DepthStencilView);
            Disposer.RemoveAndDispose(ref this.BlendingState);
            Disposer.RemoveAndDispose(ref this.OutputRenderTarget);
            Disposer.RemoveAndDispose(ref this.RenderTarget);
            Disposer.RemoveAndDispose(ref this.RenderTarget1);
            Disposer.RemoveAndDispose(ref this.RenderTarget2);
            Disposer.RemoveAndDispose(ref this.ShaderTargetView);
            Disposer.RemoveAndDispose(ref this.ShaderTarget1View);
            Disposer.RemoveAndDispose(ref this.ShaderTarget2View);
            Disposer.RemoveAndDispose(ref this.DepthStencil);

            width  = Math.Max((int)base.ActualWidth, 100);
            height = Math.Max((int)base.ActualHeight, 100);
            SampleDescription quality = new SampleDescription(1, 0);

            Texture2DDescription colordesc = new Texture2DDescription
            {
                BindFlags         = BindFlags.RenderTarget | BindFlags.ShaderResource,
                Format            = Format.B8G8R8A8_UNorm,
                Width             = (int)width,
                Height            = (int)height,
                MipLevels         = 1,
                SampleDescription = quality,
                Usage             = ResourceUsage.Default,
                OptionFlags       = ResourceOptionFlags.Shared,
                CpuAccessFlags    = CpuAccessFlags.None,
                ArraySize         = 1
            };

            Texture2DDescription depthdesc = new Texture2DDescription
            {
                BindFlags         = BindFlags.DepthStencil,
                Format            = Format.D32_Float_S8X24_UInt,
                Width             = (int)width,
                Height            = (int)height,
                MipLevels         = 1,
                SampleDescription = quality,
                Usage             = ResourceUsage.Default,
                OptionFlags       = ResourceOptionFlags.None,
                CpuAccessFlags    = CpuAccessFlags.None,
                ArraySize         = 1
            };

            this.RenderTarget       = new Texture2D(this.Device, colordesc);
            this.OutputRenderTarget = new Texture2D(this.Device, colordesc);

            this.DepthStencil = new Texture2D(this.Device, depthdesc);

            RenderTarget1 = new Texture2D(this.Device, new Texture2DDescription
            {
                ArraySize         = 1,
                BindFlags         = BindFlags.RenderTarget | BindFlags.ShaderResource,
                CpuAccessFlags    = CpuAccessFlags.None,
                Format            = Format.B8G8R8A8_UNorm,
                Width             = (int)width / 2,
                Height            = (int)height / 2,
                MipLevels         = 1,
                OptionFlags       = ResourceOptionFlags.Shared,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = ResourceUsage.Default
            });

            RenderTarget2 = new Texture2D(this.Device, new Texture2DDescription
            {
                ArraySize         = 1,
                BindFlags         = BindFlags.RenderTarget | BindFlags.ShaderResource,
                CpuAccessFlags    = CpuAccessFlags.None,
                Format            = Format.B8G8R8A8_UNorm,
                Width             = (int)width / 2,
                Height            = (int)height / 2,
                MipLevels         = 1,
                OptionFlags       = ResourceOptionFlags.Shared,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = ResourceUsage.Default
            });

            BlendStateDescription stateDesc = new BlendStateDescription
            {
                SourceBlend           = BlendOption.One,
                DestinationBlend      = BlendOption.One,
                BlendOperation        = BlendOperation.Add,
                SourceAlphaBlend      = BlendOption.One,
                DestinationAlphaBlend = BlendOption.One,
                AlphaBlendOperation   = BlendOperation.Add
            };

            stateDesc.IsBlendEnabled[0]        = true;
            stateDesc.RenderTargetWriteMask[0] = ColorWriteMaskFlags.All;
            stateDesc.IsAlphaToCoverageEnabled = false;

            BlendingState = new BlendState(Device, ref stateDesc);

            this.DepthStencilView = new DepthStencilView(this.Device, this.DepthStencil);

            this.RenderTargetView       = new RenderTargetView(this.Device, this.RenderTarget);
            this.RenderTarget1View      = new RenderTargetView(this.Device, this.RenderTarget1);
            this.RenderTarget2View      = new RenderTargetView(this.Device, this.RenderTarget2);
            this.OutputRenderTargetView = new RenderTargetView(this.Device, this.OutputRenderTarget);

            this.ShaderTargetView  = new ShaderResourceView(this.Device, this.RenderTarget);
            this.ShaderTarget1View = new ShaderResourceView(this.Device, this.RenderTarget1);
            this.ShaderTarget2View = new ShaderResourceView(this.Device, this.RenderTarget2);

            try
            {
                this.D3DSurface.SetRenderTargetDX10(this.OutputRenderTarget);
            }
            catch
            { }
        }
Пример #16
0
 protected override void Dispose(bool disposing)
 {
     Log.Info("dispose");
     Disposer.RemoveAndDispose(ref _vertexDeclaration);
 }
            public override void Render(RenderContext context, DeviceContextProxy deviceContext)
            {
                if (!enableReflector)
                {
                    return;
                }
                if (CreateCubeMapResources())
                {
                    RaiseInvalidateRender();
                    return; // Skip this frame if texture resized to reduce latency.
                }
                else if(!(IsDynamicScene || context.UpdateSceneGraphRequested || context.UpdatePerFrameRenderableRequested))
                {
                    return;
                }
                context.IsInvertCullMode = true;
                var camLook = Vector3.Normalize(context.Camera.LookDirection);

                Exception exception = null;
    #if TEST
                for (int index = 0; index < 6; ++index)
    #else
                Parallel.For(0, 6, (index) =>
    #endif
                {               
                    try
                    {
                        var ctx = contextPool.Get();
                        ctx.ClearRenderTargetView(cubeRTVs[index], context.RenderHost.ClearColor);
                        ctx.ClearDepthStencilView(cubeDSVs[index], DepthStencilClearFlags.Depth, 1, 0);
                        ctx.SetRenderTarget(cubeDSVs[index], cubeRTVs[index]);
                        ctx.SetViewport(ref viewport);
                        ctx.SetScissorRectangle(0, 0, FaceSize, FaceSize);
                        var transforms = new GlobalTransformStruct();
                        transforms.Projection = cubeFaceCameras.Cameras[index].Projection;
                        transforms.View = cubeFaceCameras.Cameras[index].View;
                        transforms.Viewport = new Vector4(FaceSize, FaceSize, 1/FaceSize, 1/FaceSize);
                        transforms.ViewProjection = transforms.View * transforms.Projection;

                        modelCB.Upload(ctx, ref transforms);

                        var frustum = new BoundingFrustum(transforms.ViewProjection);
                        //Render opaque
                        for (int i = 0; i < context.RenderHost.PerFrameOpaqueNodes.Count; ++i)
                        {
                            var node = context.RenderHost.PerFrameOpaqueNodes[i];
                            if (node.GUID != this.GUID && !IgnoredGuid.Contains(node.GUID) && node.TestViewFrustum(ref frustum))
                            {
                                node.Render(context, ctx);
                            }
                        }
                        //Render particle
                        for (int i = 0; i < context.RenderHost.PerFrameParticleNodes.Count; ++i)
                        {
                            var node = context.RenderHost.PerFrameParticleNodes[i];
                            if (node.GUID != this.GUID && !IgnoredGuid.Contains(node.GUID) && node.TestViewFrustum(ref frustum))
                            {
                                node.Render(context, ctx);
                            }
                        }
                        commands[index] = ctx.FinishCommandList(true);
                        contextPool.Put(ctx);
                    }
                    catch(Exception ex)
                    {
                        exception = ex;
                    }                
                }
    #if !TEST
                );
    #endif
                context.IsInvertCullMode = false;
                if (exception != null)
                {
                    throw exception;
                }          
                for (int i = 0; i < commands.Length; ++i)
                {
                    if (commands[i] != null)
                    {
                        Device.ImmediateContext.ExecuteCommandList(commands[i], true);
                        Disposer.RemoveAndDispose(ref commands[i]);
                    }
                }
                deviceContext.GenerateMips(CubeMap);
                context.UpdatePerFrameData(true, false, deviceContext);
            }
Пример #18
0
        public static void Update()
        {
            isUpdating = true;

            foreach (Entity entity in Entities)
            {
                entity.PreUpdate();
            }

            IEnumerable <CollisionData> Collisions = GetProbableCollisions();

            foreach (CollisionData data in Collisions)
            {
                bool collision = data.Check();
                if (collision)
                {
                    Random rand = new Random();
                    data.CalculateN();
                    data.CalculateJ();

                    ((PhysicsEntity)data.Object1).Collision(data);
                    data.Swap();
                    ((PhysicsEntity)data.Object1).Collision(data);

                    float  hue1   = 2;
                    float  hue2   = (hue1 + rand.NextFloat(0, 2)) % 6f;
                    Color4 color1 = ColorUtil.HSVToColor(hue1, 0.5f, 1);
                    Color4 color2 = ColorUtil.HSVToColor(hue2, 0.5f, 1);

                    for (int i = 0; i < 150; i++)
                    {
                        float speed = 12.0f * (1.0f - 1 / rand.NextFloat(1, 3));

                        Color4  color = Color4.Lerp(color1, color2, rand.NextFloat(0, 1));
                        Vector2 dir   = rand.NextVector2(1, 1);
                        ParticleManager.CreateParticle((data.Point1 + data.Point2) / 2, color, 190, Vector2.One, dir * speed, 0.2f);
                    }
                }
            }

            foreach (Entity entity in Entities)
            {
                entity.Update();
            }

            foreach (Entity entity in Entities)
            {
                entity.PostUpdate();
            }

            isUpdating = false;

            for (int i = Entities.Count - 1; i >= 0; i--)
            {
                Entity ent = Entities[i];
                if (ent.isExpired)
                {
                    Disposer.RemoveAndDispose(ref ent);
                    Entities.RemoveAt(i);
                }
            }

            Entities.AddRange(addedEntities);

            addedEntities.Clear();
        }