コード例 #1
0
        public void SetMesh(Vertex3D[] mesh)
        {
            if (mesh == null)
            {
                _frameworkMessenger.Report("Supplied Mesh is null");
                return;
            }

            var numVertices = mesh.Length;

            var remainder = numVertices % 3;

            if (remainder != 0)
            {
                _frameworkMessenger.Report("Supplied mesh number of vertices is not a multiple of 3. Extra vertices being cut... it's all about triangles baby");
                numVertices -= remainder;
            }

            if (numVertices <= 0)
            {
                return;
            }

            MeshNumberVertices = (uint)numVertices;

            MeshVertexBuffer?.Dispose();

            MeshVertexBuffer = _systemComponents.Factory.CreateBuffer(new BufferDescription(MeshNumberVertices * Vertex3D.SizeInBytes, BufferUsage.VertexBuffer));

            _systemComponents.Device.UpdateBuffer(MeshVertexBuffer, 0, ref mesh[0], MeshNumberVertices * Vertex3D.SizeInBytes);
        }
コード例 #2
0
        public void Render(CommandList cl, ICustomShaderStageModel stage, GpuSurface t0, GpuSurface t1, GpuSurface t2, GpuSurface t3, GpuSurface target)
        {
            if (cl == null || stage == null || target == null)
            {
                _frameworkMessenger.Report("Warning: you are feeding a Custom Effect Stage Renderer null inputs, aborting");
                return;
            }

            cl.SetPipeline(stage.Pipeline);
            cl.SetFramebuffer(target.Framebuffer);
            _viewportManager.ConfigureViewportForActiveFramebuffer(cl);
            cl.SetVertexBuffer(0, _ndcQuadVertexBuffer.Buffer);

            var assignedTextureCount = 0;
            var numUniforms          = stage.NumberUserUniforms;

            for (var n = 0; n < numUniforms; n++)
            {
                if (stage.UserUniformType(n) == ShaderUniformType.Texture)
                {
                    if (assignedTextureCount < 4)
                    {
                        GpuSurface surface = null;
                        switch (assignedTextureCount)
                        {
                        case 0:
                            surface = t0;
                            break;

                        case 1:
                            surface = t1;
                            break;

                        case 2:
                            surface = t2;
                            break;

                        case 3:
                            surface = t3;
                            break;
                        }
                        var resourceSet = surface == null ? _gpuSurfaceManager.SingleWhitePixel.ResourceSet_TexWrap : surface.ResourceSet_TexWrap;

                        cl.SetGraphicsResourceSet((uint)n, resourceSet);

                        assignedTextureCount++;
                    }
                    else
                    {
                        _frameworkMessenger.Report("Custom shader requires more than 4 textures. Should not have reached this stage...");
                    }
                }
                else
                {
                    var resourceSet = stage.UserUniformResourceSet(n);
                    cl.SetGraphicsResourceSet((uint)n, resourceSet);
                }
            }
            cl.Draw(6);
        }
コード例 #3
0
        public Shader LoadShader(string name, AssetSourceEnum assetTypes, ShaderStages stage, bool useSpirvCompile = false)
        {
            //Input path should be '/' folder delimited. It is changed to '.' delimited for embedded resources

            var shaderFileInfo = GetShaderFileInfo(name, _systemComponents.Device, useSpirvCompile);

            var shaderBytes = new byte[] { };

            switch (assetTypes)
            {
            case AssetSourceEnum.File:
                shaderBytes = TryLoadShaderBytesFromFile(shaderFileInfo);
                break;

            case AssetSourceEnum.Embedded:
                shaderFileInfo.Directory = shaderFileInfo.Directory.Replace('/', '.');
                shaderBytes = TryLoadShaderBytesFromEmbeddedResource(shaderFileInfo);
                break;
            }

            if (shaderBytes.Length == 0)
            {
                _frameworkMessenger.Report(string.Concat("Unable to load shader file: ",
                                                         shaderFileInfo.Directory, "| ", shaderFileInfo.Name, " | ", shaderFileInfo.Extension,
                                                         ", of type --> ", assetTypes.ToString()));
                return(null);
            }

            return(useSpirvCompile ?
                   _systemComponents.Factory.CreateShaderCompileFromSpirv(new ShaderDescription(stage, shaderBytes, shaderFileInfo.EntryPointMethod, true)):
                   _systemComponents.Factory.CreateShader(new ShaderDescription(stage, shaderBytes, shaderFileInfo.EntryPointMethod, true)));
        }
