Ejemplo n.º 1
0
        protected override async Task <ResultStatus> DoCommandOverride(ICommandContext commandContext)
        {
            var assetManager = new AssetManager();

            while (Interlocked.Increment(ref spawnedFbxCommands) >= 2)
            {
                Interlocked.Decrement(ref spawnedFbxCommands);
                await Task.Delay(1, CancellationToken);
            }

            try
            {
                object exportedObject;

                if (ExportType == "animation")
                {
                    // Read from model file
                    var animationClip = LoadAnimation(commandContext, assetManager);
                    exportedObject = animationClip;
                    if (animationClip == null)
                    {
                        commandContext.Logger.Info("File {0} has an empty animation.", SourcePath);
                    }
                    else if (animationClip.Duration.Ticks == 0)
                    {
                        commandContext.Logger.Warning("File {0} has a 0 tick long animation.", SourcePath);
                    }
                    else
                    {
                        animationClip.RepeatMode = AnimationRepeatMode;
                        animationClip.Optimize();
                    }
                }
                else if (ExportType == "model")
                {
                    // Read from model file
                    var model = LoadModel(commandContext, assetManager);

                    model.BoundingBox = BoundingBox.Empty;
                    var hierarchyUpdater = new ModelViewHierarchyUpdater(model.Hierarchy.Nodes);
                    hierarchyUpdater.UpdateMatrices();

                    bool hasErrors = false;
                    foreach (var mesh in model.Meshes)
                    {
                        if (TessellationAEN)
                        {
                            // TODO: Generate AEN model view
                            commandContext.Logger.Error("TessellationAEN is not supported in {0}", ContextAsString);
                            hasErrors = true;
                        }

                        if (Materials.ContainsKey(mesh.Name))
                        {
                            // set the material
                            var materialReference = Materials[mesh.Name];
                            mesh.Material = new ContentReference <MaterialData>(materialReference.Item1, materialReference.Item2);
                        }
                        else
                        {
                            commandContext.Logger.Warning("Mesh material [{0}] was not found in {1}", mesh.Name, ContextAsString);
                        }

                        // set the parameters
                        if (Parameters.ContainsKey(mesh.Name) && Parameters[mesh.Name] != null)
                        {
                            if (mesh.Parameters == null)
                            {
                                mesh.Parameters = new ParameterCollectionData();
                            }
                            foreach (var keyValue in Parameters[mesh.Name])
                            {
                                mesh.Parameters.Set(keyValue.Key, keyValue.Value);
                            }
                        }

                        // TODO: remove this when Lighting configuration will be behind a key in mesh parameters. This case will be handled by the code just above
                        // set the lighting configuration description
                        Tuple <Guid, string> lightingReference;
                        if (Lightings.TryGetValue(mesh.Name, out lightingReference))
                        {
                            mesh.Parameters.Set(LightingKeys.LightingConfigurations, new ContentReference <LightingConfigurationsSetData>(lightingReference.Item1, lightingReference.Item2));
                        }
                    }

                    // split the meshes if necessary
                    model.Meshes = SplitExtensions.SplitMeshes(model.Meshes, Allow32BitIndex);

                    // merge the meshes
                    if (Compact)
                    {
                        var indicesBlackList = new HashSet <int>();
                        if (PreservedNodes != null)
                        {
                            for (var index = 0; index < model.Hierarchy.Nodes.Length; ++index)
                            {
                                var node = model.Hierarchy.Nodes[index];
                                if (PreservedNodes.Contains(node.Name))
                                {
                                    indicesBlackList.Add(index);
                                }
                            }
                        }

                        // group meshes with same material and same root
                        var sameMaterialMeshes = new List <GroupList <int, MeshData> >();
                        GroupFromIndex(model, 0, indicesBlackList, model.Meshes, sameMaterialMeshes);

                        // remove meshes that cannot be merged
                        var excludedMeshes  = new List <MeshData>();
                        var finalMeshGroups = new List <GroupList <int, MeshData> >();
                        foreach (var meshList in sameMaterialMeshes)
                        {
                            var mergeList = new GroupList <int, MeshData> {
                                Key = meshList.Key
                            };

                            foreach (var mesh in meshList)
                            {
                                if (mesh.Skinning != null || indicesBlackList.Contains(mesh.NodeIndex))
                                {
                                    excludedMeshes.Add(mesh);
                                }
                                else
                                {
                                    mergeList.Add(mesh);
                                }
                            }

                            if (mergeList.Count <= 1)
                            {
                                excludedMeshes.AddRange(mergeList);
                            }
                            else
                            {
                                finalMeshGroups.Add(mergeList);
                            }
                        }

                        var finalMeshes = new List <MeshData>();

                        finalMeshes.AddRange(excludedMeshes);

                        foreach (var meshList in finalMeshGroups)
                        {
                            // transform the buffers
                            foreach (var mesh in meshList)
                            {
                                var transformationMatrix = GetMatrixFromIndex(model.Hierarchy.Nodes, hierarchyUpdater, meshList.Key, mesh.NodeIndex);
                                mesh.Draw.VertexBuffers[0].TransformBuffer(ref transformationMatrix);
                            }

                            // refine the groups base on several tests
                            var newMeshGroups = new List <GroupList <int, MeshData> > {
                                meshList
                            };
                            // only regroup meshes if they share the same parameters
                            newMeshGroups = RefineGroups(newMeshGroups, CompareParameters);
                            // only regroup meshes if they share the shadow options
                            newMeshGroups = RefineGroups(newMeshGroups, CompareShadowOptions);
                            //only regroup meshes if they share the same lighting configurations
                            newMeshGroups = RefineGroups(newMeshGroups, CompareLightingConfigurations);


                            // add to the final meshes groups
                            foreach (var sameParamsMeshes in newMeshGroups)
                            {
                                var baseMesh    = sameParamsMeshes[0];
                                var newMeshList = sameParamsMeshes.Select(x => x.Draw).ToList().GroupDrawData(Allow32BitIndex);
                                foreach (var generatedMesh in newMeshList)
                                {
                                    finalMeshes.Add(new MeshData {
                                        Material   = baseMesh.Material,
                                        Parameters = baseMesh.Parameters,
                                        Name       = baseMesh.Name,
                                        Draw       = generatedMesh,
                                        NodeIndex  = meshList.Key,
                                        Skinning   = null,
                                    });
                                }
                            }
                        }

                        // delete empty nodes (neither mesh nor bone attached)
                        var keptNodes = new bool[model.Hierarchy.Nodes.Length];
                        for (var i = 0; i < keptNodes.Length; ++i)
                        {
                            keptNodes[i] = false;
                        }
                        foreach (var keepIndex in indicesBlackList)
                        {
                            var nodeIndex = keepIndex;
                            while (nodeIndex != -1 && !keptNodes[nodeIndex])
                            {
                                keptNodes[nodeIndex] = true;
                                nodeIndex            = model.Hierarchy.Nodes[nodeIndex].ParentIndex;
                            }
                        }
                        foreach (var mesh in finalMeshes)
                        {
                            var nodeIndex = mesh.NodeIndex;
                            while (nodeIndex != -1 && !keptNodes[nodeIndex])
                            {
                                keptNodes[nodeIndex] = true;
                                nodeIndex            = model.Hierarchy.Nodes[nodeIndex].ParentIndex;
                            }

                            if (mesh.Skinning != null)
                            {
                                foreach (var bone in mesh.Skinning.Bones)
                                {
                                    nodeIndex = bone.NodeIndex;
                                    while (nodeIndex != -1 && !keptNodes[nodeIndex])
                                    {
                                        keptNodes[nodeIndex] = true;
                                        nodeIndex            = model.Hierarchy.Nodes[nodeIndex].ParentIndex;
                                    }
                                }
                            }
                        }

                        var newNodes   = new List <ModelNodeDefinition>();
                        var newMapping = new int[model.Hierarchy.Nodes.Length];
                        for (var i = 0; i < keptNodes.Length; ++i)
                        {
                            if (keptNodes[i])
                            {
                                var parentIndex = model.Hierarchy.Nodes[i].ParentIndex;
                                if (parentIndex != -1)
                                {
                                    model.Hierarchy.Nodes[i].ParentIndex = newMapping[parentIndex]; // assume that the nodes are well ordered
                                }
                                newMapping[i] = newNodes.Count;
                                newNodes.Add(model.Hierarchy.Nodes[i]);
                            }
                        }

                        foreach (var mesh in finalMeshes)
                        {
                            mesh.NodeIndex = newMapping[mesh.NodeIndex];

                            if (mesh.Skinning != null)
                            {
                                for (var i = 0; i < mesh.Skinning.Bones.Length; ++i)
                                {
                                    mesh.Skinning.Bones[i].NodeIndex = newMapping[mesh.Skinning.Bones[i].NodeIndex];
                                }
                            }
                        }

                        model.Meshes          = finalMeshes;
                        model.Hierarchy.Nodes = newNodes.ToArray();

                        hierarchyUpdater = new ModelViewHierarchyUpdater(model.Hierarchy.Nodes);
                        hierarchyUpdater.UpdateMatrices();
                    }

                    // bounding boxes
                    foreach (var mesh in model.Meshes)
                    {
                        var vertexBuffers = mesh.Draw.VertexBuffers;
                        if (vertexBuffers.Length > 0)
                        {
                            // Compute local mesh bounding box (no node transformation)
                            Matrix matrix = Matrix.Identity;
                            mesh.BoundingBox = vertexBuffers[0].ComputeBoundingBox(ref matrix);

                            // Compute model bounding box (includes node transformation)
                            hierarchyUpdater.GetWorldMatrix(mesh.NodeIndex, out matrix);
                            var meshBoundingBox = vertexBuffers[0].ComputeBoundingBox(ref matrix);
                            BoundingBox.Merge(ref model.BoundingBox, ref meshBoundingBox, out model.BoundingBox);
                        }

                        // TODO: temporary Always try to compact
                        mesh.Draw.CompactIndexBuffer();
                    }

                    // merges all the Draw VB and IB together to produce one final VB and IB by entity.
                    var sizeVertexBuffer      = model.Meshes.SelectMany(x => x.Draw.VertexBuffers).Select(x => x.Buffer.Value.Content.Length).Sum();
                    var sizeIndexBuffer       = model.Meshes.Select(x => x.Draw.IndexBuffer).Select(x => x.Buffer.Value.Content.Length).Sum();
                    var vertexBuffer          = new BufferData(BufferFlags.VertexBuffer, new byte[sizeVertexBuffer]);
                    var indexBuffer           = new BufferData(BufferFlags.IndexBuffer, new byte[sizeIndexBuffer]);
                    var vertexBufferNextIndex = 0;
                    var indexBufferNextIndex  = 0;
                    foreach (var drawMesh in model.Meshes.Select(x => x.Draw))
                    {
                        // the index buffer
                        var oldIndexBuffer = drawMesh.IndexBuffer.Buffer.Value.Content;

                        Array.Copy(oldIndexBuffer, 0, indexBuffer.Content, indexBufferNextIndex, oldIndexBuffer.Length);

                        drawMesh.IndexBuffer.Offset = indexBufferNextIndex;
                        drawMesh.IndexBuffer.Buffer = indexBuffer;

                        indexBufferNextIndex += oldIndexBuffer.Length;

                        // the vertex buffers
                        foreach (var vertexBufferBinding in drawMesh.VertexBuffers)
                        {
                            var oldVertexBuffer = vertexBufferBinding.Buffer.Value.Content;

                            Array.Copy(oldVertexBuffer, 0, vertexBuffer.Content, vertexBufferNextIndex, oldVertexBuffer.Length);

                            vertexBufferBinding.Offset = vertexBufferNextIndex;
                            vertexBufferBinding.Buffer = vertexBuffer;

                            vertexBufferNextIndex += oldVertexBuffer.Length;
                        }
                    }


                    // If there were any errors while importing models
                    if (hasErrors)
                    {
                        return(ResultStatus.Failed);
                    }

                    // Convert to Entity
                    exportedObject = model;
                }
                else
                {
                    commandContext.Logger.Error("Unknown export type [{0}] {1}", ExportType, ContextAsString);
                    return(ResultStatus.Failed);
                }

                if (exportedObject != null)
                {
                    assetManager.Save(Location, exportedObject);
                }

                commandContext.Logger.Info("The {0} has been successfully imported.", ContextAsString);

                return(ResultStatus.Successful);
            }
            catch (Exception ex)
            {
                commandContext.Logger.Error("Unexpected error while importing {0}", ex, ContextAsString);
                return(ResultStatus.Failed);
            }
            finally
            {
                Interlocked.Decrement(ref spawnedFbxCommands);
            }
        }
Ejemplo n.º 2
0
        private object ExportModel(ICommandContext commandContext, AssetManager assetManager)
        {
            // Read from model file
            var modelSkeleton = LoadSkeleton(commandContext, assetManager); // we get model skeleton to compare it to real skeleton we need to map to
            var model = LoadModel(commandContext, assetManager);

            // Apply materials
            foreach (var modelMaterial in Materials)
            {
                if (modelMaterial.MaterialInstance?.Material == null)
                {
                    commandContext.Logger.Warning($"The material [{modelMaterial.Name}] is null in the list of materials.");
                    continue;
                }
                model.Materials.Add(modelMaterial.MaterialInstance);
            }

            model.BoundingBox = BoundingBox.Empty;

            foreach (var mesh in model.Meshes)
            {
                if (TessellationAEN)
                {
                    // TODO: Generate AEN model view
                    commandContext.Logger.Error("TessellationAEN is not supported in {0}", ContextAsString);
                }
            }

            SkeletonMapping skeletonMapping;

            Skeleton skeleton;
            if (SkeletonUrl != null)
            {
                // Load skeleton and process it
                skeleton = assetManager.Load<Skeleton>(SkeletonUrl);

                // Assign skeleton to model
                model.Skeleton = AttachedReferenceManager.CreateSerializableVersion<Skeleton>(Guid.Empty, SkeletonUrl);
            }
            else
            {
                skeleton = null;

            }

            skeletonMapping = new SkeletonMapping(skeleton, modelSkeleton);

            // Refresh skeleton updater with model skeleton
            var hierarchyUpdater = new SkeletonUpdater(modelSkeleton);
            hierarchyUpdater.UpdateMatrices();

            // Move meshes in the new nodes
            foreach (var mesh in model.Meshes)
            {
                // Check if there was a remap using model skeleton
                if (skeletonMapping.SourceToSource[mesh.NodeIndex] != mesh.NodeIndex)
                {
                    // Transform vertices
                    var transformationMatrix = CombineMatricesFromNodeIndices(hierarchyUpdater.NodeTransformations, skeletonMapping.SourceToSource[mesh.NodeIndex], mesh.NodeIndex);
                    mesh.Draw.VertexBuffers[0].TransformBuffer(ref transformationMatrix);

                    // Check if geometry is inverted, to know if we need to reverse winding order
                    // TODO: What to do if there is no index buffer? We should create one... (not happening yet)
                    if (mesh.Draw.IndexBuffer == null)
                        throw new InvalidOperationException();

                    Matrix rotation;
                    Vector3 scale, translation;
                    if (transformationMatrix.Decompose(out scale, out rotation, out translation)
                        && scale.X * scale.Y * scale.Z < 0)
                    {
                        mesh.Draw.ReverseWindingOrder();
                    }
                }

                // Update new node index using real asset skeleton
                mesh.NodeIndex = skeletonMapping.SourceToTarget[mesh.NodeIndex];
            }

            // Merge meshes with same parent nodes, material and skinning
            var meshesByNodes = model.Meshes.GroupBy(x => x.NodeIndex).ToList();

            foreach (var meshesByNode in meshesByNodes)
            {
                // This logic to detect similar material is kept from old code; this should be reviewed/improved at some point
                foreach (var meshesPerDrawCall in meshesByNode.GroupBy(x => x,
                    new AnonymousEqualityComparer<Mesh>((x, y) =>
                    x.MaterialIndex == y.MaterialIndex // Same material
                    && ArrayExtensions.ArraysEqual(x.Skinning?.Bones, y.Skinning?.Bones) // Same bones
                    && CompareParameters(model, x, y) // Same parameters
                    && CompareShadowOptions(model, x, y), // Same shadow parameters
                    x => 0)).ToList())
                {
                    if (meshesPerDrawCall.Count() == 1)
                    {
                        // Nothing to group, skip to next entry
                        continue;
                    }

                    // Remove old meshes
                    foreach (var mesh in meshesPerDrawCall)
                    {
                        model.Meshes.Remove(mesh);
                    }

                    // Add new combined mesh(es)
                    var baseMesh = meshesPerDrawCall.First();
                    var newMeshList = meshesPerDrawCall.Select(x => x.Draw).ToList().GroupDrawData(Allow32BitIndex);

                    foreach (var generatedMesh in newMeshList)
                    {
                        model.Meshes.Add(new Mesh(generatedMesh, baseMesh.Parameters)
                        {
                            MaterialIndex = baseMesh.MaterialIndex,
                            Name = baseMesh.Name,
                            Draw = generatedMesh,
                            NodeIndex = baseMesh.NodeIndex,
                            Skinning = baseMesh.Skinning,
                        });
                    }
                }
            }

            // Remap skinning
            foreach (var skinning in model.Meshes.Select(x => x.Skinning).Where(x => x != null).Distinct())
            {
                // Update node mapping
                // Note: we only remap skinning matrices, but we could directly remap skinning bones instead
                for (int i = 0; i < skinning.Bones.Length; ++i)
                {
                    var nodeIndex = skinning.Bones[i].NodeIndex;
                    var newNodeIndex = skeletonMapping.SourceToSource[nodeIndex];

                    skinning.Bones[i].NodeIndex = skeletonMapping.SourceToTarget[nodeIndex];

                    // If it was remapped, we also need to update matrix
                    if (newNodeIndex != nodeIndex)
                    {
                        var transformationMatrix = CombineMatricesFromNodeIndices(hierarchyUpdater.NodeTransformations, newNodeIndex, nodeIndex);
                        skinning.Bones[i].LinkToMeshMatrix = Matrix.Multiply(skinning.Bones[i].LinkToMeshMatrix, transformationMatrix);
                    }
                }
            }

            // split the meshes if necessary
            model.Meshes = SplitExtensions.SplitMeshes(model.Meshes, Allow32BitIndex);

            // Refresh skeleton updater with asset skeleton
            hierarchyUpdater = new SkeletonUpdater(skeleton);
            hierarchyUpdater.UpdateMatrices();

            // bounding boxes
            var modelBoundingBox = model.BoundingBox;
            var modelBoundingSphere = model.BoundingSphere;
            foreach (var mesh in model.Meshes)
            {
                var vertexBuffers = mesh.Draw.VertexBuffers;
                if (vertexBuffers.Length > 0)
                {
                    // Compute local mesh bounding box (no node transformation)
                    Matrix matrix = Matrix.Identity;
                    mesh.BoundingBox = vertexBuffers[0].ComputeBounds(ref matrix, out mesh.BoundingSphere);

                    // Compute model bounding box (includes node transformation)
                    hierarchyUpdater.GetWorldMatrix(mesh.NodeIndex, out matrix);
                    BoundingSphere meshBoundingSphere;
                    var meshBoundingBox = vertexBuffers[0].ComputeBounds(ref matrix, out meshBoundingSphere);
                    BoundingBox.Merge(ref modelBoundingBox, ref meshBoundingBox, out modelBoundingBox);
                    BoundingSphere.Merge(ref modelBoundingSphere, ref meshBoundingSphere, out modelBoundingSphere);
                }

                // TODO: temporary Always try to compact
                mesh.Draw.CompactIndexBuffer();
            }
            model.BoundingBox = modelBoundingBox;
            model.BoundingSphere = modelBoundingSphere;

            // merges all the Draw VB and IB together to produce one final VB and IB by entity.
            var sizeVertexBuffer = model.Meshes.SelectMany(x => x.Draw.VertexBuffers).Select(x => x.Buffer.GetSerializationData().Content.Length).Sum();
            var sizeIndexBuffer = 0;
            foreach (var x in model.Meshes)
            {
                // Let's be aligned (if there was 16bit indices before, we might be off)
                if (x.Draw.IndexBuffer.Is32Bit && sizeIndexBuffer % 4 != 0)
                    sizeIndexBuffer += 2;

                sizeIndexBuffer += x.Draw.IndexBuffer.Buffer.GetSerializationData().Content.Length;
            }
            var vertexBuffer = new BufferData(BufferFlags.VertexBuffer, new byte[sizeVertexBuffer]);
            var indexBuffer = new BufferData(BufferFlags.IndexBuffer, new byte[sizeIndexBuffer]);

            // Note: reusing same instance, to avoid having many VB with same hash but different URL
            var vertexBufferSerializable = vertexBuffer.ToSerializableVersion();
            var indexBufferSerializable = indexBuffer.ToSerializableVersion();

            var vertexBufferNextIndex = 0;
            var indexBufferNextIndex = 0;
            foreach (var drawMesh in model.Meshes.Select(x => x.Draw))
            {
                // the index buffer
                var oldIndexBuffer = drawMesh.IndexBuffer.Buffer.GetSerializationData().Content;

                // Let's be aligned (if there was 16bit indices before, we might be off)
                if (drawMesh.IndexBuffer.Is32Bit && indexBufferNextIndex % 4 != 0)
                    indexBufferNextIndex += 2;

                Array.Copy(oldIndexBuffer, 0, indexBuffer.Content, indexBufferNextIndex, oldIndexBuffer.Length);

                drawMesh.IndexBuffer = new IndexBufferBinding(indexBufferSerializable, drawMesh.IndexBuffer.Is32Bit, drawMesh.IndexBuffer.Count, indexBufferNextIndex);

                indexBufferNextIndex += oldIndexBuffer.Length;

                // the vertex buffers
                for (int index = 0; index < drawMesh.VertexBuffers.Length; index++)
                {
                    var vertexBufferBinding = drawMesh.VertexBuffers[index];
                    var oldVertexBuffer = vertexBufferBinding.Buffer.GetSerializationData().Content;

                    Array.Copy(oldVertexBuffer, 0, vertexBuffer.Content, vertexBufferNextIndex, oldVertexBuffer.Length);

                    drawMesh.VertexBuffers[index] = new VertexBufferBinding(vertexBufferSerializable, vertexBufferBinding.Declaration, vertexBufferBinding.Count, vertexBufferBinding.Stride,
                        vertexBufferNextIndex);

                    vertexBufferNextIndex += oldVertexBuffer.Length;
                }
            }

            // Convert to Entity
            return model;
        }
        public void Generate(IServiceRegistry services, Model model)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            var needsTempDevice = false;
            var graphicsDevice  = services?.GetSafeServiceAs <IGraphicsDeviceService>().GraphicsDevice;

            if (graphicsDevice == null)
            {
                graphicsDevice  = GraphicsDevice.New();
                needsTempDevice = true;
            }

            var data = CreatePrimitiveMeshData();

            if (data.Vertices.Length == 0)
            {
                throw new InvalidOperationException("Invalid GeometricPrimitive [{0}]. Expecting non-zero Vertices array");
            }

            if (LocalOffset != Vector3.Zero)
            {
                for (var index = 0; index < data.Vertices.Length; index++)
                {
                    data.Vertices[index].Position += LocalOffset;
                }
            }

            //Scale if necessary
            if (Scale != Vector3.One)
            {
                var inverseMatrix = Matrix.Scaling(Scale);
                inverseMatrix.Invert();
                for (var index = 0; index < data.Vertices.Length; index++)
                {
                    data.Vertices[index].Position *= Scale;
                    Vector3.TransformCoordinate(ref data.Vertices[index].Normal, ref inverseMatrix, out data.Vertices[index].Normal);
                }
            }

            var boundingBox = BoundingBox.Empty;

            for (int i = 0; i < data.Vertices.Length; i++)
            {
                BoundingBox.Merge(ref boundingBox, ref data.Vertices[i].Position, out boundingBox);
            }

            BoundingSphere boundingSphere;

            unsafe
            {
                fixed(void *verticesPtr = data.Vertices)
                BoundingSphere.FromPoints((IntPtr)verticesPtr, 0, data.Vertices.Length, VertexPositionNormalTexture.Size, out boundingSphere);
            }

            var originalLayout = data.Vertices[0].GetLayout();

            // Generate Tangent/BiNormal vectors
            var resultWithTangentBiNormal = VertexHelper.GenerateTangentBinormal(originalLayout, data.Vertices, data.Indices);

            // Generate Multitexcoords
            var maxTexCoords = MathUtil.Clamp(NumOfTexCoords, 1, 10) - 1;
            var result       = VertexHelper.GenerateMultiTextureCoordinates(resultWithTangentBiNormal, vertexStride: 0, maxTexCoords);

            var meshDraw = new MeshDraw();

            var layout       = result.Layout;
            var vertexBuffer = result.VertexBuffer;
            var indices      = data.Indices;

            if (indices.Length < 0xFFFF)
            {
                var indicesShort = new ushort[indices.Length];
                for (int i = 0; i < indicesShort.Length; i++)
                {
                    indicesShort[i] = (ushort)indices[i];
                }
                meshDraw.IndexBuffer = new IndexBufferBinding(Buffer.Index.New(graphicsDevice, indicesShort).RecreateWith(indicesShort), false, indices.Length);
                if (needsTempDevice)
                {
                    var indexData = BufferData.New(BufferFlags.IndexBuffer, indicesShort);
                    meshDraw.IndexBuffer = new IndexBufferBinding(indexData.ToSerializableVersion(), false, indices.Length);
                }
            }
            else
            {
                if (graphicsDevice.Features.CurrentProfile <= GraphicsProfile.Level_9_3)
                {
                    throw new InvalidOperationException("Cannot generate more than 65535 indices on feature level HW <= 9.3");
                }

                meshDraw.IndexBuffer = new IndexBufferBinding(Buffer.Index.New(graphicsDevice, indices).RecreateWith(indices), true, indices.Length);
                if (needsTempDevice)
                {
                    var indexData = BufferData.New(BufferFlags.IndexBuffer, indices);
                    meshDraw.IndexBuffer = new IndexBufferBinding(indexData.ToSerializableVersion(), true, indices.Length);
                }
            }

            meshDraw.VertexBuffers = new[] { new VertexBufferBinding(Buffer.New(graphicsDevice, vertexBuffer, BufferFlags.VertexBuffer).RecreateWith(vertexBuffer), layout, data.Vertices.Length) };
            if (needsTempDevice)
            {
                var vertexData = BufferData.New(BufferFlags.VertexBuffer, vertexBuffer);
                meshDraw.VertexBuffers = new[] { new VertexBufferBinding(vertexData.ToSerializableVersion(), layout, data.Vertices.Length) };
            }

            meshDraw.DrawCount     = indices.Length;
            meshDraw.PrimitiveType = PrimitiveType.TriangleList;

            var mesh = new Mesh {
                Draw = meshDraw, BoundingBox = boundingBox, BoundingSphere = boundingSphere
            };

            model.BoundingBox    = boundingBox;
            model.BoundingSphere = boundingSphere;
            model.Add(mesh);

            if (MaterialInstance?.Material != null)
            {
                model.Materials.Add(MaterialInstance);
            }

            if (needsTempDevice)
            {
                graphicsDevice.Dispose();
            }
        }
