Пример #1
0
        /// <summary>
        ///     Copy collider geometry data to a Unity mesh
        /// </summary>
        public static void BuildColliderMesh(Mesh mesh, GeometryBuffer buffer)
        {
            int size = buffer.Vertices.Count;

            // Avoid allocations by retrieving buffers from the pool
            Vector3[] vertices = Globals.MemPools.PopVector3Array(size);

            // Fill buffers with data
            for (int i = 0; i < size; i++)
            {
                VertexDataFixed vertexData = buffer.Vertices[i];
                vertices[i] = vertexData.Vertex;
            }

            // Due to the way the memory pools work we might have received more
            // data than necessary. This little overhead is well worth it, though.
            // Fill unused data with "zeroes"
            for (int i = size; i < vertices.Length; i++)
            {
                vertices[i] = Vector3.zero;
            }

            // Prepare mesh
            mesh.vertices = vertices;
            mesh.SetTriangles(buffer.Triangles, 0);

            // Return memory back to pool
            Globals.MemPools.PushVector3Array(vertices);
        }
Пример #2
0
        public void AddMeshData(int[] tris, VertexDataFixed[] verts, Rect texture, Vector3 offset)
        {
            GeometryBuffer buffer = m_buffers[m_buffers.Count - 1];

            int initialVertCount = buffer.Vertices.Count;

            for (int i = 0; i < verts.Length; i++)
            {
                // If there are too many vertices we need to create a new separate buffer for them
                if (buffer.Vertices.Count + 1 > 65000)
                {
                    buffer = new GeometryBuffer();
                    m_buffers.Add(buffer);
                }

                VertexDataFixed v = new VertexDataFixed()
                {
                    Color   = verts[i].Color,
                    Normal  = verts[i].Normal,
                    Tangent = verts[i].Tangent,
                    // Adjust UV coordinates based on provided texture atlas
                    UV = new Vector2(
                        (verts[i].UV.x * texture.width) + texture.x,
                        (verts[i].UV.y * texture.height) + texture.y
                        ),
                    Vertex = verts[i].Vertex + offset
                };
                buffer.AddVertex(ref v);
            }

            for (int i = 0; i < tris.Length; i++)
            {
                buffer.AddIndex(tris[i] + initialVertCount);
            }
        }
Пример #3
0
    void Start()
    {
        buffer = new GeometryBuffer();

        isLoaded = false;
        //StartCoroutine(Load(url));
    }
Пример #4
0
        protected ManagedGeometryBuffer()
        {
            gb = CreateGeometryBuffer();

            batches   = new Dictionary <uint, BatchInfo>();
            materials = new Dictionary <uint, ResourceHandle <Material> >();
        }
Пример #5
0
        /// <summary>
        /// Attach vertex buffer routine
        /// </summary>
        /// <param name="context"></param>
        /// <param name="vertStartSlot"></param>
        protected override bool OnAttachBuffers(DeviceContextProxy context, ref int vertStartSlot)
        {
            bool succ = GeometryBuffer.AttachBuffers(context, this.VertexLayout, ref vertStartSlot, EffectTechnique.EffectsManager);

            InstanceBuffer?.AttachBuffer(context, ref vertStartSlot);
            return(succ);
        }
            protected override void OnUpdate(RenderContext context, DeviceContextProxy deviceContext)
            {
                //Skip if not ready
                if (preComputeBoneSkinPass.IsNULL || preComputeBoneBuffer == null || !preComputeBoneBuffer.CanPreCompute)
                {
                    return;
                }

                //Skip if not necessary
                if (!matricsChanged && !mtChanged)
                {
                    return;
                }

                var boneBuffer = sharedBoneBuffer ?? internalBoneBuffer;

                if (boneBuffer.BoneMatrices.Length == 0 && !mtChanged)
                {
                    preComputeBoneBuffer.ResetSkinnedVertexBuffer(deviceContext);
                }
                else
                {
                    GeometryBuffer.UpdateBuffers(deviceContext, EffectTechnique.EffectsManager);
                    preComputeBoneBuffer.BindSkinnedVertexBufferToOutput(deviceContext);
                    boneBuffer.Update(context, deviceContext);
                    internalMTBuffer.Update(context, deviceContext);
                    preComputeBoneSkinPass.BindShader(deviceContext);
                    boneBuffer.BindBuffer(deviceContext, boneSkinSBSlot);
                    internalMTBuffer.BindBuffers(deviceContext, mtWeightsBSlot, mtDeltasBSlot, mtOffsetsBSlot);
                    deviceContext.Draw(GeometryBuffer.VertexBuffer[0].ElementCount, 0);
                    preComputeBoneBuffer.UnBindSkinnedVertexBufferToOutput(deviceContext);
                }
                matricsChanged = false;
            }
Пример #7
0
        private void DrawGeometry(GeometryBuffer buffer, PointF position, float depth)
        {
            this.Prepare(DrawState.Geometry);

            WcR2GeometryBuffer wcR2Buffer = buffer as WcR2GeometryBuffer;
            GraphicsDevice     device     = GraphicsDevice;

            RasterizerState   rasState     = device.RasterizerState;
            BlendState        blendState   = device.BlendState;
            DepthStencilState stencilState = device.DepthStencilState;

            device.BlendState        = BlendState.NonPremultiplied;
            device.DepthStencilState = DepthStencilState.DepthRead;

            if (isClipped)
            {
                device.RasterizerState = clippingRasterizeState;
            }
            else
            {
                device.RasterizerState = rasterizeStateGeometry;
            }

            basicEffect.World      = Matrix.CreateTranslation(position.X, position.Y, depth);
            basicEffect.View       = Matrix.CreateLookAt(new Vector3(0.0f, 0.0f, 1.0f), Vector3.Zero, Vector3.Up);
            basicEffect.Projection = Matrix.CreateOrthographicOffCenter(0, (float)device.Viewport.Width, (float)device.Viewport.Height, 0, 1.0f, 1000.0f);

            device.SetVertexBuffer(wcR2Buffer.VertexBuffer);
            foreach (EffectPass pass in basicEffect.CurrentTechnique.Passes)
            {
                pass.Apply();

                switch (buffer.PrimitiveType)
                {
                case GeometryPrimitiveType.TriangleList:
                    device.DrawPrimitives(PrimitiveType.TriangleList, 0, wcR2Buffer.PrimitiveCount);
                    break;

                case GeometryPrimitiveType.TriangleStrip:
                    device.DrawPrimitives(PrimitiveType.TriangleStrip, 0, wcR2Buffer.PrimitiveCount);
                    break;

                case GeometryPrimitiveType.LineList:
                    device.DrawPrimitives(PrimitiveType.LineList, 0, wcR2Buffer.PrimitiveCount);
                    break;

                case GeometryPrimitiveType.LineStrip:
                    device.DrawPrimitives(PrimitiveType.LineStrip, 0, wcR2Buffer.PrimitiveCount);
                    break;

                default:
                    break;
                }
            }

            device.DepthStencilState = stencilState;
            device.BlendState        = blendState;
            device.RasterizerState   = rasState;
        }
Пример #8
0
        /// <summary>
        /// Draws the geometry texture.
        /// </summary>
        /// <param name="buffer">The buffer.</param>
        /// <param name="position">The position.</param>
        /// <param name="texture">The texture.</param>
        /// <param name="opacity">The opacity.</param>
        /// <param name="depth">The depth.</param>
        public override void DrawGeometryTexture(GeometryBuffer buffer, PointF position, TextureBase texture, float opacity, float depth)
        {
            XenkoGeometryBuffer paradoxBuffer = buffer as XenkoGeometryBuffer;
            Texture2D           nativeTexture = texture.GetNativeTexture() as Texture2D;

            paradoxBuffer.EffectInstance.Parameters.Set(SpriteEffectKeys.Color, Color.White * opacity);
            paradoxBuffer.EffectInstance.Parameters.Set(TexturingKeys.Texture0, nativeTexture);
            DrawGeometry(buffer, position, depth);
        }
