Пример #1
0
        public H3DMaterialWrapper(H3DMaterial mat) : base()
        {
            Material = mat;

            ImageKey         = "material";
            SelectedImageKey = "material";
        }
Пример #2
0
 private RGBA GetConstColor(H3DMaterial mtl, int stage) //TODO: this isn't always the right color, figure out when to us MaterialParams.Constant#Color instead (if Constant#Adssignment == stage number, use that one?)
 {
     if (mtl.MaterialParams.Constant0Assignment == stage)
     {
         return(mtl.MaterialParams.Constant0Color);
     }
     if (mtl.MaterialParams.Constant1Assignment == stage)
     {
         return(mtl.MaterialParams.Constant1Color);
     }
     if (mtl.MaterialParams.Constant2Assignment == stage)
     {
         return(mtl.MaterialParams.Constant2Color);
     }
     if (mtl.MaterialParams.Constant3Assignment == stage)
     {
         return(mtl.MaterialParams.Constant3Color);
     }
     if (mtl.MaterialParams.Constant4Assignment == stage)
     {
         return(mtl.MaterialParams.Constant4Color);
     }
     if (mtl.MaterialParams.Constant5Assignment == stage)
     {
         return(mtl.MaterialParams.Constant5Color);
     }
     return(mtl.MaterialParams.TexEnvStages[stage].Color);
 }
Пример #3
0
    private Material CreateMaterial(H3DMaterial spicaMaterial, List <Texture> unityTextures)
    {
        var material = ImportHelpers.CreateCharacterMaterial(ImportHelpers.GuessCharacterMaterialType(spicaMaterial.Name));

        material.name        = spicaMaterial.Name;
        material.mainTexture = unityTextures.First(t => t.name == spicaMaterial.Texture0Name);
        return(material);
    }
Пример #4
0
        public void LoadMaterial(H3DMaterialWrapper wrapper)
        {
            ActiveMaterialWrapper = wrapper;
            ActiveMaterial        = wrapper.Material;

            stTabControl1.SelectedIndex = SelectedIndex;
            UpdateTab();
        }
Пример #5
0
        public H3DMaterialWrapper(BCH bch, H3DModelWrapper model, H3DMaterial mat) : base()
        {
            ParentModel = model;
            ParentBCH   = bch;
            Material    = mat;

            ImageKey         = "material";
            SelectedImageKey = "material";

            ReloadMaterial();
        }
Пример #6
0
        public void LoadMaterial(H3DMaterialWrapper wrapper)
        {
            ActiveMaterial = wrapper.Material;
            ActiveWrapper  = wrapper;

            layerCB.SelectedItem = ActiveMaterial.MaterialParams.TranslucencyKind;

            //  LoadCombinerImages();
            UpdateTev();
            UpdateTerms();
            UpdateLUT();
        }
Пример #7
0
        private void ReplaceAction(object sender, EventArgs args)
        {
            OpenFileDialog ofd = new OpenFileDialog();

            ofd.Filter = "Supported Formats|*.json;";
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                Material = JsonConvert.DeserializeObject <H3DMaterial>(
                    System.IO.File.ReadAllText(ofd.FileName));

                ReloadMaterial();

                var editor = ParentBCH.LoadEditor <BCHMaterialEditor>();
                editor.LoadMaterial(this);
            }
        }
Пример #8
0
        private void WriteTextureString(H3DMaterial mat, int idx)
        {
            text.AppendLine($"  Texture{idx}");
            text.Append($"    Name: ");
            switch (idx) //Select the texture from the material
            {
            case 1: text.AppendLine(mat.Texture1Name); break;

            case 2: text.AppendLine(mat.Texture2Name); break;

            default: text.AppendLine(mat.Texture0Name); break;
            }

            text.AppendLine($"    Map Channel: {mat.MaterialParams.TextureSources[idx]}");
            text.AppendLine($"    Mapping Type: {mat.MaterialParams.TextureCoords[idx].MappingType}");
            text.AppendLine($"    Wrap U/V: {mat.TextureMappers[idx].WrapU}/{mat.TextureMappers[idx].WrapV}");
            text.AppendLine($"    Map Scale: {mat.MaterialParams.TextureCoords[idx].Scale}");
            text.AppendLine($"    Map Translation: {mat.MaterialParams.TextureCoords[idx].Translation}");
            text.AppendLine($"    Map Rotation: {mat.MaterialParams.TextureCoords[idx].Rotation}");

            //TODO: add support for additional mapping settings?

            text.Append('\n');
        }
Пример #9
0
        public MaterialState[] GetMaterialStates()
        {
            if (State == AnimationState.Stopped)
            {
                ResetStates();
            }

            if (State != AnimationState.Playing || Elements.Count == 0)
            {
                return(States);
            }

            for (int i = 0; i < Elements.Count; i++)
            {
                int Index = Indices[i];

                MaterialState State = States[Index];

                H3DMaterial Material = Materials[Index];

                H3DMaterialParams Params = Material.MaterialParams;

                H3DAnimationElement Elem = Elements[i];

                H3DTextureCoord[] TC = new H3DTextureCoord[]
                {
                    Params.TextureCoords[0],
                    Params.TextureCoords[1],
                    Params.TextureCoords[2]
                };

                if (Elem.PrimitiveType == H3DPrimitiveType.RGBA)
                {
                    H3DAnimRGBA RGBA = (H3DAnimRGBA)Elem.Content;

                    switch (Elem.TargetType)
                    {
                    case H3DTargetType.MaterialEmission:  SetRGBA(RGBA, ref State.Emission);  break;

                    case H3DTargetType.MaterialAmbient:   SetRGBA(RGBA, ref State.Ambient);   break;

                    case H3DTargetType.MaterialDiffuse:   SetRGBA(RGBA, ref State.Diffuse);   break;

                    case H3DTargetType.MaterialSpecular0: SetRGBA(RGBA, ref State.Specular0); break;

                    case H3DTargetType.MaterialSpecular1: SetRGBA(RGBA, ref State.Specular1); break;

                    case H3DTargetType.MaterialConstant0: SetRGBA(RGBA, ref State.Constant0); break;

                    case H3DTargetType.MaterialConstant1: SetRGBA(RGBA, ref State.Constant1); break;

                    case H3DTargetType.MaterialConstant2: SetRGBA(RGBA, ref State.Constant2); break;

                    case H3DTargetType.MaterialConstant3: SetRGBA(RGBA, ref State.Constant3); break;

                    case H3DTargetType.MaterialConstant4: SetRGBA(RGBA, ref State.Constant4); break;

                    case H3DTargetType.MaterialConstant5: SetRGBA(RGBA, ref State.Constant5); break;
                    }
                }
                else if (Elem.PrimitiveType == H3DPrimitiveType.Vector2D)
                {
                    H3DAnimVector2D Vector = (H3DAnimVector2D)Elem.Content;

                    switch (Elem.TargetType)
                    {
                    case H3DTargetType.MaterialTexCoord0Scale: SetVector2(Vector, ref TC[0].Scale);       break;

                    case H3DTargetType.MaterialTexCoord1Scale: SetVector2(Vector, ref TC[1].Scale);       break;

                    case H3DTargetType.MaterialTexCoord2Scale: SetVector2(Vector, ref TC[2].Scale);       break;

                    case H3DTargetType.MaterialTexCoord0Trans: SetVector2(Vector, ref TC[0].Translation); break;

                    case H3DTargetType.MaterialTexCoord1Trans: SetVector2(Vector, ref TC[1].Translation); break;

                    case H3DTargetType.MaterialTexCoord2Trans: SetVector2(Vector, ref TC[2].Translation); break;
                    }
                }
                else if (Elem.PrimitiveType == H3DPrimitiveType.Float)
                {
                    H3DFloatKeyFrameGroup Float = ((H3DAnimFloat)Elem.Content).Value;

                    if (!Float.Exists)
                    {
                        continue;
                    }

                    float Value = Float.GetFrameValue(Frame);

                    switch (Elem.TargetType)
                    {
                    case H3DTargetType.MaterialTexCoord0Rot: TC[0].Rotation = Value; break;

                    case H3DTargetType.MaterialTexCoord1Rot: TC[1].Rotation = Value; break;

                    case H3DTargetType.MaterialTexCoord2Rot: TC[2].Rotation = Value; break;
                    }
                }
                else if (Elem.PrimitiveType == H3DPrimitiveType.Texture)
                {
                    H3DFloatKeyFrameGroup Int = ((H3DAnimFloat)Elem.Content).Value;

                    if (!Int.Exists)
                    {
                        continue;
                    }

                    int Value = (int)Int.GetFrameValue(Frame);

                    string Name = TextureNames[Value];

                    switch (Elem.TargetType)
                    {
                    case H3DTargetType.MaterialMapper0Texture: State.Texture0Name = Name; break;

                    case H3DTargetType.MaterialMapper1Texture: State.Texture1Name = Name; break;

                    case H3DTargetType.MaterialMapper2Texture: State.Texture2Name = Name; break;
                    }
                }

                State.Transforms[0] = TC[0].GetTransform().ToMatrix4();
                State.Transforms[1] = TC[1].GetTransform().ToMatrix4();
                State.Transforms[2] = TC[2].GetTransform().ToMatrix4();
            }

            return(States);
        }
Пример #10
0
        public H3D ToH3D(string TextureSearchPath = null)
        {
            H3D Output = new H3D();

            H3DModel Model = new H3DModel();

            Model.Name = "Model";

            ushort MaterialIndex = 0;

            if (Skeleton.Count > 0)
            {
                Model.Flags = H3DModelFlags.HasSkeleton;
            }

            Model.BoneScaling = H3DBoneScaling.Maya;
            Model.MeshNodesVisibility.Add(true);

            foreach (SMDMesh Mesh in Meshes)
            {
                Vector3 MinVector = new Vector3();
                Vector3 MaxVector = new Vector3();

                Dictionary <PICAVertex, int> Vertices = new Dictionary <PICAVertex, int>();

                List <H3DSubMesh> SubMeshes = new List <H3DSubMesh>();

                Queue <PICAVertex> VerticesQueue = new Queue <PICAVertex>();

                foreach (PICAVertex Vertex in Mesh.Vertices)
                {
                    VerticesQueue.Enqueue(Vertex);
                }

                while (VerticesQueue.Count > 2)
                {
                    List <ushort> Indices     = new List <ushort>();
                    List <ushort> BoneIndices = new List <ushort>();

                    int TriCount = VerticesQueue.Count / 3;

                    while (TriCount-- > 0)
                    {
                        PICAVertex[] Triangle = new PICAVertex[3];

                        Triangle[0] = VerticesQueue.Dequeue();
                        Triangle[1] = VerticesQueue.Dequeue();
                        Triangle[2] = VerticesQueue.Dequeue();

                        List <ushort> TempIndices = new List <ushort>();

                        for (int Tri = 0; Tri < 3; Tri++)
                        {
                            PICAVertex Vertex = Triangle[Tri];

                            for (int i = 0; i < 4; i++)
                            {
                                ushort Index = (ushort)Vertex.Indices[i];

                                if (!(BoneIndices.Contains(Index) || TempIndices.Contains(Index)))
                                {
                                    TempIndices.Add(Index);
                                }
                            }
                        }

                        if (BoneIndices.Count + TempIndices.Count > 20)
                        {
                            VerticesQueue.Enqueue(Triangle[0]);
                            VerticesQueue.Enqueue(Triangle[1]);
                            VerticesQueue.Enqueue(Triangle[2]);

                            continue;
                        }

                        for (int Tri = 0; Tri < 3; Tri++)
                        {
                            PICAVertex Vertex = Triangle[Tri];

                            for (int Index = 0; Index < 4; Index++)
                            {
                                int BoneIndex = BoneIndices.IndexOf((ushort)Vertex.Indices[Index]);

                                if (BoneIndex == -1)
                                {
                                    BoneIndex = BoneIndices.Count;
                                    BoneIndices.Add((ushort)Vertex.Indices[Index]);
                                }

                                Vertex.Indices[Index] = BoneIndex;
                            }

                            if (Vertices.ContainsKey(Vertex))
                            {
                                Indices.Add((ushort)Vertices[Vertex]);
                            }
                            else
                            {
                                Indices.Add((ushort)Vertices.Count);

                                if (Vertex.Position.X < MinVector.X)
                                {
                                    MinVector.X = Vertex.Position.X;
                                }
                                if (Vertex.Position.Y < MinVector.Y)
                                {
                                    MinVector.Y = Vertex.Position.Y;
                                }
                                if (Vertex.Position.Z < MinVector.Z)
                                {
                                    MinVector.Z = Vertex.Position.Z;
                                }

                                if (Vertex.Position.X > MaxVector.X)
                                {
                                    MaxVector.X = Vertex.Position.X;
                                }
                                if (Vertex.Position.Y > MaxVector.Y)
                                {
                                    MaxVector.Y = Vertex.Position.Y;
                                }
                                if (Vertex.Position.Z > MaxVector.Z)
                                {
                                    MaxVector.Z = Vertex.Position.Z;
                                }

                                Vertices.Add(Vertex, Vertices.Count);
                            }
                        }
                    }

                    SubMeshes.Add(new H3DSubMesh()
                    {
                        Skinning         = H3DSubMeshSkinning.Smooth,
                        BoneIndicesCount = (ushort)BoneIndices.Count,
                        BoneIndices      = BoneIndices.ToArray(),
                        Indices          = Indices.ToArray()
                    });
                }

                List <PICAAttribute> Attributes = PICAAttribute.GetAttributes(
                    PICAAttributeName.Position,
                    PICAAttributeName.Normal,
                    PICAAttributeName.Color,
                    PICAAttributeName.TexCoord0,
                    PICAAttributeName.BoneIndex,
                    PICAAttributeName.BoneWeight);

                //Mesh
                H3DMesh M = new H3DMesh(Vertices.Keys, Attributes, SubMeshes)
                {
                    Skinning      = H3DMeshSkinning.Smooth,
                    MeshCenter    = (MinVector + MaxVector) * 0.5f,
                    MaterialIndex = MaterialIndex
                };

                //Material
                string TexName = Path.GetFileNameWithoutExtension(Mesh.MaterialName);
                string MatName = $"Mat{MaterialIndex++.ToString("D5")}_{TexName}";

                H3DMaterial Material = H3DMaterial.GetSimpleMaterial(Model.Name, MatName, TexName);

                Model.Materials.Add(Material);

                if (TextureSearchPath != null && !Output.Textures.Contains(TexName))
                {
                    string TextureFile = Path.Combine(TextureSearchPath, Mesh.MaterialName);

                    if (File.Exists(TextureFile))
                    {
                        Output.Textures.Add(new H3DTexture(TextureFile));
                    }
                }

                M.UpdateBoolUniforms(Material);

                Model.AddMesh(M);
            }

            //Build Skeleton
            foreach (SMDBone Bone in Skeleton)
            {
                SMDNode Node = Nodes[Bone.NodeIndex];

                Model.Skeleton.Add(new H3DBone()
                {
                    Name        = Node.Name,
                    ParentIndex = (short)Node.ParentIndex,
                    Translation = Bone.Translation,
                    Rotation    = Bone.Rotation,
                    Scale       = Vector3.One
                });
            }

            //Calculate Absolute Inverse Transforms for all bones
            foreach (H3DBone Bone in Model.Skeleton)
            {
                Bone.CalculateTransform(Model.Skeleton);
            }

            Output.Models.Add(Model);

            Output.CopyMaterials();

            return(Output);
        }