Ejemplo n.º 4
0
 private bool ValidData(BufferData obj)
 {
     return(obj is Matrix <ParsablePointD>);
 }
Ejemplo n.º 5
0
 public static void InitGL_1_5(OpenGLContext ctx)
 {
     glDeleteQueries = ctx.GetProc<DeleteQueries>("glDeleteQueries");
     glIsQuery = ctx.GetProc<IsQuery>("glIsQuery");
     glBeginQuery = ctx.GetProc<BeginQuery>("glBeginQuery");
     glEndQuery = ctx.GetProc<EndQuery>("glEndQuery");
     glGetQueryiv = ctx.GetProc<GetQueryiv>("glGetQueryiv");
     glGetQueryObjectiv = ctx.GetProc<GetQueryObjectiv>("glGetQueryObjectiv");
     glGetQueryObjectuiv = ctx.GetProc<GetQueryObjectuiv>("glGetQueryObjectuiv");
     glBindBuffer = ctx.GetProc<BindBuffer>("glBindBuffer");
     glDeleteBuffers = ctx.GetProc<DeleteBuffers>("glDeleteBuffers");
     glGenBuffers = ctx.GetProc<GenBuffers>("glGenBuffers");
     glIsBuffer = ctx.GetProc<IsBuffer>("glIsBuffer");
     glBufferData = ctx.GetProc<BufferData>("glBufferData");
     glBufferSubData = ctx.GetProc<BufferSubData>("glBufferSubData");
     glGetBufferSubData = ctx.GetProc<GetBufferSubData>("glGetBufferSubData");
     glMapBuffer = ctx.GetProc<MapBuffer>("glMapBuffer");
     glUnmapBuffer = ctx.GetProc<UnmapBuffer>("glUnmapBuffer");
     glGetBufferParameteriv = ctx.GetProc<GetBufferParameteriv>("glGetBufferParameteriv");
     glGetBufferPointerv = ctx.GetProc<GetBufferPointerv>("glGetBufferPointerv");
 }
Ejemplo n.º 6
0
 private void CopyToOtherBuffer(BufferData source, BufferData desti)
 {
 }
Ejemplo n.º 7
0
 private static void OnEncrypt(BufferData data, ref int length)
 {
     AuthCryptManager.Encrypt(data.Buffer, data.BaseOffset + data.Offset, ref length, data.RemainingLength);
 }
Ejemplo n.º 8
0
        /// <summary>
        /// Raised when an IVsTextView is created.  When this occurs it means a previously created
        /// ITextView was associated with an IVsTextView shim.  This means the ITextView will be 
        /// hooked into the Visual Studio command system and a host of other items.  Setup all of
        /// our plumbing here
        /// </summary>
        void IVsTextViewCreationListener.VsTextViewCreated(IVsTextView vsView)
        {
            // Get the ITextView created.  Shouldn't ever be null unless a non-standard Visual Studio
            // component is calling this function
            var textView = _adaptersFactory.GetWpfTextView(vsView);
            if (textView == null)
            {
                return;
            }

            // Sanity check. No reason for this to be null
            var opt = _vim.GetVimBuffer(textView);
            if (!opt.IsSome())
            {
                return;
            }

            var buffer = opt.Value;
            BufferData bufferData;
            if (_bufferMap.TryGetValue(buffer, out bufferData))
            {
                // During the lifetime of an IVimBuffer the local and editor settings are kept
                // in sync for tab values.  At startup though a decision has to be made about which
                // settings should "win" and this is controlled by 'UseEditorSettings'.
                //
                // Visual Studio of course makes this difficult.  It will create an ITextView and
                // then later force all of it's language preference settings down on the ITextView
                // if it does indeed have an IVsTextView.  This setting will inherently overwrite
                // the custom settings with the stored Visual Studio settings.
                //
                // To work around this we store the original values and reset them here.  This event
                // is raised after this propagation occurs so we can put them back
                if (!_vim.GlobalSettings.UseEditorSettings)
                {
                    buffer.LocalSettings.TabStop = bufferData.TabStop;
                    buffer.LocalSettings.ExpandTab = bufferData.ExpandTab;
                    buffer.LocalSettings.Number = bufferData.Number;
                }
            }
            else
            {
                bufferData = new BufferData();
                _bufferMap[buffer] = bufferData;
            }

            var broker = _displayWindowBrokerFactoryServcie.CreateDisplayWindowBroker(textView);
            var bufferCoordinator = _bufferCoordinatorFactory.GetVimBufferCoordinator(buffer);
            var result = VsCommandTarget.Create(bufferCoordinator, vsView, _adapter, broker, _externalEditorManager);
            if (result.IsSuccess)
            {
                // Store the value for debugging
                bufferData.VsCommandTarget = result.Value;
            }

            // Try and install the IVsFilterKeys adapter.  This cannot be done synchronously here
            // because Venus projects are not fully initialized at this state.  Merely querying
            // for properties cause them to corrupt internal state and prevents rendering of the
            // view.  Occurs for aspx and .js pages
            Action install = () => VsFilterKeysAdapter.TryInstallFilterKeysAdapter(_adapter, _editorOptionsFactoryService, buffer);

            _protectedOperations.BeginInvoke(install);
        }
Ejemplo n.º 9
0
        public void Render()
        {
            //--
            var ubo = new UniformBufferObject();

            ubo.Create();
            // if (RenderContext.LightObjects.Count >= 2)
            // {
            //     var lightsData = new GlslLight[2];
            //     lightsData[0].Position = RenderContext.LightObjects[0].Position;
            //     lightsData[0].Color = new Vector3(0.5f, 0.5f, 0.5f);
            //     lightsData[0].ShadowLayer = RenderContext.LightObjects[0].ShadowTextureIndex;
            //     lightsData[0].DirectionalLight = RenderContext.LightObjects[0].LightType == LightType.Directional ? 1 : 0;
            //     lightsData[0].LightSpaceMatrix = Matrix4.Transpose(RenderContext.LightObjects[0].LightCamera.ViewMatrix * RenderContext.LightObjects[0].LightCamera.ProjectionMatrix);
            //     lightsData[0].Linear = 0.1f;
            //     lightsData[0].Quadric = 0f;

            //     lightsData[1].Position = RenderContext.LightObjects[1].Position;
            //     lightsData[1].Color = new Vector3(0.5f, 0.5f, 0.5f);
            //     lightsData[1].ShadowLayer = RenderContext.LightObjects[1].ShadowTextureIndex;
            //     lightsData[1].DirectionalLight = RenderContext.LightObjects[1].LightType == LightType.Directional ? 1 : 0;
            //     lightsData[1].LightSpaceMatrix = Matrix4.Transpose(RenderContext.LightObjects[1].LightCamera.ViewMatrix * RenderContext.LightObjects[1].LightCamera.ProjectionMatrix);
            //     lightsData[1].Linear = 0.1f;
            //     lightsData[1].Quadric = 0f;
            //     ubo.SetData(BufferData.Create(lightsData));

            //     ubo.SetBindingPoint(RenderContext.LightBinding);
            // }

            if (RenderContext.LightObjects.Count > 0)
            {
                var lightDataList = new List <GlslLight>();
                foreach (var light in RenderContext.LightObjects)
                {
                    var lightData = new GlslLight();
                    lightData.Position         = light.Position;
                    lightData.Color            = light.Color;
                    lightData.ShadowLayer      = light.ShadowTextureIndex;
                    lightData.DirectionalLight = light.LightType == LightType.Directional ? 1 : 0;
                    lightData.LightSpaceMatrix = Matrix4.Transpose(light.LightCamera.ViewMatrix * light.LightCamera.ProjectionMatrix);
                    lightData.Linear           = light.Linear;
                    lightData.Quadric          = light.Quadric;
                    lightData.FarPlane         = light.LightCamera.FarPlane;
                    lightData.Direction        = light.Direction.Normalized();
                    lightDataList.Add(lightData);
                }
                ubo.SetData(BufferData.Create(lightDataList.ToArray()));
                ubo.SetBindingPoint(RenderContext.LightBinding);
            }

            //--
            GL.Enable(EnableCap.DepthTest);

            //--

            RenderContext.InitRender();
            RenderContext.Render();
            RenderContext.OnWorldRendered();

            //--

            // Configure

            // Render objects

            // Render Screen Surface

            //CheckForProgramError();

            ubo.Free();

            if (FlushRenderBackend == FlushRenderBackend.End)
            {
                GL.Finish();
            }
        }
Ejemplo n.º 10
0
        private bool DecodePacket(BufferData data, out ushort length)
        {
            using (var br = data.GetReader(data.Offset, data.RemainingLength))
            {
                var rawPacket = new ProtocolPacket();

                rawPacket.Read(br);

                if (rawPacket.Channel != 0)
                {
                    if (rawPacket.SequenceNumber < ReceiveSequence[rawPacket.Channel])
                    {
                        Debugger.Break();

                        length = rawPacket.Size; // throw away the packet
                        return(true);
                    }

                    ReceiveSequence[rawPacket.Channel] = rawPacket.SequenceNumber;
                }

                length = rawPacket.Size;

                data.Offset += (int)br.BaseStream.Position;

                switch (rawPacket.Type)
                {
                case ClientMessageOpcode.None:     // Send timeout check
                    if (length != 4)
                    {
                        Debugger.Break();     // If it's not send timeout check, let's investigate...
                    }
                    return(true);

                case ClientMessageOpcode.Login:
                    var loginMsg = rawPacket.Message as LoginMessage;
                    if (loginMsg == null)
                    {
                        Close(false);
                        return(false);
                    }


                    if (loginMsg.Version.Length != 8 || loginMsg.Version != "1.16.5.0")
                    {
                        Logger.WriteLog(LogType.Error, $"Client version mismatch: Server: 1.16.5.0 | Client: {loginMsg.Version}");

                        SendMessage(new LoginResponseMessage
                        {
                            ErrorCode = LoginErrorCodes.VersionMismatch,
                            Subtype   = LoginResponseMessageSubtype.Failed
                        });

                        Close(false);
                        return(false);
                    }

                    Entry = Server.AuthenticateClient(this, loginMsg.AccountId, loginMsg.OneTimeKey);     // TODO: implement ban system and check if the account is banned
                    if (Entry == null)
                    {
                        Logger.WriteLog(LogType.Error, "Client with ip: {0} tried to log in with invalid session data! User Id: {1} | OneTimeKey: {2}", Socket.RemoteAddress, loginMsg.AccountId, loginMsg.OneTimeKey);

                        SendMessage(new LoginResponseMessage
                        {
                            ErrorCode = LoginErrorCodes.AuthenticationFailed,
                            Subtype   = LoginResponseMessageSubtype.Failed
                        });

                        Close(false);
                        return(false);
                    }

                    SendMessage(new LoginResponseMessage
                    {
                        AccountId = loginMsg.AccountId,
                        Subtype   = LoginResponseMessageSubtype.Success
                    });

                    State = ClientState.LoggedIn;

                    CharacterManager.Instance.StartCharacterSelection(this);
                    return(true);

                case ClientMessageOpcode.Move:
                    break;

                case ClientMessageOpcode.CallServerMethod:
                    break;

                case ClientMessageOpcode.Ping:
                    break;
                }
            }

            /*var packet = new PythonCallPacket(length);
             * using (var br = data.GetReader())
             * {
             *  packet.Read(br);
             *
             *  if (packet.Return.HasValue)
             *      return packet.Return.Value;
             *
             *  if (packet.Type == 2)
             *  {
             *      State = ClientState.LoggedIn;
             *      Entry = Server.AuthenticateClient(this, packet.AccountId, packet.OneTimeKey);
             *      if (Entry == null)
             *      {
             *          Logger.WriteLog(LogType.Error, "Client with ip: {0} tried to log in with invalid session data! User Id: {1} | OneTimeKey: {2}", Socket.RemoteAddress, packet.AccountId, packet.OneTimeKey);
             *          Close(false);
             *          return false;
             *      }
             *
             *      CharacterManager.Instance.StartCharacterSelection(this);
             *      return true;
             *  }
             *
             *  if (packet.DataSize > 0 && br.BaseStream.Position + packet.DataSize < br.BaseStream.Length)
             *  {
             *      if (br.ReadByte() != 0x4F) // 'O' format
             *          throw new Exception("Unsupported serialization format!");
             *
             *      var packetType = PacketRouter.GetPacketType(packet.Opcode);
             *      if (packetType != null)
             *      {
             *          var pythonPacket = Activator.CreateInstance(packetType) as IBasePacket;
             *          if (pythonPacket == null)
             *              return false;
             *
             *          pythonPacket.Read(br);
             *
             *          Server.PacketQueue.EnqueueIncoming(this, pythonPacket);
             *      }
             *      else
             *          Logger.WriteLog(LogType.Error, $"Unhandled game opcode: {packet.Opcode}");
             *  }
             *  else
             *      Logger.WriteLog(LogType.Error, $"Invalid data found in Python method call! Off: {br.BaseStream.Position} | Len: {packet.DataSize} | Array len: {br.BaseStream.Length}");
             * }*/

            return(true);
        }
 private void RecycleBufferData(BufferData bufferData)
 {
     m_bufferDataPool.Enqueue(bufferData);
 }
        private void SetupGPUFrustumCullings()
        {
            if (!m_computeShaderLoaded)
            {
                return;
            }

            if (!SupportsComputeShaders())
            {
                return;
            }

            if (m_gpuFrustumCullings.Count == 0)
            {
                return;
            }

            m_gpuFrustumCullingCount = 0;
            foreach (FrustumCullingBase[] values in m_gpuFrustumCullings.Values)
            {
                m_gpuFrustumCullingCount += values.Length;
            }

            if (m_bufferDatas == null || m_bufferDatas.Length != m_gpuFrustumCullingCount)
            {
                if (m_bufferDatas != null)
                {
                    for (int i = 0; i < m_bufferDatas.Length; i++)
                    {
                        RecycleBufferData(m_bufferDatas[i]);
                    }
                }

                m_bufferDatas = new BufferData[m_gpuFrustumCullingCount];
                m_cacheIndex  = -1;
                foreach (FrustumCullingBase[] values in m_gpuFrustumCullings.Values)
                {
                    for (int i = 0; i < values.Length; i++)
                    {
                        m_cacheIndex++;
                        m_bufferData                = GetBufferData();
                        m_bufferData.center         = values[i].center;
                        m_bufferData.extents        = values[i].extents;
                        m_bufferData.extents.y     *= EXTENTS_MULTIPLIER;
                        m_bufferDatas[m_cacheIndex] = m_bufferData;
                    }
                }

                ReleaseBuffer();

                m_boundsBuffer = new ComputeBuffer(m_gpuFrustumCullingCount, sizeof(float) * 6);
                m_boundsBuffer.SetData(m_bufferDatas);
                m_computeShader.SetBuffer(m_kernelID, FrustumCullingShaderIDs.boundsBuffer, m_boundsBuffer);

                m_lastResultBuffers = new uint[m_gpuFrustumCullingCount];
                for (int i = 0; i < m_gpuFrustumCullingCount; i++)
                {
                    if (m_tempResultBufferDatas != null && m_tempResultBufferDatas.Length > 0)
                    {
                        if (i < m_tempResultBufferDatas.Length)
                        {
                            m_lastResultBuffers[i] = m_tempResultBufferDatas[i];
                        }
                        else
                        {
                            m_lastResultBuffers[i] = 99;
                        }
                    }
                    else
                    {
                        m_lastResultBuffers[i] = 99;
                    }
                }

                m_tempResultBufferDatas = new uint[m_gpuFrustumCullingCount];
                m_resultBuffer          = new ComputeBuffer(m_gpuFrustumCullingCount, sizeof(uint));
                m_computeShader.SetBuffer(m_kernelID, FrustumCullingShaderIDs.resultBuffer, m_resultBuffer);
                m_computeShader.SetInt(FrustumCullingShaderIDs._Count, m_gpuFrustumCullingCount);
                m_computeShader.SetTexture(m_kernelID, FrustumCullingShaderIDs._HiZMap, m_hiZBuffer.hiZBufferTexture);
                m_computeShader.SetVector(FrustumCullingShaderIDs._HiZTextureSize, m_hiZBuffer.hiZBufferTextureSize);

                m_threadGroups = Mathf.CeilToInt((float)m_gpuFrustumCullingCount / THREAD_GROUP_X);
            }
        }
