Esempio n. 1
0
        /// <summary>
        /// Crea un TGCMesh con DiffuseMap.
        /// </summary>
        /// <param name="meshName">Nombre de la malla que se va a crear.</param>
        /// <param name="vertices">Vertices a utilizar para crear la malla.</param>
        /// <param name="transform">Matriz que se utiliza para aplicar transformaciones a la malla.</param>
        /// <param name="texture">Textura a utilizar.</param>
        /// <param name="alphaBlendEnable">Habilita el AlphaBlending para los modelos.</param>
        /// <returns>Un nuevo TGCMesh basado en los parametros dados.</returns>
        public static TgcMesh ToDiffuseMapMesh(string meshName, CustomVertex.PositionColoredTextured[] vertices, TGCMatrix transform, TgcTexture texture, bool alphaBlendEnable)
        {
            //Crear Mesh
            var d3dMesh = new Mesh(vertices.Length / 3, vertices.Length, MeshFlags.Managed,
                                   TgcSceneLoader.DiffuseMapVertexElements, D3DDevice.Instance.Device);

            //Cargar VertexBuffer
            using (var vb = d3dMesh.VertexBuffer)
            {
                var data = vb.Lock(0, 0, LockFlags.None);
                for (var j = 0; j < vertices.Length; j++)
                {
                    var v    = new TgcSceneLoader.DiffuseMapVertex();
                    var vBox = vertices[j];

                    //vertices
                    v.Position = TGCVector3.TransformCoordinate(TGCVector3.FromVector3(vBox.Position), transform);

                    //normals
                    v.Normal = TGCVector3.Empty;

                    //texture coordinates diffuseMap
                    v.Tu = vBox.Tu;
                    v.Tv = vBox.Tv;

                    //color
                    v.Color = vBox.Color;

                    data.Write(v);
                }
                vb.Unlock();
            }

            //Cargar IndexBuffer en forma plana
            using (var ib = d3dMesh.IndexBuffer)
            {
                var indices = new short[vertices.Length];
                for (var j = 0; j < indices.Length; j++)
                {
                    indices[j] = (short)j;
                }
                ib.SetData(indices, 0, LockFlags.None);
            }

            //Calcular normales
            d3dMesh.ComputeNormals();

            //Malla de TGC
            var tgcMesh = new TgcMesh(d3dMesh, meshName, TgcMesh.MeshRenderType.DIFFUSE_MAP);

            tgcMesh.DiffuseMaps = new[] { texture.Clone() };
            tgcMesh.Materials   = new[] { D3DDevice.DEFAULT_MATERIAL };
            tgcMesh.createBoundingBox();
            tgcMesh.Enabled          = true;
            tgcMesh.AlphaBlendEnable = alphaBlendEnable;
            return(tgcMesh);
        }
Esempio n. 2
0
        /// <summary>
        ///     Crear una malla instancia de una original
        /// </summary>
        private TgcMesh crearMeshInstance(TgcMeshData meshData, List <TgcMesh> meshes)
        {
            var originalMesh = meshes[meshData.originalMesh];
            var translation  = new Vector3(meshData.position[0], meshData.position[1], meshData.position[2]);
            var rotationQuat = new Quaternion(meshData.rotation[0], meshData.rotation[1], meshData.rotation[2],
                                              meshData.rotation[3]);
            var rotation = quaternionToEuler(rotationQuat);
            var scale    = new Vector3(meshData.scale[0], meshData.scale[1], meshData.scale[2]);

            var tgcMesh = new TgcMesh(meshData.name, originalMesh, translation, rotation, scale);

            return(tgcMesh);
        }