コード例 #4
0
        public void Render(CommandList cl, IDistortionStageModel stage, GpuSurface target, ICameraModel2D camera)
        {
            cl.SetPipeline(_pipeline);
            cl.SetFramebuffer(target.Framebuffer);
            cl.ClearColorTarget(0, RgbaFloat.Clear);                          // HERE DIFFERENT TO STANDARD DRAW ONLY (FUTURE PULL OUT TO BASE?)
            cl.SetVertexBuffer(0, stage.Buffers.VertexBuffer);
            cl.SetIndexBuffer(stage.Buffers.IndexBuffer, IndexFormat.UInt32); //Extract format and type
            cl.SetGraphicsResourceSet(0, camera.ResourceSet);

            var batcher = stage.Batcher;

            for (var b = 0; b < batcher.NumberOfBatches; b++)
            {
                var batch = batcher.Pool[b];

                ResourceSet t0;
                if (batch.Texture0 == 0UL)
                {
                    t0 = _surfaceManager.SingleWhitePixel.ResourceSet_TexWrap;
                }
                else
                {
                    var retrieved = _surfaceManager.RetrieveSurface(batch.Texture0, new GpuSurfaceType[] { GpuSurfaceType.SwapChainOutput, GpuSurfaceType.Internal });

                    if (retrieved == target)
                    {
                        _frameworkMessenger.Report("Warning: A distortion stage is attempting to draw a surface onto itself. Aborting");
                        return;
                    }

                    t0 = retrieved == null ? _surfaceManager.SingleWhitePixel.ResourceSet_TexWrap :
                         batch.TextureMode0 == TextureCoordinateMode.Mirror ?
                         retrieved.ResourceSet_TexMirror : retrieved.ResourceSet_TexWrap;
                }
                cl.SetGraphicsResourceSet(1, t0);

                ResourceSet t1;
                if (batch.Texture1 == 0UL)
                {
                    t1 = _surfaceManager.SingleWhitePixel.ResourceSet_TexWrap;
                }
                else
                {
                    var retrieved = _surfaceManager.RetrieveSurface(batch.Texture1, new GpuSurfaceType[] { GpuSurfaceType.SwapChainOutput, GpuSurfaceType.Internal });

                    if (retrieved == target)
                    {
                        _frameworkMessenger.Report("Warning: A distortion stage is attempting to draw a surface onto itself. Aborting");
                        return;
                    }

                    t1 = retrieved == null ? _surfaceManager.SingleWhitePixel.ResourceSet_TexWrap :
                         batch.TextureMode1 == TextureCoordinateMode.Mirror ?
                         retrieved.ResourceSet_TexMirror : retrieved.ResourceSet_TexWrap;
                }
                cl.SetGraphicsResourceSet(2, t1);

                cl.DrawIndexed((uint)batch.NumIndices, 1, (uint)batch.StartIndex, 0, 0);
            }
        }
コード例 #5
0
        public bool Add(ulong id, T item)
        {
            if (_items.ContainsKey(id))
            {
                _frameworkMessenger.Report("Unable to add Type: " + typeof(T) + " to collection");
                return(false);
            }

            _items.Add(id, item);
            return(true);
        }
コード例 #6
0
        public bool DestroyStage(ulong id)
        {
            if (_renderStageCollection.Contains(id))
            {
                _stagesForDestruction.Add(new Tuple <ulong, bool>(id, false));
                return(true);
            }

            _frameworkMessenger.Report("Unable to Destroy a Render Stage as ulong does not exist in collection");
            return(false);
        }
コード例 #7
0
ファイル: FontCollection.cs プロジェクト: limocute/yak2d
        public bool Add(ulong id, IFontModel font)
        {
            if (_fonts.ContainsKey(id))
            {
                _frameworkMessenger.Report("FontCollection: Unable to add font, ulong exists in collection");
                return(false);
            }

            _fonts.Add(id, font);
            return(true);
        }
コード例 #8
0
        public List <string> ExtractPngFilePathsFromDotFntLines(List <string> fntFileLines)
        {
            if (fntFileLines == null)
            {
                return(new List <string>());
            }

            Regex rx = new Regex("file=\"[^\" ]*[.]png\"");

            var matches = new List <string>();

            fntFileLines.ForEach(line =>
            {
                var match = rx.Match(line);

                if (match.Success)
                {
                    IEnumerable <Group> groups = (IEnumerable <Group>)match.Groups;
                    groups.ToList().ForEach(x =>
                    {
                        matches.Add(x.Value);
                    });
                }
            });

            if (matches.Count == 0)
            {
                _frameworkMessenger.Report(string.Concat("Unable to find any .png files for a sub font load, within a font"));
                return(new List <string>()
                {
                });
            }

            //Extract file name between quotation marks
            var pngFileNames = matches.Select(x => ExtractPngFileNameBetweenQuotationMarks(x)).Where(x => !string.IsNullOrEmpty(x)).ToList();

            if (pngFileNames.Count == 0)
            {
                _frameworkMessenger.Report("Unable to find any .png filenames from regex matches for a sub font load, within a font");
                return(new List <string>()
                {
                });
            }

            if (pngFileNames.Count != matches.Count)
            {
                _frameworkMessenger.Report("Warning: finding less valid .png filenames when parsing regex matches in font");
            }

            return(pngFileNames);
        }
コード例 #9
0
        public void Render(CommandList cl, IStyleEffectsStageModel stage, GpuSurface source, GpuSurface target)
        {
            if (cl == null || stage == null || source == null || target == null)
            {
                _frameworkMessenger.Report("Warning: you are feeding the Style Effect Stage Renderer null inputs, aborting");
                return;
            }

            //Updated every time as holds the shared TexelSize
            var factors = new PixellateFactors
            {
                PixAmount     = stage.PixellateCurrent.Intensity,
                NumXDivisions = stage.PixellateCurrent.NumXDivisions,
                NumYDivisions = stage.PixellateCurrent.NumYDivisions,
                Pad0          = 0,
                TexelSize     = new Vector2(1.0f / (1.0f * target.Framebuffer.Width), 1.0f / (1.0f * target.Framebuffer.Height)),
                Pad1          = Vector2.Zero
            };

            _systemComponents.Device.UpdateBuffer(stage.PixellateBuffer, 0, ref factors);

            cl.SetFramebuffer(target.Framebuffer);
            _viewportManager.ConfigureViewportForActiveFramebuffer(cl);
            cl.SetVertexBuffer(0, _ndcQuadVertexBuffer.Buffer);
            cl.SetPipeline(_pipeline);
            cl.SetGraphicsResourceSet(0, source.ResourceSet_TexMirror);
            cl.SetGraphicsResourceSet(1, _gpuSurfaceManager.Noise.ResourceSet_TexWrap);
            cl.SetGraphicsResourceSet(2, _gpuSurfaceManager.CrtShadowMask.ResourceSet_TexWrap);
            cl.SetGraphicsResourceSet(3, stage.PixellateResourceSet);
            cl.SetGraphicsResourceSet(4, stage.EdgeDetectionResourceSet);
            cl.SetGraphicsResourceSet(5, stage.StaticResourceSet);
            cl.SetGraphicsResourceSet(6, stage.OldMovieResourceSet);
            cl.SetGraphicsResourceSet(7, stage.CrtEffectResourceSet);
            cl.Draw(6);
        }