Ejemplo n.º 13
0
 public bool ValidationCallbackDelegate(BufferData obj)
 {
     if (obj is Matrix <int> )
     {
         Matrix <int> matr = (Matrix <int>)obj;
         if (matr.Value.GetLength(0) > 10)
         {
             return(false);
         }
         else if (matr.Value.GetLength(1) > 10)
         {
             return(false);
         }
         else
         {
             bool pos = true;
             for (int i = 0; i < matr.Value.GetLength(0); i++)
             {
                 for (int j = 0; j < matr.Value.GetLength(1); j++)
                 {
                     if (matr.Value[i, j] < 0)
                     {
                         pos = false;
                     }
                 }
             }
             return(pos);
         }
     }
     if (obj is Matrix <long> )
     {
         Matrix <long> matr = (Matrix <long>)obj;
         if (matr.Value.GetLength(0) > 10)
         {
             return(false);
         }
         else if (matr.Value.GetLength(1) > 10)
         {
             return(false);
         }
         else
         {
             bool pos = true;
             for (int i = 0; i < matr.Value.GetLength(0); i++)
             {
                 for (int j = 0; j < matr.Value.GetLength(1); j++)
                 {
                     if (matr.Value[i, j] < 0)
                     {
                         pos = false;
                     }
                 }
             }
             return(pos);
         }
     }
     if (obj is Matrix <double> )
     {
         Matrix <double> matr = (Matrix <double>)obj;
         if (matr.Value.GetLength(0) > 10)
         {
             return(false);
         }
         else if (matr.Value.GetLength(1) > 10)
         {
             return(false);
         }
         else
         {
             bool pos = true;
             for (int i = 0; i < matr.Value.GetLength(0); i++)
             {
                 for (int j = 0; j < matr.Value.GetLength(1); j++)
                 {
                     if (matr.Value[i, j] < 0)
                     {
                         pos = false;
                     }
                 }
             }
             return(pos);
         }
     }
     else
     {
         return(false);
     }
 }
Ejemplo n.º 14
0
        void IWpfTextViewCreationListener.TextViewCreated(IWpfTextView textView)
        {
            // Create the IVimBuffer after loading the VimRc so that it gets the appropriate
            // settings
            var buffer = _vim.GetOrCreateVimBuffer(textView);

            // Save the tab size and expand tab in case we need to reset them later
            var bufferData = new BufferData
            {
                TabStop = buffer.LocalSettings.TabStop,
                ShiftWidth = buffer.LocalSettings.ShiftWidth,
                ExpandTab = buffer.LocalSettings.ExpandTab,
                Number = buffer.LocalSettings.Number
            };
            _bufferMap[buffer] = bufferData;
        }
Ejemplo n.º 15
0
 private static bool OnDecrypt(BufferData data)
 {
     return(AuthCryptManager.Decrypt(data.Buffer, data.BaseOffset + data.Offset, data.RemainingLength));
 }
Ejemplo n.º 16
0
		/* END STRING MARKER FUNCTIONS */
#endif

		private void LoadGLEntryPoints()
		{
			string baseErrorString;
			if (useES2)
			{
				baseErrorString = "OpenGL ES 2.0";
			}
			else
			{
				baseErrorString = "OpenGL 2.1";
			}
			baseErrorString += " support is required!";

			/* Basic entry points. If you don't have these, you're screwed. */
			try
			{
				INTERNAL_glGetString = (GetString) Marshal.GetDelegateForFunctionPointer(
					SDL.SDL_GL_GetProcAddress("glGetString"),
					typeof(GetString)
				);
				glGetIntegerv = (GetIntegerv) Marshal.GetDelegateForFunctionPointer(
					SDL.SDL_GL_GetProcAddress("glGetIntegerv"),
					typeof(GetIntegerv)
				);
				glEnable = (Enable) Marshal.GetDelegateForFunctionPointer(
					SDL.SDL_GL_GetProcAddress("glEnable"),
					typeof(Enable)
				);
				glDisable = (Disable) Marshal.GetDelegateForFunctionPointer(
					SDL.SDL_GL_GetProcAddress("glDisable"),
					typeof(Disable)
				);
				glViewport = (G_Viewport) Marshal.GetDelegateForFunctionPointer(
					SDL.SDL_GL_GetProcAddress("glViewport"),
					typeof(G_Viewport)
				);
				glScissor = (Scissor) Marshal.GetDelegateForFunctionPointer(
					SDL.SDL_GL_GetProcAddress("glScissor"),
					typeof(Scissor)
				);
				glBlendColor = (BlendColor) Marshal.GetDelegateForFunctionPointer(
					SDL.SDL_GL_GetProcAddress("glBlendColor"),
					typeof(BlendColor)
				);
				glBlendFuncSeparate = (BlendFuncSeparate) Marshal.GetDelegateForFunctionPointer(
					SDL.SDL_GL_GetProcAddress("glBlendFuncSeparate"),
					typeof(BlendFuncSeparate)
				);
				glBlendEquationSeparate = (BlendEquationSeparate) Marshal.GetDelegateForFunctionPointer(
					SDL.SDL_GL_GetProcAddress("glBlendEquationSeparate"),
					typeof(BlendEquationSeparate)
				);
				glColorMask = (ColorMask) Marshal.GetDelegateForFunctionPointer(
					SDL.SDL_GL_GetProcAddress("glColorMask"),
					typeof(ColorMask)
				);
				glDepthMask = (DepthMask) Marshal.GetDelegateForFunctionPointer(
					SDL.SDL_GL_GetProcAddress("glDepthMask"),
					typeof(DepthMask)
				);
				glDepthFunc = (DepthFunc) Marshal.GetDelegateForFunctionPointer(
					SDL.SDL_GL_GetProcAddress("glDepthFunc"),
					typeof(DepthFunc)
				);
				glStencilMask = (StencilMask) Marshal.GetDelegateForFunctionPointer(
					SDL.SDL_GL_GetProcAddress("glStencilMask"),
					typeof(StencilMask)
				);
				glStencilFuncSeparate = (StencilFuncSeparate) Marshal.GetDelegateForFunctionPointer(
					SDL.SDL_GL_GetProcAddress("glStencilFuncSeparate"),
					typeof(StencilFuncSeparate)
				);
				glStencilOpSeparate = (StencilOpSeparate) Marshal.GetDelegateForFunctionPointer(
					SDL.SDL_GL_GetProcAddress("glStencilOpSeparate"),
					typeof(StencilOpSeparate)
				);
				glStencilFunc = (StencilFunc) Marshal.GetDelegateForFunctionPointer(
					SDL.SDL_GL_GetProcAddress("glStencilFunc"),
					typeof(StencilFunc)
				);
				glStencilOp = (StencilOp) Marshal.GetDelegateForFunctionPointer(
					SDL.SDL_GL_GetProcAddress("glStencilOp"),
					typeof(StencilOp)
				);
				glFrontFace = (FrontFace) Marshal.GetDelegateForFunctionPointer(
					SDL.SDL_GL_GetProcAddress("glFrontFace"),
					typeof(FrontFace)
				);
				glPolygonOffset = (PolygonOffset) Marshal.GetDelegateForFunctionPointer(
					SDL.SDL_GL_GetProcAddress("glPolygonOffset"),
					typeof(PolygonOffset)
				);
				glGenTextures = (GenTextures) Marshal.GetDelegateForFunctionPointer(
					SDL.SDL_GL_GetProcAddress("glGenTextures"),
					typeof(GenTextures)
				);
				glDeleteTextures = (DeleteTextures) Marshal.GetDelegateForFunctionPointer(
					SDL.SDL_GL_GetProcAddress("glDeleteTextures"),
					typeof(DeleteTextures)
				);
				glBindTexture = (G_BindTexture) Marshal.GetDelegateForFunctionPointer(
					SDL.SDL_GL_GetProcAddress("glBindTexture"),
					typeof(G_BindTexture)
				);
				glTexImage2D = (TexImage2D) Marshal.GetDelegateForFunctionPointer(
					SDL.SDL_GL_GetProcAddress("glTexImage2D"),
					typeof(TexImage2D)
				);
				glTexSubImage2D = (TexSubImage2D) Marshal.GetDelegateForFunctionPointer(
					SDL.SDL_GL_GetProcAddress("glTexSubImage2D"),
					typeof(TexSubImage2D)
				);
				glCompressedTexImage2D = (CompressedTexImage2D) Marshal.GetDelegateForFunctionPointer(
					SDL.SDL_GL_GetProcAddress("glCompressedTexImage2D"),
					typeof(CompressedTexImage2D)
				);
				glCompressedTexSubImage2D = (CompressedTexSubImage2D) Marshal.GetDelegateForFunctionPointer(
					SDL.SDL_GL_GetProcAddress("glCompressedTexSubImage2D"),
					typeof(CompressedTexSubImage2D)
				);
				glTexParameteri = (TexParameteri) Marshal.GetDelegateForFunctionPointer(
					SDL.SDL_GL_GetProcAddress("glTexParameteri"),
					typeof(TexParameteri)
				);
				glTexParameterf = (TexParameterf) Marshal.GetDelegateForFunctionPointer(
					SDL.SDL_GL_GetProcAddress("glTexParameterf"),
					typeof(TexParameterf)
				);
				glActiveTexture = (ActiveTexture) Marshal.GetDelegateForFunctionPointer(
					SDL.SDL_GL_GetProcAddress("glActiveTexture"),
					typeof(ActiveTexture)
				);
				glPixelStorei = (PixelStorei) Marshal.GetDelegateForFunctionPointer(
					SDL.SDL_GL_GetProcAddress("glPixelStorei"),
					typeof(PixelStorei)
				);
				glGenBuffers = (GenBuffers) Marshal.GetDelegateForFunctionPointer(
					SDL.SDL_GL_GetProcAddress("glGenBuffers"),
					typeof(GenBuffers)
				);
				glDeleteBuffers = (DeleteBuffers) Marshal.GetDelegateForFunctionPointer(
					SDL.SDL_GL_GetProcAddress("glDeleteBuffers"),
					typeof(DeleteBuffers)
				);
				glBindBuffer = (BindBuffer) Marshal.GetDelegateForFunctionPointer(
					SDL.SDL_GL_GetProcAddress("glBindBuffer"),
					typeof(BindBuffer)
				);
				glBufferData = (BufferData) Marshal.GetDelegateForFunctionPointer(
					SDL.SDL_GL_GetProcAddress("glBufferData"),
					typeof(BufferData)
				);
				glBufferSubData = (BufferSubData) Marshal.GetDelegateForFunctionPointer(
					SDL.SDL_GL_GetProcAddress("glBufferSubData"),
					typeof(BufferSubData)
				);
				glClearColor = (ClearColor) Marshal.GetDelegateForFunctionPointer(
					SDL.SDL_GL_GetProcAddress("glClearColor"),
					typeof(ClearColor)
				);
				glClearStencil = (ClearStencil) Marshal.GetDelegateForFunctionPointer(
					SDL.SDL_GL_GetProcAddress("glClearStencil"),
					typeof(ClearStencil)
				);
				glClear = (G_Clear) Marshal.GetDelegateForFunctionPointer(
					SDL.SDL_GL_GetProcAddress("glClear"),
					typeof(G_Clear)
				);
				glDrawBuffers = (DrawBuffers) Marshal.GetDelegateForFunctionPointer(
					SDL.SDL_GL_GetProcAddress("glDrawBuffers"),
					typeof(DrawBuffers)
				);
				glReadPixels = (ReadPixels) Marshal.GetDelegateForFunctionPointer(
					SDL.SDL_GL_GetProcAddress("glReadPixels"),
					typeof(ReadPixels)
				);
				glVertexAttribPointer = (VertexAttribPointer) Marshal.GetDelegateForFunctionPointer(
					SDL.SDL_GL_GetProcAddress("glVertexAttribPointer"),
					typeof(VertexAttribPointer)
				);
				glEnableVertexAttribArray = (EnableVertexAttribArray) Marshal.GetDelegateForFunctionPointer(
					SDL.SDL_GL_GetProcAddress("glEnableVertexAttribArray"),
					typeof(EnableVertexAttribArray)
				);
				glDisableVertexAttribArray = (DisableVertexAttribArray) Marshal.GetDelegateForFunctionPointer(
					SDL.SDL_GL_GetProcAddress("glDisableVertexAttribArray"),
					typeof(DisableVertexAttribArray)
				);
				glDrawArrays = (DrawArrays) Marshal.GetDelegateForFunctionPointer(
					SDL.SDL_GL_GetProcAddress("glDrawArrays"),
					typeof(DrawArrays)
				);
			}
			catch
			{
				throw new NoSuitableGraphicsDeviceException(baseErrorString);
			}

			/* ARB_draw_elements_base_vertex is ideal! */
			IntPtr ep = SDL.SDL_GL_GetProcAddress("glDrawRangeElementsBaseVertex");
			supportsBaseVertex = ep != IntPtr.Zero;
			if (supportsBaseVertex)
			{
				glDrawRangeElementsBaseVertex = (DrawRangeElementsBaseVertex) Marshal.GetDelegateForFunctionPointer(
					ep,
					typeof(DrawRangeElementsBaseVertex)
				);
				glDrawRangeElements = (DrawRangeElements) Marshal.GetDelegateForFunctionPointer(
					SDL.SDL_GL_GetProcAddress("glDrawRangeElements"),
					typeof(DrawRangeElements)
				);
			}
			else
			{
				/* DrawRangeElements is better, but some ES2 targets don't have it. */
				ep = SDL.SDL_GL_GetProcAddress("glDrawRangeElements");
				if (ep != IntPtr.Zero)
				{
					glDrawRangeElements = (DrawRangeElements) Marshal.GetDelegateForFunctionPointer(
						ep,
						typeof(DrawRangeElements)
					);
					glDrawRangeElementsBaseVertex = DrawRangeElementsNoBase;
				}
				else
				{
					ep = SDL.SDL_GL_GetProcAddress("glDrawElements");
					if (ep == IntPtr.Zero)
					{
						throw new NoSuitableGraphicsDeviceException(baseErrorString);
					}
					glDrawElements = (DrawElements) Marshal.GetDelegateForFunctionPointer(
						ep,
						typeof(DrawElements)
					);
					glDrawRangeElements = DrawRangeElementsUnchecked;
					glDrawRangeElementsBaseVertex = DrawRangeElementsNoBaseUnchecked;
				}
			}

			/* These functions are NOT supported in ES.
			 * NVIDIA or desktop ES might, but real scenarios where you need ES
			 * will certainly not have these.
			 * -flibit
			 */
			if (useES2)
			{
				ep = SDL.SDL_GL_GetProcAddress("glPolygonMode");
				if (ep != IntPtr.Zero)
				{
					glPolygonMode = (PolygonMode) Marshal.GetDelegateForFunctionPointer(
						ep,
						typeof(PolygonMode)
					);
				}
				else
				{
					glPolygonMode = PolygonModeESError;
				}
				ep = SDL.SDL_GL_GetProcAddress("glGetTexImage");
				if (ep != IntPtr.Zero)
				{
					glGetTexImage = (GetTexImage) Marshal.GetDelegateForFunctionPointer(
						ep,
						typeof(GetTexImage)
					);
				}
				else
				{
					glGetTexImage = GetTexImageESError;
				}
				ep = SDL.SDL_GL_GetProcAddress("glGetBufferSubData");
				if (ep != IntPtr.Zero)
				{
					glGetBufferSubData = (GetBufferSubData) Marshal.GetDelegateForFunctionPointer(
						ep,
						typeof(GetBufferSubData)
					);
				}
				else
				{
					glGetBufferSubData = GetBufferSubDataESError;
				}
			}
			else
			{
				try
				{
					glPolygonMode = (PolygonMode) Marshal.GetDelegateForFunctionPointer(
						SDL.SDL_GL_GetProcAddress("glPolygonMode"),
						typeof(PolygonMode)
					);
					glGetTexImage = (GetTexImage) Marshal.GetDelegateForFunctionPointer(
						SDL.SDL_GL_GetProcAddress("glGetTexImage"),
						typeof(GetTexImage)
					);
					glGetBufferSubData = (GetBufferSubData) Marshal.GetDelegateForFunctionPointer(
						SDL.SDL_GL_GetProcAddress("glGetBufferSubData"),
						typeof(GetBufferSubData)
					);
				}
				catch
				{
					throw new NoSuitableGraphicsDeviceException(baseErrorString);
				}
			}

			/* We need _some_ form of depth range, ES... */
			IntPtr drPtr = SDL.SDL_GL_GetProcAddress("glDepthRange");
			if (drPtr != IntPtr.Zero)
			{
				glDepthRange = (DepthRange) Marshal.GetDelegateForFunctionPointer(
					drPtr,
					typeof(DepthRange)
				);
			}
			else
			{
				drPtr = SDL.SDL_GL_GetProcAddress("glDepthRangef");
				if (drPtr == IntPtr.Zero)
				{
					throw new NoSuitableGraphicsDeviceException(baseErrorString);
				}
				glDepthRangef = (DepthRangef) Marshal.GetDelegateForFunctionPointer(
					drPtr,
					typeof(DepthRangef)
				);
				glDepthRange = DepthRangeFloat;
			}
			drPtr = SDL.SDL_GL_GetProcAddress("glClearDepth");
			if (drPtr != IntPtr.Zero)
			{
				glClearDepth = (ClearDepth) Marshal.GetDelegateForFunctionPointer(
					drPtr,
					typeof(ClearDepth)
				);
			}
			else
			{
				drPtr = SDL.SDL_GL_GetProcAddress("glClearDepthf");
				if (drPtr == IntPtr.Zero)
				{
					throw new NoSuitableGraphicsDeviceException(baseErrorString);
				}
				glClearDepthf = (ClearDepthf) Marshal.GetDelegateForFunctionPointer(
					drPtr,
					typeof(ClearDepthf)
				);
				glClearDepth = ClearDepthFloat;
			}

			/* Silently fail if using GLES. You didn't need these, right...? >_> */
			try
			{
				glTexImage3D = (TexImage3D) Marshal.GetDelegateForFunctionPointer(
					TryGetEPEXT("glTexImage3D", "OES"),
					typeof(TexImage3D)
				);
				glTexSubImage3D = (TexSubImage3D) Marshal.GetDelegateForFunctionPointer(
					TryGetEPEXT("glTexSubImage3D", "OES"),
					typeof(TexSubImage3D)
				);
				glGenQueries = (GenQueries) Marshal.GetDelegateForFunctionPointer(
					SDL.SDL_GL_GetProcAddress("glGenQueries"),
					typeof(GenQueries)
				);
				glDeleteQueries = (DeleteQueries) Marshal.GetDelegateForFunctionPointer(
					SDL.SDL_GL_GetProcAddress("glDeleteQueries"),
					typeof(DeleteQueries)
				);
				glBeginQuery = (BeginQuery) Marshal.GetDelegateForFunctionPointer(
					SDL.SDL_GL_GetProcAddress("glBeginQuery"),
					typeof(BeginQuery)
				);
				glEndQuery = (EndQuery) Marshal.GetDelegateForFunctionPointer(
					SDL.SDL_GL_GetProcAddress("glEndQuery"),
					typeof(EndQuery)
				);
				glGetQueryObjectuiv = (GetQueryObjectuiv) Marshal.GetDelegateForFunctionPointer(
					SDL.SDL_GL_GetProcAddress("glGetQueryObjectuiv"),
					typeof(GetQueryObjectuiv)
				);
			}
			catch
			{
				if (useES2)
				{
					FNAPlatform.Log("Some non-ES functions failed to load. Beware...");
				}
				else
				{
					throw new NoSuitableGraphicsDeviceException(baseErrorString);
				}
			}

			/* ARB_framebuffer_object. We're flexible, but not _that_ flexible. */
			try
			{
				glGenFramebuffers = (GenFramebuffers) Marshal.GetDelegateForFunctionPointer(
					TryGetEPEXT("glGenFramebuffers"),
					typeof(GenFramebuffers)
				);
				glDeleteFramebuffers = (DeleteFramebuffers) Marshal.GetDelegateForFunctionPointer(
					TryGetEPEXT("glDeleteFramebuffers"),
					typeof(DeleteFramebuffers)
				);
				glBindFramebuffer = (G_BindFramebuffer) Marshal.GetDelegateForFunctionPointer(
					TryGetEPEXT("glBindFramebuffer"),
					typeof(G_BindFramebuffer)
				);
				glFramebufferTexture2D = (FramebufferTexture2D) Marshal.GetDelegateForFunctionPointer(
					TryGetEPEXT("glFramebufferTexture2D"),
					typeof(FramebufferTexture2D)
				);
				glFramebufferRenderbuffer = (FramebufferRenderbuffer) Marshal.GetDelegateForFunctionPointer(
					TryGetEPEXT("glFramebufferRenderbuffer"),
					typeof(FramebufferRenderbuffer)
				);
				glGenerateMipmap = (GenerateMipmap) Marshal.GetDelegateForFunctionPointer(
					TryGetEPEXT("glGenerateMipmap"),
					typeof(GenerateMipmap)
				);
				glGenRenderbuffers = (GenRenderbuffers) Marshal.GetDelegateForFunctionPointer(
					TryGetEPEXT("glGenRenderbuffers"),
					typeof(GenRenderbuffers)
				);
				glDeleteRenderbuffers = (DeleteRenderbuffers) Marshal.GetDelegateForFunctionPointer(
					TryGetEPEXT("glDeleteRenderbuffers"),
					typeof(DeleteRenderbuffers)
				);
				glBindRenderbuffer = (BindRenderbuffer) Marshal.GetDelegateForFunctionPointer(
					TryGetEPEXT("glBindRenderbuffer"),
					typeof(BindRenderbuffer)
				);
				glRenderbufferStorage = (RenderbufferStorage) Marshal.GetDelegateForFunctionPointer(
					TryGetEPEXT("glRenderbufferStorage"),
					typeof(RenderbufferStorage)
				);
			}
			catch
			{
				throw new NoSuitableGraphicsDeviceException("OpenGL framebuffer support is required!");
			}

			/* EXT_framebuffer_blit (or ARB_framebuffer_object) is needed by the faux-backbuffer. */
			supportsFauxBackbuffer = true;
			try
			{
				glBlitFramebuffer = (BlitFramebuffer) Marshal.GetDelegateForFunctionPointer(
					TryGetEPEXT("glBlitFramebuffer"),
					typeof(BlitFramebuffer)
				);
			}
			catch
			{
				supportsFauxBackbuffer = false;
			}

			/* ARB_instanced_arrays/ARB_draw_instanced are almost optional. */
			SupportsHardwareInstancing = true;
			try
			{
				glVertexAttribDivisor = (VertexAttribDivisor) Marshal.GetDelegateForFunctionPointer(
					SDL.SDL_GL_GetProcAddress("glVertexAttribDivisor"),
					typeof(VertexAttribDivisor)
				);
				/* The likelihood of someone having BaseVertex but not Instanced is 0...? */
				if (supportsBaseVertex)
				{
					glDrawElementsInstancedBaseVertex = (DrawElementsInstancedBaseVertex) Marshal.GetDelegateForFunctionPointer(
						SDL.SDL_GL_GetProcAddress("glDrawElementsInstancedBaseVertex"),
						typeof(DrawElementsInstancedBaseVertex)
					);
				}
				else
				{
					glDrawElementsInstanced = (DrawElementsInstanced) Marshal.GetDelegateForFunctionPointer(
						SDL.SDL_GL_GetProcAddress("glDrawElementsInstanced"),
						typeof(DrawElementsInstanced)
					);
					glDrawElementsInstancedBaseVertex = DrawElementsInstancedNoBase;
				}
			}
			catch
			{
				SupportsHardwareInstancing = false;
			}

			/* EXT_draw_buffers2 is probably used by nobody. */
			try
			{
				glColorMaskIndexedEXT = (ColorMaskIndexedEXT) Marshal.GetDelegateForFunctionPointer(
					SDL.SDL_GL_GetProcAddress("glColorMaskIndexedEXT"),
					typeof(ColorMaskIndexedEXT)
				);
			}
			catch
			{
				// FIXME: SupportsIndependentWriteMasks? -flibit
			}

			/* EXT_framebuffer_multisample/ARB_texture_multisample is glitter -flibit */
			supportsMultisampling = true;
			try
			{
				glRenderbufferStorageMultisample = (RenderbufferStorageMultisample) Marshal.GetDelegateForFunctionPointer(
					TryGetEPEXT("glRenderbufferStorageMultisample"),
					typeof(RenderbufferStorageMultisample)
				);
				glSampleMaski = (SampleMaski) Marshal.GetDelegateForFunctionPointer(
					SDL.SDL_GL_GetProcAddress("glSampleMaski"),
					typeof(SampleMaski)
				);
			}
			catch
			{
				supportsMultisampling = false;
			}

			if (useCoreProfile)
			{
				try
				{
					INTERNAL_glGetStringi = (GetStringi) Marshal.GetDelegateForFunctionPointer(
						SDL.SDL_GL_GetProcAddress("glGetStringi"),
						typeof(GetStringi)
					);
					glGenVertexArrays = (GenVertexArrays) Marshal.GetDelegateForFunctionPointer(
						SDL.SDL_GL_GetProcAddress("glGenVertexArrays"),
						typeof(GenVertexArrays)
					);
					glDeleteVertexArrays = (DeleteVertexArrays) Marshal.GetDelegateForFunctionPointer(
						SDL.SDL_GL_GetProcAddress("glDeleteVertexArrays"),
						typeof(DeleteVertexArrays)
					);
					glBindVertexArray = (BindVertexArray) Marshal.GetDelegateForFunctionPointer(
						SDL.SDL_GL_GetProcAddress("glBindVertexArray"),
						typeof(BindVertexArray)
					);
				}
				catch
				{
					throw new NoSuitableGraphicsDeviceException("OpenGL 3.2 support is required!");
				}
			}

#if DEBUG
			/* ARB_debug_output, for debug contexts */
			IntPtr messageCallback = SDL.SDL_GL_GetProcAddress("glDebugMessageCallbackARB");
			IntPtr messageControl = SDL.SDL_GL_GetProcAddress("glDebugMessageControlARB");
			if (messageCallback == IntPtr.Zero || messageControl == IntPtr.Zero)
			{
				FNAPlatform.Log("ARB_debug_output not supported!");
			}
			else
			{
				glDebugMessageCallbackARB = (DebugMessageCallback) Marshal.GetDelegateForFunctionPointer(
					messageCallback,
					typeof(DebugMessageCallback)
				);
				glDebugMessageControlARB = (DebugMessageControl) Marshal.GetDelegateForFunctionPointer(
					messageControl,
					typeof(DebugMessageControl)
				);
				glDebugMessageControlARB(
					GLenum.GL_DONT_CARE,
					GLenum.GL_DONT_CARE,
					GLenum.GL_DONT_CARE,
					0,
					IntPtr.Zero,
					true
				);
				glDebugMessageControlARB(
					GLenum.GL_DONT_CARE,
					GLenum.GL_DEBUG_TYPE_OTHER_ARB,
					GLenum.GL_DEBUG_SEVERITY_LOW_ARB,
					0,
					IntPtr.Zero,
					false
				);
				glDebugMessageControlARB(
					GLenum.GL_DONT_CARE,
					GLenum.GL_DEBUG_TYPE_OTHER_ARB,
					GLenum.GL_DEBUG_SEVERITY_NOTIFICATION_ARB,
					0,
					IntPtr.Zero,
					false
				);
				glDebugMessageCallbackARB(DebugCall, IntPtr.Zero);
			}

			/* GREMEDY_string_marker, for apitrace */
			IntPtr stringMarkerCallback = SDL.SDL_GL_GetProcAddress("glStringMarkerGREMEDY");
			if (stringMarkerCallback == IntPtr.Zero)
			{
				FNAPlatform.Log("GREMEDY_string_marker not supported!");
			}
			else
			{
				glStringMarkerGREMEDY = (StringMarkerGREMEDY) Marshal.GetDelegateForFunctionPointer(
					stringMarkerCallback,
					typeof(StringMarkerGREMEDY)
				);
			}
#endif
		}