Esempio n. 3
0
        /// <summary>
        ///     Libera los recursos de la malla.
        ///     Si la malla es una instancia se deshabilita pero no se liberan recursos.
        ///     Si la malla es el original y tiene varias instancias adjuntadas, se hace dispose() también de las instancias.
        /// </summary>
        public void dispose()
        {
            enabled = false;
            if (boundingBox != null)
            {
                boundingBox.dispose();
            }

            //Si es una instancia no liberar nada, lo hace el original.
            if (parentInstance != null)
            {
                parentInstance = null;
                return;
            }

            //hacer dispose de instancias
            if (meshInstances != null)
            {
                foreach (var meshInstance in meshInstances)
                {
                    meshInstance.dispose();
                }
                meshInstances = null;
            }

            //Dispose de mesh
            d3dMesh.Dispose();
            d3dMesh = null;

            //Dispose de texturas
            if (diffuseMaps != null)
            {
                for (var i = 0; i < diffuseMaps.Length; i++)
                {
                    if (diffuseMaps[i] != null)
                    {
                        diffuseMaps[i].dispose();
                    }
                }
                diffuseMaps = null;
            }
            if (lightMap != null)
            {
                lightMap.dispose();
                lightMap = null;
            }

            //VertexDeclaration
            vertexDeclaration.Dispose();
            vertexDeclaration = null;
        }
Esempio n. 4
0
        /// <summary>
        ///     Crear un nuevo mesh igual
        /// </summary>
        /// <param name="cloneName">Nombre del mesh clonado</param>
        /// <returns>Mesh clonado</returns>
        public TgcMesh clone(string cloneName)
        {
            //Clonar D3dMesh
            var d3dCloneMesh = d3dMesh.Clone(MeshFlags.Managed, d3dMesh.Declaration, D3DDevice.Instance.Device);

            //Crear mesh de TGC y cargar atributos generales
            var cloneMesh = new TgcMesh(d3dCloneMesh, cloneName, renderType);

            cloneMesh.Materials             = Materials;
            cloneMesh.layer                 = layer;
            cloneMesh.boundingBox           = boundingBox.clone();
            cloneMesh.alphaBlendEnable      = alphaBlendEnable;
            cloneMesh.enabled               = true;
            cloneMesh.AutoUpdateBoundingBox = AutoUpdateBoundingBox;

            //Transformaciones
            cloneMesh.translation         = translation;
            cloneMesh.rotation            = rotation;
            cloneMesh.scale               = scale;
            cloneMesh.transform           = transform;
            cloneMesh.autoTransformEnable = autoTransformEnable;

            //Clonar userProperties
            if (UserProperties != null)
            {
                cloneMesh.UserProperties = new Dictionary <string, string>();
                foreach (var entry in UserProperties)
                {
                    cloneMesh.UserProperties.Add(entry.Key, entry.Value);
                }
            }

            //Clonar DiffuseMaps
            if (diffuseMaps != null)
            {
                cloneMesh.diffuseMaps = new TgcTexture[diffuseMaps.Length];
                for (var i = 0; i < diffuseMaps.Length; i++)
                {
                    cloneMesh.diffuseMaps[i] = diffuseMaps[i].clone();
                }
            }

            //Clonar LightMap
            if (lightMap != null)
            {
                cloneMesh.lightMap = lightMap.clone();
            }

            return(cloneMesh);
        }
Esempio n. 5
0
        /// <summary>
        /// Crea un TGCMesh con solo color.
        /// </summary>
        /// <param name="meshName">Nombre de la malla que se va a crear.</param>
        /// <param name="vertices">Vertices a utilizar para crear la malla.</param>
        /// <param name="transform">Matriz a utilizar para aplicar transformaciones a la malla.</param>
        /// <returns>Un nuevo TGCMesh basado en los parametros dados.</returns>
        public static TgcMesh ToColorMesh(string meshName, CustomVertex.PositionColoredTextured[] vertices, TGCMatrix transform)
        {
            //Crear Mesh
            var d3dMesh = new Mesh(vertices.Length / 3, vertices.Length, MeshFlags.Managed,
                                   TgcSceneLoader.VertexColorVertexElements, D3DDevice.Instance.Device);

            //Cargar VertexBuffer
            using (var vb = d3dMesh.VertexBuffer)
            {
                var data = vb.Lock(0, 0, LockFlags.None);
                for (var j = 0; j < vertices.Length; j++)
                {
                    var v    = new TgcSceneLoader.VertexColorVertex();
                    var vBox = vertices[j];

                    //vertices
                    v.Position = TGCVector3.TransformCoordinate(TGCVector3.FromVector3(vBox.Position), transform);

                    //normals
                    v.Normal = TGCVector3.Empty;

                    //color
                    v.Color = vBox.Color;

                    data.Write(v);
                }
                vb.Unlock();
            }

            //Cargar IndexBuffer en forma plana
            using (var ib = d3dMesh.IndexBuffer)
            {
                var indices = new short[vertices.Length];
                for (var j = 0; j < indices.Length; j++)
                {
                    indices[j] = (short)j;
                }
                ib.SetData(indices, 0, LockFlags.None);
            }

            //Malla de TGC
            var tgcMesh = new TgcMesh(d3dMesh, meshName, TgcMesh.MeshRenderType.VERTEX_COLOR);

            tgcMesh.Materials = new[] { D3DDevice.DEFAULT_MATERIAL };
            tgcMesh.createBoundingBox();
            tgcMesh.Enabled = true;
            return(tgcMesh);
        }