コード例 #10
0
        public void Render(CommandList cl, ISurfaceCopyStageModel stage, GpuSurface source)
        {
            if (cl == null || stage == null || source == null)
            {
                _frameworkMessenger.Report("Warning: you are feeding the Surface Copy Stage Renderer null inputs, aborting");
                return;
            }

            //Ensure the staging texture is of the correct size
            var stagingTexture = _gpuSurfaceManager.RetrieveSurface(stage.StagingTextureId);

            var doStagingTexturePropertiesMatch = source.Texture.Width == stagingTexture.Texture.Width &&
                                                  source.Texture.Height == stagingTexture.Texture.Height;

            var pixelFormatOfSource = source.Texture.Format;

            if (pixelFormatOfSource != stagingTexture.Texture.Format)
            {
                doStagingTexturePropertiesMatch = false;
            }

            if (!doStagingTexturePropertiesMatch)
            {
                stage.SetPixelFormatAndCreateStagingTextureAndDataArray(source.Texture.Width,
                                                                        source.Texture.Height,
                                                                        TexturePixelFormatConverter.ConvertVeldridToYak(pixelFormatOfSource));
                stagingTexture = _gpuSurfaceManager.RetrieveSurface(stage.StagingTextureId);
            }

            cl.CopyTexture(source.Texture, stagingTexture.Texture);
        }
コード例 #11
0
        public void Render(CommandList cl, IMixStageModel stage, GpuSurface mix, GpuSurface t0, GpuSurface t1, GpuSurface t2, GpuSurface t3, GpuSurface target)
        {
            if (cl == null || stage == null || target == null)
            {
                _frameworkMessenger.Report("Warning: you are feeding the Mix Stage Renderer null inputs (for those that shouldn't be), aborting");
                return;
            }

            var factors = new MixStageFactors
            {
                MixAmounts = stage.MixAmount
            };

            cl.UpdateBuffer(_mixFactorsBuffer, 0, ref factors);

            cl.SetFramebuffer(target.Framebuffer);
            _viewportManager.ConfigureViewportForActiveFramebuffer(cl);
            cl.SetVertexBuffer(0, _ndcQuadVertexBuffer.Buffer);
            cl.SetPipeline(_pipeline);

            cl.SetGraphicsResourceSet(0, _mixFactorsResource);
            cl.SetGraphicsResourceSet(1, mix == null ? _gpuSurfaceManager.SingleWhitePixel.ResourceSet_TexWrap : mix.ResourceSet_TexWrap);

            cl.SetGraphicsResourceSet(2, t0 == null ? _whiteTextures[0].ResourceSet_TexWrap : t0.ResourceSet_TexWrap);
            cl.SetGraphicsResourceSet(3, t1 == null ? _whiteTextures[1].ResourceSet_TexWrap : t1.ResourceSet_TexWrap);
            cl.SetGraphicsResourceSet(4, t2 == null ? _whiteTextures[2].ResourceSet_TexWrap : t2.ResourceSet_TexWrap);
            cl.SetGraphicsResourceSet(5, t3 == null ? _whiteTextures[3].ResourceSet_TexWrap : t3.ResourceSet_TexWrap);

            cl.Draw(6);
        }
コード例 #12
0
ファイル: GpuSurfaceCollection.cs プロジェクト: AlzPatz/yak2d
        public bool Add(ulong id, GpuSurface surface)
        {
            if (surface == null)
            {
                _frameworkMessenger.Report("GpuSurfaceCollection: Will not add null surface to collection");
                return(false);
            }

            if (_surfaces.ContainsKey(id))
            {
                _frameworkMessenger.Report("GpuSurfaceCollection: Unable to add surface, ulong exists in collection");
                return(false);
            }

            _surfaces.Add(id, surface);
            return(true);
        }
コード例 #13
0
        public void Render(CommandList cl, IDistortionStageModel stage, GpuSurface source, GpuSurface target, ICameraModel2D camera)
        {
            if (cl == null || stage == null || source == null || target == null || camera == null)
            {
                _frameworkMessenger.Report("Warning: you are feeding the Distortion Stage Renderer null inputs, aborting");
                return;
            }

            _heightRenderer.Render(cl, stage, stage.HeightMapSurface, camera);
            _gradientShiftRenderer.Render(cl, stage, stage.HeightMapSurface, stage.GradientShiftSurface);
            _distortionRenderer.Render(cl, stage, source, stage.GradientShiftSurface, target);
        }
コード例 #14
0
ファイル: CommandProcessor.cs プロジェクト: limocute/yak2d
        private void ProcessRenderStage(CommandList cl, RenderCommandQueueItem command)
        {
            var renderStageModel = _renderStageManager.RetrieveStageModel(command.Stage);

            if (renderStageModel == null)
            {
                _frameworkMessenger.Report("Unable to process render stage command: error trying to locate model (null or wrong type");
                return;
            }

            renderStageModel.SendToRenderStage(_renderStageVisitor, cl, command);
        }