Пример #11
0
        public H3D ToH3D()
        {
            H3D Output = new H3D();

            H3DModel Model = new H3DModel();

            Model.MeshNodesTree = new H3DPatriciaTree();

            Model.Flags = BoneIndicesGroups.Length > 0 ? H3DModelFlags.HasSkeleton : 0;
            Model.Name  = "Model";

            foreach (MTMaterial Mat in Materials)
            {
                H3DMaterial Mtl = H3DMaterial.GetSimpleMaterial(
                    Model.Name,
                    Mat.Name,
                    Path.GetFileNameWithoutExtension(Mat.Texture0Name));

                Mtl.MaterialParams.ColorOperation.BlendMode  = Mat.AlphaBlend.BlendMode;
                Mtl.MaterialParams.BlendFunction             = Mat.AlphaBlend.BlendFunction;
                Mtl.MaterialParams.DepthColorMask.RedWrite   = Mat.AlphaBlend.RedWrite;
                Mtl.MaterialParams.DepthColorMask.GreenWrite = Mat.AlphaBlend.GreenWrite;
                Mtl.MaterialParams.DepthColorMask.BlueWrite  = Mat.AlphaBlend.BlueWrite;
                Mtl.MaterialParams.DepthColorMask.AlphaWrite = Mat.AlphaBlend.AlphaWrite;
                Mtl.MaterialParams.DepthColorMask.Enabled    = Mat.DepthStencil.DepthTest;
                Mtl.MaterialParams.DepthColorMask.DepthWrite = Mat.DepthStencil.DepthWrite;
                Mtl.MaterialParams.DepthColorMask.DepthFunc  = Mat.DepthStencil.DepthFunc;

                Model.Materials.Add(Mtl);
            }

            ushort Index = 0;

            foreach (MTMesh Mesh in Meshes)
            {
                if (Mesh.RenderType != -1)
                {
                    continue;
                }

                H3DMesh M = new H3DMesh(
                    Mesh.RawBuffer,
                    Mesh.VertexStride,
                    Mesh.Attributes,
                    null,
                    null)
                {
                    MaterialIndex = (ushort)Mesh.MaterialIndex,
                    NodeIndex     = Index,
                    Priority      = Mesh.RenderPriority
                };

                byte[] BoneIndices = BoneIndicesGroups[Mesh.BoneIndicesIndex];

                if ((Model.Flags & H3DModelFlags.HasSkeleton) != 0 && BoneIndices.Length > 0)
                {
                    M.Skinning = H3DMeshSkinning.Smooth;

                    PICAVertex[] Vertices = M.GetVertices();

                    for (int v = 0; v < Vertices.Length; v++)
                    {
                        Vector4 Position = Vector4.Zero;

                        float WeightSum = 0;

                        for (int i = 0; i < 4; i++)
                        {
                            if (Vertices[v].Weights[i] == 0)
                            {
                                break;
                            }

                            WeightSum += Vertices[v].Weights[i];

                            int bi = BoneIndicesGroups[Mesh.BoneIndicesIndex][Vertices[v].Indices[i]];

                            Vector4 Trans = Vector4.Zero;

                            for (int b = bi; b != -1; b = Skeleton[b].ParentIndex)
                            {
                                Trans += new Vector4(
                                    Skeleton[b].LocalTransform.M41,
                                    Skeleton[b].LocalTransform.M42,
                                    Skeleton[b].LocalTransform.M43, 0);
                            }

                            Matrix4x4 WT = Skeleton[bi].WorldTransform;

                            Vector3 P = new Vector3(
                                Vertices[v].Position.X,
                                Vertices[v].Position.Y,
                                Vertices[v].Position.Z);

                            Vector4 TP = Vector4.Transform(P, WT);

                            Position += (TP + Trans) * Vertices[v].Weights[i];
                        }

                        if (WeightSum < 1)
                        {
                            Position += Vertices[v].Position * (1 - WeightSum);
                        }

                        Vertices[v].Position = Position;
                    }

                    /*
                     * Removes unused bone from bone indices list, also splits sub meshes on exceeding bones if
                     * current Mesh uses more than 20 (BCH only supports up to 20).
                     */
                    Queue <ushort> IndicesQueue = new Queue <ushort>(Mesh.Indices);

                    while (IndicesQueue.Count > 0)
                    {
                        int Count = IndicesQueue.Count / 3;

                        List <ushort> Indices = new List <ushort>();
                        List <int>    Bones   = new List <int>();

                        while (Count-- > 0)
                        {
                            ushort i0 = IndicesQueue.Dequeue();
                            ushort i1 = IndicesQueue.Dequeue();
                            ushort i2 = IndicesQueue.Dequeue();

                            List <int> TempBones = new List <int>(12);

                            for (int j = 0; j < 4; j++)
                            {
                                int b0 = Vertices[i0].Indices[j];
                                int b1 = Vertices[i1].Indices[j];
                                int b2 = Vertices[i2].Indices[j];

                                if (!(Bones.Contains(b0) || TempBones.Contains(b0)))
                                {
                                    TempBones.Add(b0);
                                }
                                if (!(Bones.Contains(b1) || TempBones.Contains(b1)))
                                {
                                    TempBones.Add(b1);
                                }
                                if (!(Bones.Contains(b2) || TempBones.Contains(b2)))
                                {
                                    TempBones.Add(b2);
                                }
                            }

                            if (Bones.Count + TempBones.Count > 20)
                            {
                                IndicesQueue.Enqueue(i0);
                                IndicesQueue.Enqueue(i1);
                                IndicesQueue.Enqueue(i2);
                            }
                            else
                            {
                                Indices.Add(i0);
                                Indices.Add(i1);
                                Indices.Add(i2);

                                Bones.AddRange(TempBones);
                            }
                        }

                        H3DSubMesh SM = new H3DSubMesh();

                        SM.Skinning         = H3DSubMeshSkinning.Smooth;
                        SM.Indices          = Indices.ToArray();
                        SM.BoneIndicesCount = (ushort)Bones.Count;

                        for (int i = 0; i < Bones.Count; i++)
                        {
                            SM.BoneIndices[i] = BoneIndices[Bones[i]];
                        }

                        bool[] Visited = new bool[Vertices.Length];

                        foreach (ushort i in Indices)
                        {
                            if (!Visited[i])
                            {
                                Visited[i] = true;

                                Vertices[i].Indices[0] = Bones.IndexOf(Vertices[i].Indices[0]);
                                Vertices[i].Indices[1] = Bones.IndexOf(Vertices[i].Indices[1]);
                                Vertices[i].Indices[2] = Bones.IndexOf(Vertices[i].Indices[2]);
                                Vertices[i].Indices[3] = Bones.IndexOf(Vertices[i].Indices[3]);
                            }
                        }

                        M.SubMeshes.Add(SM);
                    }

                    M.RawBuffer = VerticesConverter.GetBuffer(Vertices, M.Attributes);
                }
                else
                {
                    M.SubMeshes.Add(new H3DSubMesh()
                    {
                        Indices = Mesh.Indices
                    });
                }

                Model.AddMesh(M);

                Model.MeshNodesTree.Add($"Mesh_{Index++}");

                Model.MeshNodesVisibility.Add(true);
            }

            int BoneIndex = 0;

            foreach (MTBone Bone in Skeleton)
            {
                Model.Skeleton.Add(new H3DBone()
                {
                    Name        = $"Bone_{BoneIndex++}",
                    ParentIndex = Bone.ParentIndex,
                    Translation = Bone.Position,
                    Scale       = Vector3.One
                });
            }

            foreach (H3DBone Bone in Model.Skeleton)
            {
                Bone.CalculateTransform(Model.Skeleton);
            }

            if (Model.Materials.Count == 0)
            {
                Model.Materials.Add(H3DMaterial.GetSimpleMaterial(Model.Name, "DummyMaterial", null));
            }

            Output.Models.Add(Model);

            Output.CopyMaterials();

            return(Output);
        }
Пример #12
0
        public H3D ToH3D(string TextureAndMtlSearchPath = null)
        {
            H3D Output = new H3D();

            Dictionary <string, OBJMaterial> Materials = new Dictionary <string, OBJMaterial>();

            if (TextureAndMtlSearchPath != null)
            {
                string MaterialFile = Path.Combine(TextureAndMtlSearchPath, MtlFile);

                if (File.Exists(MaterialFile))
                {
                    string MaterialName = null;

                    OBJMaterial Material = default(OBJMaterial);

                    TextReader Reader = new StreamReader(MaterialFile);

                    for (string Line; (Line = Reader.ReadLine()) != null;)
                    {
                        string[] Params = Line.Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);

                        if (Params.Length == 0)
                        {
                            continue;
                        }

                        switch (Params[0])
                        {
                        case "newmtl":
                            if (Params.Length > 1)
                            {
                                if (MaterialName != null && Material.DiffuseTexture != null)
                                {
                                    Materials.Add(MaterialName, Material);
                                }

                                Material = new OBJMaterial();

                                MaterialName = Line.Substring(Line.IndexOf(" ")).Trim();
                            }
                            break;

                        case "map_Kd":
                            if (Params.Length > 1)
                            {
                                string Name = Line.Substring(Line.IndexOf(Params[1]));

                                string TextureFile = Path.Combine(TextureAndMtlSearchPath, Name);
                                string TextureName = Path.GetFileNameWithoutExtension(TextureFile);

                                if (File.Exists(TextureFile) && !Output.Textures.Contains(TextureName))
                                {
                                    Output.Textures.Add(new H3DTexture(TextureFile));
                                }

                                Material.DiffuseTexture = Path.GetFileNameWithoutExtension(TextureName);
                            }
                            break;

                        case "Ka":
                        case "Kd":
                        case "Ks":
                            if (Params.Length >= 4)
                            {
                                Vector4 Color = new Vector4(
                                    float.Parse(Params[1], CultureInfo.InvariantCulture),
                                    float.Parse(Params[2], CultureInfo.InvariantCulture),
                                    float.Parse(Params[3], CultureInfo.InvariantCulture), 1);

                                switch (Params[0])
                                {
                                case "Ka": Material.Ambient = Color; break;

                                case "Kd": Material.Diffuse = Color; break;

                                case "Ks": Material.Specular = Color; break;
                                }
                            }
                            break;
                        }
                    }

                    Reader.Dispose();

                    if (MaterialName != null && Material.DiffuseTexture != null)
                    {
                        Materials.Add(MaterialName, Material);
                    }
                }
            }

            H3DModel Model = new H3DModel();

            Model.Name = "Model";

            ushort MaterialIndex = 0;

            Model.Flags       = H3DModelFlags.HasSkeleton;
            Model.BoneScaling = H3DBoneScaling.Maya;
            Model.MeshNodesVisibility.Add(true);

            float Height = 0;

            foreach (OBJMesh Mesh in Meshes)
            {
                Vector3 MinVector = new Vector3();
                Vector3 MaxVector = new Vector3();

                Dictionary <PICAVertex, int> Vertices = new Dictionary <PICAVertex, int>();

                List <H3DSubMesh> SubMeshes = new List <H3DSubMesh>();

                Queue <PICAVertex> VerticesQueue = new Queue <PICAVertex>();

                foreach (PICAVertex Vertex in Mesh.Vertices)
                {
                    VerticesQueue.Enqueue(Vertex);
                }

                while (VerticesQueue.Count > 2)
                {
                    List <ushort> Indices = new List <ushort>();

                    while (VerticesQueue.Count > 0)
                    {
                        for (int Tri = 0; Tri < 3; Tri++)
                        {
                            PICAVertex Vertex = VerticesQueue.Dequeue();

                            if (Vertices.ContainsKey(Vertex))
                            {
                                Indices.Add((ushort)Vertices[Vertex]);
                            }
                            else
                            {
                                Indices.Add((ushort)Vertices.Count);

                                if (Vertex.Position.X < MinVector.X)
                                {
                                    MinVector.X = Vertex.Position.X;
                                }
                                if (Vertex.Position.Y < MinVector.Y)
                                {
                                    MinVector.Y = Vertex.Position.Y;
                                }
                                if (Vertex.Position.Z < MinVector.Z)
                                {
                                    MinVector.Z = Vertex.Position.Z;
                                }

                                if (Vertex.Position.X > MaxVector.X)
                                {
                                    MaxVector.X = Vertex.Position.X;
                                }
                                if (Vertex.Position.Y > MaxVector.Y)
                                {
                                    MaxVector.Y = Vertex.Position.Y;
                                }
                                if (Vertex.Position.Z > MaxVector.Z)
                                {
                                    MaxVector.Z = Vertex.Position.Z;
                                }

                                Vertices.Add(Vertex, Vertices.Count);
                            }
                        }
                    }

                    H3DSubMesh SM = new H3DSubMesh();

                    SM.BoneIndices = new ushort[] { 0 };
                    SM.Skinning    = H3DSubMeshSkinning.Smooth;
                    SM.Indices     = Indices.ToArray();

                    SubMeshes.Add(SM);
                }

                //Mesh
                List <PICAAttribute> Attributes = PICAAttribute.GetAttributes(
                    PICAAttributeName.Position,
                    PICAAttributeName.Normal,
                    PICAAttributeName.TexCoord0,
                    PICAAttributeName.Color,
                    PICAAttributeName.BoneIndex,
                    PICAAttributeName.BoneWeight);

                H3DMesh M = new H3DMesh(Vertices.Keys, Attributes, SubMeshes)
                {
                    Skinning      = H3DMeshSkinning.Smooth,
                    MeshCenter    = (MinVector + MaxVector) * 0.5f,
                    MaterialIndex = MaterialIndex
                };

                if (Height < MaxVector.Y)
                {
                    Height = MaxVector.Y;
                }

                //Material
                string MatName = $"Mat{MaterialIndex++.ToString("D5")}_{Mesh.MaterialName}";

                H3DMaterial Material = H3DMaterial.GetSimpleMaterial(Model.Name, MatName, null);

                if (Materials.ContainsKey(Mesh.MaterialName))
                {
                    Material.Texture0Name = Materials[Mesh.MaterialName].DiffuseTexture;
                }
                else
                {
                    Material.Texture0Name = "NoTexture";
                }

                Model.Materials.Add(Material);

                M.UpdateBoolUniforms(Material);

                Model.AddMesh(M);
            }

            /*
             * On Pokémon, the root bone (on the animaiton file) is used by the game to move
             * characters around, and all rigged bones are parented to this bone.
             * It's usually the Waist bone, that points upward and is half the character height.
             */
            Model.Skeleton.Add(new H3DBone(
                                   new Vector3(0, Height * 0.5f, 0),
                                   new Vector3(0, 0, (float)(Math.PI * 0.5)),
                                   Vector3.One,
                                   "Waist",
                                   -1));

            Model.Skeleton[0].CalculateTransform(Model.Skeleton);

            Output.Models.Add(Model);

            Output.CopyMaterials();

            return(Output);
        }