Esempio n. 6
0
        public static TgcMesh FromTGCBox(string meshName, TgcTexture texture, CustomVertex.PositionColoredTextured[] vertices, TGCMatrix transform, bool alphaBlendEnable)
        {
            TgcMesh tgcMesh;

            if (texture != null)
            {
                //Crear mesh con DiffuseMap
                tgcMesh = TgcMesh.ToDiffuseMapMesh(meshName, vertices, transform, texture, alphaBlendEnable);
            }
            else
            {
                //Crear mesh con solo color
                tgcMesh = TgcMesh.ToColorMesh(meshName, vertices, transform);
            }

            return(tgcMesh);
        }
Esempio n. 7
0
        /// <summary>
        ///     Crea una nueva malla que es una instancia de esta malla original
        ///     Reutiliza toda la geometría de la malla original sin duplicarla.
        ///     Solo se puede crear instancias a partir de originales.
        /// </summary>
        /// <param name="name">Nombre de la malla</param>
        /// <param name="translation">Traslación respecto de la malla original</param>
        /// <param name="rotation">Rotación respecto de la malla original</param>
        /// <param name="scale">Escala respecto de la malla original</param>
        public TgcMesh createMeshInstance(string name, Vector3 translation, Vector3 rotation, Vector3 scale)
        {
            if (parentInstance != null)
            {
                throw new Exception(
                          "No se puede crear una instancia de otra malla instancia. Hay que partir del original.");
            }

            //Crear instancia
            var instance = new TgcMesh(name, this, translation, rotation, scale);

            //BoundingBox
            instance.boundingBox = new TgcBoundingBox(boundingBox.PMin, boundingBox.PMax);
            instance.updateBoundingBox();

            instance.enabled = true;
            return(instance);
        }
Esempio n. 8
0
        /// <summary>
        ///     Crea una nueva malla que es una instancia de otra malla original.
        ///     Reutiliza toda la geometría de la malla original sin duplicarla.
        /// </summary>
        /// <param name="name">Nombre de la malla</param>
        /// <param name="parentInstance">Malla original desde la cual basarse</param>
        /// <param name="translation">Traslación respecto de la malla original</param>
        /// <param name="rotation">Rotación respecto de la malla original</param>
        /// <param name="scale">Escala respecto de la malla original</param>
        public TgcMesh(string name, TgcMesh parentInstance, Vector3 translation, Vector3 rotation, Vector3 scale)
        {
            //Cargar datos en base al original
            initData(parentInstance.d3dMesh, name, parentInstance.renderType);
            diffuseMaps = parentInstance.diffuseMaps;
            materials   = parentInstance.materials;
            lightMap    = parentInstance.lightMap;
            effect      = parentInstance.effect;

            //Almacenar transformación inicial
            this.translation = translation;
            this.rotation    = rotation;
            this.scale       = scale;

            //almacenar instancia en el padre
            this.parentInstance = parentInstance;
            parentInstance.meshInstances.Add(this);
        }