コード例 #15
0
        public ulong New()
        {
            if (_idTracker == ulong.MaxValue)
            {
                _frameworkMessenger.Report("Upcoming Integer64 overflow - wow, most likely we have a bug, or perhaps this system is running on it's own for billions of years after an apocalypse, or perhaps an advanced entity is running it super fast. if the latter, hello! I don't think we need to seriously handle the upcoming error... but let's wrap the count for good order :)");
                _idTracker = initValue;
            }

            _idTracker++;

            return(_idTracker);
        }
コード例 #16
0
        public void Render(CommandList cl, GpuSurface source, GpuSurface surface)
        {
            if (cl == null || surface == null || source == null)
            {
                _frameworkMessenger.Report("Warning: you are feeding the Copy Stage Renderer null inputs, aborting");
                return;
            }

            cl.SetFramebuffer(surface.Framebuffer);
            _viewportManager.ConfigureViewportForActiveFramebuffer(cl);
            cl.SetVertexBuffer(0, _ndcQuadVertexBuffer.Buffer);
            cl.SetPipeline(_pipeline);
            cl.SetGraphicsResourceSet(0, source.ResourceSet_TexWrap);
            cl.Draw(6);
        }
コード例 #17
0
ファイル: Blur1DStageRenderer.cs プロジェクト: limocute/yak2d
        public void Render(CommandList cl, IBlur1DStageModel stage, GpuSurface source, GpuSurface target)
        {
            if (cl == null || stage == null || source == null || target == null)
            {
                _frameworkMessenger.Report("Warning: you are feeding the Blur1D Stage Renderer null inputs, aborting");
                return;
            }

            //Downsample
            _blurSamplingRenderer.Render(cl, source, stage.LinearSampledSurface, stage.SampleType);

            //Blur
            _singlePassGaussianBlurRenderer.Render(cl, stage.TexelShiftSize, stage.NumberSamples, stage.LinearSampledSurface, stage.AnistropicallySampledSurface);

            //Mix
            _blurResultMixingRenderer.Render(cl, stage.MixAmount, source, stage.AnistropicallySampledSurface, target);
        }
コード例 #18
0
        private bool Initialise()
        {
            _application.OnStartup();

            _frameworkMessenger.Report("Yak2D Framework Initialising...");

            InitialiseLoopProperties();

            _systemComponents.Window.Closed += () => { _loopProperties.Running = false; };

            _frameworkMessenger.Report("Application Initialising...");

            return(InitialiseApplication());
        }
コード例 #19
0
        public void Render(CommandList cl, IMeshRenderStageModel stage, GpuSurface source, GpuSurface surface, ICameraModel3D camera)
        {
            if (cl == null || stage == null || source == null || surface == null || camera == null)
            {
                _frameworkMessenger.Report("Warning: you are feeding the Mesh Stage Renderer null inputs, aborting");
                return;
            }

            cl.SetFramebuffer(surface.Framebuffer);
            _viewportManager.ConfigureViewportForActiveFramebuffer(cl);
            cl.ClearDepthStencil(1.0f);
            cl.SetPipeline(_pipeline);
            cl.SetGraphicsResourceSet(0, camera.WvpResource);
            cl.SetGraphicsResourceSet(1, camera.PositionResource);
            cl.SetGraphicsResourceSet(2, source.ResourceSet_TexWrap);
            cl.SetGraphicsResourceSet(3, stage.LightPropertiesResource);
            cl.SetGraphicsResourceSet(4, stage.LightsResource);
            cl.SetVertexBuffer(0, stage.MeshVertexBuffer);
            cl.Draw(stage.MeshNumberVertices);
        }
コード例 #20
0
        public void Render(CommandList cl, IColourEffectsStageModel stage, GpuSurface surface, GpuSurface source)
        {
            if (cl == null || stage == null || source == null || surface == null)
            {
                _frameworkMessenger.Report("Warning: you are feeding the Colour Effect Stage Renderer null inputs, aborting");
                return;
            }

            cl.SetPipeline(_pipeline);
            cl.SetFramebuffer(surface.Framebuffer);
            _viewportManager.ConfigureViewportForActiveFramebuffer(cl);
            if (stage.ClearBackgroundBeforeRender)
            {
                cl.ClearColorTarget(0, stage.ClearColour);
            }
            cl.SetVertexBuffer(0, _ndcQuadVertexBuffer.Buffer);
            cl.SetGraphicsResourceSet(0, stage.FactorsResourceSet);
            cl.SetGraphicsResourceSet(1, source.ResourceSet_TexWrap);
            cl.Draw(6);
        }
コード例 #21
0
ファイル: InputGameController.cs プロジェクト: limocute/yak2d
        private unsafe void UpdateGamepadRegister()
        {
            var validIds = new List <int>();

            var numJoySticks = Sdl2Native.SDL_NumJoysticks();

            var numGameControllers = 0;

            for (var c = 0; c < numJoySticks; c++)
            {
                if (Sdl2Native.SDL_IsGameController(c))
                {
                    var index      = c;
                    var controller = Sdl2Native.SDL_GameControllerOpen(index);
                    var joystick   = Sdl2Native.SDL_GameControllerGetJoystick(controller);
                    var instanceId = Sdl2Native.SDL_JoystickInstanceID(joystick);

                    var name = Marshal.PtrToStringAnsi((IntPtr)Sdl2Native.SDL_GameControllerName(controller));
                    _frameworkMessenger.Report(string.Concat("Detected Controller name: ", name));

                    var gameController = new GameController(name, controller, joystick);
                    if (_controllers.ContainsKey(instanceId))
                    {
                        if (_controllers[instanceId].Name != name)
                        {
                            _frameworkMessenger.Report(string.Concat("Warning: Controller replaced at instance id: ", instanceId, " does not have the same name as the previous controller here"));
                        }
                        _controllers.Remove(instanceId);
                    }

                    _controllers.Add(instanceId, gameController);
                    validIds.Add(instanceId);

                    numGameControllers++;
                }
            }

            var ids = _controllers.Keys.ToList();

            ids.ForEach(x =>
            {
                if (!validIds.Contains(x))
                {
                    _controllers.Remove(x);
                }
            });

            _frameworkMessenger.Report(string.Concat("Number of Joysticks detected: ", numJoySticks, " -> of those, number of GameControllers: ", numGameControllers));
        }