Пример #9
0
        /// <summary>
        /// Draws the color of the geometry.
        /// </summary>
        /// <param name="buffer">The buffer.</param>
        /// <param name="position">The position.</param>
        /// <param name="color">The color.</param>
        /// <param name="opacity">The opacity.</param>
        /// <param name="depth">The depth.</param>
        public override void DrawGeometryColor(GeometryBuffer buffer, PointF position, ColorW color, float opacity, float depth)
        {
            XenkoGeometryBuffer xenkoBuffer = buffer as XenkoGeometryBuffer;

            Color4 nativeColor = new Color4(color.PackedValue) * opacity;

            xenkoBuffer.EffectInstance.Parameters.Set(SpriteEffectKeys.Color, nativeColor);
            xenkoBuffer.EffectInstance.Parameters.Set(TexturingKeys.Texture0, GraphicsDevice.GetSharedWhiteTexture());
            DrawGeometry(buffer, position, depth);
        }
        /// <summary>
        ///     Finalize the draw calls
        /// </summary>
        public void Commit(Vector3 position, Quaternion rotation, PhysicMaterial material
#if DEBUG
                           , string debugName = null
#endif
                           )
        {
            ReleaseOldData();

            // No data means there's no mesh to build
            if (m_buffers[0].IsEmpty())
            {
                return;
            }

            for (int i = 0; i < m_buffers.Count; i++)
            {
                GeometryBuffer buffer = m_buffers[i];

                // Create a game object for collider. Unfortunatelly, we can't use object pooling
                // here for otherwise, unity would have to rebake because of change in object position
                // and that is very time consuming.
                GameObject prefab = GameObjectProvider.GetPool(m_prefabName).Prefab;
                GameObject go     = Object.Instantiate(prefab);
                go.transform.parent = GameObjectProvider.Instance.ProviderGameObject.transform;

                {
#if DEBUG
                    if (!string.IsNullOrEmpty(debugName))
                    {
                        go.name = debugName;
                        if (i > 0)
                        {
                            go.name = go.name + "_" + i;
                        }
                    }
#endif

                    Mesh mesh = Globals.MemPools.MeshPool.Pop();
                    Assert.IsTrue(mesh.vertices.Length <= 0);
                    UnityMeshBuilder.BuildColliderMesh(mesh, buffer);

                    MeshCollider collider = go.GetComponent <MeshCollider>();
                    collider.sharedMesh         = null;
                    collider.sharedMesh         = mesh;
                    collider.transform.position = position;
                    collider.transform.rotation = rotation;
                    collider.sharedMaterial     = material;

                    m_objects.Add(go);
                    m_colliders.Add(collider);
                }

                buffer.Clear();
            }
        }
Пример #11
0
        public ManagedGeometryBuffer()
        {
            gb = new GeometryBuffer();

            gb.Declarations.Add(new VertexElement(VertexAttribute.Position, VertexDataType.Float, 3));
            gb.Declarations.Add(new VertexElement(VertexAttribute.TexCoord0, VertexDataType.Float, 2));
            gb.Declarations.Add(new VertexElement(VertexAttribute.Color, VertexDataType.Float, 4));
            gb.Declarations.CalculateStrides();

            zcount = -100;
        }
Пример #12
0
        protected override GeometryBuffer CreateGeometryBuffer()
        {
            var gb = new GeometryBuffer();

            gb.Declarations.Add(new VertexElement(VertexAttribute.Position, VertexDataType.Float, 3));
            gb.Declarations.Add(new VertexElement(VertexAttribute.TexCoord0, VertexDataType.Float, 2));
            gb.Declarations.Add(new VertexElement(VertexAttribute.Color, VertexDataType.Byte, 4));
            gb.Declarations.Add(new VertexElement(VertexAttribute.Normal, VertexDataType.Float, 1));
            gb.Declarations.CalculateStrides();
            return(gb);
        }
Пример #13
0
        /// <summary>
        ///     Finalize the draw calls
        /// </summary>
        public void Commit(Vector3 position, Quaternion rotation, Material material
#if DEBUG
                           , string debugName = null
#endif
                           )
        {
            ReleaseOldData();

            // No data means there's no mesh to build
            if (m_buffers[0].IsEmpty())
            {
                return;
            }

            for (int i = 0; i < m_buffers.Count; i++)
            {
                GeometryBuffer buffer = m_buffers[i];

                var go = GameObjectProvider.PopObject(m_prefabName);
                Assert.IsTrue(go != null);
                if (go != null)
                {
#if DEBUG
                    if (!string.IsNullOrEmpty(debugName))
                    {
                        go.name = debugName;
                        if (i > 0)
                        {
                            go.name = go.name + "_" + i;
                        }
                    }
#endif

                    Mesh mesh = Globals.MemPools.MeshPool.Pop();
                    Assert.IsTrue(mesh.vertices.Length <= 0);
                    UnityMeshBuilder.BuildGeometryMesh(mesh, buffer);

                    MeshFilter filter = go.GetComponent <MeshFilter>();
                    filter.sharedMesh         = null;
                    filter.sharedMesh         = mesh;
                    filter.transform.position = position;
                    filter.transform.rotation = rotation;

                    Renderer renderer = go.GetComponent <Renderer>();
                    renderer.material = material;

                    m_objects.Add(go);
                    m_renderers.Add(renderer);
                }

                buffer.Clear();
            }
        }
Пример #14
0
 /// <summary>
 /// Attach vertex buffer routine
 /// </summary>
 /// <param name="context"></param>
 /// <param name="vertStartSlot"></param>
 protected virtual bool OnAttachBuffers(DeviceContextProxy context, ref int vertStartSlot)
 {
     if (GeometryBuffer.AttachBuffers(context, ref vertStartSlot, EffectTechnique.EffectsManager))
     {
         InstanceBuffer.AttachBuffer(context, ref vertStartSlot);
         return(true);
     }
     else
     {
         return(false);
     }
 }
Пример #15
0
 public void BuildMesh()
 {
     if(obj) {
         buffer = new GeometryBuffer(quadMode);
         SetGeometryData(obj.text);
         if(mtl)
             SetMaterialData(mtl.text);
         else
             SetMaterialData("");
         Build();
         //buffer.Trace();
     }
 }
Пример #16
0
        /// <summary>
        ///     Copy render geometry data to a Unity mesh
        /// </summary>
        public static void BuildGeometryMesh(Mesh mesh, GeometryBuffer buffer)
        {
            int size = buffer.Vertices.Count;

            // Avoid allocations by retrieving buffers from the pool
            Vector3[] vertices = Globals.MemPools.PopVector3Array(size);
            Vector2[] uvs      = Globals.MemPools.PopVector2Array(size);
            Color32[] colors   = Globals.MemPools.PopColor32Array(size);
            Vector3[] normals  = Globals.MemPools.PopVector3Array(size);
            Vector4[] tangents = Globals.MemPools.PopVector4Array(size);

            // Fill buffers with data
            for (int i = 0; i < size; i++)
            {
                VertexDataFixed vertexData = buffer.Vertices[i];
                vertices[i] = vertexData.Vertex;
                uvs[i]      = vertexData.UV;
                colors[i]   = vertexData.Color;
                normals[i]  = vertexData.Normal;
                tangents[i] = vertexData.Tangent;
            }

            // Due to the way the memory pools work we might have received more
            // data than necessary. This little overhead is well worth it, though.
            // Fill unused data with "zeroes"
            for (int i = size; i < vertices.Length; i++)
            {
                vertices[i] = Vector3.zero;
                uvs[i]      = Vector2.zero;
                colors[i]   = Color.clear;
                normals[i]  = Vector3.zero;
                tangents[i] = Vector4.zero;
            }

            // Prepare mesh
            mesh.vertices = vertices;
            mesh.uv       = uvs;
            mesh.colors32 = colors;
            mesh.normals  = normals;
            mesh.tangents = tangents;
            mesh.SetTriangles(buffer.Triangles, 0);
            mesh.RecalculateNormals();
            mesh.Optimize();

            // Return memory back to pool
            Globals.MemPools.PushVector3Array(vertices);
            Globals.MemPools.PushVector2Array(uvs);
            Globals.MemPools.PushColor32Array(colors);
            Globals.MemPools.PushVector3Array(normals);
            Globals.MemPools.PushVector4Array(tangents);
        }
