Exemple #1
0
        private void BufferSubData(int target, IntPtr offset, uint size, IntPtr ptr)
        {
            _boundBuffers.TryGetValue(target, out uint boundBuffer);
            var memoryName = $"DataBuffer{target}|{boundBuffer}";
            var offsetInt  = (int)offset;

            // It is assumed that the offset and size are valid per the already allocated buffer.
            // Check just in case.
            IntPtr wholeBuffer = UnmanagedMemoryAllocator.GetNamedMemory(memoryName, out int allocatedSize);

            if (offsetInt + size > allocatedSize)
            {
                Engine.Log.Error($"Invalid uploading sub data of {boundBuffer} in range {offsetInt}:{size}. Buffer is {allocatedSize} long.", "WebGLInternal");
                return;
            }

            // Update driver copy, in case of mapping. This could potentially be useless as mapping might not be used.
            NativeHelpers.MemCopy(ptr, IntPtr.Add(wholeBuffer, offsetInt), (int)size);

            var args = new BufferDataArgs
            {
                Ptr    = ptr,
                Target = target,
                Offset = offsetInt,
                Length = size
            };

            _gl.InvokeUnmarshalled <BufferDataArgs, object>("glBufferSubData", args);
        }
Exemple #2
0
        private bool UnmapBuffer(int target)
        {
            _boundBuffers.TryGetValue(target, out uint boundBuffer);
            var    memoryName = $"DataBuffer{target}|{boundBuffer}";
            IntPtr memory     = UnmanagedMemoryAllocator.GetNamedMemory(memoryName, out int size);

            _bufferMapping.TryGetValue(boundBuffer, out BufferMappingState state);
            if (state == null || !state.Mapping)
            {
                return(true);
            }
            state.Mapping     = false;
            state.RangeStart  = 0;
            state.RangeLength = 0;

            //Engine.Log.Info($"Flushing buffer {boundBuffer}");

            var args = new BufferDataArgs
            {
                //Usage = _bufferUsage[boundBuffer],
                //SizeWholeBuffer = (uint) bufferSize,
                Ptr    = memory,
                Target = target,
                Offset = 0,
                Length = (uint)size
            };

            _gl.InvokeUnmarshalled <BufferDataArgs, object>("glBufferSubData", args);
            return(true);
        }
Exemple #3
0
        private IntPtr GetString(int paramId)
        {
            var stringGetMemoryName = $"glGetString{paramId}";

            // Check if already gotten and allocated memory for it.
            IntPtr ptr = UnmanagedMemoryAllocator.GetNamedMemory(stringGetMemoryName, out int _);

            if (ptr != IntPtr.Zero)
            {
                return(ptr);
            }

            // Extensions are gotten from another function.
            string value;

            if (paramId == (int)StringName.Extensions)
            {
                value = _gl.InvokeUnmarshalled <string>("GetGLExtensions");
            }
            else
            {
                value = _gl.InvokeUnmarshalled <int, string>("glGet", paramId);
            }

            //Engine.Log.Trace($"String query {(StringName) paramId} got {value}", "WebGLInternal");
            ptr = NativeHelpers.StringToPtr(value);
            UnmanagedMemoryAllocator.RegisterAllocatedMemory(ptr, stringGetMemoryName, value.Length * sizeof(char));
            return(ptr);
        }
Exemple #4
0
        private void FlushMappedRange(int target, IntPtr offset, uint length)
        {
            _boundBuffers.TryGetValue(target, out uint boundBuffer);
            var    memoryName = $"DataBuffer{target}|{boundBuffer}";
            IntPtr ptr        = UnmanagedMemoryAllocator.GetNamedMemory(memoryName, out int _);

            _bufferMapping.TryGetValue(boundBuffer, out BufferMappingState state);
            if (state == null || !state.Mapping)
            {
                return;
            }
            int bufferStart = (int)offset + state.RangeStart;

            state.Mapping     = false;
            state.RangeStart  = 0;
            state.RangeLength = 0;

            //Engine.Log.Infoe($"Flushing buffer {boundBuffer} in range {offset}:{length}");
            //if (target == (int) BufferTarget.ArrayBuffer)
            //{
            //    var test = new Span<VertexData>((void*)(ptr + (int)offset), (int) length / VertexData.SizeInBytes);
            //    for (var i = 0; i < test.Length; i++)
            //    {
            //        Console.Write(test[i].Vertex + ", ");
            //    }
            //    Console.Write("\n");
            //}
            //else if (target == (int) BufferTarget.ElementArrayBuffer)
            //{
            //    var test = new Span<ushort>((void*)(ptr + (int)offset), (int) length / sizeof(ushort));
            //    for (var i = 0; i < test.Length; i++)
            //    {
            //        Console.Write(test[i] + ", ");
            //    }
            //    Console.Write("\n");
            //}

            var args = new BufferDataArgs
            {
                //Usage = _bufferUsage[boundBuffer],
                //SizeWholeBuffer = (uint) bufferSize,
                Ptr    = ptr + bufferStart,
                Target = target,
                Offset = bufferStart,
                Length = length
            };

            _gl.InvokeUnmarshalled <BufferDataArgs, object>("glBufferSubData", args);
        }