コード例 #22
0
        public void Render(CommandList cl, IBloomStageModel stage, GpuSurface source, GpuSurface target)
        {
            if (cl == null || stage == null || source == null || target == null)
            {
                _frameworkMessenger.Report("Warning: you are feeding the Bloom Stage Renderer null inputs, aborting");
                return;
            }

            //Downsample
            _bloomSamplingRenderer.Render(cl, stage.BrightnessThreshold, source, stage.LinearSampledSurface0, stage.SampleType);

            //Blur Horizontally
            _singlePassGaussianBlurRenderer.Render(cl, new Vector2(stage.TexelShiftSize.X, 0.0f), stage.NumberSamples, stage.LinearSampledSurface0, stage.LinearSampledSurface1);

            //Blur Vertically
            _singlePassGaussianBlurRenderer.Render(cl, new Vector2(0.0f, stage.TexelShiftSize.Y), stage.NumberSamples, stage.LinearSampledSurface1, stage.AnistropicallySampledSurface);

            //Mix
            _bloomResultMixingRenderer.Render(cl, stage, source, stage.AnistropicallySampledSurface, target);
        }
コード例 #23
0
        public void Render(CommandList cl, ICustomVeldridStageModel stage, GpuSurface t0, GpuSurface t1, GpuSurface t2, GpuSurface t3, GpuSurface target)
        {
            if (cl == null || stage == null)
            {
                _frameworkMessenger.Report("Warning: you are feeding a Custom Veldrid Stage Renderer null inputs, aborting");
                return;
            }

            //Auto set render target if not done in user code
            if (target != null)
            {
                cl.SetFramebuffer(target.Framebuffer);
            }

            var tex0 = t0 == null ? _gpuSurfaceManager.SingleWhitePixel.ResourceSet_TexWrap : t0.ResourceSet_TexWrap;
            var tex1 = t1 == null ? _gpuSurfaceManager.SingleWhitePixel.ResourceSet_TexWrap : t1.ResourceSet_TexWrap;
            var tex2 = t2 == null ? _gpuSurfaceManager.SingleWhitePixel.ResourceSet_TexWrap : t2.ResourceSet_TexWrap;
            var tex3 = t3 == null ? _gpuSurfaceManager.SingleWhitePixel.ResourceSet_TexWrap : t3.ResourceSet_TexWrap;

            stage.CustomStage.Render(cl, _systemComponents.Device.RawVeldridDevice, tex0, tex1, tex2, tex3, target == null ? null : target.Framebuffer);
        }
コード例 #24
0
ファイル: FontLoader.cs プロジェクト: limocute/yak2d
        public CandidateSubFontDesc TryToLoadSubFontDescription(string fontBaseFolderWithoutAssemblyDoesNotEndInDivisor,
                                                                bool isFrameworkInternal,
                                                                AssetSourceEnum assetType,
                                                                ImageFormat imageFormat,
                                                                List <string> fntFileLines)
        {
            var resourceFolder = fontBaseFolderWithoutAssemblyDoesNotEndInDivisor;

            var extractedTexturePathsWithoutBasePath = _subFontGenerator.ExtractPngFilePathsFromDotFntLines(fntFileLines);

            if (extractedTexturePathsWithoutBasePath.Count == 0)
            {
                return(null); //Fail Message already displayed in earlier method
            }

            var texturePathsWithoutBasePathsWithoutFileExtension = extractedTexturePathsWithoutBasePath.Select(x =>
            {
                if (!x.EndsWith(".png"))
                {
                    _frameworkMessenger.Report("Warning -> expected texture path name does not end with .png");
                }

                return(x.Remove(x.Length - 4, 4));
            }).ToList();

            var textures = new List <ITexture>();

            texturePathsWithoutBasePathsWithoutFileExtension.ForEach(texturePath =>
            {
                ITexture texture = null;
                var texturePathWithoutExtension = string.Concat(resourceFolder, assetType == AssetSourceEnum.Embedded ? "." : "/", texturePath);

                switch (assetType)
                {
                case AssetSourceEnum.Embedded:
                    texture = _gpuSurfaceManager.CreateFontTextureFromEmbeddedResource(isFrameworkInternal,
                                                                                       texturePathWithoutExtension,
                                                                                       imageFormat,
                                                                                       SamplerType.Anisotropic);
                    break;

                case AssetSourceEnum.File:
                    texture = _gpuSurfaceManager.CreateFontTextureFromFile(texturePathWithoutExtension, imageFormat, SamplerType.Anisotropic);
                    break;
                }
                if (texture != null)
                {
                    textures.Add(texture);
                }
            });

            if (textures.Count == 0)
            {
                _frameworkMessenger.Report(string.Concat("Texture loads for font failed: ",
                                                         resourceFolder, ",",
                                                         " Framework Internal?== ", isFrameworkInternal));
            }

            return(new CandidateSubFontDesc
            {
                DotFntLines = fntFileLines,
                TexturePaths = texturePathsWithoutBasePathsWithoutFileExtension,
                Textures = textures
            });
        }