Пример #17
0
    void Start ()
    {
		text = GameObject.Find("Text");
		/* Start of modifyed code
		* Andrey Roth Ehrenberg
		* Centro Universitário Senac - 2013
		* Programa de iniciaçao científica
		*/
		//String do Caminho completo
			string caminhoCompleto = Application.dataPath;
		//Pega o caminhoCompleto e corta as duas テコ últimas barras e assimila esse valor ao caminhoBase
			//Se for para a versao de desenvolvimento (Debug)
		string caminhoBase = (caminhoCompleto.IndexOf("/") == -1) ? "" : caminhoCompleto.Substring(0, caminhoCompleto.LastIndexOf("/") + 1);
			//Se for para a versao compilada
		/*
		string caminhoBase = "";
		if(caminhoCompleto.IndexOf('/') == -1){
			caminhoBase = "";		
		}
		
		else {
		Debug.Log(caminhoCompleto);
			caminhoCompleto = caminhoCompleto.Substring(0, caminhoCompleto.LastIndexOf("/"));
			//caminhoBase = caminhoCompleto.Substring(0, caminhoCompleto.LastIndexOf("/"));
			caminhoBase = caminhoCompleto;
		Debug.Log(caminhoBase);
		}
		*/
		//Obtém a informaçao do caminho base
		DirectoryInfo dir = new DirectoryInfo(caminhoBase);
		//Captura todos os arquivos com .obj no final
		FileInfo[] info = dir.GetFiles("*.obj*");
		//Para cada arquivo em info:
		objPath = info[0].FullName;
		//objPath = info[0].DirectoryName+'/'+info[0].Name;
		//text.guiText.text = caminhoBase;
	 	//End of the modifyed code

        buffer = new GeometryBuffer ();
        //ALTERATION 0:- To Cater for Local Files.
        if (!objPath.Contains("http://")) {
                basepath=Path.GetDirectoryName(objPath);
                objPath="file:///"+objPath;
                basepath="file:///"+basepath+Path.DirectorySeparatorChar;
        } else {
                basepath = (objPath.IndexOf("/") == -1) ? "" : objPath.Substring(0, objPath.LastIndexOf("/") + 1);
        }
        StartCoroutine (Load (objPath));
    }
Пример #18
0
        /// <summary>
        /// Draws the geometry texture.
        /// </summary>
        /// <param name="buffer">The buffer.</param>
        /// <param name="position">The position.</param>
        /// <param name="texture">The texture.</param>
        /// <param name="opacity">The opacity.</param>
        /// <param name="depth">The depth.</param>
        public override void DrawGeometryTexture(GeometryBuffer buffer, PointF position, TextureBase texture, float opacity, float depth)
        {
            if (basicEffect == null)
            {
                basicEffect = new BasicEffect(GraphicsDevice);
            }

            basicEffect.Alpha              = opacity;
            basicEffect.DiffuseColor       = new Vector3(1, 1, 1);
            basicEffect.Texture            = texture.GetNativeTexture() as Texture2D;
            basicEffect.VertexColorEnabled = false;
            basicEffect.TextureEnabled     = true;

            DrawGeometry(buffer, position, depth);
        }
Пример #19
0
        /// <summary>
        /// Draws the color of the geometry.
        /// </summary>
        /// <param name="buffer">The buffer.</param>
        /// <param name="position">The position.</param>
        /// <param name="color">The color.</param>
        /// <param name="opacity">The opacity.</param>
        /// <param name="depth">The depth.</param>
        public override void DrawGeometryColor(GeometryBuffer buffer, PointF position, ColorW color, float opacity, float depth)
        {
            if (basicEffect == null)
            {
                basicEffect = new BasicEffect(GraphicsDevice);
            }

            basicEffect.Alpha = color.A / (float)byte.MaxValue * opacity;
            //color = color * effect.Alpha;
            basicEffect.DiffuseColor       = new Vector3(color.R / (float)byte.MaxValue, color.G / (float)byte.MaxValue, color.B / (float)byte.MaxValue);
            basicEffect.TextureEnabled     = false;
            basicEffect.VertexColorEnabled = true;

            DrawGeometry(buffer, position, depth);
        }
Пример #20
0
        /// <summary>
        ///     Clear all draw calls
        /// </summary>
        public void Clear()
        {
            for (int i = 0; i < m_buffers.Count; i++)
            {
                GeometryBuffer buffer = m_buffers[i];
                if (!buffer.IsEmpty())
                {
                    m_buffers[i].Clear();
                }
            }

            ReleaseOldData();

            m_visible = false;
        }
Пример #21
0
        /// <summary>
        ///     Finalize the draw calls
        /// </summary>
        public void Commit()
        {
            ReleaseOldData();

            // No data means there's no mesh to build
            if (m_buffers[0].IsEmpty())
            {
                return;
            }

            for (int i = 0; i < m_buffers.Count; i++)
            {
                GeometryBuffer buffer = m_buffers[i];

                var go = GameObjectProvider.PopObject(GOPChunk);
                Assert.IsTrue(go != null);
                if (go != null)
                {
#if DEBUG
                    if (EngineSettings.CoreConfig.Mutlithreading == false)
                    {
                        go.name = m_chunk.Pos.ToString();
                    }
#endif

                    Mesh mesh = Globals.MemPools.MeshPool.Pop();
                    Assert.IsTrue(mesh.vertices.Length <= 0);
                    m_meshBuilder.BuildMesh(mesh, buffer);

                    MeshFilter filter = go.GetComponent <MeshFilter>();
                    filter.sharedMesh         = null;
                    filter.sharedMesh         = mesh;
                    filter.transform.position = Vector3.zero;
                    filter.transform.rotation = Quaternion.identity;

                    Renderer renderer = go.GetComponent <Renderer>();
                    //renderer.material = m_chunk.world.chunkMaterial;

                    m_objects.Add(go);
                    m_renderers.Add(renderer);
                }

                buffer.Clear();
            }
        }
Пример #22
0
 ///Initialiser
 void Start()
 {
     buffer = new GeometryBuffer();
     if (objPath != "")
     {
         if (!objPath.Contains("http://"))
         {
             basepath = Path.GetDirectoryName(objPath);
             objPath  = "file://" + objPath;
             basepath = "file://" + basepath + Path.DirectorySeparatorChar;
         }
         else
         {
             basepath = (objPath.IndexOf("/") == -1) ? "" : objPath.Substring(0, objPath.LastIndexOf("/") + 1);
         }
         StartCoroutine(Load(objPath));
     }
 }
Пример #23
0
        /// <summary>
        ///     Addds one face to our render buffer
        /// </summary>
        /// <param name="vertexData"> An array of 4 vertices forming the face</param>
        public void AddFace(VertexDataFixed[] vertexData)
        {
            Assert.IsTrue(vertexData.Length >= 4);

            GeometryBuffer buffer = m_buffers[m_buffers.Count - 1];

            // If there are too many vertices we need to create a new separate buffer for them
            if (buffer.Vertices.Count + 4 > 65000)
            {
                buffer = new GeometryBuffer();
                m_buffers.Add(buffer);
            }

            // Add data to the render buffer
            buffer.AddVertex(ref vertexData[0]);
            buffer.AddVertex(ref vertexData[1]);
            buffer.AddVertex(ref vertexData[2]);
            buffer.AddVertex(ref vertexData[3]);
            buffer.AddIndices(buffer.Vertices.Count, false);
        }