Exemple #5
0
        private IntPtr MapBuffer(int target, int access)
        {
            _boundBuffers.TryGetValue(target, out uint boundBuffer);
            var    memoryName = $"DataBuffer{target}|{boundBuffer}";
            IntPtr memory     = UnmanagedMemoryAllocator.GetNamedMemory(memoryName, out int bufferSize);

            _bufferMapping.TryGetValue(boundBuffer, out BufferMappingState state);
            if (state == null)
            {
                state = new BufferMappingState();
                _bufferMapping.Add(boundBuffer, state);
            }

            state.Mapping     = true;
            state.RangeStart  = 0;
            state.RangeLength = bufferSize;

            return(memory);
        }
Exemple #6
0
        private IntPtr MapBufferRange(int target, IntPtr offset, uint length, uint access)
        {
            _boundBuffers.TryGetValue(target, out uint boundBuffer);
            var    memoryName = $"DataBuffer{target}|{boundBuffer}";
            IntPtr memory     = UnmanagedMemoryAllocator.GetNamedMemory(memoryName, out int _);

            _bufferMapping.TryGetValue(boundBuffer, out BufferMappingState state);
            if (state == null)
            {
                state = new BufferMappingState();
                _bufferMapping.Add(boundBuffer, state);
            }

            state.Mapping     = true;
            state.RangeStart  = (int)offset;
            state.RangeLength = (int)length;

            //Engine.Log.Info($"Starting map range of buffer {boundBuffer} in range {offset}:{length}", "WebGLInternal");

            return(memory + state.RangeStart);
        }
Exemple #7
0
        private void BufferData(int target, uint size, IntPtr ptr, int usage)
        {
            _boundBuffers.TryGetValue(target, out uint boundBuffer);
            var memoryName = $"DataBuffer{target}|{boundBuffer}";

            if (ptr == IntPtr.Zero)
            {
                ptr = UnmanagedMemoryAllocator.MemAllocOrReAllocNamed((int)size, memoryName);
            }
            else
            {
                // Pointer passed from outside. Copy its data.
                IntPtr allocatedMemory = UnmanagedMemoryAllocator.MemAllocOrReAllocNamed((int)size, memoryName);
                NativeHelpers.MemCopy(ptr, allocatedMemory, (int)size);
                ptr = allocatedMemory;
            }

            if (usage != -1)
            {
                _bufferUsage[boundBuffer] = usage;
            }
            else
            {
                usage = _bufferUsage[boundBuffer];
            }

            var args = new BufferDataArgs
            {
                Usage           = usage,
                SizeWholeBuffer = size,
                Ptr             = ptr,
                Target          = target,
                Offset          = 0,
                Length          = size
            };

            _gl.InvokeUnmarshalled <BufferDataArgs, object>("glBufferData", args);
        }
Exemple #8
0
        public void GlobalSetup()
        {
            Engine.Setup();
            _asset = Engine.AssetLoader.Get <AudioAsset>("Audio/pepsi.wav");
            var testAudio = new AudioTests.TestAudioContext();

            _layer = (AudioTests.TestAudioContext.TestAudioLayer)testAudio.CreateLayer("Benchmark");
            _layer.PlayNext(new AudioTrack(_asset)
            {
                SetLoopingCurrent = true
            });
            _layer.ProcessAhead(1); // To create test array.

            _textureOne = Engine.AssetLoader.Get <TextureAsset>("logoAlpha.png");
            _textureTwo = Engine.AssetLoader.Get <TextureAsset>("logoAsymmetric.png");
            _atlas      = new TextureAtlas(false, 1);
            _atlas.TryBatchTexture(_textureOne?.Texture);
            _atlas.TryBatchTexture(_textureTwo?.Texture);

            _atlasMemorySize = VertexData.SizeInBytes * 1024;
            _atlasMemory     = UnmanagedMemoryAllocator.MemAlloc(_atlasMemorySize);

            _atlas.Update(Engine.Renderer);
        }