コード例 #25
0
ファイル: DrawQueue.cs プロジェクト: limocute/yak2d
        public bool AddIfValid(ref CoordinateSpace target,
                               ref FillType type,
                               ref Colour colour,
                               ref Vertex2D[] vertices,
                               ref int[] indices,
                               ref ulong texture0,
                               ref ulong texture1,
                               ref TextureCoordinateMode texmode0,
                               ref TextureCoordinateMode texmode1,
                               ref float depth,
                               ref int layer)
        {
            if (vertices.Length < 3)
            {
                _frameworkMessenger.Report("Add draw request failed: Less than 3 vertices provided");
                return(false);
            }

            if (indices.Length == 0)
            {
                _frameworkMessenger.Report("Add draw request failed: zero indices provided");
                return(false);
            }

            if (indices.Length % 3 != 0)
            {
                _frameworkMessenger.Report(string.Concat("Add draw request failed: Number of indices ", indices.Length, " not divisible by 3"));
                return(false);
            }

            if (type == FillType.Coloured)
            {
                texture0 = 0UL;
                texture1 = 0UL;
                texmode0 = TextureCoordinateMode.None;
                texmode1 = TextureCoordinateMode.None;
            }
            else
            {
                if (texture0 == 0UL)
                {
                    _frameworkMessenger.Report("Add draw request failed: No Texture0 provided for Textured Drawing");
                    return(false);
                }
            }

            if (type == FillType.DualTextured)
            {
                if (texture1 == 0UL)
                {
                    _frameworkMessenger.Report("Add draw request failed: No Texture1 provided for Dual Textured Drawing");
                    return(false);
                }
                if (texture0 == texture1)
                {
                    _frameworkMessenger.Report("Add draw request failed: Same texture provided for both textures in Dual Textured drawing. Not supported");
                    return(false);
                }

                if (texmode0 == TextureCoordinateMode.None)
                {
                    texmode0 = TextureCoordinateMode.Wrap;
                }

                if (texmode1 == TextureCoordinateMode.None)
                {
                    texmode1 = TextureCoordinateMode.Wrap;
                }
            }

            if (type == FillType.Textured)
            {
                if (texmode0 == TextureCoordinateMode.None)
                {
                    texmode0 = TextureCoordinateMode.Wrap;
                }

                texture1 = 0UL;
                texmode1 = TextureCoordinateMode.None;
            }

            if (depth < 0.0f || depth > 1.0f)
            {
                _frameworkMessenger.Report("Add draw request failed: Depth out of range 0 - 1");
                return(false);
            }

            if (layer < 0)
            {
                _frameworkMessenger.Report("Add draw request failed: a negative layer number is not valid");
                return(false);
            }
            ;

            Add(ref target, ref type, ref colour, ref vertices, ref indices, ref texture0, ref texture1, ref texmode0, ref texmode1, ref depth, ref layer);

            return(true);
        }
コード例 #26
0
ファイル: GpuSurfaceManager.cs プロジェクト: limocute/yak2d
        private GpuSurface LoadSystemTexture(string name, bool mipMap)
        {
            var stream = _surfaceAssembly.GetManifestResourceStream(string.Concat("Yak2D.Surface.SystemTextures.", name, ".png"));

            if (stream == null)
            {
                _frameworkMessenger.Report("Unable to load system texture: " + name);
                return(null);
            }

            var veldridTexture = _imageSharpLoader.GenerateVeldridTextureFromStream(stream, mipMap);

            return(_gpuSurfaceFactory.CreateGpuSurfaceFromTexture(veldridTexture,
                                                                  true,
                                                                  false,
                                                                  SamplerType.Anisotropic));
        }
コード例 #27
0
 public void QueueMessage(FrameworkMessage msg)
 {
     _frameworkMessenger.Report(string.Concat("Framework Message:", msg.ToString()));
     _messageQueue.Enqueue(msg);
 }