Пример #24
0
        public GeometryPass(GeometryBuffer myBuffer, RenderPass OffscreenRenderPass, SecondaryCommandBufferPool mySecondaryCommandPool, ShaderManager myShaderManager) : base(mySecondaryCommandPool, "GeometryPass")
        {
            this.myShaderManager  = myShaderManager;
            myRenderpassBeginInfo = new RenderPassBeginInfo
            {
                ClearValueCount = 4,
                ClearValues     = new ClearValue[]
                {
                    new ClearValue {
                        Color = new ClearColorValue(Color.AliceBlue)
                    },                                                               //TODO: Always remember to match these!
                    new ClearValue {
                        Color = new ClearColorValue(Color.AliceBlue)
                    },                                                               //TODO: Always remember to match these!
                    new ClearValue {
                        Color = new ClearColorValue(Color.AliceBlue)
                    },                                                               //TODO: Always remember to match these!
                    new ClearValue {
                        DepthStencil = new ClearDepthStencilValue()
                        {
                            Depth = 1.0f, Stencil = 0
                        }
                    }
                },
                RenderPass = OffscreenRenderPass,
                RenderArea = new Rect2D {
                    Extent = new Extent2D {
                        Width = VulkanRenderer.Surface.SurfaceCapabilities.CurrentExtent.Width, Height = VulkanRenderer.Surface.SurfaceCapabilities.CurrentExtent.Height
                    }, Offset = new Offset2D {
                        X = 0, Y = 0
                    }
                },
            };
            myBackbuffer = myBuffer;
            myRenderpassBeginInfo.Framebuffer = myBackbuffer;
            String[] ShaderNames = { "GBufferPassVertex", "GBufferPassFragment" };
            Tuple <PipelineLayout, Pipeline> myPipelineDefault = myShaderManager.CreatePipeline(OffscreenRenderPass, ShaderNames, out ExpectedModelSet);

            myActivePipelines.Add("Default", myPipelineDefault);
            this.OffscreenRenderPass = OffscreenRenderPass;
        }
Пример #25
0
        static public ModelGeometry Load(string objPath)
        {
            if (CachedModels.ContainsKey(objPath))
            {
                return(CachedModels[objPath]);
            }

            string         l;
            GeometryBuffer gBuffer = new GeometryBuffer();

            using (StreamReader sr = new StreamReader(objPath)) {
                while ((l = sr.ReadLine()) != null)
                {
                    ProcessOBJLine(gBuffer, l);
                }
            }
            ModelGeometry MG = gBuffer.GetGeometry();

            CachedModels.Add(objPath, MG);
            //Engine.Log("ModelGeometry.Count = " + MG.Count.ToString());

            return(MG);
        }
Пример #26
0
        protected override void OnUpdate(RenderContext context, DeviceContextProxy deviceContext)
        {
            if (preComputeBoneSkinPass.IsNULL || preComputeBoneBuffer == null || !preComputeBoneBuffer.CanPreCompute || !matricsChanged)
            {
                return;
            }
            var buffer = sharedBoneBuffer ?? internalBoneBuffer;

            if (buffer.BoneMatrices.Length == 0)
            {
                preComputeBoneBuffer.ResetSkinnedVertexBuffer(deviceContext);
            }
            else
            {
                GeometryBuffer.UpdateBuffers(deviceContext, EffectTechnique.EffectsManager);
                preComputeBoneBuffer.BindSkinnedVertexBufferToOutput(deviceContext);
                buffer.Update(context, deviceContext);
                preComputeBoneSkinPass.BindShader(deviceContext);
                buffer.BindBuffer(deviceContext, boneSkinSBSlot);
                deviceContext.Draw(GeometryBuffer.VertexBuffer[0].ElementCount, 0);
                preComputeBoneBuffer.UnBindSkinnedVertexBufferToOutput(deviceContext);
            }
            matricsChanged = false;
        }
Пример #27
0
        private void ProcessObj(string eboPath, Cube cube)
        {
            var objpath = eboPath + "?fmt=obj";
            GeometryBuffer buffer = new GeometryBuffer();
            cube.MaterialData = new List<MaterialData>();

            RestClient client = new RestClient(objpath);
            RestRequest request = new RestRequest(Method.GET);
            request.AddHeader("Accept-Encoding", "gzip, deflate");
            client.ExecuteAsync(request, (r, h) =>
            {
                if (r.Content != null)
                {
                    CubeBuilderHelpers.SetGeometryData(r.Content, buffer);
                    cube.Buffer = buffer;

                    _buildingQueue.Enqueue(cube);
                    _textureQueue.Enqueue(cube);
                }
            });
        }
Пример #28
0
 void Start()
 {
     buffer = new GeometryBuffer ();
     StartCoroutine (Load (objPath));
 }
Пример #29
0
        private void DrawGeometry(GeometryBuffer buffer, PointF position, float depth)
        {
            if (isSpriteRenderInProgress)
            {
                spriteBatch.End();
            }

            Matrix world = Matrix.Translation(position.X, position.Y, 0);

            Matrix worldView;

            Matrix.MultiplyTo(ref world, ref view, out worldView);

            Matrix worldViewProjection;

            UpdateProjection(graphicsContext.CommandList);
            Matrix.MultiplyTo(ref worldView, ref projection, out worldViewProjection);

            XenkoGeometryBuffer paradoxBuffer = buffer as XenkoGeometryBuffer;

            paradoxBuffer.EffectInstance.Parameters.Set(SpriteBaseKeys.MatrixTransform, worldViewProjection);

            if (isClipped)
            {
                geometryPipelineState.State.RasterizerState = scissorRasterizerStateDescription;
            }
            else
            {
                geometryPipelineState.State.RasterizerState = geometryRasterizerStateDescription;
            }

            switch (buffer.PrimitiveType)
            {
            case GeometryPrimitiveType.TriangleList:
                geometryPipelineState.State.PrimitiveType = PrimitiveType.TriangleList;
                break;

            case GeometryPrimitiveType.TriangleStrip:
                geometryPipelineState.State.PrimitiveType = PrimitiveType.TriangleStrip;
                break;

            case GeometryPrimitiveType.LineList:
                geometryPipelineState.State.PrimitiveType = PrimitiveType.LineList;
                break;

            case GeometryPrimitiveType.LineStrip:
                geometryPipelineState.State.PrimitiveType = PrimitiveType.LineStrip;
                break;

            default:
                break;
            }

            geometryPipelineState.State.RootSignature  = paradoxBuffer.EffectInstance.RootSignature;
            geometryPipelineState.State.EffectBytecode = paradoxBuffer.EffectInstance.Effect.Bytecode;
            geometryPipelineState.State.InputElements  = paradoxBuffer.InputElementDescriptions;
            geometryPipelineState.State.Output.CaptureState(graphicsContext.CommandList);
            geometryPipelineState.Update();
            graphicsContext.CommandList.SetPipelineState(geometryPipelineState.CurrentState);
            paradoxBuffer.EffectInstance.Apply(graphicsContext);

            graphicsContext.CommandList.SetVertexBuffer(0, paradoxBuffer.VertexBufferBinding.Buffer, 0, paradoxBuffer.VertexBufferBinding.Stride);
            graphicsContext.CommandList.Draw(paradoxBuffer.PrimitiveCount);

            if (isSpriteRenderInProgress)
            {
                if (isClipped)
                {
                    spriteBatch.Begin(graphicsContext, SpriteSortMode.Deferred,
                                      depthStencilState: DepthStencilStates.None, rasterizerState: scissorRasterizerStateDescription, effect: currentActiveEffect);
                }
                else
                {
                    spriteBatch.Begin(graphicsContext, SpriteSortMode.Deferred, depthStencilState: DepthStencilStates.None, effect: currentActiveEffect);
                }
            }
        }