Пример #13
0
        public void Load(System.IO.Stream stream)
        {
            CanSave = false;

            Renderer = new CMB_Renderer();
            DrawableContainer.Drawables.Add(Renderer);


            Skeleton = new STSkeleton();
            //These models/skeletons come out massive so scale them with an overridden scale
            Skeleton.PreviewScale   = Renderer.PreviewScale;
            Skeleton.BonePointScale = 40;
            Renderer.Skeleton       = Skeleton;

            DrawableContainer.Drawables.Add(Skeleton);


            cmb.ReadCMB(stream);

            Text = cmb.Header.Name;

            DrawableContainer.Name = Text;

            //Load textures
            if (cmb.TexturesChunk != null)
            {
                texFolder = new TextureFolder("Texture");
                TreeNode meshFolder     = new TreeNode("Meshes");
                TreeNode materialFolder = new TreeNode("Materials");
                TreeNode skeletonFolder = new TreeNode("Skeleton");

                bool HasTextures = cmb.TexturesChunk.Textures != null &&
                                   cmb.TexturesChunk.Textures.Count != 0;

                bool HasMeshes = cmb.MeshesChunk.SHP.SEPDs != null &&
                                 cmb.MeshesChunk.SHP.SEPDs.Count != 0;

                bool HasSkeleton = cmb.SkeletonChunk != null &&
                                   cmb.SkeletonChunk.Bones.Count != 0;

                bool HasMaterials = cmb.MaterialsChunk != null &&
                                    cmb.MaterialsChunk.Materials.Count != 0;

                if (HasSkeleton)
                {
                    var bonesOrdered = cmb.SkeletonChunk.Bones.OrderBy(x => x.ID).ToList();
                    foreach (var bone in bonesOrdered)
                    {
                        STBone genericBone = new STBone(Skeleton);
                        genericBone.parentIndex = bone.ParentID;
                        genericBone.Checked     = true;

                        genericBone.Text         = $"Bone {bone.ID}";
                        genericBone.RotationType = STBone.BoneRotationType.Euler;

                        genericBone.Position = new OpenTK.Vector3(
                            bone.Translation.X,
                            bone.Translation.Y,
                            bone.Translation.Z
                            );
                        genericBone.EulerRotation = new OpenTK.Vector3(
                            bone.Rotation.X,
                            bone.Rotation.Y,
                            bone.Rotation.Z
                            );
                        genericBone.Scale = new OpenTK.Vector3(
                            bone.Scale.X,
                            bone.Scale.Y,
                            bone.Scale.Z
                            );
                        Skeleton.bones.Add(genericBone);
                    }

                    foreach (var bone in Skeleton.bones)
                    {
                        if (bone.Parent == null)
                        {
                            skeletonFolder.Nodes.Add(bone);
                        }
                    }

                    Skeleton.reset();
                    Skeleton.update();
                }

                if (HasTextures)
                {
                    int texIndex = 0;
                    foreach (var tex in cmb.TexturesChunk.Textures)
                    {
                        var texWrapper = new CTXB.TextureWrapper(new CTXB.Texture());
                        texWrapper.Text             = $"Texture {texIndex++}";
                        texWrapper.ImageKey         = "texture";
                        texWrapper.SelectedImageKey = texWrapper.ImageKey;

                        if (tex.Name != string.Empty)
                        {
                            texWrapper.Text = tex.Name;
                        }

                        texWrapper.Width  = tex.Width;
                        texWrapper.Height = tex.Height;
                        CTXB.Texture.TextureFormat Format = (CTXB.Texture.TextureFormat)((tex.DataType << 16) | tex.ImageFormat);

                        texWrapper.Format    = CTR_3DS.ConvertPICAToGenericFormat(CTXB.Texture.FormatList[Format]);
                        texWrapper.ImageData = tex.ImageData;
                        texFolder.Nodes.Add(texWrapper);

                        Renderer.TextureList.Add(texWrapper);
                    }
                }

                if (HasMaterials)
                {
                    int materialIndex = 0;
                    foreach (var mat in cmb.MaterialsChunk.Materials)
                    {
                        H3DMaterial H3D = ToH3DMaterial(mat);

                        CMBMaterialWrapper material = new CMBMaterialWrapper(mat, this, H3D);
                        material.Text = $"Material {materialIndex++}";
                        materialFolder.Nodes.Add(material);
                        Materials.Add(material);

                        bool HasDiffuse = false;
                        foreach (var tex in mat.TextureMappers)
                        {
                            if (tex.TextureID != -1)
                            {
                                CMBTextureMapWrapper matTexture = new CMBTextureMapWrapper(tex, this);
                                matTexture.TextureIndex = tex.TextureID;
                                material.TextureMaps.Add(matTexture);

                                if (tex.TextureID < Renderer.TextureList.Count && tex.TextureID >= 0)
                                {
                                    matTexture.Name = Renderer.TextureList[tex.TextureID].Text;
                                    material.Nodes.Add(matTexture.Name);
                                }

                                if (!HasDiffuse && matTexture.Name != "bg_syadowmap") //Quick hack till i do texture env stuff
                                {
                                    matTexture.Type = STGenericMatTexture.TextureType.Diffuse;
                                    HasDiffuse      = true;
                                }
                            }
                        }
                    }
                }

                if (HasMeshes)
                {
                    int MeshIndex = 0;
                    foreach (var mesh in cmb.MeshesChunk.MSHS.Meshes)
                    {
                        STGenericMaterial mat = Materials[mesh.MaterialIndex];

                        CmbMeshWrapper genericMesh = new CmbMeshWrapper(mat);
                        genericMesh.Text          = $"Mesh_{MeshIndex++}_ID_{mesh.VisIndex}";
                        genericMesh.MaterialIndex = mesh.MaterialIndex;

                        var shape = cmb.MeshesChunk.SHP.SEPDs[mesh.SEPDIndex];
                        genericMesh.Mesh = shape;

                        List <ushort> SkinnedBoneTable = new List <ushort>();
                        foreach (var prim in shape.PRMS)
                        {
                            if (prim.BoneIndices != null)
                            {
                                SkinnedBoneTable.AddRange(prim.BoneIndices);
                            }
                        }

                        //Now load the vertex and face data

                        foreach (var prm in shape.PRMS)
                        {
                            if (shape.HasPosition)
                            {
                                int VertexCount = prm.VertexCount;
                                for (int v = 0; v < VertexCount; v++)
                                {
                                    Vertex vert = new Vertex();
                                    vert.pos = new OpenTK.Vector3(
                                        prm.Vertices.Position[v].X,
                                        prm.Vertices.Position[v].Y,
                                        prm.Vertices.Position[v].Z);
                                    if (shape.HasNormal)
                                    {
                                        vert.nrm = new OpenTK.Vector3(
                                            prm.Vertices.Normal[v].X,
                                            prm.Vertices.Normal[v].Y,
                                            prm.Vertices.Normal[v].Z).Normalized();
                                    }

                                    if (shape.HasColor)
                                    {
                                        vert.col = new OpenTK.Vector4(
                                            prm.Vertices.Color[v].X,
                                            prm.Vertices.Color[v].Y,
                                            prm.Vertices.Color[v].Z,
                                            prm.Vertices.Color[v].W).Normalized();
                                    }

                                    if (shape.HasUV0)
                                    {
                                        vert.uv0 = new OpenTK.Vector2(prm.Vertices.UV0[v].X, -prm.Vertices.UV0[v].Y + 1);
                                    }

                                    if (shape.HasUV1)
                                    {
                                        vert.uv1 = new OpenTK.Vector2(prm.Vertices.UV1[v].X, -prm.Vertices.UV1[v].Y + 1);
                                    }

                                    if (shape.HasUV2)
                                    {
                                        vert.uv2 = new OpenTK.Vector2(prm.Vertices.UV2[v].X, -prm.Vertices.UV2[v].Y + 1);
                                    }

                                    if (prm.SkinningMode == SkinningMode.Smooth)
                                    {
                                        //Indices
                                        if (shape.HasIndices)
                                        {
                                            if (shape.BoneDimensionCount >= 1)
                                            {
                                                vert.boneIds.Add((int)prm.Vertices.BoneIndices[v].X);
                                            }
                                            if (shape.BoneDimensionCount >= 2)
                                            {
                                                vert.boneIds.Add((int)prm.Vertices.BoneIndices[v].Y);
                                            }
                                            if (shape.BoneDimensionCount >= 3)
                                            {
                                                vert.boneIds.Add((int)prm.Vertices.BoneIndices[v].Z);
                                            }
                                            if (shape.BoneDimensionCount >= 4)
                                            {
                                                vert.boneIds.Add((int)prm.Vertices.BoneIndices[v].W);
                                            }
                                        }

                                        //Weights
                                        if (shape.HasWeights)
                                        {
                                            if (shape.BoneDimensionCount >= 1)
                                            {
                                                vert.boneWeights.Add(prm.Vertices.BoneWeights[v].X);
                                            }
                                            if (shape.BoneDimensionCount >= 2)
                                            {
                                                vert.boneWeights.Add(prm.Vertices.BoneWeights[v].Y);
                                            }
                                            if (shape.BoneDimensionCount >= 3)
                                            {
                                                vert.boneWeights.Add(prm.Vertices.BoneWeights[v].Z);
                                            }
                                            if (shape.BoneDimensionCount >= 4)
                                            {
                                                vert.boneWeights.Add(prm.Vertices.BoneWeights[v].W);
                                            }
                                        }
                                    }

                                    if (prm.SkinningMode == SkinningMode.Rigid)
                                    {
                                        int boneId = (int)prm.Vertices.BoneIndices[v].X;
                                        vert.boneIds.Add(boneId);
                                        vert.boneWeights.Add(1);

                                        vert.pos = OpenTK.Vector3.TransformPosition(vert.pos, Skeleton.bones[boneId].Transform);
                                        if (shape.HasNormal)
                                        {
                                            vert.nrm = OpenTK.Vector3.TransformNormal(vert.nrm, Skeleton.bones[boneId].Transform);
                                        }
                                    }

                                    if (prm.SkinningMode == SkinningMode.Mixed)
                                    {
                                        int boneId = prm.BoneIndices[0];
                                        vert.boneIds.Add(boneId);
                                        vert.boneWeights.Add(1);

                                        vert.pos = OpenTK.Vector3.TransformPosition(vert.pos, Skeleton.bones[boneId].Transform);
                                        if (shape.HasNormal)
                                        {
                                            vert.nrm = OpenTK.Vector3.TransformNormal(vert.nrm, Skeleton.bones[boneId].Transform);
                                        }
                                    }

                                    genericMesh.vertices.Add(vert);
                                }
                            }

                            STGenericPolygonGroup group = new STGenericPolygonGroup();
                            genericMesh.PolygonGroups.Add(group);

                            for (int i = 0; i < prm.FaceIndices.Count; i++)
                            {
                                group.faces.Add((int)prm.FaceIndices[i].X);
                                group.faces.Add((int)prm.FaceIndices[i].Y);
                                group.faces.Add((int)prm.FaceIndices[i].Z);
                            }
                        }

                        Renderer.Meshes.Add(genericMesh);
                        meshFolder.Nodes.Add(genericMesh);
                    }
                }

                if (meshFolder.Nodes.Count > 0)
                {
                    Nodes.Add(meshFolder);
                }

                if (skeletonFolder.Nodes.Count > 0)
                {
                    Nodes.Add(skeletonFolder);
                }

                if (materialFolder.Nodes.Count > 0)
                {
                    Nodes.Add(materialFolder);
                }

                if (texFolder.Nodes.Count > 0)
                {
                    Nodes.Add(texFolder);
                }
            }
        }
Пример #14
0
 public CMBMaterialWrapper(Material material, CMB cmb, H3DMaterial h3D) : base(h3D)
 {
     ParentCMB   = cmb;
     CMBMaterial = material;
 }
Пример #15
0
        public Mesh(Model Parent, H3DMesh BaseMesh)
        {
            this.Parent   = Parent;
            this.BaseMesh = BaseMesh;

            Material = Parent.BaseModel.Materials[BaseMesh.MaterialIndex];

            PosOffs = BaseMesh.PositionOffset.ToVector4();

            int VtxCount = 1, FAOffset = 0;

            if (BaseMesh.VertexStride > 0)
            {
                VtxCount = BaseMesh.RawBuffer.Length / BaseMesh.VertexStride;
                FAOffset = BaseMesh.RawBuffer.Length;
            }

            byte[] Buffer;

            using (MemoryStream VertexStream = new MemoryStream())
            {
                BinaryWriter Writer = new BinaryWriter(VertexStream);

                Writer.Write(BaseMesh.RawBuffer);

                VertexStream.Seek(0, SeekOrigin.End);

                foreach (PICAFixedAttribute Attrib in BaseMesh.FixedAttributes)
                {
                    /*
                     * OpenGL doesn't support constant attributes, so we need to write
                     * them as a tight array (waste of space).
                     */
                    for (int i = 0; i < VtxCount; i++)
                    {
                        Writer.Write(Attrib.Value.X);
                        Writer.Write(Attrib.Value.Y);
                        Writer.Write(Attrib.Value.Z);
                        Writer.Write(Attrib.Value.W);
                    }
                }

                Buffer = VertexStream.ToArray();
            }

            IntPtr Length = new IntPtr(Buffer.Length);

            VBOHandle = GL.GenBuffer();
            VAOHandle = GL.GenVertexArray();

            GL.BindBuffer(BufferTarget.ArrayBuffer, VBOHandle);
            GL.BufferData(BufferTarget.ArrayBuffer, Length, Buffer, BufferUsageHint.StaticDraw);
            GL.BindBuffer(BufferTarget.ArrayBuffer, 0);

            GL.BindVertexArray(VAOHandle);

            int Offset = 0;
            int Stride = BaseMesh.VertexStride;

            for (int AttribIndex = 0; AttribIndex < 16; AttribIndex++)
            {
                GL.DisableVertexAttribArray(AttribIndex);
            }

            foreach (PICAAttribute Attrib in BaseMesh.Attributes)
            {
                int Size = Attrib.Elements;

                VertexAttribPointerType Type = VertexAttribPointerType.Byte;

                switch (Attrib.Format)
                {
                case PICAAttributeFormat.Byte:  Type = VertexAttribPointerType.Byte;              break;

                case PICAAttributeFormat.Ubyte: Type = VertexAttribPointerType.UnsignedByte;      break;

                case PICAAttributeFormat.Short: Type = VertexAttribPointerType.Short; Size <<= 1; break;

                case PICAAttributeFormat.Float: Type = VertexAttribPointerType.Float; Size <<= 2; break;
                }

                int AttribIndex = (int)Attrib.Name;

                GL.EnableVertexAttribArray(AttribIndex);

                GL.BindBuffer(BufferTarget.ArrayBuffer, VBOHandle);

                //Short and Float types needs to be aligned into 2 bytes boundaries.
                if (Attrib.Format != PICAAttributeFormat.Byte &&
                    Attrib.Format != PICAAttributeFormat.Ubyte)
                {
                    Offset += Offset & 1;
                }

                GL.VertexAttribPointer(AttribIndex, Attrib.Elements, Type, false, Stride, Offset);

                SetScale(Attrib.Name, Attrib.Scale);

                Offset += Size;
            }

            foreach (PICAFixedAttribute Attrib in BaseMesh.FixedAttributes)
            {
                int AttribIndex = (int)Attrib.Name;

                GL.EnableVertexAttribArray(AttribIndex);

                GL.BindBuffer(BufferTarget.ArrayBuffer, VBOHandle);

                GL.VertexAttribPointer(AttribIndex, 4, VertexAttribPointerType.Float, false, 0, FAOffset);

                /*
                 * Pokémon Sun/Moon seems to have fixed attributes for all unused attributes,
                 * with the vector set to zero (?). On the H3D shader this would normally
                 * make the Tangent scale one, and this signals the shader to use the Tangent
                 * to calculate the normal quaternion, and that would ruin the lighting
                 * 'cause the tangent is actually zero, so we force it to use normals by
                 * setting the Scale to zero here. Using the original Sun/Moon shaders
                 * should avoid this issue entirely.
                 */
                SetScale(Attrib.Name, Attrib.Name != PICAAttributeName.Tangent ? 1 : 0);

                FAOffset += 0x10 * VtxCount;
            }

            GL.BindVertexArray(0);
        }