Ejemplo n.º 17
0
        public void Read(BinaryReader br)
        {
            if (br.BaseStream.Length < 4)
            {
                throw new Exception("Fragmented receive, should not happen! (4 size header)");
            }

            Size    = br.ReadUInt16();
            Channel = br.ReadByte();

            br.ReadByte(); // padding

            if (Size > br.BaseStream.Length)
            {
                throw new Exception("Fragmented receive, should not happen!");
            }

            if (Channel == 0xFF) // Internal channel: Send timeout checking, ignore the packet
            {
                return;
            }

            if (Channel != 0) // 0 == ReliableStreamChannel (no extra data), Move message uses channels
            {
                Debugger.Break();

                SequenceNumber = br.ReadUInt32(); // Sequence number? if (previousValue - newValue < 0) { process packet; previousValue = newValue; }
                br.ReadInt32();                   // 0xDEADBEEF
                br.ReadInt32();                   // skip
            }

            var packetBeginPosition = br.BaseStream.Position;

            using (var reader = new ProtocolBufferReader(br, ProtocolBufferFlags.DontFragment))
            {
                reader.ReadProtocolFlags();

                ushort type;
                bool   compress;

                reader.ReadPacketType(out type, out compress);

                Type     = (ClientMessageOpcode)type;
                Compress = compress;

                reader.ReadXORCheck((int)(br.BaseStream.Position - packetBeginPosition));
            }

            var xorCheckPosition = (int)br.BaseStream.Position;

            var readBr = br;

            BufferData buffer = null;

            if (Compress)
            {
                var someType = br.ReadByte(); // 0 = No compression
                if (someType >= 2)
                {
                    throw new Exception("Invalid compress type received!");
                }

                if (someType == 1)
                {
                    Debugger.Break(); // TODO: test

                    var uncompressedSize = br.ReadInt32();

                    byte[] uncompressedData;
                    var    offset = 0;

                    if (uncompressedSize > BufferManager.BlockSize)
                    {
                        uncompressedData = new byte[uncompressedSize];
                    }
                    else
                    {
                        buffer = BufferManager.RequestBuffer();

                        uncompressedData = buffer.Buffer;
                        offset           = buffer.BaseOffset;
                    }

                    using (var deflateStream = new DeflateStream(br.BaseStream, CompressionMode.Decompress, true)) // TODO: test if the br.BaseStream is cool as the Stream input for the DeflateStream
                        deflateStream.Read(uncompressedData, offset, uncompressedSize);

                    readBr = buffer != null?buffer.GetReader() : new BinaryReader(new MemoryStream(uncompressedData, 0, uncompressedSize, false), Encoding.UTF8, false);
                }
            }

            // ReSharper disable SwitchStatementMissingSomeCases
            switch (Type)
            {
            case ClientMessageOpcode.Login:
                Message = new LoginMessage();
                break;

            case ClientMessageOpcode.Move:
                Message = new MoveMessage();
                break;

            case ClientMessageOpcode.CallServerMethod:
                Message = new CallServerMethodMessage();
                break;

            case ClientMessageOpcode.Ping:
                Message = new PingMessage();
                break;

            default:
                throw new Exception($"Unable to handle packet type {Type}, because it's a Server -> Client packet!");
            }
            // ReSharper restore SwitchStatementMissingSomeCases

            using (var reader = new ProtocolBufferReader(readBr, ProtocolBufferFlags.DontFragment))
            {
                reader.ReadProtocolFlags();

                // Subtype and Message.Read()
                reader.ReadDebugByte(41);

                if ((Message.SubtypeFlags & ClientMessageSubtypeFlag.HasSubtype) == ClientMessageSubtypeFlag.HasSubtype)
                {
                    Message.RawSubtype = reader.ReadByte();
                    if (Message.RawSubtype < Message.MinSubtype || Message.RawSubtype > Message.MaxSubtype)
                    {
                        throw new Exception("Invalid Subtype found!");
                    }
                }

                Message.Read(reader);

                reader.ReadDebugByte(42);

                reader.ReadXORCheck((int)br.BaseStream.Position - xorCheckPosition);
            }

            if (buffer != null) // If we requested a buffer for decompressing, free it
            {
                BufferManager.FreeBuffer(buffer);
            }
        }
Ejemplo n.º 18
0
        private void InputMatr(BufferData buff)
        {
            if (buff is Matrix <double> )
            {
                Matrix <double> t = (Matrix <double>)buff;
                foreach (DataGridViewRow row in GvMatr.Rows)
                {
                    foreach (DataGridViewCell c in row.Cells)
                    {
                        if (t.Value[c.ColumnIndex, c.RowIndex] < Double.Parse(minv.Text) || t.Value[c.ColumnIndex, c.RowIndex] > Double.Parse(maxv.Text))
                        {
                            MessageBox.Show("Невідповідність данних: " + t.Value[c.ColumnIndex, c.RowIndex]);
                            return;
                        }
                    }
                }
            }
            if (buff is Matrix <int> )
            {
                Matrix <int> t = (Matrix <int>)buff;
                foreach (DataGridViewRow row in GvMatr.Rows)
                {
                    foreach (DataGridViewCell c in row.Cells)
                    {
                        if (t.Value[c.ColumnIndex, c.RowIndex] < Int32.Parse(minv.Text) || t.Value[c.ColumnIndex, c.RowIndex] > Int32.Parse(maxv.Text))
                        {
                            MessageBox.Show("Невідповідність данних: " + t.Value[c.ColumnIndex, c.RowIndex]);
                            return;
                        }
                    }
                }
            }
            if (buff is Matrix <long> )
            {
                Matrix <long> t = (Matrix <long>)buff;
                foreach (DataGridViewRow row in GvMatr.Rows)
                {
                    foreach (DataGridViewCell c in row.Cells)
                    {
                        if (t.Value[c.ColumnIndex, c.RowIndex] < Double.Parse(minv.Text) || t.Value[c.ColumnIndex, c.RowIndex] > Int32.Parse(maxv.Text))
                        {
                            MessageBox.Show("Невідповідність данних: " + t.Value[c.ColumnIndex, c.RowIndex]);
                            return;
                        }
                    }
                }
            }



            if (buff is Matrix <double> )
            {
                Matrix <double> t = (Matrix <double>)buff;
                trackBar1.Value = t.Value.GetLength(0) - 1;
                EventArgs e = new EventArgs();
                trackBar1_Scroll(this, e);
                trackBar2.Value = t.Value.GetLength(1) - 1;
                trackBar2_Scroll(this, e);
                foreach (DataGridViewRow row in GvMatr.Rows)
                {
                    foreach (DataGridViewCell c in row.Cells)
                    {
                        c.Value = t.Value[c.ColumnIndex, c.RowIndex];
                    }
                }
            }
            if (buff is Matrix <int> )
            {
                Matrix <int> t = (Matrix <int>)buff;
                trackBar1.Value = t.Value.GetLength(0) - 1;
                EventArgs e = new EventArgs();
                trackBar1_Scroll(this, e);
                trackBar2.Value = t.Value.GetLength(1) - 1;
                trackBar2_Scroll(this, e);
                foreach (DataGridViewRow row in GvMatr.Rows)
                {
                    foreach (DataGridViewCell c in row.Cells)
                    {
                        c.Value = t.Value[c.RowIndex, c.ColumnIndex];
                    }
                }
            }
            if (buff is Matrix <long> )
            {
                Matrix <long> t = (Matrix <long>)buff;
                trackBar1.Value = t.Value.GetLength(0) - 1;
                EventArgs e = new EventArgs();
                trackBar1_Scroll(this, e);
                trackBar2.Value = t.Value.GetLength(1) - 1;
                trackBar2_Scroll(this, e);
                foreach (DataGridViewRow row in GvMatr.Rows)
                {
                    foreach (DataGridViewCell c in row.Cells)
                    {
                        c.Value = t.Value[c.RowIndex, c.ColumnIndex];
                    }
                }
            }
        }
Ejemplo n.º 19
0
 /// <summary>
 /// 將Json資料寫入字典裡
 /// </summary>
 static void LoadJsonDataToDic()
 {
     //文字字典
     String_AttributeDic = new Dictionary <string, String_AttributeData>();
     String_AttributeData.SetData(String_AttributeDic);
     //Sprite字典
     SpriteDic = new Dictionary <string, SpriteData>();
     SpriteData.SetData(SpriteDic);
     //被動施法
     PSpellDic = new Dictionary <int, PassiveSpellData>();
     PassiveSpellData.SetData(PSpellDic);
     //主動施法
     ASpellDic = new Dictionary <int, ActivitySpellData>();
     ActivitySpellData.SetData(ASpellDic);
     DamageDic = new Dictionary <int, DamageData>();
     DamageData.SetData(DamageDic);
     CureDic = new Dictionary <int, CureData>();
     CureData.SetData(CureDic);
     BufferDic = new Dictionary <int, BufferData>();
     BufferData.SetData(BufferDic);
     //天賦字典
     TalentDic = new Dictionary <int, TalentData>();
     TalentData.SetData(TalentDic);
     //武器
     WeaponDic = new Dictionary <int, WeaponData>();
     WeaponData.SetData(WeaponDic);
     //防具
     ArmorDic = new Dictionary <int, ArmorData>();
     ArmorData.SetData(ArmorDic);
     //裝備
     ProtectorDic = new Dictionary <int, ProtectorData>();
     ProtectorData.SetData(ProtectorDic);
     //裝備
     DropDic = new Dictionary <int, DropData>();
     DropData.SetData(DropDic);
     //冒險
     AdventureDic = new Dictionary <int, AdventureData>();
     AdventureData.SetData(AdventureDic);
     //出怪事件
     MonsterEventDic = new Dictionary <int, MonsterEventData>();
     MonsterEventData.SetData(MonsterEventDic);
     //調查事件
     InvestigateEventDic = new Dictionary <int, List <InvestigateEventData> >();
     InvestigateEventData.SetData(InvestigateEventDic);
     //意外事件
     AccidentEventDic = new Dictionary <int, List <AccidentEventData> >();
     AccidentEventData.SetData(AccidentEventDic);
     //結果事件
     EventResultDic = new Dictionary <int, EventResultData>();
     EventResultData.SetData(EventResultDic);
     //紮營事件
     CampDic = new Dictionary <int, List <CampEventData> >();
     CampEventData.SetData(CampDic);
     //怪物
     MonsterGroupDic = new Dictionary <int, List <MonsterData> >();
     MonsterDic      = new Dictionary <int, MonsterData>();
     MonsterData.SetData(MonsterGroupDic, MonsterDic);
     //腳色字典
     RoleDic = new Dictionary <int, RoleData>();
     RoleData.SetData(RoleDic);
     //主屬性字典
     MainAttributeDic = new Dictionary <MainAttribute, MainAttributeData>();
     MainAttributeData.SetData(MainAttributeDic);
     //等級字典
     LevelDic = new Dictionary <int, LevelData>();
     LevelData.SetData(LevelDic);
 }
Ejemplo n.º 20
0
        /// <summary>
        /// 获得剩余次数
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        private static int GetLeftCountByType(GameClient client, int type, int copyId)
        {
            int leftnum = 0;

            switch ((CandoType)type)
            {
            case CandoType.DailyTask:
            {
                DailyTaskData dailyTaskData = Global.FindDailyTaskDataByTaskClass(client, 8);
                if (null == dailyTaskData)
                {
                    return(Global.MaxDailyTaskNumForMU);
                }
                int maxnum = Global.GetMaxDailyTaskNum(client, 8, dailyTaskData);


                //获取最大日常任务次数

                leftnum = maxnum - dailyTaskData.RecNum;
            }
            break;

            case CandoType.StoryCopy:
            case CandoType.GoldCopy:
            case CandoType.GroupCopy:
            case CandoType.EXPCopy:
            {
                SystemXmlItem systemFuBenItem = null;
                if (!GameManager.systemFuBenMgr.SystemXmlItemDict.TryGetValue(copyId, out systemFuBenItem))
                {
                    return(-1);
                }
                int total = systemFuBenItem.GetIntValue("EnterNumber");
                if (type == (int)CandoType.StoryCopy || type == (int)CandoType.GroupCopy)
                {
                    total = systemFuBenItem.GetIntValue("FinishNumber");
                }


                if (type == (int)CandoType.GoldCopy || type == (int)CandoType.EXPCopy)
                {
                    int[] nAddNum = GameManager.systemParamsList.GetParamValueIntArrayByName("VIPJinBiFuBenNum");
                    if (type == (int)CandoType.EXPCopy)
                    {
                        nAddNum = GameManager.systemParamsList.GetParamValueIntArrayByName("VIPJinYanFuBenNum");
                    }
                    if (client.ClientData.VipLevel > 0 && client.ClientData.VipLevel <= (int)VIPEumValue.VIPENUMVALUE_MAXLEVEL && nAddNum != null && nAddNum.Length > 0 && nAddNum.Length <= 13)
                    {
                        total = total + nAddNum[client.ClientData.VipLevel];
                    }
                }

                FuBenData tmpfubdata = Global.GetFuBenData(client, copyId);
                if (null != tmpfubdata)
                {
                    leftnum = total - tmpfubdata.EnterNum;
                }
                else
                {
                    return(total);
                }
            }
            break;

            case CandoType.DemonSquare:
            {
                int nMapID = Global.GetDaimonSquareCopySceneIDForRole(client);
                DaimonSquareDataInfo bcDataTmp = null;

                Data.DaimonSquareDataInfoList.TryGetValue(nMapID, out bcDataTmp);

                int nDate  = DateTime.Now.DayOfYear;                       // 当前时间
                int nCount = Global.QueryDayActivityEnterCountToDB(client, client.ClientData.RoleID, nDate, (int)SpecialActivityTypes.DemoSque);
                if (nCount < 0)
                {
                    nCount = 0;
                }
                int nVipLev = client.ClientData.VipLevel;

                int   nNum  = 0;
                int[] nArry = null;
                nArry = GameManager.systemParamsList.GetParamValueIntArrayByName("VIPEnterDaimonSquareCountAddValue");

                if (nVipLev > 0 && nArry != null && nArry[nVipLev] > 0)
                {
                    nNum = nArry[nVipLev];
                }
                leftnum = bcDataTmp.MaxEnterNum + nNum - nCount;
            }
            break;

            case CandoType.AngelTemple:
            {
                DateTime now = DateTime.Now;

                string        nowTime        = DateTime.Now.ToString("HH:mm");
                List <string> timePointsList = GameManager.AngelTempleMgr.m_AngelTempleData.BeginTime;

                leftnum = 0;
                for (int i = 0; i < timePointsList.Count; i++)
                {
                    DateTime staticTime  = DateTime.Parse(timePointsList[i]);
                    DateTime perpareTime = staticTime.AddMinutes((double)(GameManager.AngelTempleMgr.m_AngelTempleData.PrepareTime / 60));

                    if (now <= perpareTime)
                    {
                        leftnum += 1;
                    }
                }
            }
            break;

            case CandoType.BloodCity:
            {
                int nMapID = Global.GetBloodCastleCopySceneIDForRole(client);
                BloodCastleDataInfo bcDataTmp = null;

                if (!Data.BloodCastleDataInfoList.TryGetValue(nMapID, out bcDataTmp))
                {
                    break;
                }

                int nDate = DateTime.Now.DayOfYear;                              // 当前时间
                int nType = (int)SpecialActivityTypes.BloodCastle;               // 血色堡垒

                int nCount = Global.QueryDayActivityEnterCountToDB(client, client.ClientData.RoleID, nDate, nType);
                if (nCount < 0)
                {
                    nCount = 0;
                }
                // VIP检测

                int nVipLev = client.ClientData.VipLevel;

                int   nNum  = 0;
                int[] nArry = null;
                nArry = GameManager.systemParamsList.GetParamValueIntArrayByName("VIPEnterBloodCastleCountAddValue");

                if (nVipLev > 0 && nArry != null && nArry[nVipLev] > 0)
                {
                    nNum = nArry[nVipLev];
                }
                leftnum = bcDataTmp.MaxEnterNum + nNum - nCount;
            }
            break;

            case CandoType.Arena:
            {
                leftnum = JingJiChangManager.getInstance().GetLeftEnterCount(client);
            }
            break;

            case CandoType.OldBattlefield:
            {
                //古墓 古战场  剩余时间
                BufferData bufferData = Global.GetBufferDataByID(client, (int)BufferItemTypes.GuMuTimeLimit);
                leftnum = (int)(bufferData.BufferVal - bufferData.BufferSecs);
            }
            break;

            case CandoType.PartWar:
            {
                leftnum = GameManager.BattleMgr.LeftEnterCount();
            }
            break;

            case CandoType.PKKing:
            {
                leftnum = GameManager.ArenaBattleMgr.LeftEnterCount();
            }
            break;

            case CandoType.WanmoTower:
            {
                leftnum = 1;
                if (SweepWanMotaManager.GetSweepCount(client) >= SweepWanMotaManager.nWanMoTaMaxSweepNum)
                {
                    leftnum = 0;
                }
            }
            break;

            case CandoType.TaofaTaskCanDo:
            {
                DailyTaskData dailyTaskData = Global.FindDailyTaskDataByTaskClass(client, (int)TaskClasses.TaofaTask);
                if (null == dailyTaskData)
                {
                    return(Global.MaxTaofaTaskNumForMU);
                }
                int maxnum = Global.GetMaxDailyTaskNum(client, (int)TaskClasses.TaofaTask, dailyTaskData);

                //获取最大讨伐任务次数
                leftnum = maxnum - dailyTaskData.RecNum;
            }
            break;

            case CandoType.CrystalCollectCanDo:
            {
                //获取剩余水晶采集次数
                int temp = 0;
                CaiJiLogic.ReqCaiJiLastNum(client, 0, out temp);
                leftnum = temp;
            }
            break;
            }
            return(leftnum);
        }