Пример #30
0
    /*
     * This is the major OBJ API to load obj and build body
     */
    private IEnumerator Load(string path, bool load_local)
    {
        bool update_local = !load_local;
        if (load_local)
        {
            if (!obj_path.StartsWith("file:"))
                path = "file://" + obj_path;
        }

        mtllib = null;

        renderer.enabled = false;
        if (buffer != null)
            buffer.Release();
        buffer = new GeometryBuffer();
        //load obj file
        string basepath = (path.IndexOf("/") == -1) ? "" : path.Substring(0, path.LastIndexOf("/") + 1);
        if (text != null)
        {
            text.enabled = true;
            text.text = "loading " + path;
        }
        Debug.Log(DateTime.Now.Second + "." + DateTime.Now.Millisecond + "paoku load obj:" + path);
        WWW loader = new WWW(path);
        yield return loader;

        if (loader.error != null)
        {
            Debug.Log(DateTime.Now.Second + "paoku load model failed" + loader.error);
            if (text!=null)
                text.text = loader.error;
            yield break;
        }

        Debug.Log(DateTime.Now.Second + "." + DateTime.Now.Millisecond + "paoku is decoding obj file");
        SetGeometryData(loader.text);
        if (update_local)
        {
            Debug.Log("update local obj:" + obj_path);
            FileStream fileStream = new FileStream(obj_path, FileMode.Create);
            fileStream.Write(loader.bytes, 0, loader.bytes.Length);
            fileStream.Close();
        }

        if(hasMaterials) {
            //load material
            if (load_local)
                mtllib = mtl_path;
            if (mtllib.StartsWith("./"))
                mtllib = mtllib.Substring(2);
            if (text != null)
                text.text = "loading " + basepath + mtllib;
            Debug.Log("paoku load material:" + basepath + mtllib);
            loader = new WWW(basepath + mtllib);
            yield return loader;
            if (loader.text == null)
            {
                Debug.Log("paoku load material fail");
                yield break;
            }

            SetMaterialData(loader.text);
            if (update_local)
            {
                string bpath = (obj_path.IndexOf("/") == -1) ? "" : obj_path.Substring(0, obj_path.LastIndexOf("/") + 1);
                Debug.Log("update local material:" + bpath + mtl_path);
                FileStream fileStream = new FileStream(bpath+mtl_path, FileMode.Create);
                fileStream.Write(loader.bytes, 0, loader.bytes.Length);
                fileStream.Close();
            }
            //load texture
            foreach(MaterialData m in materialData) {
                if (load_local)
                    m.diffuseTexPath = img_path;
                if(m.diffuseTexPath != null) {
                    if (text!=null)
                        text.text = "loading " + basepath + m.diffuseTexPath;
                    Debug.Log("paoku load texture:" + basepath + m.diffuseTexPath);
                    WWW texloader = new WWW(basepath + m.diffuseTexPath);
                    yield return texloader;
                    if (texloader.texture == null)
                    {
                        Debug.Log("paoku load texture fail");
                        yield break;
                    }
                    m.diffuseTex = texloader.texture;
                    if (update_local)
                    {
                        string bpath = (obj_path.IndexOf("/") == -1) ? "" : obj_path.Substring(0, obj_path.LastIndexOf("/") + 1);
                        Debug.Log("update local texture:" + bpath + img_path);
                        FileStream fileStream = new FileStream(bpath+img_path, FileMode.Create);
                        fileStream.Write(texloader.bytes, 0, texloader.bytes.Length);
                        fileStream.Close();
                    }
                }
            }
        }
        if (text!=null)
            text.enabled = false;

        Build();
        renderer.enabled = true;

        #if STANDALONE_DEBUG
        CameraMove3D c3d = GameObject.Find("Main Camera").GetComponent("CameraMove3D") as CameraMove3D;
        c3d.StartObserve();
        #endif
        load_state = LoadState.RUNNING;
    }
Пример #31
0
 void Start()
 {
     if(objPath != ""){
         buffer = new GeometryBuffer(quadMode);
         StartCoroutine (Load (objPath));
     }
 }
Пример #32
0
        private IEnumerator ProcessLoadCubeRequest(LoadCubeRequest loadRequest)
        {
            DebugLog("+LoadCube(L{3}:{0}_{1}_{2})", loadRequest.X, loadRequest.Y, loadRequest.Z, loadRequest.Lod);
            var modelPath = loadRequest.Query.GetModelPath(loadRequest.Lod, loadRequest.X, loadRequest.Y, loadRequest.Z);
            var pyriteLevel =
                loadRequest.Query.DetailLevels[loadRequest.Lod];

            var buffer = new GeometryBuffer();

            WWW loader;
            if (!UseEbo)
            {
                if (!_objCache.ContainsKey(modelPath))
                {
                    _objCache[modelPath] = null;
                    yield return StartCoroutine(StartRequest(modelPath));
                    if (!UseWww)
                    {
                        var client = new RestClient(modelPath);
                        var request = new RestRequest(Method.GET);
                        request.AddHeader("Accept-Encoding", "gzip, deflate");
                        client.ExecuteAsync(request, (r, h) =>
                        {
                            LogResponseError(r, modelPath);
                            if (r.RawBytes != null)
                            {
                                _objCache[modelPath] = r.Content;
                            }
                            else
                            {
                                Debug.LogError("Error getting model data");
                            }
                        });
                    }
                    else
                    {
                        loader = WwwExtensions.CreateWWW(modelPath + "?fmt=obj", true);
                        yield return loader;
                        LogWwwError(loader, modelPath);
                        _objCache[modelPath] = loader.GetDecompressedText();
                    }
                    while (_objCache[modelPath] == null)
                    {
                        yield return null;
                    }
                    EndRequest(modelPath);
                }
                while (_objCache[modelPath] == null)
                {
                    yield return null;
                }
                CubeBuilderHelpers.SetGeometryData(_objCache[modelPath], buffer);
            }
            else
            {
                if (!_eboCache.ContainsKey(modelPath))
                {
                    _eboCache[modelPath] = null;
                    yield return StartCoroutine(StartRequest(modelPath));
                    if (!UseWww)
                    {
                        var client = new RestClient(modelPath);
                        var request = new RestRequest(Method.GET);
                        client.ExecuteAsync(request, (r, h) =>
                        {
                            LogResponseError(r, modelPath);
                            if (r.RawBytes != null)
                            {
                                _eboCache[modelPath] = r.RawBytes;
                            }
                            else
                            {
                                Debug.LogError("Error getting model data");
                            }
                        });
                    }
                    else
                    {
                        loader = WwwExtensions.CreateWWW(modelPath);
                        yield return loader;
                        LogWwwError(loader, modelPath);
                        _eboCache[modelPath] = loader.GetDecompressedBytes();
                    }
                    while (_eboCache[modelPath] == null)
                    {
                        yield return null;
                    }
                    EndRequest(modelPath);
                }
                // Loop while other tasks finish getting ebo data
                while (_eboCache[modelPath] == null)
                {
                    // Another task is in the process of filling out this cache entry.
                    // Loop until it is set
                    yield return null;
                }
                buffer.EboBuffer = _eboCache[modelPath];
            }

            var textureCoordinates = pyriteLevel.TextureCoordinatesForCube(loadRequest.X, loadRequest.Y);
            var materialDataKey = string.Format("model.mtl_{0}_{1}_{2}", textureCoordinates.x, textureCoordinates.y,
                loadRequest.Lod);
            if (!_materialDataCache.ContainsKey(materialDataKey))
            {
                var materialData = new List<MaterialData>();
                _materialDataCache[materialDataKey] = null;
                CubeBuilderHelpers.SetDefaultMaterialData(materialData, (int) textureCoordinates.x,
                    (int) textureCoordinates.y, loadRequest.Lod);

                foreach (var m in materialData)
                {
                    var texturePath = loadRequest.Query.GetTexturePath(loadRequest.Query.GetLodKey(loadRequest.Lod),
                        (int) textureCoordinates.x,
                        (int) textureCoordinates.y);
                    if (!_textureCache.ContainsKey(texturePath))
                    {
                        // Set to null to signal to other tasks that the key is in the process
                        // of being filled
                        _textureCache[texturePath] = null;
                        yield return StartCoroutine(StartRequest(texturePath));
                        byte[] textureData = null;
                        if (!UseWww)
                        {
                            var client = new RestClient(texturePath);
                            var request = new RestRequest(Method.GET);
                            client.ExecuteAsync(request, (r, h) =>
                            {
                                LogResponseError(r, texturePath);
                                if (r.RawBytes != null)
                                {
                                    textureData = r.RawBytes;
                                }
                                else
                                {
                                    Debug.LogError("Error getting texture data");
                                }
                            });
                        }
                        else
                        {
                            // Do not request compression for textures
                            var texloader = WwwExtensions.CreateWWW(texturePath, false);
                            yield return texloader;
                            LogWwwError(texloader, texturePath);
                            textureData = texloader.bytes;
                        }

                        while (textureData == null)
                        {
                            yield return null;
                        }

                        var texture = new Texture2D(1, 1, TextureFormat.DXT1, false);
                        texture.LoadImage(textureData);
                        _textureCache[texturePath] = texture;
                        EndRequest(texturePath);
                    }

                    // Loop while other tasks finish creating texture
                    while (_textureCache[texturePath] == null)
                    {
                        // Another task is in the process of filling out this cache entry.
                        // Loop until it is set
                        yield return null;
                    }
                    m.DiffuseTex = _textureCache[texturePath];
                }
                _materialDataCache[materialDataKey] = materialData;
            }
            while (_materialDataCache[materialDataKey] == null)
            {
                // Another task is in the process of filling out this cache entry.
                // Loop until it is set
                yield return null;
            }
            Build(buffer, _materialDataCache[materialDataKey], loadRequest.X, loadRequest.Y, loadRequest.Z,
                loadRequest.Lod, loadRequest.RegisterCreatedObjects);
            DebugLog("-LoadCube(L{3}:{0}_{1}_{2})", loadRequest.X, loadRequest.Y, loadRequest.Z, loadRequest.Lod);
        }