Пример #16
0
        /// <summary>
        /// Creates MaxScript code to create a bitmap texture map for the selected texture in the given material
        /// </summary>
        /// <param name="mat">The H3D material containing the desired texture</param>
        /// <param name="idx">the index of the desired texture</param>
        /// <returns>MaxScript code string</returns>
        private string GetTextureString(H3DMaterial mat, int idx)
        {
            StringBuilder txtString = new StringBuilder($"txt{idx} = bitmapTexture()\n");

            switch (idx) //Select the texture from the material
            {
            case 1:  txtString.AppendLine($"txt{idx}.filename = scriptPath + \"/{mat.Texture1Name}.png\""); break;

            case 2:  txtString.AppendLine($"txt{idx}.filename = scriptPath + \"/{mat.Texture2Name}.png\""); break;

            default: txtString.AppendLine($"txt{idx}.filename = scriptPath + \"/{mat.Texture0Name}.png\""); break;
            }

            //set map name and disable pre-multiplied alpha
            txtString.AppendLine($"txt{idx}.name = \"{mat.Name}_txt{idx}\"");
            txtString.AppendLine($"txt{idx}.preMultAlpha = false");

            //if alpha test is enabled, disable alpha on the diffuse texture
            if (mat.MaterialParams.AlphaTest.Enabled)
            {
                txtString.AppendLine($"txt{idx}.alphasource = 2");              //TODO: ensure this doesn't interfere with decal textures (or anything else for that matter)
            }
            //if texture uses non-default map channel, add the code to set it
            if (mat.MaterialParams.TextureSources[idx] > 0)
            {
                txtString.AppendLine($"txt{idx}.coordinates.mapChannel = {mat.MaterialParams.TextureSources[idx]+1}");
            }

            //set translation if non-zero
            if (mat.MaterialParams.TextureCoords[idx].Translation != new Vector2(0))
            {
                txtString.AppendLine($"txt{idx}.coordinates.U_Offset = {mat.MaterialParams.TextureCoords[idx].Translation.X}");
                txtString.AppendLine($"txt{idx}.coordinates.V_Offset = {mat.MaterialParams.TextureCoords[idx].Translation.Y}");
            }

            //set rotation if non-zero (Max needs degrees, so convert)
            if (mat.MaterialParams.TextureCoords[idx].Rotation != 0)
            {
                txtString.AppendLine($"txt{idx}.coordinates.W_Angle = {180*mat.MaterialParams.TextureCoords[idx].Rotation/Math.PI}");
            }

            //set scale if not one
            if (mat.MaterialParams.TextureCoords[idx].Scale != new Vector2(1))
            {
                txtString.AppendLine($"txt{idx}.coordinates.U_Tiling = {mat.MaterialParams.TextureCoords[idx].Scale.X}");
                txtString.AppendLine($"txt{idx}.coordinates.V_Tiling = {mat.MaterialParams.TextureCoords[idx].Scale.Y}");
            }

            //set map wrapping  //TODO: this sucks, do it better
            //TODO: mirroring seems to mess with scaling. Correct it in here?
            switch (mat.TextureMappers[idx].WrapU)
            {
            //SPICA.PICA.Commands.PICATextureWrap.Repeat //Max's Default
            case PICATextureWrap.Mirror:
                txtString.AppendLine($"txt{idx}.coordinates.U_Mirror = true");
                break;

            case PICATextureWrap.ClampToEdge:
                txtString.AppendLine($"--TODO: txt{idx} ClampToEdge U");
                break;

            case PICATextureWrap.ClampToBorder:
                txtString.AppendLine($"--TODO: txt{idx} ClampToBorder U");
                break;
            }
            switch (mat.TextureMappers[idx].WrapV)
            {
            //SPICA.PICA.Commands.PICATextureWrap.Repeat //Max's Default
            case PICATextureWrap.Mirror:
                txtString.AppendLine($"txt{idx}.coordinates.V_Mirror = true");
                break;

            case PICATextureWrap.ClampToEdge:
                txtString.AppendLine($"--TODO: txt{idx} ClampToEdge V");
                break;

            case PICATextureWrap.ClampToBorder:
                txtString.AppendLine($"--TODO: txt{idx} ClampToBorder V");
                break;
            }

            txtString.AppendLine($"--TODO: txt{idx} Mapping Type: {mat.MaterialParams.TextureCoords[idx].MappingType}");

            //TODO: add support for additional mapping settings?

            return(txtString.ToString());
        }
Пример #17
0
        public H3DModel ToH3DModel()
        {
            H3DModel Output = new H3DModel()
            {
                Name = Name
            };

            //Skeleton
            foreach (GFBone Bone in Skeleton)
            {
                Output.Skeleton.Add(new H3DBone()
                {
                    ParentIndex = (short)Skeleton.FindIndex(x => x.Name == Bone.Parent),

                    Name        = Bone.Name,
                    Scale       = Bone.Scale,
                    Rotation    = Bone.Rotation,
                    Translation = Bone.Translation
                });
            }

            foreach (H3DBone Bone in Output.Skeleton)
            {
                Bone.CalculateTransform(Output.Skeleton);

                Bone.Flags |= H3DBoneFlags.IsSegmentScaleCompensate;
            }

            if (Output.Skeleton.Count > 0)
            {
                Output.Flags = H3DModelFlags.HasSkeleton;
            }

            //Materials
            foreach (GFMaterial Material in Materials)
            {
                H3DMaterial Mat = new H3DMaterial();

                H3DMaterialParams Params = Mat.MaterialParams;

                Mat.Name = Material.MaterialName;

                Params.FragmentFlags = H3DFragmentFlags.IsLUTReflectionEnabled;

                Array.Copy(Material.TextureSources, Params.TextureSources, 4);

                for (int Unit = 0; Unit < Material.TextureCoords.Length; Unit++)
                {
                    string TextureName = Material.TextureCoords[Unit].Name;

                    Mat.EnabledTextures[Unit] = TextureName != null;

                    switch (Unit)
                    {
                    case 0: Mat.Texture0Name = TextureName; break;

                    case 1: Mat.Texture1Name = TextureName; break;

                    case 2: Mat.Texture2Name = TextureName; break;
                    }

                    //Texture Coords
                    GFTextureMappingType MappingType = Material.TextureCoords[Unit].MappingType;

                    Params.TextureCoords[Unit].MappingType = (H3DTextureMappingType)MappingType;

                    Params.TextureCoords[Unit].Scale       = Material.TextureCoords[Unit].Scale;
                    Params.TextureCoords[Unit].Rotation    = Material.TextureCoords[Unit].Rotation;
                    Params.TextureCoords[Unit].Translation = Material.TextureCoords[Unit].Translation;

                    //Texture Mapper
                    Mat.TextureMappers[Unit].WrapU = (PICATextureWrap)Material.TextureCoords[Unit].WrapU;
                    Mat.TextureMappers[Unit].WrapV = (PICATextureWrap)Material.TextureCoords[Unit].WrapV;

                    Mat.TextureMappers[Unit].MagFilter = (H3DTextureMagFilter)Material.TextureCoords[Unit].MagFilter;
                    Mat.TextureMappers[Unit].MinFilter = (H3DTextureMinFilter)Material.TextureCoords[Unit].MinFilter;

                    Mat.TextureMappers[Unit].MinLOD = (byte)Material.TextureCoords[Unit].MinLOD;

                    Mat.TextureMappers[Unit].BorderColor = Material.BorderColor[Unit];
                }

                Params.EmissionColor  = Material.EmissionColor;
                Params.AmbientColor   = Material.AmbientColor;
                Params.DiffuseColor   = Material.DiffuseColor;
                Params.Specular0Color = Material.Specular0Color;
                Params.Specular1Color = Material.Specular1Color;
                Params.Constant0Color = Material.Constant0Color;
                Params.Constant1Color = Material.Constant1Color;
                Params.Constant2Color = Material.Constant2Color;
                Params.Constant3Color = Material.Constant3Color;
                Params.Constant4Color = Material.Constant4Color;
                Params.Constant5Color = Material.Constant5Color;
                Params.BlendColor     = Material.BlendColor;

                //HACK: It's usually 0 on Sun/Moon, this causes issues on some
                //models being rendered transparent (Shader differences).
                Params.DiffuseColor.A = 0xff;

                Params.ColorScale = 1f;

                Params.LUTInputAbsolute  = Material.LUTInputAbsolute;
                Params.LUTInputSelection = Material.LUTInputSelection;
                Params.LUTInputScale     = Material.LUTInputScale;

                Params.ColorOperation   = Material.ColorOperation;
                Params.BlendFunction    = Material.BlendFunction;
                Params.LogicalOperation = Material.LogicalOperation;
                Params.AlphaTest        = Material.AlphaTest;
                Params.StencilTest      = Material.StencilTest;
                Params.StencilOperation = Material.StencilOperation;
                Params.DepthColorMask   = Material.DepthColorMask;
                Params.FaceCulling      = Material.FaceCulling;

                Params.ColorBufferRead  = Material.ColorBufferRead;
                Params.ColorBufferWrite = Material.ColorBufferWrite;

                Params.StencilBufferRead  = Material.StencilBufferRead;
                Params.StencilBufferWrite = Material.StencilBufferWrite;

                Params.DepthBufferRead  = Material.DepthBufferRead;
                Params.DepthBufferWrite = Material.DepthBufferWrite;

                if (Material.LUT0HashId != 0)
                {
                    Params.LUTReflecRTableName   = DefaultLUTName;
                    Params.LUTReflecRSamplerName = GetLUTName(Material.LUT0HashId);
                }

                if (Material.LUT1HashId != 0)
                {
                    Params.LUTReflecGTableName   = DefaultLUTName;
                    Params.LUTReflecGSamplerName = GetLUTName(Material.LUT1HashId);
                }

                if (Material.LUT2HashId != 0)
                {
                    Params.LUTReflecBTableName   = DefaultLUTName;
                    Params.LUTReflecBSamplerName = GetLUTName(Material.LUT2HashId);
                }

                if (Material.BumpTexture != -1)
                {
                    Params.BumpTexture = (byte)Material.BumpTexture;
                    Params.BumpMode    = H3DBumpMode.AsBump;
                }

                Params.Constant0Assignment = Material.Constant0Assignment;
                Params.Constant1Assignment = Material.Constant1Assignment;
                Params.Constant2Assignment = Material.Constant2Assignment;
                Params.Constant3Assignment = Material.Constant3Assignment;
                Params.Constant4Assignment = Material.Constant4Assignment;
                Params.Constant5Assignment = Material.Constant5Assignment;

                string VtxShaderName = Material.VtxShaderName;

                //Make shader names match X/Y/OR/AS shader names.
                if (VtxShaderName == "Poke" ||
                    VtxShaderName == "PokeNormal")
                {
                    VtxShaderName = "PokePack";
                }

                Params.ShaderReference = $"0@{VtxShaderName}";
                Params.ModelReference  = $"{Mat.Name}@{Name}";

                /*
                 * Add those for compatibility with the older BCH models.
                 * It's worth noting that ShaderParam0 is usually used as "UVScale" on model that uses
                 * geometry shader to make billboarded point sprites. On the new shader it have a
                 * multiplication of the Color by 3, while the older one doesn't have such multiplication,
                 * so for compatibility with the older shader, the easiest thing to do is just multiply the
                 * scale by 3 to give the same results on the old shader.
                 */
                Params.MetaData = new H3DMetaData();

                Params.MetaData.Add(new H3DMetaDataValue("EdgeType", Material.EdgeType));
                Params.MetaData.Add(new H3DMetaDataValue("IDEdgeEnable", Material.IDEdgeEnable));
                Params.MetaData.Add(new H3DMetaDataValue("EdgeID", Material.EdgeID));

                Params.MetaData.Add(new H3DMetaDataValue("ProjectionType", Material.ProjectionType));

                Params.MetaData.Add(new H3DMetaDataValue("RimPow", Material.RimPower));
                Params.MetaData.Add(new H3DMetaDataValue("RimScale", Material.RimScale));
                Params.MetaData.Add(new H3DMetaDataValue("PhongPow", Material.PhongPower));
                Params.MetaData.Add(new H3DMetaDataValue("PhongScale", Material.PhongScale));

                Params.MetaData.Add(new H3DMetaDataValue("IDEdgeOffsetEnable", Material.IDEdgeOffsetEnable));

                Params.MetaData.Add(new H3DMetaDataValue("EdgeMapAlphaMask", Material.EdgeMapAlphaMask));

                Params.MetaData.Add(new H3DMetaDataValue("BakeTexture0", Material.BakeTexture0));
                Params.MetaData.Add(new H3DMetaDataValue("BakeTexture1", Material.BakeTexture1));
                Params.MetaData.Add(new H3DMetaDataValue("BakeTexture2", Material.BakeTexture2));
                Params.MetaData.Add(new H3DMetaDataValue("BakeConstant0", Material.BakeConstant0));
                Params.MetaData.Add(new H3DMetaDataValue("BakeConstant1", Material.BakeConstant1));
                Params.MetaData.Add(new H3DMetaDataValue("BakeConstant2", Material.BakeConstant2));
                Params.MetaData.Add(new H3DMetaDataValue("BakeConstant3", Material.BakeConstant3));
                Params.MetaData.Add(new H3DMetaDataValue("BakeConstant4", Material.BakeConstant4));
                Params.MetaData.Add(new H3DMetaDataValue("BakeConstant5", Material.BakeConstant5));

                Params.MetaData.Add(new H3DMetaDataValue("VertexShaderType", Material.VertexShaderType));

                Params.MetaData.Add(new H3DMetaDataValue("ShaderParam0", Material.ShaderParam0 * 3));
                Params.MetaData.Add(new H3DMetaDataValue("ShaderParam1", Material.ShaderParam1));
                Params.MetaData.Add(new H3DMetaDataValue("ShaderParam2", Material.ShaderParam2));
                Params.MetaData.Add(new H3DMetaDataValue("ShaderParam3", Material.ShaderParam3));

                Output.Materials.Add(Mat);
            }

            //Meshes
            Output.MeshNodesTree = new H3DPatriciaTree();

            foreach (GFMesh Mesh in Meshes)
            {
                //Note: GFModel have one Vertex Buffer for each SubMesh,
                //while on H3D all SubMeshes shares the same Vertex Buffer.
                //For this reason we need to store SubMeshes as Meshes on H3D.
                foreach (GFSubMesh SubMesh in Mesh.SubMeshes)
                {
                    int NodeIndex = Output.MeshNodesTree.Find(Mesh.Name);

                    if (NodeIndex == -1)
                    {
                        Output.MeshNodesTree.Add(Mesh.Name);
                        Output.MeshNodesVisibility.Add(true);

                        NodeIndex = Output.MeshNodesCount++;
                    }

                    List <H3DSubMesh> SubMeshes = new List <H3DSubMesh>();

                    ushort[] BoneIndices = new ushort[SubMesh.BoneIndicesCount];

                    for (int Index = 0; Index < BoneIndices.Length; Index++)
                    {
                        BoneIndices[Index] = SubMesh.BoneIndices[Index];
                    }

                    H3DSubMeshSkinning SMSk = Output.Skeleton.Count > 0
                        ? H3DSubMeshSkinning.Smooth
                        : H3DSubMeshSkinning.None;

                    SubMeshes.Add(new H3DSubMesh()
                    {
                        Skinning         = SMSk,
                        BoneIndicesCount = SubMesh.BoneIndicesCount,
                        BoneIndices      = BoneIndices,
                        Indices          = SubMesh.Indices
                    });

                    H3DMesh M = new H3DMesh(
                        SubMesh.RawBuffer,
                        SubMesh.VertexStride,
                        SubMesh.Attributes,
                        SubMesh.FixedAttributes,
                        SubMeshes);

                    M.Skinning = H3DMeshSkinning.Smooth;

                    int MatIndex = Materials.FindIndex(x => x.MaterialName == SubMesh.Name);

                    GFMaterial Mat = Materials[MatIndex];

                    M.MaterialIndex = (ushort)MatIndex;
                    M.NodeIndex     = (ushort)NodeIndex;
                    M.Layer         = Mat.RenderLayer;
                    M.Priority      = Mat.RenderPriority;

                    M.UpdateBoolUniforms(Output.Materials[MatIndex]);

                    Output.AddMesh(M);
                }
            }

            return(Output);
        }