Esempio n. 9
0
        /// <summary>
        ///     Cargar datos iniciales
        /// </summary>
        protected void initData(Mesh mesh, string name, MeshRenderType renderType)
        {
            d3dMesh          = mesh;
            this.name        = name;
            this.renderType  = renderType;
            enabled          = false;
            parentInstance   = null;
            meshInstances    = new List <TgcMesh>();
            alphaBlendEnable = false;

            autoTransformEnable   = true;
            AutoUpdateBoundingBox = true;
            translation           = new Vector3(0f, 0f, 0f);
            rotation  = new Vector3(0f, 0f, 0f);
            scale     = new Vector3(1f, 1f, 1f);
            transform = Matrix.Identity;

            //Shader
            vertexDeclaration = new VertexDeclaration(mesh.Device, mesh.Declaration);
            effect            = TgcShaders.Instance.TgcMeshShader;
            technique         = TgcShaders.Instance.getTgcMeshTechnique(this.renderType);
        }
Esempio n. 10
0
        /// <summary>
        ///     Cargar datos iniciales
        /// </summary>
        protected void initData(Mesh mesh, string name, MeshRenderType renderType)
        {
            d3dMesh          = mesh;
            this.name        = name;
            this.renderType  = renderType;
            enabled          = false;
            parentInstance   = null;
            meshInstances    = new List <TgcMesh>();
            AlphaBlendEnable = false;

            AutoTransformEnable   = false;
            AutoUpdateBoundingBox = true;
            translation           = TGCVector3.Empty;
            rotation  = TGCVector3.Empty;
            scale     = TGCVector3.One;
            transform = TGCMatrix.Identity;

            //Shader
            vertexDeclaration = new VertexDeclaration(mesh.Device, mesh.Declaration);
            Effect            = TGCShaders.Instance.TgcMeshShader;
            Technique         = TGCShaders.Instance.GetTGCMeshTechnique(this.renderType);
        }
Esempio n. 11
0
        public TgcMesh(string name, TgcMesh parentInstance, TGCVector3 translation, TGCVector3 rotation, TGCVector3 scale)
        {
            //Cargar datos en base al original
            initData(parentInstance.d3dMesh, name, parentInstance.renderType);
            //Si no se hace clone luego no pueden cambiar las texturas.
            diffuseMaps = new TgcTexture[parentInstance.diffuseMaps.Length];
            for (var i = 0; i < diffuseMaps.Length; i++)
            {
                diffuseMaps[i] = parentInstance.diffuseMaps[i].Clone();
            }
            materials = parentInstance.materials; //es un clone necesario?
            lightMap  = parentInstance.lightMap;  //es un clone necesario?
            Effect    = parentInstance.Effect;    //.Clone() pide device ????...... FIXIT.

            //Almacenar transformación inicial
            this.translation = translation;
            this.rotation    = rotation;
            this.scale       = scale;

            //almacenar instancia en el padre
            this.parentInstance = parentInstance;
            parentInstance.meshInstances.Add(this);
        }
Esempio n. 12
0
 public TgcMesh createNewMeshInstance(string meshName, TgcMesh originalMesh, Vector3 translation,
                                      Vector3 rotation, Vector3 scale)
 {
     return(new TgcMesh(meshName, originalMesh, translation, rotation, scale));
 }