Exemple #9
0
        protected override void RenderContent(RenderComposer composer)
        {
            ImGui.Text(UnmanagedMemoryAllocator.GetDebugInformation());

            var assetBytes = 0;

            foreach (Asset asset in Engine.AssetLoader.LoadedAssets)
            {
                assetBytes += asset.ByteSize;
            }

            ImGui.Text($"Assets Rough Estimate: {Helpers.FormatByteAmountAsString(assetBytes)}");
            var totalBytes = 0;

            for (var i = 0; i < Texture.AllTextures.Count; i++)
            {
                Texture texture  = Texture.AllTextures[i];
                int     byteSize = (int)(texture.Size.X * texture.Size.Y) * Gl.PixelTypeToByteCount(texture.PixelType) *
                                   Gl.PixelFormatToComponentCount(texture.PixelFormat);
                totalBytes += byteSize;
            }

            ImGui.Text($"Texture Memory Estimate: {Helpers.FormatByteAmountAsString(totalBytes)}");
            ImGui.Text($"Audio Buffer Memory: {Helpers.FormatByteAmountAsString(AudioLayer.MetricAllocatedDataBlocks)}");
            ImGui.Text($"Managed Memory (Game): {Helpers.FormatByteAmountAsString(GC.GetTotalMemory(false))}");

            long usedRam     = _p.WorkingSet64;
            long usedRamMost = _p.PrivateMemorySize64;

            ImGui.Text($"Total Memory Used: {Helpers.FormatByteAmountAsString(usedRam)} | Allocated: {Helpers.FormatByteAmountAsString(usedRamMost)}");

            ImGui.NewLine();
            ImGui.BeginGroup();
            ImGui.BeginTabBar("TabBar");
            if (ImGui.BeginTabItem("Assets"))
            {
                ImGui.BeginChild("Assets", new Vector2(450, 500), true, ImGuiWindowFlags.HorizontalScrollbar);

                Asset[] loadedAssets = Engine.AssetLoader.LoadedAssets;
                IOrderedEnumerable <Asset> orderedEnum = loadedAssets.OrderByDescending(x => x.ByteSize);
                foreach (Asset asset in orderedEnum)
                {
                    float percent = (float)asset.ByteSize / assetBytes;
                    ImGui.Text($"{asset.Name} {Helpers.FormatByteAmountAsString(asset.ByteSize)} {percent * 100:0}%%");
                    ImGui.Text($"\t{asset.GetType()}");
                }

                ImGui.EndChild();
                ImGui.EndTabItem();
            }

            if (ImGui.BeginTabItem("XML Cache"))
            {
                ImGui.BeginChild("XMLType", new Vector2(450, 500), true, ImGuiWindowFlags.HorizontalScrollbar);

                LazyConcurrentDictionary <Type, XMLTypeHandler?> xmlCachedHandlers = XMLHelpers.Handlers;

                var counter = 0;
                foreach ((Type type, Lazy <XMLTypeHandler?> typeHandlerLazy) in xmlCachedHandlers)
                {
                    if (!typeHandlerLazy.IsValueCreated)
                    {
                        continue;
                    }

                    counter++;
                    ImGui.PushID(counter);

                    XMLTypeHandler typeHandler = typeHandlerLazy.Value !;
                    if (ImGui.TreeNode($"{typeHandler.TypeName} ({typeHandler.GetType().ToString().Replace("Emotion.Standard.XML.TypeHandlers.", "")})"))
                    {
                        ImGui.Text($"\t Full TypeName: {type}");
                        if (typeHandler is XMLComplexTypeHandler complexHandler)
                        {
                            ImGui.Text($"\t Fields: {complexHandler.FieldCount()}");
                        }

                        ImGui.TreePop();
                    }

                    ImGui.PopID();
                }

                ImGui.EndChild();
                ImGui.EndTabItem();
            }

            ImGui.EndTabBar();
            ImGui.EndGroup();
        }