Ejemplo n.º 21
0
        private object ExportModel(ICommandContext commandContext, ContentManager contentManager)
        {
            // Read from model file
            var modelSkeleton = LoadSkeleton(commandContext, contentManager); // we get model skeleton to compare it to real skeleton we need to map to

            AdjustSkeleton(modelSkeleton);
            var model = LoadModel(commandContext, contentManager);

            // Apply materials
            foreach (var modelMaterial in Materials)
            {
                if (modelMaterial.MaterialInstance?.Material == null)
                {
                    commandContext.Logger.Warning($"The material [{modelMaterial.Name}] is null in the list of materials.");
                    continue;
                }
                model.Materials.Add(modelMaterial.MaterialInstance);
            }

            model.BoundingBox = BoundingBox.Empty;

            foreach (var mesh in model.Meshes)
            {
                if (TessellationAEN)
                {
                    // TODO: Generate AEN model view
                    commandContext.Logger.Error("TessellationAEN is not supported in {0}", ContextAsString);
                }
            }

            SkeletonMapping skeletonMapping;

            Skeleton skeleton;

            if (SkeletonUrl != null)
            {
                // Load skeleton and process it
                skeleton = contentManager.Load <Skeleton>(SkeletonUrl);

                // Assign skeleton to model
                model.Skeleton = AttachedReferenceManager.CreateProxyObject <Skeleton>(Guid.Empty, SkeletonUrl);
            }
            else
            {
                skeleton = null;
            }

            skeletonMapping = new SkeletonMapping(skeleton, modelSkeleton);

            // Refresh skeleton updater with model skeleton
            var hierarchyUpdater = new SkeletonUpdater(modelSkeleton);

            hierarchyUpdater.UpdateMatrices();

            // Move meshes in the new nodes
            foreach (var mesh in model.Meshes)
            {
                // Check if there was a remap using model skeleton
                if (skeletonMapping.SourceToSource[mesh.NodeIndex] != mesh.NodeIndex)
                {
                    // Transform vertices
                    var transformationMatrix = CombineMatricesFromNodeIndices(hierarchyUpdater.NodeTransformations, skeletonMapping.SourceToSource[mesh.NodeIndex], mesh.NodeIndex);
                    mesh.Draw.VertexBuffers[0].TransformBuffer(ref transformationMatrix);

                    // Check if geometry is inverted, to know if we need to reverse winding order
                    // TODO: What to do if there is no index buffer? We should create one... (not happening yet)
                    if (mesh.Draw.IndexBuffer == null)
                    {
                        throw new InvalidOperationException();
                    }

                    Matrix  rotation;
                    Vector3 scale, translation;
                    if (transformationMatrix.Decompose(out scale, out rotation, out translation) &&
                        scale.X * scale.Y * scale.Z < 0)
                    {
                        mesh.Draw.ReverseWindingOrder();
                    }
                }

                // Update new node index using real asset skeleton
                mesh.NodeIndex = skeletonMapping.SourceToTarget[mesh.NodeIndex];
            }

            // Merge meshes with same parent nodes, material and skinning
            var meshesByNodes = model.Meshes.GroupBy(x => x.NodeIndex).ToList();

            foreach (var meshesByNode in meshesByNodes)
            {
                // This logic to detect similar material is kept from old code; this should be reviewed/improved at some point
                foreach (var meshesPerDrawCall in meshesByNode.GroupBy(x => x,
                                                                       new AnonymousEqualityComparer <Mesh>((x, y) =>
                                                                                                            x.MaterialIndex == y.MaterialIndex && // Same material
                                                                                                            ArrayExtensions.ArraysEqual(x.Skinning?.Bones, y.Skinning?.Bones) && // Same bones
                                                                                                            CompareParameters(model, x, y) && // Same parameters
                                                                                                            CompareShadowOptions(model, x, y), // Same shadow parameters
                                                                                                            x => 0)).ToList())
                {
                    if (meshesPerDrawCall.Count() == 1)
                    {
                        // Nothing to group, skip to next entry
                        continue;
                    }

                    // Remove old meshes
                    foreach (var mesh in meshesPerDrawCall)
                    {
                        model.Meshes.Remove(mesh);
                    }

                    // Add new combined mesh(es)
                    var baseMesh    = meshesPerDrawCall.First();
                    var newMeshList = meshesPerDrawCall.Select(x => x.Draw).ToList().GroupDrawData(Allow32BitIndex);

                    foreach (var generatedMesh in newMeshList)
                    {
                        model.Meshes.Add(new Mesh(generatedMesh, baseMesh.Parameters)
                        {
                            MaterialIndex = baseMesh.MaterialIndex,
                            Name          = baseMesh.Name,
                            Draw          = generatedMesh,
                            NodeIndex     = baseMesh.NodeIndex,
                            Skinning      = baseMesh.Skinning,
                        });
                    }
                }
            }

            // Remap skinning
            foreach (var skinning in model.Meshes.Select(x => x.Skinning).Where(x => x != null).Distinct())
            {
                // Update node mapping
                // Note: we only remap skinning matrices, but we could directly remap skinning bones instead
                for (int i = 0; i < skinning.Bones.Length; ++i)
                {
                    var nodeIndex    = skinning.Bones[i].NodeIndex;
                    var newNodeIndex = skeletonMapping.SourceToSource[nodeIndex];

                    skinning.Bones[i].NodeIndex = skeletonMapping.SourceToTarget[nodeIndex];

                    // If it was remapped, we also need to update matrix
                    if (newNodeIndex != nodeIndex)
                    {
                        var transformationMatrix = CombineMatricesFromNodeIndices(hierarchyUpdater.NodeTransformations, newNodeIndex, nodeIndex);
                        skinning.Bones[i].LinkToMeshMatrix = Matrix.Multiply(skinning.Bones[i].LinkToMeshMatrix, transformationMatrix);
                    }

                    // Cancel pivot translation
                    // TODO: Review if that is the correct way to do that...
                    if (skeleton == null)
                    {
                        skinning.Bones[i].LinkToMeshMatrix = Matrix.Multiply(skinning.Bones[i].LinkToMeshMatrix, Matrix.Translation(PivotPosition * ScaleImport));
                    }
                }
            }

            // split the meshes if necessary
            model.Meshes = SplitExtensions.SplitMeshes(model.Meshes, Allow32BitIndex);

            // Refresh skeleton updater with asset skeleton
            hierarchyUpdater = new SkeletonUpdater(skeleton);
            hierarchyUpdater.UpdateMatrices();

            // bounding boxes
            var modelBoundingBox    = model.BoundingBox;
            var modelBoundingSphere = model.BoundingSphere;

            foreach (var mesh in model.Meshes)
            {
                var vertexBuffers = mesh.Draw.VertexBuffers;
                if (vertexBuffers.Length > 0)
                {
                    // Compute local mesh bounding box (no node transformation)
                    Matrix matrix = Matrix.Identity;
                    mesh.BoundingBox = vertexBuffers[0].ComputeBounds(ref matrix, out mesh.BoundingSphere);

                    // Compute model bounding box (includes node transformation)
                    hierarchyUpdater.GetWorldMatrix(mesh.NodeIndex, out matrix);
                    BoundingSphere meshBoundingSphere;
                    var            meshBoundingBox = vertexBuffers[0].ComputeBounds(ref matrix, out meshBoundingSphere);
                    BoundingBox.Merge(ref modelBoundingBox, ref meshBoundingBox, out modelBoundingBox);
                    BoundingSphere.Merge(ref modelBoundingSphere, ref meshBoundingSphere, out modelBoundingSphere);
                }

                // TODO: temporary Always try to compact
                mesh.Draw.CompactIndexBuffer();
            }
            model.BoundingBox    = modelBoundingBox;
            model.BoundingSphere = modelBoundingSphere;

            // merges all the Draw VB and IB together to produce one final VB and IB by entity.
            var sizeVertexBuffer = model.Meshes.SelectMany(x => x.Draw.VertexBuffers).Select(x => x.Buffer.GetSerializationData().Content.Length).Sum();
            var sizeIndexBuffer  = 0;

            foreach (var x in model.Meshes)
            {
                // Let's be aligned (if there was 16bit indices before, we might be off)
                if (x.Draw.IndexBuffer.Is32Bit && sizeIndexBuffer % 4 != 0)
                {
                    sizeIndexBuffer += 2;
                }

                sizeIndexBuffer += x.Draw.IndexBuffer.Buffer.GetSerializationData().Content.Length;
            }
            var vertexBuffer = new BufferData(BufferFlags.VertexBuffer, new byte[sizeVertexBuffer]);
            var indexBuffer  = new BufferData(BufferFlags.IndexBuffer, new byte[sizeIndexBuffer]);

            // Note: reusing same instance, to avoid having many VB with same hash but different URL
            var vertexBufferSerializable = vertexBuffer.ToSerializableVersion();
            var indexBufferSerializable  = indexBuffer.ToSerializableVersion();

            var vertexBufferNextIndex = 0;
            var indexBufferNextIndex  = 0;

            foreach (var drawMesh in model.Meshes.Select(x => x.Draw))
            {
                // the index buffer
                var oldIndexBuffer = drawMesh.IndexBuffer.Buffer.GetSerializationData().Content;

                // Let's be aligned (if there was 16bit indices before, we might be off)
                if (drawMesh.IndexBuffer.Is32Bit && indexBufferNextIndex % 4 != 0)
                {
                    indexBufferNextIndex += 2;
                }

                Array.Copy(oldIndexBuffer, 0, indexBuffer.Content, indexBufferNextIndex, oldIndexBuffer.Length);

                drawMesh.IndexBuffer = new IndexBufferBinding(indexBufferSerializable, drawMesh.IndexBuffer.Is32Bit, drawMesh.IndexBuffer.Count, indexBufferNextIndex);

                indexBufferNextIndex += oldIndexBuffer.Length;

                // the vertex buffers
                for (int index = 0; index < drawMesh.VertexBuffers.Length; index++)
                {
                    var vertexBufferBinding = drawMesh.VertexBuffers[index];
                    var oldVertexBuffer     = vertexBufferBinding.Buffer.GetSerializationData().Content;

                    Array.Copy(oldVertexBuffer, 0, vertexBuffer.Content, vertexBufferNextIndex, oldVertexBuffer.Length);

                    drawMesh.VertexBuffers[index] = new VertexBufferBinding(vertexBufferSerializable, vertexBufferBinding.Declaration, vertexBufferBinding.Count, vertexBufferBinding.Stride,
                                                                            vertexBufferNextIndex);

                    vertexBufferNextIndex += oldVertexBuffer.Length;
                }
            }

            // Convert to Entity
            return(model);
        }
Ejemplo n.º 22
0
            private static unsafe void ProcessMaterial(ContentManager manager, ICollection <EntityChunk> chunks, MaterialInstance material, Model prefabModel)
            {
                //we need to futher group by VertexDeclaration
                var meshes = new Dictionary <VertexDeclaration, MeshData>();

                //actually create the mesh
                foreach (var chunk in chunks)
                {
                    foreach (var modelMesh in chunk.Model.Meshes)
                    {
                        //process only right material
                        if (modelMesh.MaterialIndex == chunk.MaterialIndex)
                        {
                            MeshData mesh;
                            if (!meshes.TryGetValue(modelMesh.Draw.VertexBuffers[0].Declaration, out mesh))
                            {
                                mesh = new MeshData {
                                    VertexStride = modelMesh.Draw.VertexBuffers[0].Stride
                                };
                                meshes.Add(modelMesh.Draw.VertexBuffers[0].Declaration, mesh);
                            }

                            //vertexes
                            var    vertexBufferRef = AttachedReferenceManager.GetAttachedReference(modelMesh.Draw.VertexBuffers[0].Buffer);
                            byte[] vertexData;
                            if (vertexBufferRef.Data != null)
                            {
                                vertexData = ((BufferData)vertexBufferRef.Data).Content;
                            }
                            else if (!string.IsNullOrEmpty(vertexBufferRef.Url))
                            {
                                var dataAsset = manager.Load <Buffer>(vertexBufferRef.Url);
                                vertexData = dataAsset.GetSerializationData().Content;
                            }
                            else
                            {
                                throw new Exception($"Failed to get Vertex BufferData for entity {chunk.Entity.Name}'s model.");
                            }

                            //transform the vertexes according to the entity
                            var vertexDataCopy = vertexData.ToArray();
                            chunk.Entity.Transform.UpdateWorldMatrix(); //make sure matrix is computed
                            var  worldMatrix       = chunk.Entity.Transform.WorldMatrix;
                            var  up                = Vector3.Cross(worldMatrix.Right, worldMatrix.Forward);
                            bool isScalingNegative = Vector3.Dot(worldMatrix.Up, up) < 0.0f;

                            modelMesh.Draw.VertexBuffers[0].TransformBuffer(vertexDataCopy, ref worldMatrix);

                            //add to the big single array
                            var vertexes = vertexDataCopy
                                           .Skip(modelMesh.Draw.VertexBuffers[0].Offset)
                                           .Take(modelMesh.Draw.VertexBuffers[0].Count * modelMesh.Draw.VertexBuffers[0].Stride)
                                           .ToArray();

                            mesh.VertexData.AddRange(vertexes);

                            //indices
                            var    indexBufferRef = AttachedReferenceManager.GetAttachedReference(modelMesh.Draw.IndexBuffer.Buffer);
                            byte[] indexData;
                            if (indexBufferRef.Data != null)
                            {
                                indexData = ((BufferData)indexBufferRef.Data).Content;
                            }
                            else if (!string.IsNullOrEmpty(indexBufferRef.Url))
                            {
                                var dataAsset = manager.Load <Buffer>(indexBufferRef.Url);
                                indexData = dataAsset.GetSerializationData().Content;
                            }
                            else
                            {
                                throw new Exception("Failed to get Indices BufferData for entity {chunk.Entity.Name}'s model.");
                            }

                            var indexSize = modelMesh.Draw.IndexBuffer.Is32Bit ? sizeof(uint) : sizeof(ushort);

                            byte[] indices;
                            if (isScalingNegative)
                            {
                                // Get reversed winding order
                                modelMesh.Draw.GetReversedWindingOrder(out indices);
                                indices = indices.Skip(modelMesh.Draw.IndexBuffer.Offset)
                                          .Take(modelMesh.Draw.IndexBuffer.Count * indexSize)
                                          .ToArray();
                            }
                            else
                            {
                                // Get indices normally
                                indices = indexData
                                          .Skip(modelMesh.Draw.IndexBuffer.Offset)
                                          .Take(modelMesh.Draw.IndexBuffer.Count * indexSize)
                                          .ToArray();
                            }

                            // Convert indices to 32 bits
                            if (indexSize == sizeof(ushort))
                            {
                                var uintIndices = new byte[indices.Length * 2];
                                fixed(byte *psrc = indices)
                                fixed(byte *pdst = uintIndices)
                                {
                                    var src = (ushort *)psrc;
                                    var dst = (uint *)pdst;

                                    int numIndices = indices.Length / sizeof(ushort);

                                    for (var i = 0; i < numIndices; i++)
                                    {
                                        dst[i] = src[i];
                                    }
                                }
                                indices = uintIndices;
                            }

                            // Offset indices by mesh.IndexOffset
                            fixed(byte *pdst = indices)
                            {
                                var dst = (uint *)pdst;

                                int numIndices = indices.Length / sizeof(uint);

                                for (var i = 0; i < numIndices; i++)
                                {
                                    // Offset indices
                                    dst[i] += (uint)mesh.IndexOffset;
                                }
                            }

                            mesh.IndexOffset += modelMesh.Draw.VertexBuffers[0].Count;

                            mesh.IndexData.AddRange(indices);
                        }
                    }
                }

                //Sort out material
                var matIndex = prefabModel.Materials.Count;

                prefabModel.Materials.Add(material);

                foreach (var meshData in meshes)
                {
                    //todo need to take care of short index
                    var vertexArray = meshData.Value.VertexData.ToArray();
                    var indexArray  = meshData.Value.IndexData.ToArray();

                    var vertexCount = vertexArray.Length / meshData.Value.VertexStride;
                    var indexCount  = indexArray.Length / 4;

                    var gpuMesh = new Mesh
                    {
                        Draw = new MeshDraw {
                            PrimitiveType = PrimitiveType.TriangleList, DrawCount = indexCount, StartLocation = 0
                        },
                        MaterialIndex = matIndex
                    };

                    var vertexBuffer = new BufferData(BufferFlags.VertexBuffer, new byte[vertexArray.Length]);
                    var indexBuffer  = new BufferData(BufferFlags.IndexBuffer, new byte[indexArray.Length]);

                    var vertexBufferSerializable = vertexBuffer.ToSerializableVersion();
                    var indexBufferSerializable  = indexBuffer.ToSerializableVersion();

                    Array.Copy(vertexArray, vertexBuffer.Content, vertexArray.Length);
                    Array.Copy(indexArray, indexBuffer.Content, indexArray.Length);

                    gpuMesh.Draw.VertexBuffers    = new VertexBufferBinding[1];
                    gpuMesh.Draw.VertexBuffers[0] = new VertexBufferBinding(vertexBufferSerializable, meshData.Key, vertexCount);
                    gpuMesh.Draw.IndexBuffer      = new IndexBufferBinding(indexBufferSerializable, true, indexCount);

                    prefabModel.Meshes.Add(gpuMesh);
                }
            }
Ejemplo n.º 23
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="buffer">Buffer</param>
 /// <param name="span">Span</param>
 /// <param name="lengthSpan">Span of length</param>
 /// <param name="data">Data</param>
 /// <param name="tokens">Tokens referencing this blob or an empty collection</param>
 /// <param name="heap">Owner heap</param>
 public BlobHeapRecordData(HexBuffer buffer, HexSpan span, HexSpan lengthSpan, BufferData data, ReadOnlyCollection <uint> tokens, BlobHeap heap)
     : base(NAME, new HexBufferSpan(buffer, span))
 {
     if (lengthSpan.Start != span.Start)
     {
         throw new ArgumentOutOfRangeException(nameof(lengthSpan));
     }
     if (data == null)
     {
         throw new ArgumentNullException(nameof(data));
     }
     Heap   = heap ?? throw new ArgumentNullException(nameof(heap));
     Tokens = tokens ?? throw new ArgumentNullException(nameof(tokens));
     Length = new StructField <BlobEncodedUInt32Data>("Length", new BlobEncodedUInt32Data(new HexBufferSpan(buffer, lengthSpan)));
     Data   = new StructField <BufferData>("Data", data);
     Fields = new BufferField[] {
         Length,
         Data,
     };
 }