Пример #33
0
        private void Build(GeometryBuffer buffer, List<MaterialData> materialData, int x, int y, int z, int lod,
            Action<GameObject[]> registerCreatedObjects)
        {
            var materials = new Dictionary<string, Material[]>();

            foreach (var md in materialData)
            {
                if (!_materialCache.ContainsKey(md.Name))
                {
                    _materialCache[md.Name] = CubeBuilderHelpers.GetMaterial(UseUnlitShader, md);
                }
                materials.Add(md.Name, _materialCache[md.Name]);
            }

            var ms = new GameObject[buffer.NumObjects];

            for (var i = 0; i < buffer.NumObjects; i++)
            {
                var go = new GameObject();
                go.name = String.Format("cube_L{4}:{0}_{1}_{2}.{3}", x, y, z, i, lod);
                go.transform.parent = gameObject.transform;
                go.AddComponent(typeof (MeshFilter));
                go.AddComponent(typeof (MeshRenderer));
                ms[i] = go;
            }

            if (registerCreatedObjects != null)
            {
                registerCreatedObjects(ms);
            }

            buffer.PopulateMeshes(ms, materials);
        }
Пример #34
0
 void Start()
 {
     buffer = new GeometryBuffer();
 }
Пример #35
0
	public IEnumerator Load(string path) {
        renderer.enabled = false;
        if (buffer != null)
            buffer.Release();
        buffer = new GeometryBuffer();
        mtllib = null;
		string basepath = (path.IndexOf("/") == -1) ? "" : path.Substring(0, path.LastIndexOf("/") + 1);
        if (text != null)
        {
            text.enabled = true;
            text.text = "loading " + path;
        }        
        Debug.Log(DateTime.Now.Second + "." + DateTime.Now.Millisecond + "paoku load " + path);
        WWW loader = new WWW(path);        
        yield return loader;

        if (loader.error != null)
        {
            Debug.Log(DateTime.Now.Second + "paoku load model failed" + loader.error);
            if (text!=null)
                text.text = loader.error;
            yield break;
        }
            
        Debug.Log(DateTime.Now.Second + "." + DateTime.Now.Millisecond + "paoku is decoding obj file");
        SetGeometryData(loader.text);                 

		if(hasMaterials) {
            if (mtllib.StartsWith("./"))
                mtllib = mtllib.Substring(2);
            if (text != null)
                text.text = "loading " + basepath + mtllib;
            Debug.Log("paoku load " + basepath + mtllib);
            loader = new WWW(basepath + mtllib);
            yield return loader;
            if (loader.text == null)
            {
                Debug.Log("paoku load material fail");
                yield break;
            }

            SetMaterialData(loader.text);
			
			foreach(MaterialData m in materialData) {
				if(m.diffuseTexPath != null) {
                    if (text!=null)
                        text.text = "loading " + basepath + m.diffuseTexPath;
                    Debug.Log("paoku load " + basepath + m.diffuseTexPath);
					WWW texloader = new WWW(basepath + m.diffuseTexPath);
					yield return texloader;
                    if (texloader.texture == null)
                    {
                        Debug.Log("paoku load texture fail");
                        yield break;
                    }                        
					m.diffuseTex = texloader.texture;
				}
			}
		}
        if (text!=null)
            text.enabled = false;		
        
		Build();
        renderer.enabled = true;
        
#if STANDALONE_DEBUG
        CameraMove3D c3d = GameObject.Find("Main Camera").GetComponent("CameraMove3D") as CameraMove3D;
        c3d.StartObserve();
#endif
        load_state = LoadState.IDLE;
	}
Пример #36
0
 public override void DrawGeometry(GeometryBuffer buffer, TextureBase texture, Renderer renderer, double elapsedGameTime, PointF position, float opacity)
 {
     throw new NotImplementedException();
 }
Пример #37
0
        protected ManagedGeometryBuffer()
        {
            gb = CreateGeometryBuffer();

            batches = new Dictionary<uint, BatchInfo>();
            materials = new Dictionary<uint, ResourceHandle<Material>>();
        }