Пример #18
0
        public H3D ToH3D()
        {
            H3D Output = new H3D();

            foreach (GfxModel Model in Models)
            {
                H3DModel Mdl = new H3DModel();

                Mdl.Name = Model.Name;

                Mdl.WorldTransform = Model.WorldTransform;

                foreach (GfxMaterial Material in Model.Materials)
                {
                    H3DMaterial Mat = new H3DMaterial()
                    {
                        Name = Material.Name
                    };

                    Mat.MaterialParams.ModelReference  = $"{Mat.Name}@{Model.Name}";
                    Mat.MaterialParams.ShaderReference = "0@DefaultShader";

                    Mat.MaterialParams.Flags = (H3DMaterialFlags)Material.Flags;

                    Mat.MaterialParams.TranslucencyKind = (H3DTranslucencyKind)Material.TranslucencyKind;
                    Mat.MaterialParams.TexCoordConfig   = (H3DTexCoordConfig)Material.TexCoordConfig;

                    Mat.MaterialParams.EmissionColor  = Material.Colors.Emission;
                    Mat.MaterialParams.AmbientColor   = Material.Colors.Ambient;
                    Mat.MaterialParams.DiffuseColor   = Material.Colors.Diffuse;
                    Mat.MaterialParams.Specular0Color = Material.Colors.Specular0;
                    Mat.MaterialParams.Specular1Color = Material.Colors.Specular1;
                    Mat.MaterialParams.Constant0Color = Material.Colors.Constant0;
                    Mat.MaterialParams.Constant1Color = Material.Colors.Constant1;
                    Mat.MaterialParams.Constant2Color = Material.Colors.Constant2;
                    Mat.MaterialParams.Constant3Color = Material.Colors.Constant3;
                    Mat.MaterialParams.Constant4Color = Material.Colors.Constant4;
                    Mat.MaterialParams.Constant5Color = Material.Colors.Constant5;
                    Mat.MaterialParams.ColorScale     = Material.Colors.Scale;

                    if (Material.Rasterization.IsPolygonOffsetEnabled)
                    {
                        Mat.MaterialParams.Flags |= H3DMaterialFlags.IsPolygonOffsetEnabled;
                    }

                    Mat.MaterialParams.FaceCulling       = Material.Rasterization.FaceCulling.ToPICAFaceCulling();
                    Mat.MaterialParams.PolygonOffsetUnit = Material.Rasterization.PolygonOffsetUnit;

                    Mat.MaterialParams.DepthColorMask = Material.FragmentOperation.Depth.ColorMask;

                    Mat.MaterialParams.DepthColorMask.RedWrite   = true;
                    Mat.MaterialParams.DepthColorMask.GreenWrite = true;
                    Mat.MaterialParams.DepthColorMask.BlueWrite  = true;
                    Mat.MaterialParams.DepthColorMask.AlphaWrite = true;
                    Mat.MaterialParams.DepthColorMask.DepthWrite = true;

                    Mat.MaterialParams.ColorBufferRead  = false;
                    Mat.MaterialParams.ColorBufferWrite = true;

                    Mat.MaterialParams.StencilBufferRead  = false;
                    Mat.MaterialParams.StencilBufferWrite = false;

                    Mat.MaterialParams.DepthBufferRead  = true;
                    Mat.MaterialParams.DepthBufferWrite = true;

                    Mat.MaterialParams.ColorOperation   = Material.FragmentOperation.Blend.ColorOperation;
                    Mat.MaterialParams.LogicalOperation = Material.FragmentOperation.Blend.LogicalOperation;
                    Mat.MaterialParams.BlendFunction    = Material.FragmentOperation.Blend.Function;
                    Mat.MaterialParams.BlendColor       = Material.FragmentOperation.Blend.Color;

                    Mat.MaterialParams.StencilOperation = Material.FragmentOperation.Stencil.Operation;
                    Mat.MaterialParams.StencilTest      = Material.FragmentOperation.Stencil.Test;

                    int TCIndex = 0;

                    foreach (GfxTextureCoord TexCoord in Material.TextureCoords)
                    {
                        H3DTextureCoord TC = new H3DTextureCoord();

                        TC.MappingType = (H3DTextureMappingType)TexCoord.MappingType;

                        TC.ReferenceCameraIndex = (sbyte)TexCoord.ReferenceCameraIndex;

                        TC.TransformType = (H3DTextureTransformType)TexCoord.TransformType;

                        TC.Scale       = TexCoord.Scale;
                        TC.Rotation    = TexCoord.Rotation;
                        TC.Translation = TexCoord.Translation;

                        switch (TexCoord.MappingType)
                        {
                        case GfxTextureMappingType.UvCoordinateMap:
                            Mat.MaterialParams.TextureSources[TCIndex] = TexCoord.SourceCoordIndex;
                            break;

                        case GfxTextureMappingType.CameraCubeEnvMap:
                            Mat.MaterialParams.TextureSources[TCIndex] = 3;
                            break;

                        case GfxTextureMappingType.CameraSphereEnvMap:
                            Mat.MaterialParams.TextureSources[TCIndex] = 4;
                            break;
                        }

                        Mat.MaterialParams.TextureCoords[TCIndex++] = TC;

                        if (TCIndex == Material.UsedTextureCoordsCount)
                        {
                            break;
                        }
                    }

                    int TMIndex = 0;

                    foreach (GfxTextureMapper TexMapper in Material.TextureMappers)
                    {
                        if (TexMapper == null)
                        {
                            break;
                        }

                        H3DTextureMapper TM = new H3DTextureMapper();

                        TM.WrapU = TexMapper.WrapU;
                        TM.WrapV = TexMapper.WrapV;

                        TM.MagFilter = (H3DTextureMagFilter)TexMapper.MinFilter;

                        switch ((uint)TexMapper.MagFilter | ((uint)TexMapper.MipFilter << 1))
                        {
                        case 0: TM.MinFilter = H3DTextureMinFilter.NearestMipmapNearest; break;

                        case 1: TM.MinFilter = H3DTextureMinFilter.LinearMipmapNearest;  break;

                        case 2: TM.MinFilter = H3DTextureMinFilter.NearestMipmapLinear;  break;

                        case 3: TM.MinFilter = H3DTextureMinFilter.LinearMipmapLinear;   break;
                        }

                        TM.LODBias = TexMapper.LODBias;
                        TM.MinLOD  = TexMapper.MinLOD;

                        TM.BorderColor = TexMapper.BorderColor;

                        Mat.TextureMappers[TMIndex++] = TM;
                    }

                    Mat.EnabledTextures[0] = Material.TextureMappers[0] != null;
                    Mat.EnabledTextures[1] = Material.TextureMappers[1] != null;
                    Mat.EnabledTextures[2] = Material.TextureMappers[2] != null;

                    Mat.Texture0Name = Material.TextureMappers[0]?.Texture.Path;
                    Mat.Texture1Name = Material.TextureMappers[1]?.Texture.Path;
                    Mat.Texture2Name = Material.TextureMappers[2]?.Texture.Path;

                    GfxFragmentFlags SrcFlags = Material.FragmentShader.Lighting.Flags;
                    H3DFragmentFlags DstFlags = 0;

                    if ((SrcFlags & GfxFragmentFlags.IsClampHighLightEnabled) != 0)
                    {
                        DstFlags |= H3DFragmentFlags.IsClampHighLightEnabled;
                    }

                    if ((SrcFlags & GfxFragmentFlags.IsLUTDist0Enabled) != 0)
                    {
                        DstFlags |= H3DFragmentFlags.IsLUTDist0Enabled;
                    }

                    if ((SrcFlags & GfxFragmentFlags.IsLUTDist1Enabled) != 0)
                    {
                        DstFlags |= H3DFragmentFlags.IsLUTDist1Enabled;
                    }

                    if ((SrcFlags & GfxFragmentFlags.IsLUTGeoFactor0Enabled) != 0)
                    {
                        DstFlags |= H3DFragmentFlags.IsLUTGeoFactor0Enabled;
                    }

                    if ((SrcFlags & GfxFragmentFlags.IsLUTGeoFactor1Enabled) != 0)
                    {
                        DstFlags |= H3DFragmentFlags.IsLUTGeoFactor1Enabled;
                    }

                    if ((SrcFlags & GfxFragmentFlags.IsLUTReflectionEnabled) != 0)
                    {
                        DstFlags |= H3DFragmentFlags.IsLUTReflectionEnabled;
                    }

                    if (Material.FragmentShader.Lighting.IsBumpRenormalize)
                    {
                        DstFlags |= H3DFragmentFlags.IsBumpRenormalizeEnabled;
                    }

                    Mat.MaterialParams.FragmentFlags = DstFlags;

                    Mat.MaterialParams.FresnelSelector = (H3DFresnelSelector)Material.FragmentShader.Lighting.FresnelSelector;

                    Mat.MaterialParams.BumpTexture = (byte)Material.FragmentShader.Lighting.BumpTexture;

                    Mat.MaterialParams.BumpMode = (H3DBumpMode)Material.FragmentShader.Lighting.BumpMode;

                    Mat.MaterialParams.LUTInputSelection.ReflecR = Material.FragmentShader.LUTs.ReflecR?.Input ?? 0;
                    Mat.MaterialParams.LUTInputSelection.ReflecG = Material.FragmentShader.LUTs.ReflecG?.Input ?? 0;
                    Mat.MaterialParams.LUTInputSelection.ReflecB = Material.FragmentShader.LUTs.ReflecB?.Input ?? 0;
                    Mat.MaterialParams.LUTInputSelection.Dist0   = Material.FragmentShader.LUTs.Dist0?.Input ?? 0;
                    Mat.MaterialParams.LUTInputSelection.Dist1   = Material.FragmentShader.LUTs.Dist1?.Input ?? 0;
                    Mat.MaterialParams.LUTInputSelection.Fresnel = Material.FragmentShader.LUTs.Fresnel?.Input ?? 0;

                    Mat.MaterialParams.LUTInputScale.ReflecR = Material.FragmentShader.LUTs.ReflecR?.Scale ?? 0;
                    Mat.MaterialParams.LUTInputScale.ReflecG = Material.FragmentShader.LUTs.ReflecG?.Scale ?? 0;
                    Mat.MaterialParams.LUTInputScale.ReflecB = Material.FragmentShader.LUTs.ReflecB?.Scale ?? 0;
                    Mat.MaterialParams.LUTInputScale.Dist0   = Material.FragmentShader.LUTs.Dist0?.Scale ?? 0;
                    Mat.MaterialParams.LUTInputScale.Dist1   = Material.FragmentShader.LUTs.Dist1?.Scale ?? 0;
                    Mat.MaterialParams.LUTInputScale.Fresnel = Material.FragmentShader.LUTs.Fresnel?.Scale ?? 0;

                    Mat.MaterialParams.LUTReflecRTableName = Material.FragmentShader.LUTs.ReflecR?.Sampler.TableName;
                    Mat.MaterialParams.LUTReflecGTableName = Material.FragmentShader.LUTs.ReflecG?.Sampler.TableName;
                    Mat.MaterialParams.LUTReflecBTableName = Material.FragmentShader.LUTs.ReflecB?.Sampler.TableName;
                    Mat.MaterialParams.LUTDist0TableName   = Material.FragmentShader.LUTs.Dist0?.Sampler.TableName;
                    Mat.MaterialParams.LUTDist1TableName   = Material.FragmentShader.LUTs.Dist1?.Sampler.TableName;
                    Mat.MaterialParams.LUTFresnelTableName = Material.FragmentShader.LUTs.Fresnel?.Sampler.TableName;

                    Mat.MaterialParams.LUTReflecRSamplerName = Material.FragmentShader.LUTs.ReflecR?.Sampler.SamplerName;
                    Mat.MaterialParams.LUTReflecGSamplerName = Material.FragmentShader.LUTs.ReflecG?.Sampler.SamplerName;
                    Mat.MaterialParams.LUTReflecBSamplerName = Material.FragmentShader.LUTs.ReflecB?.Sampler.SamplerName;
                    Mat.MaterialParams.LUTDist0SamplerName   = Material.FragmentShader.LUTs.Dist0?.Sampler.SamplerName;
                    Mat.MaterialParams.LUTDist1SamplerName   = Material.FragmentShader.LUTs.Dist1?.Sampler.SamplerName;
                    Mat.MaterialParams.LUTFresnelSamplerName = Material.FragmentShader.LUTs.Fresnel?.Sampler.SamplerName;

                    Mat.MaterialParams.TexEnvStages[0] = Material.FragmentShader.TextureEnvironments[0].Stage;
                    Mat.MaterialParams.TexEnvStages[1] = Material.FragmentShader.TextureEnvironments[1].Stage;
                    Mat.MaterialParams.TexEnvStages[2] = Material.FragmentShader.TextureEnvironments[2].Stage;
                    Mat.MaterialParams.TexEnvStages[3] = Material.FragmentShader.TextureEnvironments[3].Stage;
                    Mat.MaterialParams.TexEnvStages[4] = Material.FragmentShader.TextureEnvironments[4].Stage;
                    Mat.MaterialParams.TexEnvStages[5] = Material.FragmentShader.TextureEnvironments[5].Stage;

                    Mat.MaterialParams.AlphaTest = Material.FragmentShader.AlphaTest.Test;

                    Mat.MaterialParams.TexEnvBufferColor = Material.FragmentShader.TexEnvBufferColor;

                    Mdl.Materials.Add(Mat);
                }

                foreach (GfxMesh Mesh in Model.Meshes)
                {
                    GfxShape Shape = Model.Shapes[Mesh.ShapeIndex];

                    H3DMesh M = new H3DMesh();

                    PICAVertex[] Vertices = null;

                    foreach (GfxVertexBuffer VertexBuffer in Shape.VertexBuffers)
                    {
                        /*
                         * CGfx supports 3 types of vertex buffer:
                         * - Non-Interleaved: Each attribute is stored on it's on stream, like this:
                         * P0 P1 P2 P3 P4 P5 ... N0 N1 N2 N3 N4 N5
                         * - Interleaved: All attributes are stored on the same stream, like this:
                         * P0 N0 P1 N1 P2 N2 P3 N3 P4 N4 P5 N5 ...
                         * - Fixed: The attribute have only a single fixed value, so instead of a stream,
                         * it have a single vector.
                         */
                        if (VertexBuffer is GfxAttribute)
                        {
                            //Non-Interleaved buffer
                            GfxAttribute Attr = (GfxAttribute)VertexBuffer;

                            M.Attributes.Add(Attr.ToPICAAttribute());

                            int Length = Attr.Elements;

                            switch (Attr.Format)
                            {
                            case GfxGLDataType.GL_SHORT: Length <<= 1; break;

                            case GfxGLDataType.GL_FLOAT: Length <<= 2; break;
                            }

                            M.VertexStride += Length;

                            Vector4[] Vectors = Attr.GetVectors();

                            if (Vertices == null)
                            {
                                Vertices = new PICAVertex[Vectors.Length];
                            }

                            for (int i = 0; i < Vectors.Length; i++)
                            {
                                switch (Attr.AttrName)
                                {
                                case PICAAttributeName.Position:  Vertices[i].Position = Vectors[i]; break;

                                case PICAAttributeName.Normal:    Vertices[i].Normal = Vectors[i]; break;

                                case PICAAttributeName.Tangent:   Vertices[i].Tangent = Vectors[i]; break;

                                case PICAAttributeName.TexCoord0: Vertices[i].TexCoord0 = Vectors[i]; break;

                                case PICAAttributeName.TexCoord1: Vertices[i].TexCoord1 = Vectors[i]; break;

                                case PICAAttributeName.TexCoord2: Vertices[i].TexCoord2 = Vectors[i]; break;

                                case PICAAttributeName.Color:     Vertices[i].Color = Vectors[i]; break;

                                case PICAAttributeName.BoneIndex:
                                    Vertices[i].Indices[0] = (int)Vectors[i].X;
                                    Vertices[i].Indices[1] = (int)Vectors[i].Y;
                                    Vertices[i].Indices[2] = (int)Vectors[i].Z;
                                    Vertices[i].Indices[3] = (int)Vectors[i].W;
                                    break;

                                case PICAAttributeName.BoneWeight:
                                    Vertices[i].Weights[0] = Vectors[i].X;
                                    Vertices[i].Weights[1] = Vectors[i].Y;
                                    Vertices[i].Weights[2] = Vectors[i].Z;
                                    Vertices[i].Weights[3] = Vectors[i].W;
                                    break;
                                }
                            }
                        }
                        else if (VertexBuffer is GfxVertexBufferFixed)
                        {
                            //Fixed vector
                            float[] Vector = ((GfxVertexBufferFixed)VertexBuffer).Vector;

                            M.FixedAttributes.Add(new PICAFixedAttribute()
                            {
                                Name = VertexBuffer.AttrName,

                                Value = new PICAVectorFloat24(
                                    Vector.Length > 0 ? Vector[0] : 0,
                                    Vector.Length > 1 ? Vector[1] : 0,
                                    Vector.Length > 2 ? Vector[2] : 0,
                                    Vector.Length > 3 ? Vector[3] : 0)
                            });
                        }
                        else
                        {
                            //Interleaved buffer
                            GfxVertexBufferInterleaved VtxBuff = (GfxVertexBufferInterleaved)VertexBuffer;

                            foreach (GfxAttribute Attr in ((GfxVertexBufferInterleaved)VertexBuffer).Attributes)
                            {
                                M.Attributes.Add(Attr.ToPICAAttribute());
                            }

                            M.RawBuffer    = VtxBuff.RawBuffer;
                            M.VertexStride = VtxBuff.VertexStride;
                        }
                    }

                    if (Vertices != null)
                    {
                        M.RawBuffer = VerticesConverter.GetBuffer(Vertices, M.Attributes);
                    }

                    Vector4 PositionOffset = new Vector4(Shape.PositionOffset, 0);

                    int Layer = (int)Model.Materials[Mesh.MaterialIndex].TranslucencyKind;

                    M.MaterialIndex  = (ushort)Mesh.MaterialIndex;
                    M.NodeIndex      = (ushort)Mesh.MeshNodeIndex;
                    M.PositionOffset = PositionOffset;
                    M.MeshCenter     = Shape.BoundingBox.Center;
                    M.Layer          = Layer;
                    M.Priority       = Mesh.RenderPriority;

                    H3DBoundingBox OBB = new H3DBoundingBox()
                    {
                        Center      = Shape.BoundingBox.Center,
                        Orientation = Shape.BoundingBox.Orientation,
                        Size        = Shape.BoundingBox.Size
                    };

                    M.MetaData = new H3DMetaData();

                    M.MetaData.Add(new H3DMetaDataValue(OBB));

                    int SmoothCount = 0;

                    foreach (GfxSubMesh SubMesh in Shape.SubMeshes)
                    {
                        foreach (GfxFace Face in SubMesh.Faces)
                        {
                            foreach (GfxFaceDescriptor Desc in Face.FaceDescriptors)
                            {
                                H3DSubMesh SM = new H3DSubMesh();

                                SM.BoneIndicesCount = (ushort)SubMesh.BoneIndices.Count;

                                for (int i = 0; i < SubMesh.BoneIndices.Count; i++)
                                {
                                    SM.BoneIndices[i] = (ushort)SubMesh.BoneIndices[i];
                                }

                                switch (SubMesh.Skinning)
                                {
                                case GfxSubMeshSkinning.None:   SM.Skinning = H3DSubMeshSkinning.None;   break;

                                case GfxSubMeshSkinning.Rigid:  SM.Skinning = H3DSubMeshSkinning.Rigid;  break;

                                case GfxSubMeshSkinning.Smooth: SM.Skinning = H3DSubMeshSkinning.Smooth; break;
                                }

                                SM.Indices = Desc.Indices;

                                SM.Indices = new ushort[Desc.Indices.Length];

                                Array.Copy(Desc.Indices, SM.Indices, SM.Indices.Length);

                                M.SubMeshes.Add(SM);
                            }
                        }

                        if (SubMesh.Skinning == GfxSubMeshSkinning.Smooth)
                        {
                            SmoothCount++;
                        }
                    }

                    if (SmoothCount == Shape.SubMeshes.Count)
                    {
                        M.Skinning = H3DMeshSkinning.Smooth;
                    }
                    else if (SmoothCount > 0)
                    {
                        M.Skinning = H3DMeshSkinning.Mixed;
                    }
                    else
                    {
                        M.Skinning = H3DMeshSkinning.Rigid;
                    }

                    GfxMaterial Mat = Model.Materials[Mesh.MaterialIndex];

                    M.UpdateBoolUniforms(Mdl.Materials[Mesh.MaterialIndex]);

                    Mdl.AddMesh(M);
                }

                //Workaround to fix blending problems until I can find a proper way.
                Mdl.MeshesLayer1.Reverse();

                Mdl.MeshNodesTree = new H3DPatriciaTree();

                foreach (GfxMeshNodeVisibility MeshNode in Model.MeshNodeVisibilities)
                {
                    Mdl.MeshNodesTree.Add(MeshNode.Name);
                    Mdl.MeshNodesVisibility.Add(MeshNode.IsVisible);
                }

                if (Model is GfxModelSkeletal)
                {
                    foreach (GfxBone Bone in ((GfxModelSkeletal)Model).Skeleton.Bones)
                    {
                        H3DBone B = new H3DBone()
                        {
                            Name             = Bone.Name,
                            ParentIndex      = (short)Bone.ParentIndex,
                            Translation      = Bone.Translation,
                            Rotation         = Bone.Rotation,
                            Scale            = Bone.Scale,
                            InverseTransform = Bone.InvWorldTransform
                        };

                        bool ScaleCompensate = (Bone.Flags & GfxBoneFlags.IsSegmentScaleCompensate) != 0;

                        if (ScaleCompensate)
                        {
                            B.Flags |= H3DBoneFlags.IsSegmentScaleCompensate;
                        }

                        Mdl.Skeleton.Add(B);
                    }

                    Mdl.Flags |= H3DModelFlags.HasSkeleton;

                    Mdl.BoneScaling = (H3DBoneScaling)((GfxModelSkeletal)Model).Skeleton.ScalingRule;
                }

                Output.Models.Add(Mdl);
            }

            foreach (GfxTexture Texture in Textures)
            {
                H3DTexture Tex = new H3DTexture()
                {
                    Name       = Texture.Name,
                    Width      = Texture.Width,
                    Height     = Texture.Height,
                    Format     = Texture.HwFormat,
                    MipmapSize = (byte)Texture.MipmapSize
                };

                if (Texture is GfxTextureCube)
                {
                    Tex.RawBufferXPos = ((GfxTextureCube)Texture).ImageXPos.RawBuffer;
                    Tex.RawBufferXNeg = ((GfxTextureCube)Texture).ImageXNeg.RawBuffer;
                    Tex.RawBufferYPos = ((GfxTextureCube)Texture).ImageYPos.RawBuffer;
                    Tex.RawBufferYNeg = ((GfxTextureCube)Texture).ImageYNeg.RawBuffer;
                    Tex.RawBufferZPos = ((GfxTextureCube)Texture).ImageZPos.RawBuffer;
                    Tex.RawBufferZNeg = ((GfxTextureCube)Texture).ImageZNeg.RawBuffer;
                }
                else
                {
                    Tex.RawBuffer = ((GfxTextureImage)Texture).Image.RawBuffer;
                }

                Output.Textures.Add(Tex);
            }

            foreach (GfxLUT LUT in LUTs)
            {
                H3DLUT L = new H3DLUT()
                {
                    Name = LUT.Name
                };

                foreach (GfxLUTSampler Sampler in LUT.Samplers)
                {
                    L.Samplers.Add(new H3DLUTSampler()
                    {
                        Flags = Sampler.IsAbsolute ? H3DLUTFlags.IsAbsolute : 0,
                        Name  = Sampler.Name,
                        Table = Sampler.Table
                    });
                }

                Output.LUTs.Add(L);
            }

            foreach (GfxCamera Camera in Cameras)
            {
                Output.Cameras.Add(Camera.ToH3DCamera());
            }

            foreach (GfxLight Light in Lights)
            {
                Output.Lights.Add(Light.ToH3DLight());
            }

            foreach (GfxAnimation SklAnim in SkeletalAnimations)
            {
                Output.SkeletalAnimations.Add(SklAnim.ToH3DAnimation());
            }

            foreach (GfxAnimation MatAnim in MaterialAnimations)
            {
                Output.MaterialAnimations.Add(new H3DMaterialAnim(MatAnim.ToH3DAnimation()));
            }

            foreach (GfxAnimation VisAnim in VisibilityAnimations)
            {
                Output.VisibilityAnimations.Add(VisAnim.ToH3DAnimation());
            }

            foreach (GfxAnimation CamAnim in CameraAnimations)
            {
                Output.CameraAnimations.Add(CamAnim.ToH3DAnimation());
            }

            Output.CopyMaterials();

            return(Output);
        }