Ejemplo n.º 24
0
        private object ExportModel(ICommandContext commandContext, ContentManager contentManager)
        {
            // Read from model file
            var modelSkeleton = LoadSkeleton(commandContext, contentManager); // we get model skeleton to compare it to real skeleton we need to map to

            AdjustSkeleton(modelSkeleton);
            var model = LoadModel(commandContext, contentManager);

            if (!CheckInputSlots(commandContext, model))
            {
                return(null);
            }

            // Apply materials
            foreach (var modelMaterial in Materials)
            {
                if (modelMaterial.MaterialInstance?.Material == null)
                {
                    commandContext.Logger.Verbose($"The material [{modelMaterial.Name}] is null in the list of materials.");
                }
                model.Materials.Add(modelMaterial.MaterialInstance);
            }

            model.BoundingBox = BoundingBox.Empty;

            Skeleton skeleton;

            if (SkeletonUrl != null || !MergeMeshes)
            {
                if (SkeletonUrl != null)
                {
                    // Load the skeleton
                    skeleton = contentManager.Load <Skeleton>(SkeletonUrl);
                }
                else
                {
                    skeleton    = modelSkeleton;
                    SkeletonUrl = Location + "_Skeleton_" + Guid.NewGuid();
                    contentManager.Save(SkeletonUrl, skeleton);
                }

                // Assign skeleton to model
                model.Skeleton = AttachedReferenceManager.CreateProxyObject <Skeleton>(AssetId.Empty, SkeletonUrl);
            }
            else
            {
                skeleton = null;
            }

            var skeletonMapping = new SkeletonMapping(skeleton, modelSkeleton);

            // Refresh skeleton updater with model skeleton
            var hierarchyUpdater = new SkeletonUpdater(modelSkeleton);

            hierarchyUpdater.UpdateMatrices();

            // Move meshes in the new nodes
            foreach (var mesh in model.Meshes)
            {
                // Apply scale import on meshes
                if (!MathUtil.NearEqual(ScaleImport, 1.0f))
                {
                    var transformationMatrix = Matrix.Scaling(ScaleImport);
                    for (int vbIdx = 0; vbIdx < mesh.Draw.VertexBuffers.Length; vbIdx++)
                    {
                        mesh.Draw.VertexBuffers[vbIdx].TransformBuffer(ref transformationMatrix);
                    }
                }

                var skinning = mesh.Skinning;
                if (skinning != null)
                {
                    // Update node mapping
                    // Note: we only remap skinning matrices, but we could directly remap skinning bones instead
                    for (int i = 0; i < skinning.Bones.Length; ++i)
                    {
                        var linkNodeIndex    = skinning.Bones[i].NodeIndex;
                        var newLinkNodeIndex = skeletonMapping.SourceToSource[linkNodeIndex];

                        var nodeIndex    = mesh.NodeIndex;
                        var newNodeIndex = skeletonMapping.SourceToSource[mesh.NodeIndex];

                        skinning.Bones[i].NodeIndex = skeletonMapping.SourceToTarget[linkNodeIndex];

                        // Adjust scale import
                        if (!MathUtil.NearEqual(ScaleImport, 1.0f))
                        {
                            skinning.Bones[i].LinkToMeshMatrix.TranslationVector = skinning.Bones[i].LinkToMeshMatrix.TranslationVector * ScaleImport;
                        }

                        // If it was remapped, we also need to update matrix
                        if (nodeIndex != newNodeIndex)
                        {
                            // Update mesh part
                            var transformMatrix = CombineMatricesFromNodeIndices(hierarchyUpdater.NodeTransformations, newNodeIndex, nodeIndex);
                            transformMatrix.Invert();
                            skinning.Bones[i].LinkToMeshMatrix = Matrix.Multiply(transformMatrix, skinning.Bones[i].LinkToMeshMatrix);
                        }

                        if (newLinkNodeIndex != linkNodeIndex)
                        {
                            // Update link part
                            var transformLinkMatrix = CombineMatricesFromNodeIndices(hierarchyUpdater.NodeTransformations, newLinkNodeIndex, linkNodeIndex);
                            skinning.Bones[i].LinkToMeshMatrix = Matrix.Multiply(skinning.Bones[i].LinkToMeshMatrix, transformLinkMatrix);
                        }
                    }
                }

                // Check if there was a remap using model skeleton
                if (skeletonMapping.SourceToSource[mesh.NodeIndex] != mesh.NodeIndex)
                {
                    // Transform vertices
                    var transformationMatrix = CombineMatricesFromNodeIndices(hierarchyUpdater.NodeTransformations, skeletonMapping.SourceToSource[mesh.NodeIndex], mesh.NodeIndex);
                    for (int vbIdx = 0; vbIdx < mesh.Draw.VertexBuffers.Length; vbIdx++)
                    {
                        mesh.Draw.VertexBuffers[vbIdx].TransformBuffer(ref transformationMatrix);
                    }

                    // Check if geometry is inverted, to know if we need to reverse winding order
                    // TODO: What to do if there is no index buffer? We should create one... (not happening yet)
                    if (mesh.Draw.IndexBuffer == null)
                    {
                        throw new InvalidOperationException();
                    }

                    Matrix  rotation;
                    Vector3 scale, translation;
                    if (transformationMatrix.Decompose(out scale, out rotation, out translation) &&
                        scale.X * scale.Y * scale.Z < 0)
                    {
                        mesh.Draw.ReverseWindingOrder();
                    }
                }

                // Update new node index using real asset skeleton
                mesh.NodeIndex = skeletonMapping.SourceToTarget[mesh.NodeIndex];
            }

            // Apply custom model modifiers
            if (ModelModifiers != null)
            {
                foreach (var modifier in ModelModifiers)
                {
                    modifier.Apply(commandContext, model);
                }
            }

            // Merge meshes with same parent nodes, material and skinning
            var meshesByNodes = model.Meshes.GroupBy(x => x.NodeIndex).ToList();

            foreach (var meshesByNode in meshesByNodes)
            {
                // This logic to detect similar material is kept from old code; this should be reviewed/improved at some point
                foreach (var meshesPerDrawCall in meshesByNode.GroupBy(x => x,
                                                                       new AnonymousEqualityComparer <Mesh>((x, y) =>
                                                                                                            x.MaterialIndex == y.MaterialIndex && // Same material
                                                                                                            ArrayExtensions.ArraysEqual(x.Skinning?.Bones, y.Skinning?.Bones) && // Same bones
                                                                                                            CompareParameters(model, x, y) && // Same parameters
                                                                                                            CompareShadowOptions(model, x, y), // Same shadow parameters
                                                                                                            x => 0)).ToList())
                {
                    if (meshesPerDrawCall.Count() == 1)
                    {
                        // Nothing to group, skip to next entry
                        continue;
                    }

                    // Remove old meshes
                    foreach (var mesh in meshesPerDrawCall)
                    {
                        model.Meshes.Remove(mesh);
                    }

                    // Add new combined mesh(es)
                    var baseMesh    = meshesPerDrawCall.First();
                    var newMeshList = meshesPerDrawCall.Select(x => x.Draw).ToList().GroupDrawData(Allow32BitIndex);

                    foreach (var generatedMesh in newMeshList)
                    {
                        model.Meshes.Add(new Mesh(generatedMesh, baseMesh.Parameters)
                        {
                            MaterialIndex = baseMesh.MaterialIndex,
                            Name          = baseMesh.Name,
                            Draw          = generatedMesh,
                            NodeIndex     = baseMesh.NodeIndex,
                            Skinning      = baseMesh.Skinning,
                        });
                    }
                }
            }

            // split the meshes if necessary
            model.Meshes = SplitExtensions.SplitMeshes(model.Meshes, Allow32BitIndex);

            // Refresh skeleton updater with asset skeleton
            hierarchyUpdater = new SkeletonUpdater(skeleton);
            hierarchyUpdater.UpdateMatrices();

            // bounding boxes
            var modelBoundingBox    = model.BoundingBox;
            var modelBoundingSphere = model.BoundingSphere;

            foreach (var mesh in model.Meshes)
            {
                var vertexBuffers = mesh.Draw.VertexBuffers;
                for (int vbIdx = 0; vbIdx < vertexBuffers.Length; vbIdx++)
                {
                    // Compute local mesh bounding box (no node transformation)
                    Matrix matrix = Matrix.Identity;
                    mesh.BoundingBox = vertexBuffers[vbIdx].ComputeBounds(ref matrix, out mesh.BoundingSphere);

                    // Compute model bounding box (includes node transformation)
                    hierarchyUpdater.GetWorldMatrix(mesh.NodeIndex, out matrix);
                    BoundingSphere meshBoundingSphere;
                    var            meshBoundingBox = vertexBuffers[vbIdx].ComputeBounds(ref matrix, out meshBoundingSphere);
                    BoundingBox.Merge(ref modelBoundingBox, ref meshBoundingBox, out modelBoundingBox);
                    BoundingSphere.Merge(ref modelBoundingSphere, ref meshBoundingSphere, out modelBoundingSphere);
                }

                // TODO: temporary Always try to compact
                mesh.Draw.CompactIndexBuffer();
            }
            model.BoundingBox    = modelBoundingBox;
            model.BoundingSphere = modelBoundingSphere;

            // Count unique meshes (they can be shared)
            var uniqueDrawMeshes = model.Meshes.Select(x => x.Draw).Distinct();

            // Count unique vertex buffers and squish them together in a single buffer
            var uniqueVB = uniqueDrawMeshes.SelectMany(x => x.VertexBuffers).Distinct().ToList();

            var vbMap                    = new Dictionary <VertexBufferBinding, VertexBufferBinding>();
            var sizeVertexBuffer         = uniqueVB.Select(x => x.Buffer.GetSerializationData().Content.Length).Sum();
            var vertexBuffer             = new BufferData(BufferFlags.VertexBuffer, new byte[sizeVertexBuffer]);
            var vertexBufferSerializable = vertexBuffer.ToSerializableVersion();

            var vertexBufferNextIndex = 0;

            foreach (var vbBinding in uniqueVB)
            {
                var oldVertexBuffer = vbBinding.Buffer.GetSerializationData().Content;
                Array.Copy(oldVertexBuffer, 0, vertexBuffer.Content, vertexBufferNextIndex, oldVertexBuffer.Length);

                vbMap.Add(vbBinding, new VertexBufferBinding(vertexBufferSerializable, vbBinding.Declaration, vbBinding.Count, vbBinding.Stride, vertexBufferNextIndex));

                vertexBufferNextIndex += oldVertexBuffer.Length;
            }

            // Count unique index buffers and squish them together in a single buffer
            var uniqueIB        = uniqueDrawMeshes.Select(x => x.IndexBuffer).NotNull().Distinct().ToList();
            var sizeIndexBuffer = 0;

            foreach (var ibBinding in uniqueIB)
            {
                // Make sure 32bit indices are properly aligned to 4 bytes in case the last alignment was 2 bytes
                if (ibBinding.Is32Bit && sizeIndexBuffer % 4 != 0)
                {
                    sizeIndexBuffer += 2;
                }

                sizeIndexBuffer += ibBinding.Buffer.GetSerializationData().Content.Length;
            }

            var ibMap = new Dictionary <IndexBufferBinding, IndexBufferBinding>();

            if (uniqueIB.Count > 0)
            {
                var indexBuffer             = new BufferData(BufferFlags.IndexBuffer, new byte[sizeIndexBuffer]);
                var indexBufferSerializable = indexBuffer.ToSerializableVersion();
                var indexBufferNextIndex    = 0;

                foreach (var ibBinding in uniqueIB)
                {
                    var oldIndexBuffer = ibBinding.Buffer.GetSerializationData().Content;

                    // Make sure 32bit indices are properly aligned to 4 bytes in case the last alignment was 2 bytes
                    if (ibBinding.Is32Bit && indexBufferNextIndex % 4 != 0)
                    {
                        indexBufferNextIndex += 2;
                    }

                    Array.Copy(oldIndexBuffer, 0, indexBuffer.Content, indexBufferNextIndex, oldIndexBuffer.Length);

                    ibMap.Add(ibBinding, new IndexBufferBinding(indexBufferSerializable, ibBinding.Is32Bit, ibBinding.Count, indexBufferNextIndex));

                    indexBufferNextIndex += oldIndexBuffer.Length;
                }
            }

            // Assign new vertex and index buffer bindings
            foreach (var drawMesh in uniqueDrawMeshes)
            {
                for (int i = 0; i < drawMesh.VertexBuffers.Length; i++)
                {
                    drawMesh.VertexBuffers[i] = vbMap[drawMesh.VertexBuffers[i]];
                }

                if (drawMesh.IndexBuffer != null)
                {
                    drawMesh.IndexBuffer = ibMap[drawMesh.IndexBuffer];
                }
            }

            vbMap.Clear();
            ibMap.Clear();

            // Convert to Entity
            return(model);
        }
Ejemplo n.º 25
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="data">Data type</param>
 /// <param name="index">Array index</param>
 public ArrayField(BufferData data, uint index)
     : base(data) => this.index = index;
Ejemplo n.º 26
0
            private static void ProcessMaterial(ContentManager manager, ICollection <EntityChunk> chunks, MaterialInstance material, Rendering.Model prefabModel)
            {
                //we need to futher group by VertexDeclaration
                var meshes = new Dictionary <VertexDeclaration, MeshData>();

                //actually create the mesh
                foreach (var chunk in chunks)
                {
                    foreach (var modelMesh in chunk.Model.Meshes)
                    {
                        //process only right material
                        if (modelMesh.MaterialIndex == chunk.MaterialIndex)
                        {
                            MeshData mesh;
                            if (!meshes.TryGetValue(modelMesh.Draw.VertexBuffers[0].Declaration, out mesh))
                            {
                                mesh = new MeshData {
                                    VertexStride = modelMesh.Draw.VertexBuffers[0].Stride
                                };
                                meshes.Add(modelMesh.Draw.VertexBuffers[0].Declaration, mesh);
                            }

                            //vertexes
                            var    vertexBufferRef = AttachedReferenceManager.GetAttachedReference(modelMesh.Draw.VertexBuffers[0].Buffer);
                            byte[] vertexData;
                            if (vertexBufferRef.Data != null)
                            {
                                vertexData = ((BufferData)vertexBufferRef.Data).Content;
                            }
                            else if (!vertexBufferRef.Url.IsNullOrEmpty())
                            {
                                var dataAsset = manager.Load <Graphics.Buffer>(vertexBufferRef.Url);
                                vertexData = dataAsset.GetSerializationData().Content;
                            }
                            else
                            {
                                throw new Exception($"Failed to get Vertex BufferData for entity {chunk.Entity.Name}'s model.");
                            }

                            //transform the vertexes according to the entity
                            var vertexDataCopy = vertexData.ToArray();
                            chunk.Entity.Transform.UpdateWorldMatrix(); //make sure matrix is computed
                            modelMesh.Draw.VertexBuffers[0].TransformBuffer(vertexDataCopy, ref chunk.Entity.Transform.WorldMatrix);

                            //add to the big single array
                            var vertexes = vertexDataCopy
                                           .Skip(modelMesh.Draw.VertexBuffers[0].Offset)
                                           .Take(modelMesh.Draw.VertexBuffers[0].Count * modelMesh.Draw.VertexBuffers[0].Stride)
                                           .ToArray();

                            mesh.VertexData.AddRange(vertexes);

                            //indices
                            var    indexBufferRef = AttachedReferenceManager.GetAttachedReference(modelMesh.Draw.IndexBuffer.Buffer);
                            byte[] indexData;
                            if (indexBufferRef.Data != null)
                            {
                                indexData = ((BufferData)indexBufferRef.Data).Content;
                            }
                            else if (!indexBufferRef.Url.IsNullOrEmpty())
                            {
                                var dataAsset = manager.Load <Graphics.Buffer>(indexBufferRef.Url);
                                indexData = dataAsset.GetSerializationData().Content;
                            }
                            else
                            {
                                throw new Exception("Failed to get Indices BufferData for entity {chunk.Entity.Name}'s model.");
                            }

                            var indexSize = modelMesh.Draw.IndexBuffer.Is32Bit ? sizeof(uint) : sizeof(ushort);

                            var indices = indexData
                                          .Skip(modelMesh.Draw.IndexBuffer.Offset)
                                          .Take(modelMesh.Draw.IndexBuffer.Count * indexSize)
                                          .ToArray();

                            //todo this code is not optimal, use unsafe

                            //must convert to 32bits
                            if (indexSize == sizeof(ushort))
                            {
                                var uintIndex = new List <byte>();
                                for (var i = 0; i < indices.Length; i += sizeof(ushort))
                                {
                                    var index = BitConverter.ToUInt16(indices, i);
                                    var bi    = BitConverter.GetBytes((uint)index);
                                    uintIndex.Add(bi[0]);
                                    uintIndex.Add(bi[1]);
                                    uintIndex.Add(bi[2]);
                                    uintIndex.Add(bi[3]);
                                }
                                indices = uintIndex.ToArray();
                            }

                            //need to offset the indices
                            for (var i = 0; i < indices.Length; i += sizeof(uint))
                            {
                                var index = BitConverter.ToUInt32(indices, i) + mesh.IndexOffset;
                                var bi    = BitConverter.GetBytes(index);
                                indices[i + 0] = bi[0];
                                indices[i + 1] = bi[1];
                                indices[i + 2] = bi[2];
                                indices[i + 3] = bi[3];
                            }

                            mesh.IndexOffset += modelMesh.Draw.VertexBuffers[0].Count;

                            mesh.IndexData.AddRange(indices);
                        }
                    }
                }

                //Sort out material
                var matIndex = prefabModel.Materials.Count;

                prefabModel.Materials.Add(material);

                foreach (var meshData in meshes)
                {
                    //todo need to take care of short index
                    var vertexArray = meshData.Value.VertexData.ToArray();
                    var indexArray  = meshData.Value.IndexData.ToArray();

                    var vertexCount = vertexArray.Length / meshData.Value.VertexStride;
                    var indexCount  = indexArray.Length / 4;

                    var gpuMesh = new Mesh
                    {
                        Draw = new MeshDraw {
                            PrimitiveType = PrimitiveType.TriangleList, DrawCount = indexCount, StartLocation = 0
                        },
                        MaterialIndex = matIndex
                    };

                    var vertexBuffer = new BufferData(BufferFlags.VertexBuffer, new byte[vertexArray.Length]);
                    var indexBuffer  = new BufferData(BufferFlags.IndexBuffer, new byte[indexArray.Length]);

                    var vertexBufferSerializable = vertexBuffer.ToSerializableVersion();
                    var indexBufferSerializable  = indexBuffer.ToSerializableVersion();

                    Array.Copy(vertexArray, vertexBuffer.Content, vertexArray.Length);
                    Array.Copy(indexArray, indexBuffer.Content, indexArray.Length);

                    gpuMesh.Draw.VertexBuffers    = new VertexBufferBinding[1];
                    gpuMesh.Draw.VertexBuffers[0] = new VertexBufferBinding(vertexBufferSerializable, meshData.Key, vertexCount);
                    gpuMesh.Draw.IndexBuffer      = new IndexBufferBinding(indexBufferSerializable, true, indexCount);

                    prefabModel.Meshes.Add(gpuMesh);
                }
            }
Ejemplo n.º 27
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="name">Name</param>
 /// <param name="data">Data type</param>
 public StructField(string name, BufferData data)
     : base(data) => this.name = name ?? throw new ArgumentNullException(nameof(name));