Пример #38
0
        public override void UnprojectPoint(GeometryBuffer buff, Vector2 pIn, out Vector2 pOut)
        {
            if (!d_matrixValid)
            {
                UpdateMatrix();
            }

            var gb = (OpenGLGeometryBufferBase)buff;

            var vp = new[] { (int)d_area.Left, (int)d_area.Top, (int)d_area.Width, (int)d_area.Height };

            var viewPort    = new Vector4(vp[0], vp[1], vp[2], vp[3]);
            var projMatrix  = d_matrix;
            var modelMatrix = gb.GetModelMatrix();
            var wvp         = modelMatrix * Matrix.Identity * projMatrix;

            // unproject the ends of the ray
            var inX          = vp[2] * 0.5f;
            var inY          = vp[3] * 0.5f;
            var inZ          = -d_viewDistance;
            var unprojected1 = Vector3.Unproject(new Vector3(inX, inY, inZ),
                                                 viewPort.X, viewPort.Y, viewPort.Z, viewPort.W, 0f,
                                                 1f,
                                                 wvp);

            inX = pIn.X;
            inY = vp[3] - pIn.Y;
            inZ = 0.0f;
            var unprojected2 = Vector3.Unproject(new Vector3(inX, inY, inZ),
                                                 viewPort.X, viewPort.Y, viewPort.Z, viewPort.W, 0f,
                                                 1f,
                                                 wvp);

            // project points to orientate them with GeometryBuffer plane
            inX = 0.0f;
            inY = 0.0f;
            var projected1 = Vector3.Project(new Vector3(inX, inY, inZ),
                                             viewPort.X, viewPort.Y, viewPort.Z, viewPort.W, 0f, 1f,
                                             wvp);

            inX = 1.0f;
            inY = 0.0f;
            var projected2 = Vector3.Project(new Vector3(inX, inY, inZ),
                                             viewPort.X, viewPort.Y, viewPort.Z, viewPort.W, 0f, 1f,
                                             wvp);

            inX = 0.0f;
            inY = 1.0f;
            var projected3 = Vector3.Project(new Vector3(inX, inY, inZ),
                                             viewPort.X, viewPort.Y, viewPort.Z, viewPort.W, 0f, 1f,
                                             wvp);

            // calculate vectors for generating the plane
            var pv1 = projected2 - projected1;
            var pv2 = projected3 - projected1;
            // given the vectors, calculate the plane normal
            var planeNormal = Vector3.Cross(pv1, pv2);
            // calculate plane
            var planeNormalNormalized = Vector3.Normalize(planeNormal);
            var pl_d = -Vector3.Dot(projected1, planeNormalNormalized);
            // calculate vector of picking ray
            var rv = unprojected1 - unprojected2;
            // calculate intersection of ray and plane
            var pn_dot_r1 = Vector3.Dot(unprojected1, planeNormal);
            var pn_dot_rv = Vector3.Dot(rv, planeNormal);
            var tmp1      = pn_dot_rv != 0.0 ? (pn_dot_r1 + pl_d) / pn_dot_rv : 0.0;
            var isX       = unprojected1.X - rv.X * tmp1;
            var isY       = unprojected1.Y - rv.Y * tmp1;

            pOut = new Vector2((float)isX, (float)isY);
        }
Пример #39
0
        private void ProcessEbo(string eboPath, Cube cube)
        {
            GeometryBuffer buffer = new GeometryBuffer();
            cube.MaterialData = new List<MaterialData>();

            RestClient client = new RestClient(eboPath);
            RestRequest request = new RestRequest(Method.GET);
            request.AddHeader("Accept-Encoding", "gzip, deflate");
            client.ExecuteAsync(request, (r, h) =>
            {
                if (r.RawBytes != null)
                {
                    buffer.EboBuffer = r.RawBytes;
                    cube.Buffer = buffer;

                    _buildingQueue.Enqueue(cube);
                    _textureQueue.Enqueue(cube);
                }
            });
        }
Пример #40
0
 protected override GeometryBuffer CreateGeometryBuffer()
 {
     var gb = new GeometryBuffer();
     gb.Declarations.Add(new VertexElement(VertexAttribute.Position, VertexDataType.Float, 3));
     gb.Declarations.Add(new VertexElement(VertexAttribute.TexCoord0, VertexDataType.Float, 2));
     gb.Declarations.Add(new VertexElement(VertexAttribute.Color, VertexDataType.Byte, 4));
     gb.Declarations.Add(new VertexElement(VertexAttribute.Normal, VertexDataType.Float, 1));
     gb.Declarations.CalculateStrides();
     return gb;
 }
        /// <summary>
        ///
        /// </summary>
        /// <param name="LogicalDevice"></param>
        /// <param name="DescriptorPoolManager">Since it's possible for one device to support both the compute and the rendering, the VulkanInitializer will decide and send it to us. </param>
        /// <param name="PhysicalDevice"></param>
        /// <param name="MainGraphicsQueue"></param>
        /// <param name="mySettings"></param>
        public VulkanRenderer(LightingManager myManager, SurfaceKHR Surface, VulkanInstance myInstance, VulkanLogicalDevice LogicalDevice, DescriptorSetPoolManager DescriptorPoolManager, VulkanPhysicalDevice PhysicalDevice, Engine.Renderer.Vulkan.Queue MainGraphicsQueue, GraphicsSettings mySettings)
        {
            #region Variables from Initializer, Fences, Semaphores
            GlobalLightingManager  = myManager;
            VulkanRenderer.Surface = Surface;
            VulkanRenderer.Window  = myInstance;
            VulkanRenderer.SelectedLogicalDevice  = LogicalDevice;
            VulkanRenderer.SelectedPhysicalDevice = PhysicalDevice;
            //For now we'll only support one main Graphics Queue that may or may not be used in other places like the Compute Shader. Depends on graphics card.
            GraphicsQueue = MainGraphicsQueue;
            ActiveGraphicsFamilyQueueIndex = GraphicsQueue.QueueFamilyIndex;
            //Creates Debug Camera

            this.ActiveCamera = new CameraComponent(); //TODO: Remove after debug phase is finally over.

            VulkanRenderer.Viewport = new Viewport
            {
                Width    = mySettings.SCREEN_WIDTH,
                Height   = mySettings.SCREEN_HEIGHT,
                MinDepth = 0,
                MaxDepth = 1.0f,
            };
            FenceCreateInfo fenceInfo = new FenceCreateInfo();
            DrawingFence = VulkanRenderer.SelectedLogicalDevice.CreateFence(fenceInfo);
            OffscreenRenderFinishedSemaphore = VulkanRenderer.SelectedLogicalDevice.CreateSemaphore(new SemaphoreCreateInfo());
            #endregion
            #region Vulkan Pools and Queues Initialization
            myDescriptorPoolManager = DescriptorPoolManager;
            myShaderManager         = new ShaderManager(myDescriptorPoolManager);
            myFramebufferManager    = new FrameBufferManager(mySettings.SCREEN_WIDTH, mySettings.SCREEN_HEIGHT);//TODO: Needed?
            myModelResourceManager  = new ResourceSetManager();
            mySwapchain             = new SwapchainManager(LogicalDevice, Surface.SelectedSurfaceFormat);
            PrimaryCommandPool      = new PrimaryCommandBufferPool(LogicalDevice, GraphicsQueue.QueueFamilyIndex, 1);
            int Count = LogicalDevice.QueueManager.GetFreeQueueCount(QueueFlags.Graphics);
            for (int i = 0; i < Count; i++)
            {
                myDeferredPassesCommandPoolQueue.Enqueue(new SecondaryCommandBufferPool(LogicalDevice, GraphicsQueue.QueueFamilyIndex, 30));
            }
            #endregion
            #region GBuffer, Subpass Initialization
            GeometryBuffer myGeometryBuffer = new GeometryBuffer();


            mySubpasses = GetSubpassesFromGraphics(mySettings);
            uint starting = 1;
            uint ending   = 2;
            for (int i = 0; i < mySubpasses.Length; i++)
            {
                mySubpasses[i].SetSubpassStart(starting + 1);
                if (i + 1 >= mySubpasses.Length)
                {
                    mySubpasses[i].SetSubpassEnd(UInt32.MaxValue);
                }
                ending++;
                starting++;
            }

            var OffscreenRenderPass = new RenderPass(myGeometryBuffer, mySubpasses);

            GeometryPass = new GeometryPass(myGeometryBuffer, OffscreenRenderPass, myDeferredPassesCommandPoolQueue.Dequeue(), myShaderManager);

            #endregion

            #region Final Composition Render Setup
            OnScreenRenderPass = new RenderPass();                                                                                                                                       // this.CreateFinalRenderPass(LogicalDevice);
            var Result = myShaderManager.CreatePipeline(OnScreenRenderPass, new String[] { "OffscreenToOnScreenVert", "OffscreenToOnScreenFrag" }, out myDeferredRendererDescriptorSet); //TODO: create method that returns resource set for shader of a given type.
            DeferredRendererOutputPipe       = Result.Item2;
            DeferredRendererOutputPipeLayout = Result.Item1;
            Tuple <String, DescriptorImageInfo>[] myDescriptorInfo = GeometryPass.GetGBufferDescriptorImageInfo();
            if (mySubpasses.Length != 0)
            {
                foreach (var A in myDescriptorInfo)
                {
                    foreach (SubPass B in mySubpasses)
                    {
                        //ResourceSet mySet = B.GetResourceSet();
                        // mySet.Write(A.Item1, A.Item2);
                    }
                }
            }
            //Tell our deferred renderer that we can
            foreach (var A in myDescriptorInfo)
            {
                myDeferredRendererDescriptorSet.Write(A.Item1, A.Item2);
            }
            CreateFinalQuadRenderingSpace();
            #endregion
        }