Esempio n. 13
0
        /// <summary>
        ///     Carga la escena a partir de un objeto TgcSceneData ya parseado
        /// </summary>
        /// <param name="sceneData">Objeto con datos de la escena ya parseados</param>
        /// <param name="mediaPath">Path a partir del cual hay que buscar los recursos de escena (Texturas, LightMaps, etc.)</param>
        /// <returns></returns>
        public TgcScene loadScene(TgcSceneData sceneData, string mediaPath)
        {
            var tgcScene = new TgcScene(sceneData.name, null);

            //Cargar Texturas
            var materialsArray = new TgcSceneLoaderMaterialAux[sceneData.materialsData.Length];

            for (var i = 0; i < sceneData.materialsData.Length; i++)
            {
                var materialData = sceneData.materialsData[i];
                var texturesPath = mediaPath + sceneData.texturesDir + "\\";

                //Crear StandardMaterial
                if (materialData.type.Equals(TgcMaterialData.StandardMaterial))
                {
                    materialsArray[i] = createTextureAndMaterial(materialData, texturesPath);
                }

                //Crear MultiMaterial
                else if (materialData.type.Equals(TgcMaterialData.MultiMaterial))
                {
                    var matAux = new TgcSceneLoaderMaterialAux();
                    materialsArray[i]   = matAux;
                    matAux.subMaterials = new TgcSceneLoaderMaterialAux[materialData.subMaterials.Length];
                    for (var j = 0; j < materialData.subMaterials.Length; j++)
                    {
                        matAux.subMaterials[j] = createTextureAndMaterial(materialData.subMaterials[j], texturesPath);
                    }
                }
            }

            //Cargar Meshes
            for (var i = 0; i < sceneData.meshesData.Length; i++)
            {
                var     meshData = sceneData.meshesData[i];
                TgcMesh tgcMesh  = null;

                //Crear malla original
                if (meshData.instanceType.Equals(TgcMeshData.ORIGINAL))
                {
                    //Crear mesh que no tiene Material, con un color simple
                    if (meshData.materialId == -1)
                    {
                        tgcMesh = crearMeshSoloColor(meshData);
                    }

                    //Para los que si tienen Material
                    else
                    {
                        //Crear MeshFormat que soporte LightMaps
                        if (meshData.lightmapEnabled)
                        {
                            tgcMesh = crearMeshDiffuseMapLightmap(sceneData, mediaPath, materialsArray, meshData);
                        }

                        //Formato de Mesh con Textura pero sin Lightmap
                        else
                        {
                            tgcMesh = crearMeshDiffuseMap(materialsArray, meshData);
                        }
                    }
                }

                //Crear malla instancia
                else if (meshData.instanceType.Equals(TgcMeshData.INSTANCE))
                {
                    tgcMesh = crearMeshInstance(meshData, tgcScene.Meshes);
                }

                //Crear BoundingBox, aprovechar lo que viene del XML o crear uno por nuestra cuenta
                if (meshData.pMin != null && meshData.pMax != null)
                {
                    tgcMesh.BoundingBox = new TgcBoundingBox(
                        TgcParserUtils.float3ArrayToVector3(meshData.pMin),
                        TgcParserUtils.float3ArrayToVector3(meshData.pMax),
                        tgcMesh.Position,
                        tgcMesh.Scale
                        );
                }
                else
                {
                    tgcMesh.createBoundingBox();
                }

                //Cargar layer
                tgcMesh.Layer = meshData.layerName;

                //Cargar AlphaBlending
                tgcMesh.AlphaBlendEnable = meshData.alphaBlending;

                //agregar mesh a escena
                tgcMesh.Enabled = true;
                tgcScene.Meshes.Add(tgcMesh);

                //Cargar userProperties, si hay
                tgcMesh.UserProperties = meshData.userProperties;
            }

            //BoundingBox del escenario, utilizar el que viene del XML o crearlo nosotros
            if (sceneData.pMin != null && sceneData.pMax != null)
            {
                tgcScene.BoundingBox = new TgcBoundingBox(
                    new Vector3(sceneData.pMin[0], sceneData.pMin[1], sceneData.pMin[2]),
                    new Vector3(sceneData.pMax[0], sceneData.pMax[1], sceneData.pMax[2])
                    );
            }
            else
            {
                var boundingBoxes = new List <TgcBoundingBox>();
                foreach (var mesh in tgcScene.Meshes)
                {
                    boundingBoxes.Add(mesh.BoundingBox);
                }
                tgcScene.BoundingBox = TgcBoundingBox.computeFromBoundingBoxes(boundingBoxes);
            }

            //Cargar parte de PortalRendering, solo hay información
            if (sceneData.portalData != null)
            {
                var portalLoader = new TgcPortalRenderingLoader();
                tgcScene.PortalRendering = portalLoader.loadFromData(tgcScene, sceneData.portalData);
            }

            return(tgcScene);
        }