コード例 #28
0
ファイル: SubFontGenerator.cs プロジェクト: limocute/yak2d
        public SubFont Generate(CandidateSubFontDesc description)
        {
            if (description == null)
            {
                _frameworkMessenger.Report("Error loading a sub font, dsecription object is null");
                return(null);
            }

            if (description.Textures == null || description.Textures.Count == 0)
            {
                _frameworkMessenger.Report("Error loading a sub font, dsecription textures array is null or zero length");
                return(null);
            }

            if (description.TexturePaths == null || description.TexturePaths.Count == 0)
            {
                _frameworkMessenger.Report("Error loading a sub font, dsecription texture paths array is null or zero length");
                return(null);
            }

            var lines = description.DotFntLines;

            if (lines == null)
            {
                _frameworkMessenger.Report("Error loading a sub font, .fnt file line data is null");
                return(null);
            }

            if (lines.Count < 3)
            {
                _frameworkMessenger.Report("Error loading a sub font, less than three lines in .fnt data");
                return(null);
            }

            //Pull font size from the first line
            var fontSize = ExtractNamedFloatFromLineWriteToDebugOnFail("size", lines[0]);

            if (fontSize == null)
            {
                return(null);
            }

            //Pull data from the second line
            var lineHeight = ExtractNamedIntFromLineWriteToDebugOnFail("lineHeight", lines[1]);
            var pageWidth  = ExtractNamedIntFromLineWriteToDebugOnFail("scaleW", lines[1]);
            var pageHeight = ExtractNamedIntFromLineWriteToDebugOnFail("scaleH", lines[1]);
            var numPages   = ExtractNamedIntFromLineWriteToDebugOnFail("pages", lines[1]);

            if ((lineHeight == null) || (pageWidth == null) || (pageHeight == null) || (numPages == null))
            {
                return(null);
            }

            var numberOfCharactersExpected = 0;
            var characters = new Dictionary <char, FontCharacter>();

            var numberOfKerningsExpected = 0;
            var kernings = new Dictionary <char, Dictionary <char, short> >();
            var numberOfKerningsExtracted = 0;

            for (var l = 2; l < lines.Count; l++)
            {
                var line = lines[l];

                if (_subFontTools.LineStartsWith("char ", line))
                {
                    var charExtracted = _subFontTools.ExtractCharacterFromLine(line, (int)pageWidth, (int)pageHeight);
                    if (charExtracted.Item2 == null)
                    {
                        _frameworkMessenger.Report("Error loading a sub font, a character line failed to pass. Continuing without");
                        continue;
                    }
                    characters.Add((char)charExtracted.Item1, charExtracted.Item2);
                    continue;
                }

                if (_subFontTools.LineStartsWith("kerning ", line))
                {
                    var kerningExtracted = _subFontTools.ExtractKerningFromLine(line);
                    //Item1 = first character (nullable), Item2 = second character, Item3 = kerning amount
                    if (kerningExtracted.Item1 == null)
                    {
                        _frameworkMessenger.Report("Error loading a sub font, a kerning line failed to pass. Continuing without");
                        continue;
                    }
                    if (kernings.ContainsKey((char)kerningExtracted.Item1))
                    {
                        var dictionaryOfCharacter = kernings[(char)kerningExtracted.Item1];

                        if (dictionaryOfCharacter.ContainsKey(kerningExtracted.Item2))
                        {
                            _frameworkMessenger.Report("Kerning dictionary already contains entry. Continuing without");
                            continue;
                        }

                        dictionaryOfCharacter.Add(kerningExtracted.Item2, kerningExtracted.Item3);
                        numberOfKerningsExtracted++;
                    }
                    else
                    {
                        var newDictionaryForCharacter = new Dictionary <char, short>();
                        newDictionaryForCharacter.Add(kerningExtracted.Item2, kerningExtracted.Item3);
                        kernings.Add((char)kerningExtracted.Item1, newDictionaryForCharacter);
                        numberOfKerningsExtracted++;
                    }
                    continue;
                }

                if (_subFontTools.LineStartsWith("chars", line))
                {
                    var num = _subFontTools.ExtractNamedIntFromLine("count", line);
                    if (num == null)
                    {
                        _frameworkMessenger.Report("Error loading a sub font, number of characters failed to extract from .fnt file");
                        return(null);
                    }
                    numberOfCharactersExpected = (int)num;
                    continue;
                }

                if (_subFontTools.LineStartsWith("kernings", line))
                {
                    var num = _subFontTools.ExtractNamedIntFromLine("count", line);
                    if (num == null)
                    {
                        _frameworkMessenger.Report("Error loading a sub font, number of kernings failed to extract from .fnt file");
                        return(null);
                    }
                    numberOfKerningsExpected = (int)num;
                    continue;
                }
            }

            if (characters.Count != numberOfCharactersExpected)
            {
                _frameworkMessenger.Report("Warning loading a sub font, the number of characters extracted does not match expected");
            }

            if (numberOfKerningsExtracted != numberOfKerningsExpected)
            {
                _frameworkMessenger.Report("Warning loading a sub font, the number of kernings extracted does not match expected");
            }

            //Fixing Space Character
            if (!characters.ContainsKey((char)32))
            {
                if (characters.ContainsKey((char)0) && characters[(char)0].XAdvance > 0)
                {
                    var zero = characters[(char)0];
                    characters.Add((char)32, zero);
                }
                else
                {
                    characters.Add((char)32, new FontCharacter((int)pageWidth, (int)pageHeight, 0, 0, 0, 0, 0, 0, (int)fontSize / 3, 0));
                }
            }

            if (characters.Count == 0)
            {
                _frameworkMessenger.Report("Error: No characters were loaded for subFont, returning null");
                return(null);
            }

            //Note: The texture list is pulled out from the .fnt file (and textures loaded) before this function so we do not extract names here
            var subFont = new SubFont((float)fontSize,
                                      (float)lineHeight,
                                      characters,
                                      description.Textures.ToArray(),
                                      numberOfKerningsExtracted > 0,
                                      kernings);

            return(subFont);
        }