Ejemplo n.º 28
0
        public void LoadGLEntryPoints()
        {
            /* Basic entry points. If you don't have these, you're screwed. */
            try
            {
                INTERNAL_glGetString = (GetString) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glGetString"),
                    typeof(GetString)
                );
                glGetIntegerv = (GetIntegerv) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glGetIntegerv"),
                    typeof(GetIntegerv)
                );
                glEnable = (Enable) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glEnable"),
                    typeof(Enable)
                );
                glDisable = (Disable) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glDisable"),
                    typeof(Disable)
                );
                glViewport = (G_Viewport) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glViewport"),
                    typeof(G_Viewport)
                );
                glDepthRange = (DepthRange) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glDepthRange"),
                    typeof(DepthRange)
                );
                glScissor = (Scissor) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glScissor"),
                    typeof(Scissor)
                );
                glBlendColor = (BlendColor) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glBlendColor"),
                    typeof(BlendColor)
                );
                glBlendFuncSeparate = (BlendFuncSeparate) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glBlendFuncSeparate"),
                    typeof(BlendFuncSeparate)
                );
                glBlendEquationSeparate = (BlendEquationSeparate) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glBlendEquationSeparate"),
                    typeof(BlendEquationSeparate)
                );
                glColorMask = (ColorMask) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glColorMask"),
                    typeof(ColorMask)
                );
                glDepthMask = (DepthMask) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glDepthMask"),
                    typeof(DepthMask)
                );
                glDepthFunc = (DepthFunc) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glDepthFunc"),
                    typeof(DepthFunc)
                );
                glStencilMask = (StencilMask) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glStencilMask"),
                    typeof(StencilMask)
                );
                glStencilFuncSeparate = (StencilFuncSeparate) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glStencilFuncSeparate"),
                    typeof(StencilFuncSeparate)
                );
                glStencilOpSeparate = (StencilOpSeparate) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glStencilOpSeparate"),
                    typeof(StencilOpSeparate)
                );
                glStencilFunc = (StencilFunc) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glStencilFunc"),
                    typeof(StencilFunc)
                );
                glStencilOp = (StencilOp) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glStencilOp"),
                    typeof(StencilOp)
                );
                glCullFace = (CullFace) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glCullFace"),
                    typeof(CullFace)
                );
                glFrontFace = (FrontFace) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glFrontFace"),
                    typeof(FrontFace)
                );
                glPolygonMode = (PolygonMode) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glPolygonMode"),
                    typeof(PolygonMode)
                );
                glPolygonOffset = (PolygonOffset) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glPolygonOffset"),
                    typeof(PolygonOffset)
                );
                glGenTextures = (GenTextures) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glGenTextures"),
                    typeof(GenTextures)
                );
                glDeleteTextures = (DeleteTextures) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glDeleteTextures"),
                    typeof(DeleteTextures)
                );
                glBindTexture = (G_BindTexture) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glBindTexture"),
                    typeof(G_BindTexture)
                );
                glTexImage2D = (TexImage2D) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glTexImage2D"),
                    typeof(TexImage2D)
                );
                glTexSubImage2D = (TexSubImage2D) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glTexSubImage2D"),
                    typeof(TexSubImage2D)
                );
                glCompressedTexImage2D = (CompressedTexImage2D) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glCompressedTexImage2D"),
                    typeof(CompressedTexImage2D)
                );
                glCompressedTexSubImage2D = (CompressedTexSubImage2D) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glCompressedTexSubImage2D"),
                    typeof(CompressedTexSubImage2D)
                );
                glTexImage3D = (TexImage3D) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glTexImage3D"),
                    typeof(TexImage3D)
                );
                glTexSubImage3D = (TexSubImage3D) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glTexSubImage3D"),
                    typeof(TexSubImage3D)
                );
                glGetTexImage = (GetTexImage) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glGetTexImage"),
                    typeof(GetTexImage)
                );
                glTexParameteri = (TexParameteri) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glTexParameteri"),
                    typeof(TexParameteri)
                );
                glTexParameterf = (TexParameterf) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glTexParameterf"),
                    typeof(TexParameterf)
                );
                glActiveTexture = (ActiveTexture) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glActiveTexture"),
                    typeof(ActiveTexture)
                );
                glGetTexLevelParameteriv = (GetTexLevelParameteriv) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glGetTexLevelParameteriv"),
                    typeof(GetTexLevelParameteriv)
                );
                glPixelStorei = (PixelStorei) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glPixelStorei"),
                    typeof(PixelStorei)
                );
                glGenBuffers = (GenBuffers) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glGenBuffers"),
                    typeof(GenBuffers)
                );
                glDeleteBuffers = (DeleteBuffers) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glDeleteBuffers"),
                    typeof(DeleteBuffers)
                );
                glBindBuffer = (BindBuffer) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glBindBuffer"),
                    typeof(BindBuffer)
                );
                glBufferData = (BufferData) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glBufferData"),
                    typeof(BufferData)
                );
                glBufferSubData = (BufferSubData) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glBufferSubData"),
                    typeof(BufferSubData)
                );
                glMapBuffer = (MapBuffer) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glMapBuffer"),
                    typeof(MapBuffer)
                );
                glUnmapBuffer = (UnmapBuffer) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glUnmapBuffer"),
                    typeof(UnmapBuffer)
                );
                glEnableVertexAttribArray = (EnableVertexAttribArray) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glEnableVertexAttribArray"),
                    typeof(EnableVertexAttribArray)
                );
                glDisableVertexAttribArray = (DisableVertexAttribArray) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glDisableVertexAttribArray"),
                    typeof(DisableVertexAttribArray)
                );
                glVertexAttribPointer = (G_VertexAttribPointer) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glVertexAttribPointer"),
                    typeof(G_VertexAttribPointer)
                );
                glClearColor = (ClearColor) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glClearColor"),
                    typeof(ClearColor)
                );
                glClearDepth = (ClearDepth) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glClearDepth"),
                    typeof(ClearDepth)
                );
                glClearStencil = (ClearStencil) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glClearStencil"),
                    typeof(ClearStencil)
                );
                glClear = (G_Clear) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glClear"),
                    typeof(G_Clear)
                );
                glDrawBuffers = (DrawBuffers) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glDrawBuffers"),
                    typeof(DrawBuffers)
                );
                glReadPixels = (ReadPixels) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glReadPixels"),
                    typeof(ReadPixels)
                );
                glDrawRangeElements = (DrawRangeElements) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glDrawRangeElements"),
                    typeof(DrawRangeElements)
                );
                glDrawArrays = (DrawArrays) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glDrawArrays"),
                    typeof(DrawArrays)
                );
                glGenQueries = (GenQueries) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glGenQueries"),
                    typeof(GenQueries)
                );
                glDeleteQueries = (DeleteQueries) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glDeleteQueries"),
                    typeof(DeleteQueries)
                );
                glBeginQuery = (BeginQuery) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glBeginQuery"),
                    typeof(BeginQuery)
                );
                glEndQuery = (EndQuery) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glEndQuery"),
                    typeof(EndQuery)
                );
                glGetQueryObjectiv = (GetQueryObjectiv) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glGetQueryObjectiv"),
                    typeof(GetQueryObjectiv)
                );
                glCreateShader = (CreateShader) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glCreateShader"),
                    typeof(CreateShader)
                );
                glDeleteShader = (DeleteShader) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glDeleteShader"),
                    typeof(DeleteShader)
                );
                glShaderSource = (ShaderSource) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glShaderSource"),
                    typeof(ShaderSource)
                );
                glCompileShader = (CompileShader) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glCompileShader"),
                    typeof(CompileShader)
                );
                glCreateProgram = (CreateProgram) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glCreateProgram"),
                    typeof(CreateProgram)
                );
                glDeleteProgram = (DeleteProgram) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glDeleteProgram"),
                    typeof(DeleteProgram)
                );
                glAttachShader = (AttachShader) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glAttachShader"),
                    typeof(AttachShader)
                );
                glDetachShader = (DetachShader) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glDetachShader"),
                    typeof(DetachShader)
                );
                glLinkProgram = (LinkProgram) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glLinkProgram"),
                    typeof(LinkProgram)
                );
                glUseProgram = (UseProgram) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glUseProgram"),
                    typeof(UseProgram)
                );
                glUniform1i = (Uniform1i) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glUniform1i"),
                    typeof(Uniform1i)
                );
                glUniform4fv = (Uniform4fv) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glUniform4fv"),
                    typeof(Uniform4fv)
                );
                glGetShaderiv = (GetShaderiv) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glGetShaderiv"),
                    typeof(GetShaderiv)
                );
                glGetProgramiv = (GetProgramiv) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glGetProgramiv"),
                    typeof(GetProgramiv)
                );
                glGetUniformLocation = (GetUniformLocation) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glGetUniformLocation"),
                    typeof(GetUniformLocation)
                );
                glGetAttribLocation = (GetAttribLocation) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glGetAttribLocation"),
                    typeof(GetAttribLocation)
                );
                glBindAttribLocation = (BindAttribLocation) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glBindAttribLocation"),
                    typeof(BindAttribLocation)
                );
                glIsShader = (IsShader) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glIsShader"),
                    typeof(IsShader)
                );
                glIsProgram = (IsProgram) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glIsProgram"),
                    typeof(IsProgram)
                );
                glGetShaderInfoLog = (GetShaderInfoLog) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glGetShaderInfoLog"),
                    typeof(GetShaderInfoLog)
                );
                glGetProgramInfoLog = (GetProgramInfoLog) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glGetProgramInfoLog"),
                    typeof(GetProgramInfoLog)
                );
                glFlush = (Flush) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glFlush"),
                    typeof(Flush)
                );
            }
            catch
            {
                throw new NoSuitableGraphicsDeviceException("OpenGL 2.1 support is required!");
            }

            /* ARB_framebuffer_object. We're flexible, but not _that_ flexible. */
            try
            {
                glGenFramebuffers = (GenFramebuffers) Marshal.GetDelegateForFunctionPointer(
                    TryGetFramebufferEP("glGenFramebuffers"),
                    typeof(GenFramebuffers)
                );
                glDeleteFramebuffers = (DeleteFramebuffers) Marshal.GetDelegateForFunctionPointer(
                    TryGetFramebufferEP("glDeleteFramebuffers"),
                    typeof(DeleteFramebuffers)
                );
                glBindFramebuffer = (G_BindFramebuffer) Marshal.GetDelegateForFunctionPointer(
                    TryGetFramebufferEP("glBindFramebuffer"),
                    typeof(G_BindFramebuffer)
                );
                glFramebufferTexture2D = (FramebufferTexture2D) Marshal.GetDelegateForFunctionPointer(
                    TryGetFramebufferEP("glFramebufferTexture2D"),
                    typeof(FramebufferTexture2D)
                );
                glFramebufferRenderbuffer = (FramebufferRenderbuffer) Marshal.GetDelegateForFunctionPointer(
                    TryGetFramebufferEP("glFramebufferRenderbuffer"),
                    typeof(FramebufferRenderbuffer)
                );
            #if !DISABLE_FAUXBACKBUFFER
                glBlitFramebuffer = (BlitFramebuffer) Marshal.GetDelegateForFunctionPointer(
                    TryGetFramebufferEP("glBlitFramebuffer"),
                    typeof(BlitFramebuffer)
                );
            #endif
                glGenRenderbuffers = (GenRenderbuffers) Marshal.GetDelegateForFunctionPointer(
                    TryGetFramebufferEP("glGenRenderbuffers"),
                    typeof(GenRenderbuffers)
                );
                glDeleteRenderbuffers = (DeleteRenderbuffers) Marshal.GetDelegateForFunctionPointer(
                    TryGetFramebufferEP("glDeleteRenderbuffers"),
                    typeof(DeleteRenderbuffers)
                );
                glBindRenderbuffer = (BindRenderbuffer) Marshal.GetDelegateForFunctionPointer(
                    TryGetFramebufferEP("glBindRenderbuffer"),
                    typeof(BindRenderbuffer)
                );
                glRenderbufferStorage = (RenderbufferStorage) Marshal.GetDelegateForFunctionPointer(
                    TryGetFramebufferEP("glRenderbufferStorage"),
                    typeof(RenderbufferStorage)
                );
            }
            catch
            {
                throw new NoSuitableGraphicsDeviceException("OpenGL framebuffer support is required!");
            }

            /* ARB_instanced_arrays/ARB_draw_instanced are almost optional. */
            SupportsHardwareInstancing = true;
            try
            {
                glVertexAttribDivisor = (VertexAttribDivisor) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glVertexAttribDivisor"),
                    typeof(VertexAttribDivisor)
                );
                glDrawElementsInstanced = (DrawElementsInstanced) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glDrawElementsInstanced"),
                    typeof(DrawElementsInstanced)
                );
            }
            catch
            {
                SupportsHardwareInstancing = false;
            }

            #if DEBUG
            /* ARB_debug_output, for debug contexts */
            IntPtr messageCallback = SDL.SDL_GL_GetProcAddress("glDebugMessageCallbackARB");
            IntPtr messageControl = SDL.SDL_GL_GetProcAddress("glDebugMessageControlARB");
            if (messageCallback == IntPtr.Zero || messageControl == IntPtr.Zero)
            {
                System.Console.WriteLine("ARB_debug_output not supported!");
            }
            else
            {
                glDebugMessageCallbackARB = (DebugMessageCallback) Marshal.GetDelegateForFunctionPointer(
                    messageCallback,
                    typeof(DebugMessageCallback)
                );
                glDebugMessageControlARB = (DebugMessageControl) Marshal.GetDelegateForFunctionPointer(
                    messageControl,
                    typeof(DebugMessageControl)
                );
                glDebugMessageCallbackARB(DebugCall, IntPtr.Zero);
                glDebugMessageControlARB(
                    GLenum.GL_DONT_CARE,
                    GLenum.GL_DONT_CARE,
                    GLenum.GL_DONT_CARE,
                    0,
                    IntPtr.Zero,
                    true
                );
                glDebugMessageControlARB(
                    GLenum.GL_DONT_CARE,
                    GLenum.GL_DEBUG_TYPE_OTHER_ARB,
                    GLenum.GL_DEBUG_SEVERITY_LOW_ARB,
                    0,
                    IntPtr.Zero,
                    false
                );
            }

            /* GREMEDY_string_marker, for apitrace */
            IntPtr stringMarkerCallback = SDL.SDL_GL_GetProcAddress("glStringMarkerGREMEDY");
            if (stringMarkerCallback == IntPtr.Zero)
            {
                System.Console.WriteLine("GREMEDY_string_marker not supported!");
            }
            else
            {
                glStringMarkerGREMEDY = (StringMarkerGREMEDY) Marshal.GetDelegateForFunctionPointer(
                    stringMarkerCallback,
                    typeof(StringMarkerGREMEDY)
                );
            }
            #endif
        }
Ejemplo n.º 29
0
        private bool DecodePacket(BufferData data, out ushort length)
        {
            using (var br = data.GetReader(data.Offset, data.RemainingLength))
            {
                var rawPacket = new ProtocolPacket();

                rawPacket.Read(br);

                if (rawPacket.Channel != 0)
                {
                    if (rawPacket.SequenceNumber < ReceiveSequence[rawPacket.Channel])
                    {
                        Debugger.Break();

                        length = rawPacket.Size; // throw away the packet
                        return(true);
                    }

                    ReceiveSequence[rawPacket.Channel] = rawPacket.SequenceNumber;
                }

                length = rawPacket.Size;

                data.Offset += (int)br.BaseStream.Position;

                if (rawPacket.Type == ClientMessageOpcode.None)
                {
                    if (length != 4)
                    {
                        Debugger.Break(); // If it's not send timeout check, let's investigate...
                    }
                    return(true);
                }

                _packetQueue.EnqueueIncoming(rawPacket);
            }

            /*var packet = new PythonCallPacket(length);
             * using (var br = data.GetReader())
             * {
             *  packet.Read(br);
             *
             *  if (packet.Return.HasValue)
             *      return packet.Return.Value;
             *
             *  if (packet.Type == 2)
             *  {
             *      State = ClientState.LoggedIn;
             *      Entry = Server.AuthenticateClient(this, packet.AccountId, packet.OneTimeKey);
             *      if (Entry == null)
             *      {
             *          Logger.WriteLog(LogType.Error, "Client with ip: {0} tried to log in with invalid session data! User Id: {1} | OneTimeKey: {2}", Socket.RemoteAddress, packet.AccountId, packet.OneTimeKey);
             *          Close(false);
             *          return false;
             *      }
             *
             *      CharacterManager.Instance.StartCharacterSelection(this);
             *      return true;
             *  }
             *
             *  if (packet.DataSize > 0 && br.BaseStream.Position + packet.DataSize < br.BaseStream.Length)
             *  {
             *      if (br.ReadByte() != 0x4F) // 'O' format
             *          throw new Exception("Unsupported serialization format!");
             *
             *      var packetType = PacketRouter.GetPacketType(packet.Opcode);
             *      if (packetType != null)
             *      {
             *          var pythonPacket = Activator.CreateInstance(packetType) as IBasePacket;
             *          if (pythonPacket == null)
             *              return false;
             *
             *          pythonPacket.Read(br);
             *
             *          Server.PacketQueue.EnqueueIncoming(this, pythonPacket);
             *      }
             *      else
             *          Logger.WriteLog(LogType.Error, $"Unhandled game opcode: {packet.Opcode}");
             *  }
             *  else
             *      Logger.WriteLog(LogType.Error, $"Invalid data found in Python method call! Off: {br.BaseStream.Position} | Len: {packet.DataSize} | Array len: {br.BaseStream.Length}");
             * }*/

            return(true);
        }
Ejemplo n.º 30
0
 /// <summary>
 /// 將字典傳入,依json表設定資料
 /// </summary>
 public static void SetData(Dictionary<int, BufferData> _dic)
 {
     string jsonStr = Resources.Load<TextAsset>("Json/Buffer").ToString();
     JsonData jd = JsonMapper.ToObject(jsonStr);
     JsonData BufferItems = jd["Buffer"];
     for (int i = 0; i < BufferItems.Count; i++)
     {
         BufferData BufferData = new BufferData(BufferItems[i]);
         int id = int.Parse(BufferItems[i]["ID"].ToString());
         _dic.Add(id, BufferData);
     }
 }
Ejemplo n.º 31
0
        /// <summary>
        /// 添加、移除buff
        /// </summary>
        /// <param name="scene"></param>
        /// <param name="client"></param>
        /// <param name="buffType"></param>
        /// <param name="buffCfg"></param>
        /// <param name="bAdd"></param>
        private void ModifyBuff(CoupleArenaCopyScene scene, GameClient client, BufferItemTypes buffType, CoupleArenaBuffCfg buffCfg, bool bAdd)
        {
            if (scene == null || client == null || buffCfg == null)
            {
                return;
            }

            lock (Mutex)
            {
                bool       bChanged = false;
                BufferData buffData = Global.GetBufferDataByID(client, (int)buffType);

                int noSaveDbBuffType = 1;

                if (bAdd && (buffData == null || Global.IsBufferDataOver(buffData)))
                {
                    // 持有真爱buff的玩家无法获得勇气buff
                    if (buffType != BufferItemTypes.CoupleArena_YongQi_Buff ||
                        scene.ZhenAiBuff_Role != client.ClientData.RoleID)
                    {
                        double[] bufferParams = new double[1] {
                            1
                        };
                        Global.UpdateBufferData(client, buffType, bufferParams, noSaveDbBuffType);

                        foreach (var prop in buffCfg.ExtProps)
                        {
                            client.ClientData.PropsCacheManager.SetExtPropsSingle((int)PropsSystemTypes.CoupleArena, (int)prop.Key, prop.Value);
                        }

                        bChanged = true;
                    }
                }

                if (!bAdd && buffData != null && !Global.IsBufferDataOver(buffData))
                {
                    double[] bufferParams = new double[1] {
                        0
                    };
                    Global.UpdateBufferData(client, buffType, bufferParams, noSaveDbBuffType);

                    foreach (var prop in buffCfg.ExtProps)
                    {
                        client.ClientData.PropsCacheManager.SetExtPropsSingle((int)PropsSystemTypes.CoupleArena, (int)prop.Key, 0);
                    }

                    bChanged = true;
                }

                if (bChanged)
                {
                    if (buffType == BufferItemTypes.CoupleArena_ZhenAi_Buff)
                    {
                        if (bAdd)
                        {
                            scene.ZhenAiBuff_Role    = client.ClientData.RoleID;
                            scene.ZhenAiBuff_StartMs = TimeUtil.NOW();
                        }
                        else
                        {
                            scene.ZhenAiBuff_Role = 0;
                        }
                    }
                    else if (buffType == BufferItemTypes.CoupleArena_YongQi_Buff)
                    {
                        if (bAdd)
                        {
                            scene.YongQiBuff_Role = client.ClientData.RoleID;
                        }
                        else
                        {
                            scene.YongQiBuff_Role = 0;
                        }
                    }

                    NtfBuffHoldData(scene);
                    GameManager.ClientMgr.NotifyUpdateEquipProps(Global._TCPManager.MySocketListener, Global._TCPManager.TcpOutPacketPool, client);
                    // 总生命值和魔法值变化通知(同一个地图才需要通知)
                    GameManager.ClientMgr.NotifyOthersLifeChanged(Global._TCPManager.MySocketListener, Global._TCPManager.TcpOutPacketPool, client);
                }
            }
        }
Ejemplo n.º 32
0
 /// <summary>
 /// Sets the serialized data version of this <see cref="Buffer" />.
 /// </summary>
 /// <param name="buffer">The buffer.</param>
 /// <param name="bufferData">The buffer data.</param>
 public static void SetSerializationData(this Buffer buffer, BufferData bufferData)
 {
     var attachedReference = AttachedReferenceManager.GetOrCreateAttachedReference(buffer);
     attachedReference.Data = bufferData;
 }
Ejemplo n.º 33
0
        public static void AddTempBufferProp(GameClient client, BufferItemTypes bufferID, int type)
        {
            EquipPropItem item = null;

            if (Global.CanMapUseBuffer(client.ClientData.MapCode, (int)bufferID))
            {
                BufferData bufferData = Global.GetBufferDataByID(client, (int)bufferID);
                if (null != bufferData)
                {
                    if (!Global.IsBufferDataOver(bufferData, 0L))
                    {
                        int bufferGoodsId = 0;
                        if (type == 0)
                        {
                            int goodsIndex;
                            if (bufferID == BufferItemTypes.ZuanHuang)
                            {
                                goodsIndex = client.ClientData.VipLevel;
                            }
                            else
                            {
                                goodsIndex = (int)bufferData.BufferVal;
                            }
                            int[] goodsIds = AdvanceBufferPropsMgr.GetCachingIDsByID((int)bufferID);
                            if (null == goodsIds)
                            {
                                goto IL_F8;
                            }
                            if (goodsIndex < 0 || goodsIndex >= goodsIds.Length)
                            {
                                goto IL_F8;
                            }
                            bufferGoodsId = goodsIds[goodsIndex];
                        }
                        else if (type == 1)
                        {
                            bufferGoodsId = (int)bufferData.BufferVal;
                        }
                        if (bufferGoodsId > 0)
                        {
                            item = GameManager.EquipPropsMgr.FindEquipPropItem(bufferGoodsId);
                        }
                    }
                }
            }
IL_F8:
            if (null != item)
            {
                client.ClientData.PropsCacheManager.SetExtProps(new object[]
                {
                    PropsSystemTypes.BufferByGoodsProps,
                    bufferID,
                    item.ExtProps
                });
            }
            else
            {
                client.ClientData.PropsCacheManager.SetExtProps(new object[]
                {
                    PropsSystemTypes.BufferByGoodsProps,
                    bufferID,
                    PropsCacheManager.ConstExtProps
                });
            }
        }
Ejemplo n.º 34
0
        void IWpfTextViewCreationListener.TextViewCreated(IWpfTextView textView)
        {
            // Load the VimRC file if we haven't tried yet
            MaybeLoadVimRc();

            // Create the IVimBuffer after loading the VimRc so that it gets the appropriate
            // settings
            var buffer = _vim.GetOrCreateVimBuffer(textView);

            // Save the tab size and expand tab in case we need to reset them later
            var bufferData = new BufferData
            {
                TabStop = buffer.LocalSettings.TabStop,
                ExpandTab = buffer.LocalSettings.ExpandTab,
                Number = buffer.LocalSettings.Number
            };
            _bufferMap[buffer] = bufferData;

            Action doCheck = () =>
            {
                // Run the key binding check now
                if (_keyBindingService.ConflictingKeyBindingState == ConflictingKeyBindingState.HasNotChecked)
                {
                    if (Settings.Settings.Default.IgnoredConflictingKeyBinding)
                    {
                        _keyBindingService.IgnoreAnyConflicts();
                    }
                    else
                    {
                        _keyBindingService.RunConflictingKeyBindingStateCheck(buffer, (x, y) => { });
                    }
                }
            };

            _protectedOperations.BeginInvoke(doCheck);
        }
Ejemplo n.º 35
0
        /// <summary>
        /// Raised when an IVsTextView is created.  When this occurs it means a previously created
        /// ITextView was associated with an IVsTextView shim.  This means the ITextView will be
        /// hooked into the Visual Studio command system and a host of other items.  Setup all of
        /// our plumbing here
        /// </summary>
        void IVsTextViewCreationListener.VsTextViewCreated(IVsTextView vsView)
        {
            // Get the ITextView created.  Shouldn't ever be null unless a non-standard Visual Studio
            // component is calling this function
            var textView = _adaptersFactory.GetWpfTextView(vsView);

            if (textView == null)
            {
                return;
            }

            // Sanity check. No reason for this to be null
            var opt = _vim.GetVimBuffer(textView);

            if (!opt.IsSome())
            {
                return;
            }

            var        buffer = opt.Value;
            BufferData bufferData;

            if (_bufferMap.TryGetValue(buffer, out bufferData))
            {
                // During the lifetime of an IVimBuffer the local and editor settings are kept
                // in sync for tab values.  At startup though a decision has to be made about which
                // settings should "win" and this is controlled by 'UseEditorSettings'.
                //
                // Visual Studio of course makes this difficult.  It will create an ITextView and
                // then later force all of it's language preference settings down on the ITextView
                // if it does indeed have an IVsTextView.  This setting will inherently overwrite
                // the custom settings with the stored Visual Studio settings.
                //
                // To work around this we store the original values and reset them here.  This event
                // is raised after this propagation occurs so we can put them back
                if (!_vim.GlobalSettings.UseEditorSettings)
                {
                    buffer.LocalSettings.TabStop   = bufferData.TabStop;
                    buffer.LocalSettings.ExpandTab = bufferData.ExpandTab;
                    buffer.LocalSettings.Number    = bufferData.Number;
                }
            }
            else
            {
                bufferData         = new BufferData();
                _bufferMap[buffer] = bufferData;
            }

            var broker            = _displayWindowBrokerFactoryServcie.CreateDisplayWindowBroker(textView);
            var bufferCoordinator = _bufferCoordinatorFactory.GetVimBufferCoordinator(buffer);
            var result            = VsCommandTarget.Create(bufferCoordinator, vsView, _adapter, broker, _resharperUtil, _keyUtil);

            if (result.IsSuccess)
            {
                // Store the value for debugging
                bufferData.VsCommandTarget = result.Value;
            }

            // Try and install the IVsFilterKeys adapter.  This cannot be done synchronously here
            // because Venus projects are not fully initialized at this state.  Merely querying
            // for properties cause them to corrupt internal state and prevents rendering of the
            // view.  Occurs for aspx and .js pages
            Action install = () => VsFilterKeysAdapter.TryInstallFilterKeysAdapter(_adapter, _editorOptionsFactoryService, buffer);

            _protectedOperations.BeginInvoke(install);
        }