Пример #19
0
        public H3DMaterial ToH3DMaterial(Material mat)
        {
            H3DMaterial h3dMaterial = new H3DMaterial();
            var         matParams   = h3dMaterial.MaterialParams;

            if (mat.IsVertexLightingEnabled)
            {
                matParams.Flags |= H3DMaterialFlags.IsVertexLightingEnabled;
            }
            if (mat.IsFragmentLightingEnabled)
            {
                matParams.Flags |= H3DMaterialFlags.IsFragmentLightingEnabled;
            }
            if (mat.IsHemiSphereLightingEnabled)
            {
                matParams.Flags |= H3DMaterialFlags.IsHemiSphereLightingEnabled;
            }
            if (mat.IsHemiSphereOcclusionEnabled)
            {
                matParams.Flags |= H3DMaterialFlags.IsHemiSphereOcclusionEnabled;
            }

            switch (mat.LayerConfig)
            {
            case LayerConfig.LayerConfig0: matParams.TranslucencyKind = H3DTranslucencyKind.LayerConfig0; break;

            case LayerConfig.LayerConfig1: matParams.TranslucencyKind = H3DTranslucencyKind.LayerConfig1; break;

            case LayerConfig.LayerConfig2: matParams.TranslucencyKind = H3DTranslucencyKind.LayerConfig2; break;

            case LayerConfig.LayerConfig3: matParams.TranslucencyKind = H3DTranslucencyKind.LayerConfig3; break;

            case LayerConfig.LayerConfig4: matParams.TranslucencyKind = H3DTranslucencyKind.LayerConfig4; break;

            case LayerConfig.LayerConfig5: matParams.TranslucencyKind = H3DTranslucencyKind.LayerConfig5; break;

            case LayerConfig.LayerConfig6: matParams.TranslucencyKind = H3DTranslucencyKind.LayerConfig6; break;

            case LayerConfig.LayerConfig7: matParams.TranslucencyKind = H3DTranslucencyKind.LayerConfig7; break;
            }

            for (int i = 0; i < mat.TextureMappers?.Count; i++)
            {
                string texture = GetTextureName(mat.TextureMappers[i].TextureID);
                if (texture == string.Empty)
                {
                    continue;
                }

                if (i == 0)
                {
                    h3dMaterial.Texture0Name = texture;
                }
                if (i == 0)
                {
                    h3dMaterial.Texture1Name = texture;
                }
                if (i == 0)
                {
                    h3dMaterial.Texture2Name = texture;
                }

                h3dMaterial.TextureMappers[i].WrapU       = ConvertWrapMode(mat.TextureMappers[i].WrapU);
                h3dMaterial.TextureMappers[i].WrapV       = ConvertWrapMode(mat.TextureMappers[i].WrapV);
                h3dMaterial.TextureMappers[i].MagFilter   = ConvertTexMagFilter(mat.TextureMappers[i].TextureMagFilter);
                h3dMaterial.TextureMappers[i].MinFilter   = ConvertTexMinFilter(mat.TextureMappers[i].TextureMinFilter);
                h3dMaterial.TextureMappers[i].LODBias     = mat.TextureMappers[i].LODBias;
                h3dMaterial.TextureMappers[i].MinLOD      = (byte)(mat.TextureMappers[i].MinLODBias / 255);
                h3dMaterial.TextureMappers[i].BorderColor = new SPICA.Math3D.RGBA(
                    mat.TextureMappers[i].BorderColor.R,
                    mat.TextureMappers[i].BorderColor.G,
                    mat.TextureMappers[i].BorderColor.B,
                    mat.TextureMappers[i].BorderColor.A);

                matParams.TextureCoords[i].TransformType = H3DTextureTransformType.DccMaya;
                matParams.TextureCoords[i].MappingType   = H3DTextureMappingType.UvCoordinateMap;

                matParams.TextureCoords[i].Scale = new System.Numerics.Vector2(
                    mat.TextureCoords[i].Scale.X, mat.TextureCoords[i].Scale.Y);
                matParams.TextureCoords[i].Translation = new System.Numerics.Vector2(
                    mat.TextureCoords[i].Translation.X, mat.TextureCoords[i].Translation.Y);

                matParams.TextureCoords[i].Rotation = mat.TextureCoords[i].Rotation;
            }

            matParams.DiffuseColor      = ConvertRGBA(mat.DiffuseColor);
            matParams.Specular0Color    = ConvertRGBA(mat.Specular0Color);
            matParams.Specular1Color    = ConvertRGBA(mat.Specular1Color);
            matParams.EmissionColor     = ConvertRGBA(mat.EmissionColor);
            matParams.Constant0Color    = ConvertRGBA(mat.ConstantColors[0]);
            matParams.Constant1Color    = ConvertRGBA(mat.ConstantColors[1]);
            matParams.Constant2Color    = ConvertRGBA(mat.ConstantColors[2]);
            matParams.Constant3Color    = ConvertRGBA(mat.ConstantColors[3]);
            matParams.Constant4Color    = ConvertRGBA(mat.ConstantColors[4]);
            matParams.Constant5Color    = ConvertRGBA(mat.ConstantColors[5]);
            matParams.BlendColor        = ConvertRGBA(mat.BlendColor);
            matParams.TexEnvBufferColor = ConvertRGBA(mat.BufferColor);

            if (mat.CullMode == CullMode.Back)
            {
                matParams.FaceCulling = PICAFaceCulling.BackFace;
            }
            else if (mat.CullMode == CullMode.Front)
            {
                matParams.FaceCulling = PICAFaceCulling.FrontFace;
            }
            else
            {
                matParams.FaceCulling = PICAFaceCulling.Never;
            }

            matParams.AlphaTest.Enabled          = mat.AlphaTest.Enabled;
            matParams.AlphaTest.Function         = ConvertTestFunction(mat.AlphaTest.Function);
            matParams.AlphaTest.Reference        = mat.AlphaTest.Reference;
            matParams.BlendFunction.ColorSrcFunc = ConvertBlendFunc(mat.BlendFunction.ColorSrcFunc);
            matParams.BlendFunction.ColorDstFunc = ConvertBlendFunc(mat.BlendFunction.ColorDstFunc);
            matParams.BlendFunction.AlphaSrcFunc = ConvertBlendFunc(mat.BlendFunction.AlphaSrcFunc);
            matParams.BlendFunction.AlphaDstFunc = ConvertBlendFunc(mat.BlendFunction.AlphaDstFunc);

            for (int i = 0; i < mat.TexEnvStages.Count; i++)
            {
                var combiner = mat.TexEnvStages[i];
                var h3dStage = new PICATexEnvStage();
                h3dStage.Source.Color[0]  = ConvertCombinerSrc[combiner.Source.Color[0]];
                h3dStage.Source.Color[1]  = ConvertCombinerSrc[combiner.Source.Color[1]];
                h3dStage.Source.Color[2]  = ConvertCombinerSrc[combiner.Source.Color[2]];
                h3dStage.Source.Alpha[0]  = ConvertCombinerSrc[combiner.Source.Alpha[0]];
                h3dStage.Source.Alpha[1]  = ConvertCombinerSrc[combiner.Source.Alpha[1]];
                h3dStage.Source.Alpha[2]  = ConvertCombinerSrc[combiner.Source.Alpha[2]];
                h3dStage.Operand.Alpha[0] = ConvertConvertCombinerAlphaOp[combiner.Operand.Alpha[0]];
                h3dStage.Operand.Alpha[1] = ConvertConvertCombinerAlphaOp[combiner.Operand.Alpha[1]];
                h3dStage.Operand.Alpha[2] = ConvertConvertCombinerAlphaOp[combiner.Operand.Alpha[2]];
                h3dStage.Operand.Color[0] = ConvertConvertCombinerColorOp[combiner.Operand.Color[0]];
                h3dStage.Operand.Color[1] = ConvertConvertCombinerColorOp[combiner.Operand.Color[1]];
                h3dStage.Operand.Color[2] = ConvertConvertCombinerColorOp[combiner.Operand.Color[2]];
                h3dStage.Scale.Color      = ConvertScale[combiner.Scale.Color];
                h3dStage.Scale.Alpha      = ConvertScale[combiner.Scale.Alpha];
                h3dStage.Combiner.Alpha   = ConvertConvertCombiner[combiner.Combiner.Alpha];
                h3dStage.Combiner.Color   = ConvertConvertCombiner[combiner.Combiner.Color];

                matParams.TexEnvStages[i] = h3dStage;
            }

            matParams.LUTInputAbsolute.Dist0   = mat.Distibution0SamplerIsAbs;
            matParams.LUTInputAbsolute.Dist1   = mat.Distibution1SamplerIsAbs;
            matParams.LUTInputAbsolute.ReflecR = mat.ReflectanceRSamplerIsAbs;
            matParams.LUTInputAbsolute.ReflecG = mat.ReflectanceGSamplerIsAbs;
            matParams.LUTInputAbsolute.ReflecB = mat.ReflectanceBSamplerIsAbs;
            matParams.LUTInputAbsolute.Fresnel = mat.FresnelSamplerIsAbs;

            return(h3dMaterial);
        }