コード例 #29
0
ファイル: DrawStageRenderer.cs プロジェクト: limocute/yak2d
        public void Render(CommandList cl, IDrawStageModel stage, GpuSurface surface, ICameraModel2D camera)
        {
            if (cl == null || stage == null || surface == null || camera == null)
            {
                _frameworkMessenger.Report("Warning: you are feeding DrawStage Renderer null inputs, aborting");
                return;
            }

            cl.SetFramebuffer(surface.Framebuffer);
            _viewportManager.ConfigureViewportForActiveFramebuffer(cl);
            cl.SetVertexBuffer(0, stage.Buffers.VertexBuffer);
            cl.SetIndexBuffer(stage.Buffers.IndexBuffer, IndexFormat.UInt32); //Extract format and type
            cl.SetPipeline(_pipelineFactory.ReturnDrawingPipeline(stage.BlendState));
            cl.SetGraphicsResourceSet(0, camera.ResourceSet);

            //When drawing commands are queued need to check and ensure the same texture is not used for both tex inputs
            //We also need to trigger the sort somewhere earlier than this and ensure if already sorted into batches dont do it
            var batcher = stage.Batcher;

            for (var b = 0; b < batcher.NumberOfBatches; b++)
            {
                var batch = batcher.Pool[b];

                ResourceSet t0;
                if (batch.Texture0 == 0UL)
                {
                    t0 = _surfaceManager.SingleWhitePixel.ResourceSet_TexWrap;
                }
                else
                {
                    var retrieved = _surfaceManager.RetrieveSurface(batch.Texture0, new GpuSurfaceType[] { GpuSurfaceType.SwapChainOutput, GpuSurfaceType.Internal });

                    if (retrieved == surface)
                    {
                        _frameworkMessenger.Report("Warning: A draw stage is attempting to draw a surface onto itself. Aborting");
                        return;
                    }

                    t0 = retrieved == null ? _surfaceManager.SingleWhitePixel.ResourceSet_TexWrap :
                         batch.TextureMode0 == TextureCoordinateMode.Mirror ?
                         retrieved.ResourceSet_TexMirror : retrieved.ResourceSet_TexWrap;
                }
                cl.SetGraphicsResourceSet(1, t0);

                ResourceSet t1;
                if (batch.Texture1 == 0UL)
                {
                    t1 = _surfaceManager.SingleWhitePixel.ResourceSet_TexWrap;
                }
                else
                {
                    var retrieved = _surfaceManager.RetrieveSurface(batch.Texture1, new GpuSurfaceType[] { GpuSurfaceType.SwapChainOutput, GpuSurfaceType.Internal });

                    t1 = retrieved == null ? _surfaceManager.SingleWhitePixel.ResourceSet_TexWrap :
                         batch.TextureMode1 == TextureCoordinateMode.Mirror ?
                         retrieved.ResourceSet_TexMirror : retrieved.ResourceSet_TexWrap;

                    if (retrieved == surface)
                    {
                        _frameworkMessenger.Report("Warning: A draw stage is attempting to draw a surface onto itself. Aborting");
                        return;
                    }
                }
                cl.SetGraphicsResourceSet(2, t1);

                cl.DrawIndexed((uint)batch.NumIndices, 1, (uint)batch.StartIndex, 0, 0);
            }
        }
コード例 #30
0
        private void CreateShaders()
        {
            //Vertex layout is the same for all custom shaders
            var vertexLayout = new VertexLayoutDescription
                               (
                16,
                0,
                new VertexElementDescription[]
            {
                new VertexElementDescription("Position", VertexElementFormat.Float2, VertexElementSemantic.Position),
                new VertexElementDescription("VTex", VertexElementFormat.Float2, VertexElementSemantic.TextureCoordinate)
            }
                               );

            //Build up the uniform descriptions & create buffers where required
            var uniformDescriptions = new List <ResourceLayoutElementDescription[]>();

            var numUniforms = _userUniformDescriptions.Length;

            var textureCount = 0;

            for (var n = 0; n < numUniforms; n++)
            {
                var desc = _userUniformDescriptions[n];

                switch (desc.UniformType)
                {
                case ShaderUniformType.Texture:
                    if (textureCount >= 4)
                    {
                        _frameworkMessenger.Report("Customer Shader has more than 4 textures, not currently allowed, skipping uniform");
                        continue;
                    }
                    textureCount++;

                    uniformDescriptions.Add(
                        new ResourceLayoutElementDescription[]
                    {
                        new ResourceLayoutElementDescription(string.Concat("Sampler_", desc.Name), ResourceKind.TextureReadOnly, ShaderStages.Fragment),
                        new ResourceLayoutElementDescription(string.Concat("Texture_", desc.Name), ResourceKind.Sampler, ShaderStages.Fragment)
                    }
                        );
                    break;

                case ShaderUniformType.Data:
                    var description = new ResourceLayoutElementDescription[]
                    {
                        new ResourceLayoutElementDescription(desc.Name, ResourceKind.UniformBuffer, ShaderStages.Fragment)
                    };
                    uniformDescriptions.Add(description);
                    var buffer = CreateUniformBuffer(description, desc);
                    _uniformBuffers[n] = buffer;
                    _uniformBufferNameLookup.Add(desc.Name, n);
                    break;
                }
            }

            var vertexShaderFileName = "Vertex2D";

            if (_useSpirvCompile)
            {
                //Different Vertex Shaders account for differences in backend (incl. Texcoord origin)
                switch (_systemComponents.Device.BackendType)
                {
                case GraphicsApi.Direct3D11:
                case GraphicsApi.Metal:
                    vertexShaderFileName = "Vertex2D-TcTopLeft";
                    break;

                case GraphicsApi.Vulkan:
                case GraphicsApi.OpenGL:
                    vertexShaderFileName = "Vertex2D-TcBottomLeft";
                    break;

                case GraphicsApi.OpenGLES:
                case GraphicsApi.SystemDefault:
                    throw new Yak2DException("Type is either unsupported or erroneously stored as system default");
                }
            }

            _shaderPackage = _shaderLoader.CreateShaderPackage(vertexShaderFileName,
                                                               AssetSourceEnum.Embedded,
                                                               _fragmentShaderFilename,
                                                               _shaderFileAssetType,
                                                               vertexLayout,
                                                               uniformDescriptions.ToArray(),
                                                               _useSpirvCompile,
                                                               _useSpirvCompile);
        }