Esempio n. 14
0
        public static TgcMesh FromTGCSphere(string meshName, TgcTexture texture, List <int> indices, List <TGCSphere.Vertex.PositionColoredTexturedNormal> vertices, TGCMatrix transform, bool alphaBlendEnable)
        {
            //Crear mesh con DiffuseMap
            if (texture != null)
            {
                //Crear Mesh
                var d3dMesh = new Mesh(indices.Count / 3, indices.Count, MeshFlags.Managed,
                                       TgcSceneLoader.DiffuseMapVertexElements, D3DDevice.Instance.Device);

                //Cargar VertexBuffer
                using (var vb = d3dMesh.VertexBuffer)
                {
                    var data = vb.Lock(0, 0, LockFlags.None);
                    for (var j = 0; j < indices.Count; j++)
                    {
                        var v       = new TgcSceneLoader.DiffuseMapVertex();
                        var vSphere = vertices[indices[j]];

                        //vertices
                        v.Position = TGCVector3.TransformCoordinate(vSphere.getPosition(), transform);

                        //normals
                        v.Normal = vSphere.getNormal();

                        //texture coordinates diffuseMap
                        v.Tu = vSphere.Tu;
                        v.Tv = vSphere.Tv;

                        //color
                        v.Color = vSphere.Color;

                        data.Write(v);
                    }
                    vb.Unlock();
                }

                //Cargar IndexBuffer en forma plana
                using (var ib = d3dMesh.IndexBuffer)
                {
                    var vIndices = new short[indices.Count];
                    for (var j = 0; j < vIndices.Length; j++)
                    {
                        vIndices[j] = (short)j;
                    }
                    ib.SetData(vIndices, 0, LockFlags.None);
                }

                //Calcular normales
                //d3dMesh.ComputeNormals();

                //Malla de TGC
                var tgcMesh = new TgcMesh(d3dMesh, meshName, TgcMesh.MeshRenderType.DIFFUSE_MAP);
                tgcMesh.DiffuseMaps = new[] { texture.Clone() };
                tgcMesh.Materials   = new[] { D3DDevice.DEFAULT_MATERIAL };
                tgcMesh.createBoundingBox();
                tgcMesh.Enabled = true;
                return(tgcMesh);
            }

            //Crear mesh con solo color
            else
            {
                //Crear Mesh
                var d3dMesh = new Mesh(indices.Count / 3, indices.Count, MeshFlags.Managed,
                                       TgcSceneLoader.VertexColorVertexElements, D3DDevice.Instance.Device);

                //Cargar VertexBuffer
                using (var vb = d3dMesh.VertexBuffer)
                {
                    var data = vb.Lock(0, 0, LockFlags.None);
                    for (var j = 0; j < indices.Count; j++)
                    {
                        var v       = new TgcSceneLoader.VertexColorVertex();
                        var vSphere = vertices[indices[j]];

                        //vertices
                        v.Position = TGCVector3.TransformCoordinate(vSphere.getPosition(), transform);

                        //normals
                        v.Normal = vSphere.getNormal();

                        //color
                        v.Color = vSphere.Color;

                        data.Write(v);
                    }
                    vb.Unlock();
                }

                //Cargar IndexBuffer en forma plana
                using (var ib = d3dMesh.IndexBuffer)
                {
                    var vIndices = new short[indices.Count];
                    for (var j = 0; j < vIndices.Length; j++)
                    {
                        vIndices[j] = (short)j;
                    }
                    ib.SetData(vIndices, 0, LockFlags.None);
                }

                //Malla de TGC
                var tgcMesh = new TgcMesh(d3dMesh, meshName, TgcMesh.MeshRenderType.VERTEX_COLOR);
                tgcMesh.Materials = new[] { D3DDevice.DEFAULT_MATERIAL };
                tgcMesh.createBoundingBox();
                tgcMesh.Enabled          = true;
                tgcMesh.AlphaBlendEnable = alphaBlendEnable;
                return(tgcMesh);
            }
        }