Пример #20
0
        public void UpdateShaders()
        {
            DisposeShaders();

            foreach (H3DMaterial Material in BaseModel.Materials)
            {
                H3DMaterialParams Params = Material.MaterialParams;

                int Hash = GetMaterialShaderHash(Params);

                bool HasHash = false;

                if (ShaderHashes.TryGetValue(Hash, out int ShaderIndex))
                {
                    HasHash = true;

                    H3DMaterial m = BaseModel.Materials[ShaderIndex];

                    if (CompareMaterials(m.MaterialParams, Params))
                    {
                        Shaders.Add(Shaders[ShaderIndex]);

                        continue;
                    }
                }

                if (!HasHash)
                {
                    ShaderHashes.Add(Hash, Shaders.Count);
                }

                FragmentShaderGenerator FragShaderGen = new FragmentShaderGenerator(Params);

                int FragmentShaderHandle = GL.CreateShader(ShaderType.FragmentShader);

                Shader.CompileAndCheck(FragmentShaderHandle, FragShaderGen.GetFragShader());

                VertexShader VtxShader = Renderer.GetShader(Params.ShaderReference);

                Shader Shdr = new Shader(FragmentShaderHandle, VtxShader);

                Shaders.Add(Shdr);

                GL.UseProgram(Shdr.Handle);

                GL.Uniform1(GL.GetUniformLocation(Shdr.Handle, "Textures[0]"), 0);
                GL.Uniform1(GL.GetUniformLocation(Shdr.Handle, "Textures[1]"), 1);
                GL.Uniform1(GL.GetUniformLocation(Shdr.Handle, "Textures[2]"), 2);
                GL.Uniform1(GL.GetUniformLocation(Shdr.Handle, "TextureCube"), 3);
                GL.Uniform1(GL.GetUniformLocation(Shdr.Handle, "LUTs[0]"), 4);
                GL.Uniform1(GL.GetUniformLocation(Shdr.Handle, "LUTs[1]"), 5);
                GL.Uniform1(GL.GetUniformLocation(Shdr.Handle, "LUTs[2]"), 6);
                GL.Uniform1(GL.GetUniformLocation(Shdr.Handle, "LUTs[3]"), 7);
                GL.Uniform1(GL.GetUniformLocation(Shdr.Handle, "LUTs[4]"), 8);
                GL.Uniform1(GL.GetUniformLocation(Shdr.Handle, "LUTs[5]"), 9);

                for (int i = 0; i < 3; i++)
                {
                    int j = i * 2;

                    GL.Uniform1(GL.GetUniformLocation(Shdr.Handle, $"LUTs[{6 + j}]"), 10 + j);
                    GL.Uniform1(GL.GetUniformLocation(Shdr.Handle, $"LUTs[{7 + j}]"), 11 + j);
                }

                //Pokémon uses this
                Vector4 ShaderParam = Vector4.Zero;

                if (Params.MetaData != null)
                {
                    foreach (H3DMetaDataValue MD in Params.MetaData)
                    {
                        if (MD.Type == H3DMetaDataType.Single)
                        {
                            switch (MD.Name)
                            {
                            case "$ShaderParam0": ShaderParam.W = (float)MD.Values[0]; break;

                            case "$ShaderParam1": ShaderParam.Z = (float)MD.Values[0]; break;

                            case "$ShaderParam2": ShaderParam.Y = (float)MD.Values[0]; break;

                            case "$ShaderParam3": ShaderParam.X = (float)MD.Values[0]; break;
                            }
                        }
                    }
                }

                Shdr.SetVtxVector4(85, ShaderParam);

                //Send values from material matching register ids to names.
                foreach (KeyValuePair <uint, System.Numerics.Vector4> KV in Params.VtxShaderUniforms)
                {
                    Shdr.SetVtxVector4((int)KV.Key, KV.Value.ToVector4());
                }

                foreach (KeyValuePair <uint, System.Numerics.Vector4> KV in Params.GeoShaderUniforms)
                {
                    Shdr.SetGeoVector4((int)KV.Key, KV.Value.ToVector4());
                }

                Vector4 MatAmbient = new Vector4(
                    Params.AmbientColor.R / 255f,
                    Params.AmbientColor.G / 255f,
                    Params.AmbientColor.B / 255F,
                    Params.ColorScale);

                Vector4 MatDiffuse = new Vector4(
                    Params.DiffuseColor.R / 255f,
                    Params.DiffuseColor.G / 255f,
                    Params.DiffuseColor.B / 255f,
                    1f);

                Vector4 TexCoordMap = new Vector4(
                    Params.TextureSources[0],
                    Params.TextureSources[1],
                    Params.TextureSources[2],
                    Params.TextureSources[3]);

                Shdr.SetVtxVector4(DefaultShaderIds.MatAmbi, MatAmbient);
                Shdr.SetVtxVector4(DefaultShaderIds.MatDiff, MatDiffuse);
                Shdr.SetVtxVector4(DefaultShaderIds.TexcMap, TexCoordMap);
            }

            UpdateUniforms();
        }