Exemple #10
0
        private Dictionary <uint, BufferMappingState> _bufferMapping = new Dictionary <uint, BufferMappingState>(); // <BufferId, state>

        public WebGLContext(IJSUnmarshalledRuntime glContext)
        {
            Native = false;
            _gl    = glContext;

            const int maxGenAtOnce = 5;

            _objectGenPtrHolder = UnmanagedMemoryAllocator.MemAlloc(sizeof(uint) * maxGenAtOnce);

            _webGlFuncDictionary.Add("glGetError", (Gl.Delegates.glGetError)GetError);
            _webGlFuncDictionary.Add("glGetString", (Gl.Delegates.glGetString)GetString);
            _webGlFuncDictionary.Add("glGetIntegerv", (Gl.Delegates.glGetIntegerv)GetInteger);
            _webGlFuncDictionary.Add("glGetFloatv", (Gl.Delegates.glGetFloatv)GetFloat);

            _webGlFuncDictionary.Add("glGenBuffers", (Gl.Delegates.glGenBuffers)GenBuffers);
            _webGlFuncDictionary.Add("glBindBuffer", (Gl.Delegates.glBindBuffer)BindBuffer);
            _webGlFuncDictionary.Add("glBufferData", (Gl.Delegates.glBufferData)BufferData);
            _webGlFuncDictionary.Add("glBufferSubData", (Gl.Delegates.glBufferSubData)BufferSubData);

            _webGlFuncDictionary.Add("glMapBuffer", (Gl.Delegates.glMapBuffer)MapBuffer);
            _webGlFuncDictionary.Add("glMapBufferRange", (Gl.Delegates.glMapBufferRange)MapBufferRange);
            _webGlFuncDictionary.Add("glUnmapBuffer", (Gl.Delegates.glUnmapBuffer)UnmapBuffer);
            _webGlFuncDictionary.Add("glFlushMappedBufferRange", (Gl.Delegates.glFlushMappedBufferRange)FlushMappedRange);

            _webGlFuncDictionary.Add("glClear", (Gl.Delegates.glClear)Clear);
            _webGlFuncDictionary.Add("glClearColor", (Gl.Delegates.glClearColor)SetClearColor);
            _webGlFuncDictionary.Add("glColorMask", (Gl.Delegates.glColorMask)ColorMask);
            _webGlFuncDictionary.Add("glEnable", (Gl.Delegates.glEnable)Enable);
            _webGlFuncDictionary.Add("glDisable", (Gl.Delegates.glDisable)Disable);
            _webGlFuncDictionary.Add("glDepthFunc", (Gl.Delegates.glDepthFunc)DepthFunc);
            _webGlFuncDictionary.Add("glStencilMask", (Gl.Delegates.glStencilMask)StencilMask);
            _webGlFuncDictionary.Add("glStencilFunc", (Gl.Delegates.glStencilFunc)StencilFunc);
            _webGlFuncDictionary.Add("glStencilOp", (Gl.Delegates.glStencilOp)StencilOpF);
            _webGlFuncDictionary.Add("glBlendFuncSeparate", (Gl.Delegates.glBlendFuncSeparate)BlendFuncSeparate);
            _webGlFuncDictionary.Add("glViewport", (Gl.Delegates.glViewport)Viewport);

            _webGlFuncDictionary.Add("glCreateShader", (Gl.Delegates.glCreateShader)CreateShader);
            _webGlFuncDictionary.Add("glShaderSource", (Gl.Delegates.glShaderSource)ShaderSource);
            _webGlFuncDictionary.Add("glCompileShader", (Gl.Delegates.glCompileShader)CompileShader);
            _webGlFuncDictionary.Add("glGetShaderiv", (Gl.Delegates.glGetShaderiv)ShaderGetParam);
            _webGlFuncDictionary.Add("glGetShaderInfoLog", (Gl.Delegates.glGetShaderInfoLog)ShaderInfoLog);

            _webGlFuncDictionary.Add("glCreateProgram", (Gl.Delegates.glCreateProgram)CreateProgram);
            _webGlFuncDictionary.Add("glDeleteShader", (Gl.Delegates.glDeleteShader)DeleteShader);
            _webGlFuncDictionary.Add("glUseProgram", (Gl.Delegates.glUseProgram)UseProgram);
            _webGlFuncDictionary.Add("glAttachShader", (Gl.Delegates.glAttachShader)AttachShader);
            _webGlFuncDictionary.Add("glBindAttribLocation", (Gl.Delegates.glBindAttribLocation)BindAttributeLocation);
            _webGlFuncDictionary.Add("glLinkProgram", (Gl.Delegates.glLinkProgram)LinkProgram);
            _webGlFuncDictionary.Add("glGetProgramInfoLog", (Gl.Delegates.glGetProgramInfoLog)ProgramInfoLog);
            _webGlFuncDictionary.Add("glGetProgramiv", (Gl.Delegates.glGetProgramiv)ProgramGetParam);
            _webGlFuncDictionary.Add("glGetUniformLocation", (Gl.Delegates.glGetUniformLocation)GetUniformLocation);
            _webGlFuncDictionary.Add("glUniform1iv", (Gl.Delegates.glUniform1iv)UploadUniform);
            _webGlFuncDictionary.Add("glUniform1f", (Gl.Delegates.glUniform1f)UploadUniform);
            _webGlFuncDictionary.Add("glUniform2f", (Gl.Delegates.glUniform2f)UploadUniform);
            _webGlFuncDictionary.Add("glUniform1i", (Gl.Delegates.glUniform1i)UploadUniform);
            _webGlFuncDictionary.Add("glUniform3f", (Gl.Delegates.glUniform3f)UploadUniform);
            _webGlFuncDictionary.Add("glUniform4f", (Gl.Delegates.glUniform4f)UploadUniform);
            _webGlFuncDictionary.Add("glUniform1fv", (Gl.Delegates.glUniform1fv)UploadUniform);
            _webGlFuncDictionary.Add("glUniform2fv", (Gl.Delegates.glUniform2fv)UploadUniformFloatArrayMultiComponent2);
            _webGlFuncDictionary.Add("glUniform3fv", (Gl.Delegates.glUniform3fv)UploadUniformFloatArrayMultiComponent3);
            _webGlFuncDictionary.Add("glUniform4fv", (Gl.Delegates.glUniform4fv)UploadUniformFloatArrayMultiComponent4);
            _webGlFuncDictionary.Add("glUniformMatrix4fv", (Gl.Delegates.glUniformMatrix4fv)UploadUniformMat4);

            _webGlFuncDictionary.Add("glGenFramebuffers", (Gl.Delegates.glGenFramebuffers)CreateFramebuffer);
            _webGlFuncDictionary.Add("glBindFramebuffer", (Gl.Delegates.glBindFramebuffer)BindFramebuffer);
            _webGlFuncDictionary.Add("glFramebufferTexture2D", (Gl.Delegates.glFramebufferTexture2D)FramebufferUploadTexture2D);
            _webGlFuncDictionary.Add("glCheckFramebufferStatus", (Gl.Delegates.glCheckFramebufferStatus)FramebufferStatus);
            _webGlFuncDictionary.Add("glDrawBuffers", (Gl.Delegates.glDrawBuffers)DrawBuffers);

            _webGlFuncDictionary.Add("glGenVertexArrays", (Gl.Delegates.glGenVertexArrays)GenVertexArrays);
            _webGlFuncDictionary.Add("glBindVertexArray", (Gl.Delegates.glBindVertexArray)BindVertexArray);
            _webGlFuncDictionary.Add("glEnableVertexAttribArray", (Gl.Delegates.glEnableVertexAttribArray)EnableVertexAttribArray);
            _webGlFuncDictionary.Add("glVertexAttribPointer", (Gl.Delegates.glVertexAttribPointer)VertexAttribPointer);

            _webGlFuncDictionary.Add("glDrawElements", (Gl.Delegates.glDrawElements)DrawElements);
            _webGlFuncDictionary.Add("glDrawArrays", (Gl.Delegates.glDrawArrays)DrawArrays);

            _webGlFuncDictionary.Add("glFenceSync", (Gl.Delegates.glFenceSync)FenceSync);
            _webGlFuncDictionary.Add("glClientWaitSync", (Gl.Delegates.glClientWaitSync)ClientWaitSync);

            _webGlFuncDictionary.Add("glGenTextures", (Gl.Delegates.glGenTextures)CreateTexture);
            _webGlFuncDictionary.Add("glDeleteTextures", (Gl.Delegates.glDeleteTextures)DeleteTextures);
            _webGlFuncDictionary.Add("glBindTexture", (Gl.Delegates.glBindTexture)BindTexture);
            _webGlFuncDictionary.Add("glActiveTexture", (Gl.Delegates.glActiveTexture)ActiveTexture);
            _webGlFuncDictionary.Add("glTexImage2D", (Gl.Delegates.glTexImage2D)UploadTexture);
            _webGlFuncDictionary.Add("glTexParameteri", (Gl.Delegates.glTexParameteri)TexParameterInteger);

            _webGlFuncDictionary.Add("glGenRenderbuffers", (Gl.Delegates.glGenRenderbuffers)CreateRenderbuffer);
            _webGlFuncDictionary.Add("glBindRenderbuffer", (Gl.Delegates.glBindRenderbuffer)BindRenderbuffer);
            _webGlFuncDictionary.Add("glRenderbufferStorage", (Gl.Delegates.glRenderbufferStorage)RenderbufferStorage);
            _webGlFuncDictionary.Add("glFramebufferRenderbuffer", (Gl.Delegates.glFramebufferRenderbuffer)FramebufferRenderbuffer);

            Valid = true;
        }