Ejemplo n.º 36
0
        private void LoadGLEntryPoints()
        {
            /* Basic entry points. If you don't have these, you're screwed. */
            try
            {
                INTERNAL_glGetString = (GetString) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glGetString"),
                    typeof(GetString)
                );
                glGetIntegerv = (GetIntegerv) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glGetIntegerv"),
                    typeof(GetIntegerv)
                );
                glEnable = (Enable) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glEnable"),
                    typeof(Enable)
                );
                glDisable = (Disable) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glDisable"),
                    typeof(Disable)
                );
                glViewport = (G_Viewport) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glViewport"),
                    typeof(G_Viewport)
                );
                glDepthRange = (DepthRange) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glDepthRange"),
                    typeof(DepthRange)
                );
                glScissor = (Scissor) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glScissor"),
                    typeof(Scissor)
                );
                glBlendColor = (BlendColor) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glBlendColor"),
                    typeof(BlendColor)
                );
                glBlendFuncSeparate = (BlendFuncSeparate) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glBlendFuncSeparate"),
                    typeof(BlendFuncSeparate)
                );
                glBlendEquationSeparate = (BlendEquationSeparate) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glBlendEquationSeparate"),
                    typeof(BlendEquationSeparate)
                );
                glColorMask = (ColorMask) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glColorMask"),
                    typeof(ColorMask)
                );
                glDepthMask = (DepthMask) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glDepthMask"),
                    typeof(DepthMask)
                );
                glDepthFunc = (DepthFunc) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glDepthFunc"),
                    typeof(DepthFunc)
                );
                glStencilMask = (StencilMask) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glStencilMask"),
                    typeof(StencilMask)
                );
                glStencilFuncSeparate = (StencilFuncSeparate) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glStencilFuncSeparate"),
                    typeof(StencilFuncSeparate)
                );
                glStencilOpSeparate = (StencilOpSeparate) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glStencilOpSeparate"),
                    typeof(StencilOpSeparate)
                );
                glStencilFunc = (StencilFunc) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glStencilFunc"),
                    typeof(StencilFunc)
                );
                glStencilOp = (StencilOp) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glStencilOp"),
                    typeof(StencilOp)
                );
                glCullFace = (CullFace) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glCullFace"),
                    typeof(CullFace)
                );
                glFrontFace = (FrontFace) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glFrontFace"),
                    typeof(FrontFace)
                );
                glPolygonMode = (PolygonMode) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glPolygonMode"),
                    typeof(PolygonMode)
                );
                glPolygonOffset = (PolygonOffset) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glPolygonOffset"),
                    typeof(PolygonOffset)
                );
                glGenTextures = (GenTextures) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glGenTextures"),
                    typeof(GenTextures)
                );
                glDeleteTextures = (DeleteTextures) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glDeleteTextures"),
                    typeof(DeleteTextures)
                );
                glBindTexture = (G_BindTexture) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glBindTexture"),
                    typeof(G_BindTexture)
                );
                glTexImage2D = (TexImage2D) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glTexImage2D"),
                    typeof(TexImage2D)
                );
                glTexSubImage2D = (TexSubImage2D) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glTexSubImage2D"),
                    typeof(TexSubImage2D)
                );
                glCompressedTexImage2D = (CompressedTexImage2D) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glCompressedTexImage2D"),
                    typeof(CompressedTexImage2D)
                );
                glCompressedTexSubImage2D = (CompressedTexSubImage2D) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glCompressedTexSubImage2D"),
                    typeof(CompressedTexSubImage2D)
                );
                glTexImage3D = (TexImage3D) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glTexImage3D"),
                    typeof(TexImage3D)
                );
                glTexSubImage3D = (TexSubImage3D) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glTexSubImage3D"),
                    typeof(TexSubImage3D)
                );
                glGetTexImage = (GetTexImage) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glGetTexImage"),
                    typeof(GetTexImage)
                );
                glTexParameteri = (TexParameteri) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glTexParameteri"),
                    typeof(TexParameteri)
                );
                glTexParameterf = (TexParameterf) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glTexParameterf"),
                    typeof(TexParameterf)
                );
                glActiveTexture = (ActiveTexture) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glActiveTexture"),
                    typeof(ActiveTexture)
                );
                glPixelStorei = (PixelStorei) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glPixelStorei"),
                    typeof(PixelStorei)
                );
                glGenBuffers = (GenBuffers) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glGenBuffers"),
                    typeof(GenBuffers)
                );
                glDeleteBuffers = (DeleteBuffers) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glDeleteBuffers"),
                    typeof(DeleteBuffers)
                );
                glBindBuffer = (BindBuffer) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glBindBuffer"),
                    typeof(BindBuffer)
                );
                glBufferData = (BufferData) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glBufferData"),
                    typeof(BufferData)
                );
                glBufferSubData = (BufferSubData) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glBufferSubData"),
                    typeof(BufferSubData)
                );
                glMapBuffer = (MapBuffer) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glMapBuffer"),
                    typeof(MapBuffer)
                );
                glUnmapBuffer = (UnmapBuffer) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glUnmapBuffer"),
                    typeof(UnmapBuffer)
                );
                glClearColor = (ClearColor) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glClearColor"),
                    typeof(ClearColor)
                );
                glClearDepth = (ClearDepth) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glClearDepth"),
                    typeof(ClearDepth)
                );
                glClearStencil = (ClearStencil) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glClearStencil"),
                    typeof(ClearStencil)
                );
                glClear = (G_Clear) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glClear"),
                    typeof(G_Clear)
                );
                glDrawBuffers = (DrawBuffers) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glDrawBuffers"),
                    typeof(DrawBuffers)
                );
                glReadPixels = (ReadPixels) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glReadPixels"),
                    typeof(ReadPixels)
                );
                glVertexAttribPointer = (VertexAttribPointer) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glVertexAttribPointer"),
                    typeof(VertexAttribPointer)
                );
                glEnableVertexAttribArray = (EnableVertexAttribArray) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glEnableVertexAttribArray"),
                    typeof(EnableVertexAttribArray)
                );
                glDisableVertexAttribArray = (DisableVertexAttribArray) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glDisableVertexAttribArray"),
                    typeof(DisableVertexAttribArray)
                );
                glDrawRangeElements = (DrawRangeElements) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glDrawRangeElements"),
                    typeof(DrawRangeElements)
                );
                glDrawArrays = (DrawArrays) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glDrawArrays"),
                    typeof(DrawArrays)
                );
                glGenQueries = (GenQueries) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glGenQueries"),
                    typeof(GenQueries)
                );
                glDeleteQueries = (DeleteQueries) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glDeleteQueries"),
                    typeof(DeleteQueries)
                );
                glBeginQuery = (BeginQuery) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glBeginQuery"),
                    typeof(BeginQuery)
                );
                glEndQuery = (EndQuery) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glEndQuery"),
                    typeof(EndQuery)
                );
                glGetQueryObjectiv = (GetQueryObjectiv) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glGetQueryObjectiv"),
                    typeof(GetQueryObjectiv)
                );
            }
            catch
            {
                throw new NoSuitableGraphicsDeviceException("OpenGL 2.1 support is required!");
            }

            /* ARB_framebuffer_object. We're flexible, but not _that_ flexible. */
            try
            {
                glGenFramebuffers = (GenFramebuffers) Marshal.GetDelegateForFunctionPointer(
                    TryGetFramebufferEP("glGenFramebuffers"),
                    typeof(GenFramebuffers)
                );
                glDeleteFramebuffers = (DeleteFramebuffers) Marshal.GetDelegateForFunctionPointer(
                    TryGetFramebufferEP("glDeleteFramebuffers"),
                    typeof(DeleteFramebuffers)
                );
                glBindFramebuffer = (G_BindFramebuffer) Marshal.GetDelegateForFunctionPointer(
                    TryGetFramebufferEP("glBindFramebuffer"),
                    typeof(G_BindFramebuffer)
                );
                glFramebufferTexture2D = (FramebufferTexture2D) Marshal.GetDelegateForFunctionPointer(
                    TryGetFramebufferEP("glFramebufferTexture2D"),
                    typeof(FramebufferTexture2D)
                );
                glFramebufferRenderbuffer = (FramebufferRenderbuffer) Marshal.GetDelegateForFunctionPointer(
                    TryGetFramebufferEP("glFramebufferRenderbuffer"),
                    typeof(FramebufferRenderbuffer)
                );
                glGenerateMipmap = (GenerateMipmap) Marshal.GetDelegateForFunctionPointer(
                    TryGetFramebufferEP("glGenerateMipmap"),
                    typeof(GenerateMipmap)
                );
            #if !DISABLE_FAUXBACKBUFFER
                glBlitFramebuffer = (BlitFramebuffer) Marshal.GetDelegateForFunctionPointer(
                    TryGetFramebufferEP("glBlitFramebuffer"),
                    typeof(BlitFramebuffer)
                );
            #endif
                glGenRenderbuffers = (GenRenderbuffers) Marshal.GetDelegateForFunctionPointer(
                    TryGetFramebufferEP("glGenRenderbuffers"),
                    typeof(GenRenderbuffers)
                );
                glDeleteRenderbuffers = (DeleteRenderbuffers) Marshal.GetDelegateForFunctionPointer(
                    TryGetFramebufferEP("glDeleteRenderbuffers"),
                    typeof(DeleteRenderbuffers)
                );
                glBindRenderbuffer = (BindRenderbuffer) Marshal.GetDelegateForFunctionPointer(
                    TryGetFramebufferEP("glBindRenderbuffer"),
                    typeof(BindRenderbuffer)
                );
                glRenderbufferStorage = (RenderbufferStorage) Marshal.GetDelegateForFunctionPointer(
                    TryGetFramebufferEP("glRenderbufferStorage"),
                    typeof(RenderbufferStorage)
                );
            }
            catch
            {
                throw new NoSuitableGraphicsDeviceException("OpenGL framebuffer support is required!");
            }

            /* ARB_instanced_arrays/ARB_draw_instanced are almost optional. */
            SupportsHardwareInstancing = true;
            try
            {
                glVertexAttribDivisor = (VertexAttribDivisor) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glVertexAttribDivisor"),
                    typeof(VertexAttribDivisor)
                );
                glDrawElementsInstanced = (DrawElementsInstanced) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glDrawElementsInstanced"),
                    typeof(DrawElementsInstanced)
                );
            }
            catch
            {
                SupportsHardwareInstancing = false;
            }

            /* EXT_draw_buffers2 is probably used by nobody. */
            try
            {
                glColorMaskIndexedEXT = (ColorMaskIndexedEXT) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glColorMaskIndexedEXT"),
                    typeof(ColorMaskIndexedEXT)
                );
            }
            catch
            {
                // FIXME: SupportsIndependentWriteMasks? -flibit
            }

            /* EXT_framebuffer_multisample/ARB_texture_multisample is glitter -flibit */
            supportsMultisampling = true;
            try
            {
                glRenderbufferStorageMultisample = (RenderbufferStorageMultisample) Marshal.GetDelegateForFunctionPointer(
                    TryGetFramebufferEP("glRenderbufferStorageMultisample"),
                    typeof(RenderbufferStorageMultisample)
                );
                glSampleMaski = (SampleMaski) Marshal.GetDelegateForFunctionPointer(
                    SDL.SDL_GL_GetProcAddress("glSampleMaski"),
                    typeof(SampleMaski)
                );
            }
            catch
            {
                supportsMultisampling = false;
            }

            if (useCoreProfile)
            {
                try
                {
                    INTERNAL_glGetStringi = (GetStringi) Marshal.GetDelegateForFunctionPointer(
                        SDL.SDL_GL_GetProcAddress("glGetStringi"),
                        typeof(GetStringi)
                    );
                    glGenVertexArrays = (GenVertexArrays) Marshal.GetDelegateForFunctionPointer(
                        SDL.SDL_GL_GetProcAddress("glGenVertexArrays"),
                        typeof(GenVertexArrays)
                    );
                    glDeleteVertexArrays = (DeleteVertexArrays) Marshal.GetDelegateForFunctionPointer(
                        SDL.SDL_GL_GetProcAddress("glDeleteVertexArrays"),
                        typeof(DeleteVertexArrays)
                    );
                    glBindVertexArray = (BindVertexArray) Marshal.GetDelegateForFunctionPointer(
                        SDL.SDL_GL_GetProcAddress("glBindVertexArray"),
                        typeof(BindVertexArray)
                    );
                }
                catch
                {
                    throw new NoSuitableGraphicsDeviceException("OpenGL 3.2 support is required!");
                }
            }

            #if DEBUG
            /* ARB_debug_output, for debug contexts */
            IntPtr messageCallback = SDL.SDL_GL_GetProcAddress("glDebugMessageCallbackARB");
            IntPtr messageControl = SDL.SDL_GL_GetProcAddress("glDebugMessageControlARB");
            if (messageCallback == IntPtr.Zero || messageControl == IntPtr.Zero)
            {
                System.Console.WriteLine("ARB_debug_output not supported!");
            }
            else
            {
                glDebugMessageCallbackARB = (DebugMessageCallback) Marshal.GetDelegateForFunctionPointer(
                    messageCallback,
                    typeof(DebugMessageCallback)
                );
                glDebugMessageControlARB = (DebugMessageControl) Marshal.GetDelegateForFunctionPointer(
                    messageControl,
                    typeof(DebugMessageControl)
                );
                glDebugMessageControlARB(
                    GLenum.GL_DONT_CARE,
                    GLenum.GL_DONT_CARE,
                    GLenum.GL_DONT_CARE,
                    0,
                    IntPtr.Zero,
                    true
                );
                glDebugMessageControlARB(
                    GLenum.GL_DONT_CARE,
                    GLenum.GL_DEBUG_TYPE_OTHER_ARB,
                    GLenum.GL_DEBUG_SEVERITY_LOW_ARB,
                    0,
                    IntPtr.Zero,
                    false
                );
                glDebugMessageControlARB(
                    GLenum.GL_DONT_CARE,
                    GLenum.GL_DEBUG_TYPE_OTHER_ARB,
                    GLenum.GL_DEBUG_SEVERITY_NOTIFICATION_ARB,
                    0,
                    IntPtr.Zero,
                    false
                );
                glDebugMessageCallbackARB(DebugCall, IntPtr.Zero);
            }

            /* GREMEDY_string_marker, for apitrace */
            IntPtr stringMarkerCallback = SDL.SDL_GL_GetProcAddress("glStringMarkerGREMEDY");
            if (stringMarkerCallback == IntPtr.Zero)
            {
                System.Console.WriteLine("GREMEDY_string_marker not supported!");
            }
            else
            {
                glStringMarkerGREMEDY = (StringMarkerGREMEDY) Marshal.GetDelegateForFunctionPointer(
                    stringMarkerCallback,
                    typeof(StringMarkerGREMEDY)
                );
            }
            #endif
        }
Ejemplo n.º 37
0
        private static int GetLeftCountByType(GameClient client, int type, int copyId)
        {
            int leftnum = 0;

            switch (type)
            {
            case 1:
            {
                DailyTaskData dailyTaskData = Global.FindDailyTaskDataByTaskClass(client, 8);
                if (null == dailyTaskData)
                {
                    return(10);
                }
                int maxnum = Global.GetMaxDailyTaskNum(client, 8, dailyTaskData);
                leftnum = maxnum - dailyTaskData.RecNum;
                goto IL_4AC;
            }

            case 5:
            {
                int nMapID = Global.GetDaimonSquareCopySceneIDForRole(client);
                DaimonSquareDataInfo bcDataTmp = null;
                Data.DaimonSquareDataInfoList.TryGetValue(nMapID, out bcDataTmp);
                int nDate  = TimeUtil.NowDateTime().DayOfYear;
                int nCount = Global.QueryDayActivityEnterCountToDB(client, client.ClientData.RoleID, nDate, 2);
                if (nCount < 0)
                {
                    nCount = 0;
                }
                int   nVipLev = client.ClientData.VipLevel;
                int   nNum    = 0;
                int[] nArry   = GameManager.systemParamsList.GetParamValueIntArrayByName("VIPEnterDaimonSquareCountAddValue", ',');
                if (nVipLev > 0 && nArry != null && nArry[nVipLev] > 0)
                {
                    nNum = nArry[nVipLev];
                }
                leftnum = bcDataTmp.MaxEnterNum + nNum - nCount;
                goto IL_4AC;
            }

            case 6:
            {
                int nMapID = Global.GetBloodCastleCopySceneIDForRole(client);
                BloodCastleDataInfo bcDataTmp2 = null;
                if (!Data.BloodCastleDataInfoList.TryGetValue(nMapID, out bcDataTmp2))
                {
                    goto IL_4AC;
                }
                int nDate  = TimeUtil.NowDateTime().DayOfYear;
                int nType  = 1;
                int nCount = Global.QueryDayActivityEnterCountToDB(client, client.ClientData.RoleID, nDate, nType);
                if (nCount < 0)
                {
                    nCount = 0;
                }
                int   nVipLev = client.ClientData.VipLevel;
                int   nNum    = 0;
                int[] nArry   = GameManager.systemParamsList.GetParamValueIntArrayByName("VIPEnterBloodCastleCountAddValue", ',');
                if (nVipLev > 0 && nArry != null && nArry[nVipLev] > 0)
                {
                    nNum = nArry[nVipLev];
                }
                leftnum = bcDataTmp2.MaxEnterNum + nNum - nCount;
                goto IL_4AC;
            }

            case 7:
            {
                DateTime      now            = TimeUtil.NowDateTime();
                string        nowTime        = TimeUtil.NowDateTime().ToString("HH:mm");
                List <string> timePointsList = GameManager.AngelTempleMgr.m_AngelTempleData.BeginTime;
                leftnum = 0;
                for (int i = 0; i < timePointsList.Count; i++)
                {
                    DateTime perpareTime = DateTime.Parse(timePointsList[i]).AddMinutes((double)(GameManager.AngelTempleMgr.m_AngelTempleData.PrepareTime / 60));
                    if (now <= perpareTime)
                    {
                        leftnum++;
                    }
                }
                goto IL_4AC;
            }

            case 8:
                leftnum = 1;
                if (SweepWanMotaManager.GetSweepCount(client) >= SweepWanMotaManager.nWanMoTaMaxSweepNum)
                {
                    leftnum = 0;
                }
                goto IL_4AC;

            case 9:
            {
                BufferData bufferData = Global.GetBufferDataByID(client, 34);
                leftnum = (int)(bufferData.BufferVal - (long)bufferData.BufferSecs);
                goto IL_4AC;
            }

            case 10:
                leftnum = GameManager.BattleMgr.LeftEnterCount();
                goto IL_4AC;

            case 11:
                leftnum = GameManager.ArenaBattleMgr.LeftEnterCount();
                goto IL_4AC;

            case 13:
                leftnum = JingJiChangManager.getInstance().GetLeftEnterCount(client);
                goto IL_4AC;

            case 15:
            {
                DailyTaskData dailyTaskData = Global.FindDailyTaskDataByTaskClass(client, 9);
                if (null == dailyTaskData)
                {
                    return(Global.MaxTaofaTaskNumForMU);
                }
                int maxnum = Global.GetMaxDailyTaskNum(client, 9, dailyTaskData);
                leftnum = maxnum - dailyTaskData.RecNum;
                goto IL_4AC;
            }

            case 16:
            {
                int temp = 0;
                CaiJiLogic.ReqCaiJiLastNum(client, 0, out temp);
                leftnum = temp;
                goto IL_4AC;
            }

            case 19:
                leftnum = HuanYingSiYuanManager.getInstance().GetLeftCount(client);
                goto IL_4AC;
            }
            if (copyId > 0)
            {
                SystemXmlItem systemFuBenItem = null;
                if (!GameManager.systemFuBenMgr.SystemXmlItemDict.TryGetValue(copyId, out systemFuBenItem))
                {
                    return(-1);
                }
                int enternum  = systemFuBenItem.GetIntValue("EnterNumber", -1);
                int finishnum = systemFuBenItem.GetIntValue("FinishNumber", -1);
                int total     = (enternum < finishnum) ? finishnum : enternum;
                if (type == 4 || type == 3)
                {
                    int[] nAddNum = GameManager.systemParamsList.GetParamValueIntArrayByName("VIPJinBiFuBenNum", ',');
                    if (type == 3)
                    {
                        nAddNum = GameManager.systemParamsList.GetParamValueIntArrayByName("VIPJinYanFuBenNum", ',');
                    }
                    if (client.ClientData.VipLevel > 0 && client.ClientData.VipLevel <= VIPEumValue.VIPENUMVALUE_MAXLEVEL && nAddNum != null && nAddNum.Length > VIPEumValue.VIPENUMVALUE_MAXLEVEL)
                    {
                        total += nAddNum[client.ClientData.VipLevel];
                    }
                }
                FuBenData tmpfubdata = Global.GetFuBenData(client, copyId);
                if (null == tmpfubdata)
                {
                    return(total);
                }
                leftnum = total - tmpfubdata.EnterNum;
            }
IL_4AC:
            return(leftnum);
        }