Пример #21
0
        public H3D ToH3D(string TextureAndMtlSearchPath = null, bool noTextures = false)
        {
            H3D Output = new H3D();

            Dictionary <string, OBJMaterial> Materials = new Dictionary <string, OBJMaterial>();

            if (TextureAndMtlSearchPath != null)
            {
                TextReader Reader = null;
                if (textureOnly)
                {
                    Reader = new StreamReader(textureOnlyFile);
                }
                else
                {
                    string MaterialFile = Path.Combine(TextureAndMtlSearchPath, MtlFile);

                    if (File.Exists(MaterialFile))
                    {
                        Reader = new StreamReader(MaterialFile);
                    }
                }
                if (Reader != null)
                {
                    string MaterialName = null;

                    OBJMaterial Material = default(OBJMaterial);

                    for (string Line; (Line = Reader.ReadLine()) != null;)
                    {
                        string[] Params = Line.Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);

                        if (Params.Length == 0)
                        {
                            continue;
                        }

                        switch (Params[0])
                        {
                        case "newmtl":
                            if (Params.Length > 1)
                            {
                                if (MaterialName != null && Material.DiffuseTexture != null)
                                {
                                    Materials.Add(MaterialName, Material);
                                }

                                Material = new OBJMaterial();

                                MaterialName = Line.Substring(Line.IndexOf(" ")).Trim();
                            }
                            break;

                        case "map_Kd":
                            if (Params.Length > 1)
                            {
                                string Name = Line.Substring(Line.IndexOf(Params[1]));

                                string TextureFile = Path.Combine(TextureAndMtlSearchPath, Name);
                                string TextureName = Path.GetFileName(TextureFile);

                                if (File.Exists(TextureFile) && !noTextures)
                                {
                                    if (Output.Textures.Contains(TextureName))
                                    {
                                        Output.Textures.Remove(Output.Textures[Output.Textures.Find(TextureName)]);
                                    }
                                    Output.Textures.Add(new H3DTexture(TextureFile));
                                }

                                Material.DiffuseTexture = TextureName;
                            }
                            break;

                        case "Ka":
                        case "Kd":
                        case "Ks":
                            if (Params.Length >= 4)
                            {
                                Vector4 Color = new Vector4(
                                    float.Parse(Params[1], CultureInfo.InvariantCulture),
                                    float.Parse(Params[2], CultureInfo.InvariantCulture),
                                    float.Parse(Params[3], CultureInfo.InvariantCulture), 1);

                                switch (Params[0])
                                {
                                case "Ka": Material.Ambient = Color; break;

                                case "Kd": Material.Diffuse = Color; break;

                                case "Ks": Material.Specular = Color; break;
                                }
                            }
                            break;
                        }
                    }

                    Reader.Dispose();

                    if (MaterialName != null && !textureOnly)
                    {
                        Materials.Add(MaterialName, Material);
                    }
                }
            }

            if (!textureOnly)
            {
                H3DModel Model = new H3DModel();

                string newName = Microsoft.VisualBasic.Interaction.InputBox("Enter model name: ", "Name", Model.Name);

                if (newName != "")
                {
                    Model.Name = newName;
                }

                ushort MaterialIndex = 0;

                Model.Flags       = 0;
                Model.BoneScaling = H3DBoneScaling.Standard;
                Model.MeshNodesVisibility.Clear();
                Model.Skeleton.Clear();
                Model.MeshNodesVisibility.Add(true);

                float Height = 0;

                Meshes.Sort((x, y) => string.Compare(x.Name, y.Name));

                foreach (OBJMesh Mesh in Meshes)
                {
                    Vector3 MinVector = new Vector3();
                    Vector3 MaxVector = new Vector3();

                    Dictionary <PICAVertex, int> Vertices = new Dictionary <PICAVertex, int>();

                    List <H3DSubMesh> SubMeshes = new List <H3DSubMesh>();

                    Queue <PICAVertex> VerticesQueue = new Queue <PICAVertex>();

                    foreach (PICAVertex Vertex in Mesh.Vertices)
                    {
                        VerticesQueue.Enqueue(Vertex);
                    }

                    while (VerticesQueue.Count > 2)
                    {
                        List <ushort> Indices = new List <ushort>();

                        while (VerticesQueue.Count > 0)
                        {
                            for (int Tri = 0; Tri < 3; Tri++)
                            {
                                PICAVertex Vertex = VerticesQueue.Dequeue();

                                if (Mesh.Name.Contains("uncolor"))
                                {
                                    Vertex.Color = Vector4.One;
                                }

                                if (Vertices.ContainsKey(Vertex))
                                {
                                    Indices.Add((ushort)Vertices[Vertex]);
                                }
                                else
                                {
                                    Indices.Add((ushort)Vertices.Count);

                                    if (Vertex.Position.X < MinVector.X)
                                    {
                                        MinVector.X = Vertex.Position.X;
                                    }
                                    if (Vertex.Position.Y < MinVector.Y)
                                    {
                                        MinVector.Y = Vertex.Position.Y;
                                    }
                                    if (Vertex.Position.Z < MinVector.Z)
                                    {
                                        MinVector.Z = Vertex.Position.Z;
                                    }

                                    if (Vertex.Position.X > MaxVector.X)
                                    {
                                        MaxVector.X = Vertex.Position.X;
                                    }
                                    if (Vertex.Position.Y > MaxVector.Y)
                                    {
                                        MaxVector.Y = Vertex.Position.Y;
                                    }
                                    if (Vertex.Position.Z > MaxVector.Z)
                                    {
                                        MaxVector.Z = Vertex.Position.Z;
                                    }

                                    Vertices.Add(Vertex, Vertices.Count);
                                }
                            }
                        }

                        H3DSubMesh SM = new H3DSubMesh();

                        SM.BoneIndices = new ushort[] { };
                        SM.Skinning    = H3DSubMeshSkinning.None;
                        SM.Indices     = Indices.ToArray();

                        SubMeshes.Add(SM);
                    }

                    //Mesh
                    List <PICAAttribute> Attributes = PICAAttribute.GetAttributes(
                        PICAAttributeName.Position,
                        PICAAttributeName.Normal,
                        PICAAttributeName.TexCoord0,
                        PICAAttributeName.Color
                        );

                    H3DMesh M = new H3DMesh(Vertices.Keys, Attributes, SubMeshes)
                    {
                        Skinning      = H3DMeshSkinning.Rigid,
                        MeshCenter    = (MinVector + MaxVector) * 0.5f,
                        MaterialIndex = MaterialIndex,
                    };

                    if (Height < MaxVector.Y)
                    {
                        Height = MaxVector.Y;
                    }

                    //Material
                    string MatName = $"Mat{MaterialIndex++.ToString("D5")}_{Mesh.MaterialName}";

                    H3DMaterial Material = H3DMaterial.GetSimpleMaterial(Model.Name, Mesh.MaterialName, Materials[Mesh.MaterialName].DiffuseTexture);

                    Material.Texture0Name = Materials[Mesh.MaterialName].DiffuseTexture;

                    Material.MaterialParams.FaceCulling      = PICAFaceCulling.BackFace;
                    Material.MaterialParams.Flags            = H3DMaterialFlags.IsFragmentLightingEnabled | H3DMaterialFlags.IsVertexLightingEnabled | H3DMaterialFlags.IsFragmentLightingPolygonOffsetDirty;
                    Material.MaterialParams.FragmentFlags    = 0;
                    Material.MaterialParams.LightSetIndex    = 0;
                    Material.MaterialParams.FogIndex         = 0;
                    Material.MaterialParams.LogicalOperation = PICALogicalOp.Noop;

                    Material.MaterialParams.AmbientColor        = RGBA.White;
                    Material.MaterialParams.DiffuseColor        = RGBA.White;
                    Material.MaterialParams.EmissionColor       = RGBA.Black;
                    Material.MaterialParams.Specular0Color      = RGBA.Black;
                    Material.MaterialParams.Specular1Color      = RGBA.Black;
                    Material.MaterialParams.Constant0Color      = RGBA.White;
                    Material.MaterialParams.Constant1Color      = RGBA.White;
                    Material.MaterialParams.Constant2Color      = RGBA.White;
                    Material.MaterialParams.Constant3Color      = RGBA.White;
                    Material.MaterialParams.Constant4Color      = RGBA.White;
                    Material.MaterialParams.Constant5Color      = RGBA.White;
                    Material.MaterialParams.BlendColor          = RGBA.Black;
                    Material.MaterialParams.Constant2Assignment = 2;

                    Material.MaterialParams.ColorScale = 1;

                    Material.MaterialParams.FresnelSelector   = H3DFresnelSelector.No;
                    Material.MaterialParams.BumpMode          = H3DBumpMode.NotUsed;
                    Material.MaterialParams.BumpTexture       = 0;
                    Material.MaterialParams.PolygonOffsetUnit = 0;

                    Material.MaterialParams.TexEnvBufferColor = RGBA.White;

                    Material.MaterialParams.ColorOperation.FragOpMode = PICAFragOpMode.Default;
                    Material.MaterialParams.ColorOperation.BlendMode  = PICABlendMode.Blend;

                    Material.MaterialParams.ColorBufferRead  = true;
                    Material.MaterialParams.ColorBufferWrite = true;

                    Material.MaterialParams.StencilBufferRead  = true;
                    Material.MaterialParams.StencilBufferWrite = true;

                    Material.MaterialParams.DepthBufferRead                   = true;
                    Material.MaterialParams.DepthBufferWrite                  = false;
                    Material.MaterialParams.TexEnvStages[0].Source.Color      = new PICATextureCombinerSource[] { PICATextureCombinerSource.Texture0, PICATextureCombinerSource.PrimaryColor, PICATextureCombinerSource.Texture0 };
                    Material.MaterialParams.TexEnvStages[0].Source.Alpha      = new PICATextureCombinerSource[] { PICATextureCombinerSource.Texture0, PICATextureCombinerSource.Texture0, PICATextureCombinerSource.Texture0 };
                    Material.MaterialParams.TexEnvStages[0].Operand.Color     = new PICATextureCombinerColorOp[] { PICATextureCombinerColorOp.Color, PICATextureCombinerColorOp.Color, PICATextureCombinerColorOp.Color };
                    Material.MaterialParams.TexEnvStages[0].Operand.Alpha     = new PICATextureCombinerAlphaOp[] { PICATextureCombinerAlphaOp.Alpha, PICATextureCombinerAlphaOp.Alpha, PICATextureCombinerAlphaOp.Alpha };
                    Material.MaterialParams.TexEnvStages[0].Combiner.Color    = PICATextureCombinerMode.Modulate;
                    Material.MaterialParams.TexEnvStages[0].Combiner.Alpha    = PICATextureCombinerMode.Replace;
                    Material.MaterialParams.TexEnvStages[0].Color             = RGBA.White;
                    Material.MaterialParams.TexEnvStages[0].Scale.Color       = PICATextureCombinerScale.One;
                    Material.MaterialParams.TexEnvStages[0].Scale.Alpha       = PICATextureCombinerScale.One;
                    Material.MaterialParams.TexEnvStages[0].UpdateColorBuffer = false;
                    Material.MaterialParams.TexEnvStages[0].UpdateAlphaBuffer = false;

                    Material.MaterialParams.TexEnvStages[1].Source.Color      = new PICATextureCombinerSource[] { PICATextureCombinerSource.Previous, PICATextureCombinerSource.FragmentPrimaryColor, PICATextureCombinerSource.Previous };
                    Material.MaterialParams.TexEnvStages[1].Source.Alpha      = new PICATextureCombinerSource[] { PICATextureCombinerSource.Previous, PICATextureCombinerSource.Previous, PICATextureCombinerSource.Previous };
                    Material.MaterialParams.TexEnvStages[1].Operand.Color     = new PICATextureCombinerColorOp[] { PICATextureCombinerColorOp.Color, PICATextureCombinerColorOp.Color, PICATextureCombinerColorOp.Color };
                    Material.MaterialParams.TexEnvStages[1].Operand.Alpha     = new PICATextureCombinerAlphaOp[] { PICATextureCombinerAlphaOp.Alpha, PICATextureCombinerAlphaOp.Alpha, PICATextureCombinerAlphaOp.Alpha };
                    Material.MaterialParams.TexEnvStages[1].Combiner.Color    = PICATextureCombinerMode.Modulate;
                    Material.MaterialParams.TexEnvStages[1].Combiner.Alpha    = PICATextureCombinerMode.Replace;
                    Material.MaterialParams.TexEnvStages[1].Color             = RGBA.Black;
                    Material.MaterialParams.TexEnvStages[1].Scale.Color       = PICATextureCombinerScale.One;
                    Material.MaterialParams.TexEnvStages[1].Scale.Alpha       = PICATextureCombinerScale.One;
                    Material.MaterialParams.TexEnvStages[1].UpdateColorBuffer = false;
                    Material.MaterialParams.TexEnvStages[1].UpdateAlphaBuffer = false;

                    Material.MaterialParams.TexEnvStages[2].Source.Color      = new PICATextureCombinerSource[] { PICATextureCombinerSource.Previous, PICATextureCombinerSource.Previous, PICATextureCombinerSource.Previous };
                    Material.MaterialParams.TexEnvStages[2].Source.Alpha      = new PICATextureCombinerSource[] { PICATextureCombinerSource.Previous, PICATextureCombinerSource.PrimaryColor, PICATextureCombinerSource.Previous };
                    Material.MaterialParams.TexEnvStages[2].Operand.Color     = new PICATextureCombinerColorOp[] { PICATextureCombinerColorOp.Color, PICATextureCombinerColorOp.Color, PICATextureCombinerColorOp.Color };
                    Material.MaterialParams.TexEnvStages[2].Operand.Alpha     = new PICATextureCombinerAlphaOp[] { PICATextureCombinerAlphaOp.Alpha, PICATextureCombinerAlphaOp.Alpha, PICATextureCombinerAlphaOp.Alpha };
                    Material.MaterialParams.TexEnvStages[2].Combiner.Color    = PICATextureCombinerMode.Replace;
                    Material.MaterialParams.TexEnvStages[2].Combiner.Alpha    = PICATextureCombinerMode.Modulate;
                    Material.MaterialParams.TexEnvStages[2].Color             = RGBA.White;
                    Material.MaterialParams.TexEnvStages[2].Scale.Color       = PICATextureCombinerScale.One;
                    Material.MaterialParams.TexEnvStages[2].Scale.Alpha       = PICATextureCombinerScale.One;
                    Material.MaterialParams.TexEnvStages[2].UpdateColorBuffer = false;
                    Material.MaterialParams.TexEnvStages[2].UpdateAlphaBuffer = false;

                    Material.MaterialParams.TexEnvStages[3].Source.Color      = new PICATextureCombinerSource[] { PICATextureCombinerSource.Previous, PICATextureCombinerSource.Previous, PICATextureCombinerSource.Previous };
                    Material.MaterialParams.TexEnvStages[3].Source.Alpha      = new PICATextureCombinerSource[] { PICATextureCombinerSource.Previous, PICATextureCombinerSource.Constant, PICATextureCombinerSource.Previous };
                    Material.MaterialParams.TexEnvStages[3].Operand.Color     = new PICATextureCombinerColorOp[] { PICATextureCombinerColorOp.Color, PICATextureCombinerColorOp.Color, PICATextureCombinerColorOp.Color };
                    Material.MaterialParams.TexEnvStages[3].Operand.Alpha     = new PICATextureCombinerAlphaOp[] { PICATextureCombinerAlphaOp.Alpha, PICATextureCombinerAlphaOp.Alpha, PICATextureCombinerAlphaOp.Alpha };
                    Material.MaterialParams.TexEnvStages[3].Combiner.Color    = PICATextureCombinerMode.Replace;
                    Material.MaterialParams.TexEnvStages[3].Combiner.Alpha    = PICATextureCombinerMode.Modulate;
                    Material.MaterialParams.TexEnvStages[3].Color             = RGBA.White;
                    Material.MaterialParams.TexEnvStages[3].Scale.Color       = PICATextureCombinerScale.One;
                    Material.MaterialParams.TexEnvStages[3].Scale.Alpha       = PICATextureCombinerScale.One;
                    Material.MaterialParams.TexEnvStages[3].UpdateColorBuffer = false;
                    Material.MaterialParams.TexEnvStages[3].UpdateAlphaBuffer = false;

                    Material.MaterialParams.TexEnvStages[4].Source.Color      = new PICATextureCombinerSource[] { PICATextureCombinerSource.Previous, PICATextureCombinerSource.Previous, PICATextureCombinerSource.Previous };
                    Material.MaterialParams.TexEnvStages[4].Source.Alpha      = new PICATextureCombinerSource[] { PICATextureCombinerSource.Previous, PICATextureCombinerSource.Previous, PICATextureCombinerSource.Previous };
                    Material.MaterialParams.TexEnvStages[4].Operand.Color     = new PICATextureCombinerColorOp[] { PICATextureCombinerColorOp.Color, PICATextureCombinerColorOp.Color, PICATextureCombinerColorOp.Color };
                    Material.MaterialParams.TexEnvStages[4].Operand.Alpha     = new PICATextureCombinerAlphaOp[] { PICATextureCombinerAlphaOp.Alpha, PICATextureCombinerAlphaOp.Alpha, PICATextureCombinerAlphaOp.Alpha };
                    Material.MaterialParams.TexEnvStages[4].Combiner.Color    = PICATextureCombinerMode.Replace;
                    Material.MaterialParams.TexEnvStages[4].Combiner.Alpha    = PICATextureCombinerMode.Replace;
                    Material.MaterialParams.TexEnvStages[4].Color             = RGBA.Black;
                    Material.MaterialParams.TexEnvStages[4].Scale.Color       = PICATextureCombinerScale.One;
                    Material.MaterialParams.TexEnvStages[4].Scale.Alpha       = PICATextureCombinerScale.One;
                    Material.MaterialParams.TexEnvStages[4].UpdateColorBuffer = true;
                    Material.MaterialParams.TexEnvStages[4].UpdateAlphaBuffer = false;

                    Material.MaterialParams.TexEnvStages[5].Source.Color      = new PICATextureCombinerSource[] { PICATextureCombinerSource.Previous, PICATextureCombinerSource.Previous, PICATextureCombinerSource.Previous };
                    Material.MaterialParams.TexEnvStages[5].Source.Alpha      = new PICATextureCombinerSource[] { PICATextureCombinerSource.Previous, PICATextureCombinerSource.Previous, PICATextureCombinerSource.Previous };
                    Material.MaterialParams.TexEnvStages[5].Operand.Color     = new PICATextureCombinerColorOp[] { PICATextureCombinerColorOp.Color, PICATextureCombinerColorOp.Color, PICATextureCombinerColorOp.Color };
                    Material.MaterialParams.TexEnvStages[5].Operand.Alpha     = new PICATextureCombinerAlphaOp[] { PICATextureCombinerAlphaOp.Alpha, PICATextureCombinerAlphaOp.Alpha, PICATextureCombinerAlphaOp.Alpha };
                    Material.MaterialParams.TexEnvStages[5].Combiner.Color    = PICATextureCombinerMode.Replace;
                    Material.MaterialParams.TexEnvStages[5].Combiner.Alpha    = PICATextureCombinerMode.Replace;
                    Material.MaterialParams.TexEnvStages[5].Color             = RGBA.Black;
                    Material.MaterialParams.TexEnvStages[5].Scale.Color       = PICATextureCombinerScale.One;
                    Material.MaterialParams.TexEnvStages[5].Scale.Alpha       = PICATextureCombinerScale.One;
                    Material.MaterialParams.TexEnvStages[5].UpdateColorBuffer = false;
                    Material.MaterialParams.TexEnvStages[5].UpdateAlphaBuffer = false;

                    if (Mesh.Name.Contains("alpha"))
                    {
                        if (Mesh.Name.Contains("alphablend"))
                        {
                            M.Layer = 1;
                            Material.MaterialParams.ColorOperation.BlendMode    = PICABlendMode.Blend;
                            Material.MaterialParams.BlendFunction.ColorDstFunc  = PICABlendFunc.OneMinusSourceAlpha;
                            Material.MaterialParams.BlendFunction.ColorEquation = PICABlendEquation.FuncAdd;
                            Material.MaterialParams.BlendFunction.ColorSrcFunc  = PICABlendFunc.SourceAlpha;
                            Material.MaterialParams.BlendFunction.AlphaDstFunc  = PICABlendFunc.OneMinusSourceAlpha;
                            Material.MaterialParams.BlendFunction.AlphaEquation = PICABlendEquation.FuncAdd;
                            Material.MaterialParams.BlendFunction.AlphaSrcFunc  = PICABlendFunc.SourceAlpha;
                            if (Mesh.Name.Contains("rl"))
                            {
                                int digit = Mesh.Name[Mesh.Name.IndexOf("rl") + 2] - '0';
                                if (digit >= 0 && digit <= 3)
                                {
                                    //set renderlayer
                                    M.Priority = digit;
                                }
                            }
                        }
                        Material.MaterialParams.AlphaTest.Enabled   = true;
                        Material.MaterialParams.AlphaTest.Function  = PICATestFunc.Greater;
                        Material.MaterialParams.AlphaTest.Reference = 0;
                    }

                    if (Mesh.Name.Contains("unculled"))
                    {
                        Material.MaterialParams.FaceCulling = PICAFaceCulling.Never;
                    }

                    if (Material.Name.Contains("mado") || Material.Name.Contains("window"))
                    {
                        Material.MaterialParams.LightSetIndex = 1;
                    }

                    Material.TextureMappers[0].MagFilter = H3DTextureMagFilter.Linear;

                    if (Model.Materials.Find(Material.Name) != -1)
                    {
                        M.MaterialIndex = (ushort)Model.Materials.Find(Material.Name);

                        MaterialIndex--;

                        M.UpdateBoolUniforms(Model.Materials[M.MaterialIndex]);
                    }
                    else
                    {
                        Model.Materials.Add(Material);

                        M.UpdateBoolUniforms(Material);
                    }

                    Model.AddMesh(M);
                }


                /*
                 * On Pokémon, the root bone (on the animaiton file) is used by the game to move
                 * characters around, and all rigged bones are parented to this bone.
                 * It's usually the Waist bone, that points upward and is half the character height.
                 */
                /*Model.Skeleton.Add(new H3DBone(
                 *  new Vector3(0, Height * 0.5f, 0),
                 *  new Vector3(0, 0, (float)(Math.PI * 0.5)),
                 *  Vector3.One,
                 *  "Waist",
                 *  -1));*/

                //Model.Skeleton[0].CalculateTransform(Model.Skeleton);

                Output.Models.Add(Model);

                Output.CopyMaterials();
            }

            return(Output);
        }