Пример #42
0
 // Awake so that the Buffer is always instantiated in time.
 void Awake()
 {
     buffer = new GeometryBuffer();
 }
Пример #43
0
    public void OnGUI()
    {
        if (onProcessing)
        {
            return;
        }
        GUI.depth = 10;

        GUI.enabled = false;
        objPath     = GUI.TextField(new Rect(10, 10, 300, 20), objPath);
        GUI.enabled = true;

        if (GUI.Button(new Rect(310, 10, 20, 20), "..."))
        {
            OpenFileName ofn = new OpenFileName();

            ofn.structSize = Marshal.SizeOf(ofn);

            ofn.filter = "Object Files (*.obj)\0*.obj\0\0";

            ofn.file = new string(new char[256]);

            ofn.maxFile = ofn.file.Length;

            ofn.fileTitle = new string(new char[64]);

            ofn.maxFileTitle = ofn.fileTitle.Length;

            ofn.initialDir = UnityEngine.Application.dataPath;

            ofn.title = "Select Object";

            ofn.defExt = "OBJ";                                            //显示文件的类型

            ofn.flags = 0x00080000 | 0x00001000 | 0x00000800 | 0x00000008; //OFN_EXPLORER|OFN_FILEMUSTEXIST|OFN_PATHMUSTEXIST| OFN_ALLOWMULTISELECT|OFN_NOCHANGEDIR
            // ofn.flags = 0x00080000 | 0x00001000 | 0x00000800 | 0x00000200 | 0x00000008;

            if (DllTest.GetOpenFileName(ofn))
            {
                // StartCoroutine(WaitLoad(ofn.file));//加载图片到panle
                objPath = ofn.file;
                Debug.Log("Selected file with full path: " + ofn.file);
            }

            /*
             * if(openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK){
             *      objPath = openFileDialog.FileName;
             * }else{
             *      objPath="";
             * }
             */
            //objPath = EditorUtility.OpenFilePanel("Please select an object file","","obj");
            Debug.Log(objPath);
        }

        if (GUI.Button(new Rect(10, 40, 100, 20), "import"))
        {
            hasLegoized = false;
            if (objPath == "")
            {
                MessageBox.Show("You Must Select an Object first!", "Select Object");

                /*EditorUtility.DisplayDialog(
                 *      "Select Object",
                 *      "You Must Select an Object first!",
                 *      "Ok");*/
                return;
            }
            else
            {
                isObjectLoaded = false;
                Destroy(GetComponent("MeshFilter"));
                Destroy(GetComponent("MeshRenderer"));
                Destroy(GetComponent("MeshCollider"));

                GameObject voxelContainer = GameObject.Find("Voxelized");
                GameObject legoContainer  = GameObject.Find("Legoizer");
                StartCoroutine(removeVoxels(voxelContainer));
                StartCoroutine(removeVoxels(legoContainer));
                buffer = new GeometryBuffer();
                mtllib = "";
                StartCoroutine(Load("file:///" + objPath));
            }
        }

        GUI.enabled = isObjectLoaded;

        GUI.Label(new Rect(10, 70, 220, 20), "Sample Resolution (1000-8000000): ");
        samplingResolutionStr = GUI.TextField(new Rect(230, 70, 100, 20), samplingResolutionStr, 25);
        samplingResolutionStr = Regex.Replace(samplingResolutionStr, "[^0-9]", "");
        sampleResoultion      = int.Parse(samplingResolutionStr);

        colorMode = GUI.SelectionGrid(new Rect(10, 100, 220, 20), colorMode, colorModes, colorModes.Length, GUI.skin.toggle);

        if (GUI.Button(new Rect(10, 130, 100, 20), "Legoize"))
        {
            hasLegoized = false;
            if (sampleResoultion < 1001 || sampleResoultion > 8000000)
            {
                MessageBox.Show("The sample resolution must be in between 1000 to 8000000", "Out of Range");

                /*EditorUtility.DisplayDialog(
                 *      "Out of Range",
                 *      "The sample resolution must be in between 1000 to 8000000",
                 *      "Ok");*/
                return;
            }
            GameObject voxelContainer = GameObject.Find("Voxelized");
            GameObject legoContainer  = GameObject.Find("Legoizer");

            while (voxelContainer.transform.childCount > 0)
            {
                GameObject.DestroyImmediate(voxelContainer.transform.GetChild(0).gameObject);
            }

            while (legoContainer.transform.childCount > 0)
            {
                GameObject.DestroyImmediate(legoContainer.transform.GetChild(0).gameObject);
            }

            Resources.UnloadUnusedAssets();
            System.GC.Collect();
            Voxelizer voxelizer = GameObject.Find("Voxelized").GetComponent <Voxelizer> ();
            StartCoroutine(voxelizer.voxelize());
        }

        GUI.enabled = true;

        if (hasLegoized)
        {
            if (GUI.Button(new Rect(10, 160, 100, 20), "Save"))
            {
                LxfmlWriter xmlWriter = GameObject.Find("FileWriter").GetComponent <LxfmlWriter> ();
                StartCoroutine(xmlWriter.writeXML(legos));
            }
        }
    }
Пример #44
0
	void Start ()
	{
		buffer = new GeometryBuffer ();
		Load (obj);
	}
Пример #45
0
        public static void SetGeometryData(string data, GeometryBuffer buffer)
        {
            var lines = data.Split("\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

            for (var i = 0; i < lines.Length; i++)
            {
                var l = lines[i].Trim();

                if (l.IndexOf("#") != -1)
                    l = l.Substring(0, l.IndexOf("#"));
                var p = l.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                if (p.Length > 1)
                {
                    switch (p[0])
                    {
                        case O:
                            buffer.PushObject(p[1].Trim());
                            break;
                        case G:
                            buffer.PushGroup(p[1].Trim());
                            break;
                        case V:
                            buffer.PushVertex(new Vector3(
                                Cf(p[1]),
                                Cf(p[2]),
                                Cf(p[3]))
                                );
                            break;
                        case Vt:
                            buffer.PushUv(new Vector2(Cf(p[1]), Cf(p[2])));
                            break;
                        case Vn:
                            buffer.PushNormal(new Vector3(Cf(p[1]), Cf(p[2]), Cf(p[3])));
                            break;
                        case F:
                            for (var j = 1; j < p.Length; j++)
                            {
                                var c = p[j].Trim().Split("/".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                                var fi = new FaceIndices();
                                fi.Vi = Ci(c[0]) - 1;
                                if (c.Length > 1)
                                {
                                    fi.Vu = Ci(c[1]) - 1;
                                }
                                if (c.Length > 2)
                                {
                                    fi.Vn = Ci(c[2]) - 1;
                                }
                                buffer.PushFace(fi);
                            }
                            break;
                        case Mtl:
                            // mtllib = p[1].Trim();
                            break;
                        case Uml:
                            buffer.PushMaterialName(p[1].Trim());
                            break;
                    }
                }
            }
            // buffer.Trace();
        }