Esempio n. 1
0
        public override void Export(BinaryWriter writer, string path, Hair hair)
        {
            base.Export(writer, path, hair);

            foreach (HairMesh mesh in hair.meshes)
                if (mesh != null)
                    foreach (HairStrand strand in mesh.strands)
                        foreach (HairStrandVertex vertex in strand.vertices)
                            WriteVector4(writer, vertex.texcoord);
        }
Esempio n. 2
0
        public override HairMesh[] Import(BinaryReader reader, string path, Hair hair, HairImportSettings importSettings)
        {
            HairMesh[] meshes = base.Import(reader, path, hair, importSettings);
            int id = 0;

            foreach (HairMesh mesh in meshes)
                if (mesh != null)
                    foreach (HairStrand strand in mesh.strands)
                        foreach (HairStrandVertex vertex in strand.vertices)
                        {
                            vertex.texcoord = ReadVector4(reader);
                            id++;
                        }

            return meshes;
        }
Esempio n. 3
0
        public virtual void Export(BinaryWriter writer, string path, Hair hair)
        {
            // Get simulation data
            HairSimulationData simulationData = hair.hairSimulationData;

            int vertexCount = hair.vertexCount;

            // Write the header
            writer.Write(vertexCount);
            writer.Write(hair.strandCount);
            writer.Write(hair.maxNumVerticesPerStrand);
            writer.Write(simulationData.guideHairVertexCount);
            writer.Write(simulationData.guideHairStrandCount);
            writer.Write(simulationData.followHairsPerOneGuideHair);

            // Write data
            foreach (int strandType in simulationData.strandTypes)
                writer.Write(strandType);

            // Reference vectors
            foreach (Vector4 refVector in simulationData.referenceVectors)
                WriteVector4(writer, refVector);

            // Global rotations
            foreach (Quaternion globalRot in simulationData.globalRotations)
                WriteQuaternion(writer, globalRot);

            // Local rotations
            foreach (Quaternion localRot in simulationData.localRotations)
                WriteQuaternion(writer, localRot);

            // Position vectors
            foreach (Vector4 vertex in simulationData.vertices)
                WriteVector4(writer, vertex);

            // Tangent vectors
            foreach (Vector4 tangent in simulationData.tangents)
                WriteVector4(writer, tangent);

            // Write binary 0 as triangle vertices as they arent used anyway.
            for (int i = 0; i < vertexCount; i++)
            {
                WriteVector3(writer, Vector3.Zero); // Positions
                WriteVector3(writer, Vector3.Zero); // Tangents
                WriteVector4(writer, Vector4.Zero); // Texcoord
            }

            // Thickness coeffs
            foreach (float thicknessCoeff in simulationData.thicknessCoefficients)
                writer.Write(thicknessCoeff);

            // Follow root offsets vectors
            foreach (Vector4 followRootOffset in simulationData.followRootOffsets)
                WriteVector4(writer, followRootOffset);

            // Rest lengths
            foreach (float restLength in simulationData.restLength)
                writer.Write(restLength);

            // Write bounding sphere
            WriteVector3(writer, hair.boundingSphere.center);
            writer.Write(hair.boundingSphere.radius);

            // Triangle indices
            writer.Write(hair.triangleIndices.Length);
            foreach (int triangleIndices in hair.triangleIndices)
                writer.Write(triangleIndices);

            // Line indices
            writer.Write(hair.lineIndices.Length);
            foreach (int lineIndices in hair.lineIndices)
                writer.Write(lineIndices);
        }
Esempio n. 4
0
 public void SetHair(Hair hair)
 {
     hairMesh.sharedMesh = hair.mesh;
     hairMesh.GetComponent <MeshRenderer>().sharedMaterial = hair.material;
 }
        public override int GetHashCode()
        {
            int hash = 1;

            if (Skin != 0)
            {
                hash ^= Skin.GetHashCode();
            }
            if (Hair != 0)
            {
                hash ^= Hair.GetHashCode();
            }
            if (Shirt != 0)
            {
                hash ^= Shirt.GetHashCode();
            }
            if (Pants != 0)
            {
                hash ^= Pants.GetHashCode();
            }
            if (Hat != 0)
            {
                hash ^= Hat.GetHashCode();
            }
            if (Shoes != 0)
            {
                hash ^= Shoes.GetHashCode();
            }
            if (Avatar != 0)
            {
                hash ^= Avatar.GetHashCode();
            }
            if (Eyes != 0)
            {
                hash ^= Eyes.GetHashCode();
            }
            if (Backpack != 0)
            {
                hash ^= Backpack.GetHashCode();
            }
            if (AvatarHair.Length != 0)
            {
                hash ^= AvatarHair.GetHashCode();
            }
            if (AvatarShirt.Length != 0)
            {
                hash ^= AvatarShirt.GetHashCode();
            }
            if (AvatarPants.Length != 0)
            {
                hash ^= AvatarPants.GetHashCode();
            }
            if (AvatarHat.Length != 0)
            {
                hash ^= AvatarHat.GetHashCode();
            }
            if (AvatarShoes.Length != 0)
            {
                hash ^= AvatarShoes.GetHashCode();
            }
            if (AvatarEyes.Length != 0)
            {
                hash ^= AvatarEyes.GetHashCode();
            }
            if (AvatarBackpack.Length != 0)
            {
                hash ^= AvatarBackpack.GetHashCode();
            }
            if (AvatarGloves.Length != 0)
            {
                hash ^= AvatarGloves.GetHashCode();
            }
            if (AvatarSocks.Length != 0)
            {
                hash ^= AvatarSocks.GetHashCode();
            }
            if (AvatarBelt.Length != 0)
            {
                hash ^= AvatarBelt.GetHashCode();
            }
            if (AvatarGlasses.Length != 0)
            {
                hash ^= AvatarGlasses.GetHashCode();
            }
            if (AvatarNecklace.Length != 0)
            {
                hash ^= AvatarNecklace.GetHashCode();
            }
            if (_unknownFields != null)
            {
                hash ^= _unknownFields.GetHashCode();
            }
            return(hash);
        }
Esempio n. 6
0
 public Hair(Hair hair)
     : base(hair)
 {
     this.color = hair.color;
     this.type = hair.type;
 }
Esempio n. 7
0
        public HairMesh[] Import(BinaryReader reader, string path, Hair hair, HairImportSettings importSettings)
        {
            reader.Close();
            // Initialize the import
            // Load the ase file content
            // Create a List for all meshes
            // Create a list for the current-mesh strands
            string[]          aseContent     = File.ReadAllLines(path);
            List <HairMesh>   hairMeshes     = new List <HairMesh>();
            List <HairStrand> currentStrands = new List <HairStrand>();

            // Init "state"-variables
            int   currentStrand      = 0;
            int   currentHairId      = -1;
            float texcoordMultiplier = 0;

            // Now the hard part begins...
            for (int i = 0; i < aseContent.Length; i++)
            {
                string[] tokens = aseContent[i].Split('\t');

                if (aseContent[i].Contains("*SHAPE_LINECOUNT"))
                {
                    tokens = tokens[1].Split(' ');
                }
                else if (aseContent[i].Contains("SHAPE_LINE"))
                {
                    tokens = tokens[1].Split(' ');
                }

                if (tokens.Length >= 2)
                {
                    if (tokens[0] == "*SHAPE_LINECOUNT")
                    {
                        if (currentStrand > 0)
                        {
                            // Start parsing next mesh after flushing the current strands buffer
                            currentHairId++;
                            currentStrand = 0;

                            // Add to mesh list / flush current strands buffer
                            HairMesh hairMesh = new HairMesh();
                            foreach (HairStrand strand in currentStrands)
                            {
                                hairMesh.strands.Add(strand);
                            }
                            hairMeshes.Add(hairMesh);

                            // Clear current strands
                            currentStrands.Clear();
                            texcoordMultiplier = 1.0f / (float)int.Parse(tokens[1]);
                        }
                    }
                    else if (tokens[0] == "*SHAPE_LINE")
                    {
                        HairStrand strand = new HairStrand();
                        strand.isGuidanceStrand = true;

                        string[] vertexCountTokens = aseContent[i + 1].Split(' ');

                        // Parse the current line
                        int vertexCount = int.Parse(vertexCountTokens[1]);

                        // Parse vertices
                        for (int j = 0; j < vertexCount; j++)
                        {
                            string[] vertexTokens = aseContent[i + 2 + j].Replace('.', ',').Split('\t');

                            if (vertexTokens[2] == "*SHAPE_VERTEX_INTERP")
                            {
                                continue;
                            }

                            System.Globalization.NumberFormatInfo nf
                                = new System.Globalization.NumberFormatInfo()
                                {
                                NumberGroupSeparator = "."
                                };

                            vertexTokens[4] = vertexTokens[4].Replace(',', '.');
                            vertexTokens[5] = vertexTokens[5].Replace(',', '.');
                            vertexTokens[6] = vertexTokens[6].Replace(',', '.');
                            Vector3 position = new Vector3(float.Parse(vertexTokens[4], nf), float.Parse(vertexTokens[6], nf), float.Parse(vertexTokens[5], nf));

                            position = Vector3.Multiply(position, importSettings.scale);
                            HairStrandVertex v = new HairStrandVertex(position, Vector3.Zero, Vector4.Zero);

                            if (strand.vertices.Count == 0)
                            {
                                v.isMovable = false;
                            }

                            strand.vertices.Add(v);
                        }
                        currentStrands.Add(strand);

                        // Increment file-line-pointer
                        i = i + 1 + vertexCount;

                        currentStrand++;
                    }
                }
            }

            // Get last mesh
            HairMesh lastMesh = new HairMesh();

            lastMesh.strands.AddRange(currentStrands);
            hairMeshes.Add(lastMesh);

            return(hairMeshes.ToArray());
        }
Esempio n. 8
0
        public HairMesh[] Import(BinaryReader reader, string path, Hair hair, HairImportSettings importSettings)
        {
            reader.Close();
            // Initialize the import
            // Load the ase file content
            // Create a List for all meshes
            // Create a list for the current-mesh strands
            string[] aseContent = File.ReadAllLines(path);
            List<HairMesh> hairMeshes = new List<HairMesh>();
            List<HairStrand> currentStrands = new List<HairStrand>();

            // Init "state"-variables
            int currentStrand = 0;
            int currentHairId = -1;
            float texcoordMultiplier = 0;

            // Now the hard part begins...
            for (int i = 0; i < aseContent.Length; i++)
            {
                string[] tokens = aseContent[i].Split('\t');

                if (aseContent[i].Contains("*SHAPE_LINECOUNT"))
                {
                    tokens = tokens[1].Split(' ');
                }
                else if (aseContent[i].Contains("SHAPE_LINE"))
                {
                    tokens = tokens[1].Split(' ');
                }

                if (tokens.Length >= 2)
                {
                    if (tokens[0] == "*SHAPE_LINECOUNT")
                    {
                        if (currentStrand > 0)
                        {
                            // Start parsing next mesh after flushing the current strands buffer
                            currentHairId++;
                            currentStrand = 0;

                            // Add to mesh list / flush current strands buffer
                            HairMesh hairMesh = new HairMesh();
                            foreach (HairStrand strand in currentStrands)
                            {
                                hairMesh.strands.Add(strand);
                            }
                            hairMeshes.Add(hairMesh);

                            // Clear current strands
                            currentStrands.Clear();
                            texcoordMultiplier = 1.0f / (float)int.Parse(tokens[1]);
                        }
                    }
                    else if (tokens[0] == "*SHAPE_LINE")
                    {
                        HairStrand strand = new HairStrand();
                        strand.isGuidanceStrand = true;

                        string[] vertexCountTokens = aseContent[i + 1].Split(' ');

                        // Parse the current line
                        int vertexCount = int.Parse(vertexCountTokens[1]);

                        // Parse vertices
                        for (int j = 0; j < vertexCount; j++)
                        {
                            string[] vertexTokens = aseContent[i + 2 + j].Replace('.', ',').Split('\t');

                            if (vertexTokens[2] == "*SHAPE_VERTEX_INTERP")
                                continue;

                            System.Globalization.NumberFormatInfo nf
                            = new System.Globalization.NumberFormatInfo()
                            {
                                NumberGroupSeparator = "."
                            };

                            vertexTokens[4] = vertexTokens[4].Replace(',', '.');
                            vertexTokens[5] = vertexTokens[5].Replace(',', '.');
                            vertexTokens[6] = vertexTokens[6].Replace(',', '.');
                            Vector3 position = new Vector3(float.Parse(vertexTokens[4], nf), float.Parse(vertexTokens[6], nf), float.Parse(vertexTokens[5], nf));

                            position = Vector3.Multiply(position, importSettings.scale);
                            HairStrandVertex v = new HairStrandVertex(position, Vector3.Zero, Vector4.Zero);

                            if (strand.vertices.Count == 0)
                                v.isMovable = false;

                            strand.vertices.Add(v);
                        }
                        currentStrands.Add(strand);

                        // Increment file-line-pointer
                        i = i + 1 + vertexCount;

                        currentStrand++;
                    }
                }
            }

            // Get last mesh
            HairMesh lastMesh = new HairMesh();
            lastMesh.strands.AddRange(currentStrands);
            hairMeshes.Add(lastMesh);

            return hairMeshes.ToArray();
        }
Esempio n. 9
0
        public static async Task DetectAllFaceAtributes(IFaceClient client, string url, string recognitionModel)
        {
            Console.WriteLine("========DETECT FACES========");
            Console.WriteLine();

            // Create a list of images
            List <string> imageFileNames = Directory.GetFiles("C:\\imagenes", "*.*", SearchOption.AllDirectories).ToList();

            imageFileNames = imageFileNames.Where(item => item.Contains("WebCam")).ToList();

            if (imageFileNames.Count >= 10)
            {
                // Intente tirar directamentela excepción, pero no te muestra el message en la consola....
                string message = "Límite de imágenes excedido, no se puede mandar más de 10 imágenes";
                Console.WriteLine("ERROR: " + message);
                throw new Exception(message);
            }

            foreach (var imageFileName in imageFileNames)
            {
                IList <DetectedFace> detectedFaces;

                // Detect faces with all attributes from image url.
                FileStream file = new FileStream(imageFileName, FileMode.Open);
                detectedFaces = await client.Face.DetectWithStreamAsync(
                    file,
                    returnFaceLandmarks : true,
                    returnFaceAttributes : new List <FaceAttributeType> {
                    FaceAttributeType.Accessories, FaceAttributeType.Age,
                    FaceAttributeType.Blur, FaceAttributeType.Emotion, FaceAttributeType.Exposure, FaceAttributeType.FacialHair,
                    FaceAttributeType.Gender, FaceAttributeType.Glasses, FaceAttributeType.Hair, FaceAttributeType.HeadPose,
                    FaceAttributeType.Makeup, FaceAttributeType.Noise, FaceAttributeType.Occlusion, FaceAttributeType.Smile,
                },
                    recognitionModel : recognitionModel);

                Console.WriteLine($"{detectedFaces.Count} face(s) detected from image `{imageFileName}`.");

                // Parse and print all attributes of each detected face.
                foreach (var face in detectedFaces)
                {
                    Console.WriteLine($"Face attributes for {imageFileName}:");

                    // Get bounding box of the faces
                    Console.WriteLine($"Rectangle(Left/Top/Width/Height) : {face.FaceRectangle.Left} {face.FaceRectangle.Top} {face.FaceRectangle.Width} {face.FaceRectangle.Height}");

                    // Get accessories of the faces
                    List <Accessory> accessoriesList = (List <Accessory>)face.FaceAttributes.Accessories;
                    int    count = face.FaceAttributes.Accessories.Count;
                    string accessory; string[] accessoryArray = new string[count];
                    if (count == 0)
                    {
                        accessory = "NoAccessories";
                    }
                    else
                    {
                        for (int i = 0; i < count; ++i)
                        {
                            accessoryArray[i] = accessoriesList[i].Type.ToString();
                        }
                        accessory = string.Join(",", accessoryArray);
                    }
                    Console.WriteLine($"Accessories : {accessory}");

                    // Get face other attributes
                    Console.WriteLine($"Age : {face.FaceAttributes.Age}");
                    Console.WriteLine($"Blur : {face.FaceAttributes.Blur.BlurLevel}");

                    // Get emotion on the face
                    string  emotionType  = string.Empty;
                    double  emotionValue = 0.0;
                    Emotion emotion      = face.FaceAttributes.Emotion;
                    if (emotion.Anger > emotionValue)
                    {
                        emotionValue = emotion.Anger; emotionType = "Anger";
                    }
                    if (emotion.Contempt > emotionValue)
                    {
                        emotionValue = emotion.Contempt; emotionType = "Contempt";
                    }
                    if (emotion.Disgust > emotionValue)
                    {
                        emotionValue = emotion.Disgust; emotionType = "Disgust";
                    }
                    if (emotion.Fear > emotionValue)
                    {
                        emotionValue = emotion.Fear; emotionType = "Fear";
                    }
                    if (emotion.Happiness > emotionValue)
                    {
                        emotionValue = emotion.Happiness; emotionType = "Happiness";
                    }
                    if (emotion.Neutral > emotionValue)
                    {
                        emotionValue = emotion.Neutral; emotionType = "Neutral";
                    }
                    if (emotion.Sadness > emotionValue)
                    {
                        emotionValue = emotion.Sadness; emotionType = "Sadness";
                    }
                    if (emotion.Surprise > emotionValue)
                    {
                        emotionType = "Surprise";
                    }
                    Console.WriteLine($"Emotion : {emotionType}");

                    // Get more face attributes
                    Console.WriteLine($"Exposure : {face.FaceAttributes.Exposure.ExposureLevel}");
                    Console.WriteLine($"FacialHair : {string.Format("{0}", face.FaceAttributes.FacialHair.Moustache + face.FaceAttributes.FacialHair.Beard + face.FaceAttributes.FacialHair.Sideburns > 0 ? "Yes" : "No")}");
                    Console.WriteLine($"Gender : {face.FaceAttributes.Gender}");
                    Console.WriteLine($"Glasses : {face.FaceAttributes.Glasses}");

                    // Get hair color
                    Hair   hair  = face.FaceAttributes.Hair;
                    string color = null;
                    if (hair.HairColor.Count == 0)
                    {
                        if (hair.Invisible)
                        {
                            color = "Invisible";
                        }
                        else
                        {
                            color = "Bald";
                        }
                    }
                    HairColorType returnColor   = HairColorType.Unknown;
                    double        maxConfidence = 0.0f;
                    foreach (HairColor hairColor in hair.HairColor)
                    {
                        if (hairColor.Confidence <= maxConfidence)
                        {
                            continue;
                        }
                        maxConfidence = hairColor.Confidence; returnColor = hairColor.Color; color = returnColor.ToString();
                    }
                    Console.WriteLine($"Hair : {color}");

                    // Get more attributes
                    Console.WriteLine($"HeadPose : {string.Format("Pitch: {0}, Roll: {1}, Yaw: {2}", Math.Round(face.FaceAttributes.HeadPose.Pitch, 2), Math.Round(face.FaceAttributes.HeadPose.Roll, 2), Math.Round(face.FaceAttributes.HeadPose.Yaw, 2))}");
                    Console.WriteLine($"Makeup : {string.Format("{0}", (face.FaceAttributes.Makeup.EyeMakeup || face.FaceAttributes.Makeup.LipMakeup) ? "Yes" : "No")}");
                    Console.WriteLine($"Noise : {face.FaceAttributes.Noise.NoiseLevel}");
                    Console.WriteLine($"Occlusion : {string.Format("EyeOccluded: {0}", face.FaceAttributes.Occlusion.EyeOccluded ? "Yes" : "No")} " +
                                      $" {string.Format("ForeheadOccluded: {0}", face.FaceAttributes.Occlusion.ForeheadOccluded ? "Yes" : "No")}   {string.Format("MouthOccluded: {0}", face.FaceAttributes.Occlusion.MouthOccluded ? "Yes" : "No")}");
                    Console.WriteLine($"Smile : {face.FaceAttributes.Smile}");
                    Console.WriteLine();
                }
            }
        }
Esempio n. 10
0
 public void EditHair(Hair hair)
 {
     db.Entry(hair).State = EntityState.Modified;
     db.SaveChanges();
 }
Esempio n. 11
0
 public int CreateHair(Hair hair)
 {
     db.Hairs.Add(hair);
     db.SaveChanges();
     return(hair.HairID);
 }
Esempio n. 12
0
 public void SetHairCut(Hair hair)
 {
     this.Hair = hair;
 }
Esempio n. 13
0
 public static void ChangeHair(Hair hair, GameObject character)
 {
     foreach (Transform t in character.transform.FindChild("Character").FindChild("Armature").FindChild("Head_slot").FindChild("Hair"))
     {
         if (t.gameObject.name == hair.GetTypeHair.ToString())
         {
             t.gameObject.SetActive(true);
             t.gameObject.GetComponentInChildren<Renderer>().material.mainTexture = hair.Texture;
         }
         else
             t.gameObject.SetActive(false);
     }
 }
Esempio n. 14
0
 public Skin(Beard beard, Hair hair, Hat hat, Body body, Tshirt tshirt, Pant pant, Gloves gloves, Eyes eyes)
 {
     this.beard = beard;
     this.hair = hair;
     this.hat = hat;
     this.body = body;
     this.tshirt = tshirt;
     this.pant = pant;
     this.gloves = gloves;
     this.eyes = eyes;
 }
Esempio n. 15
0
 // Constructeur
 public Skin()
 {
     this.beard = new Beard();
     this.hair = new Hair();
     this.hat = new Hat();
     this.body = new Body();
     this.tshirt = new Tshirt();
     this.pant = new Pant();
     this.gloves = new Gloves();
     this.eyes = new Eyes();
 }
Esempio n. 16
0
        public HairMesh[] Import(BinaryReader reader, string path, Hair hair, HairImportSettings importSettings)
        {
            reader.Close();
            // Initialize the importer
            string[] objContent = File.ReadAllLines(path);
            List<Vector3> vertices = new List<Vector3>();
            List<Line> indices = new List<Line>();
            List<HairStrand> currentStrands = new List<HairStrand>();
            
            // Parse all vertices and indices
            for (int i = 0; i < objContent.Length; i++)
            {
                // Get all parts
                List<string> partsList = new List<string>(objContent[i].Split(' '));
                partsList.RemoveAll(x => string.IsNullOrEmpty(x.Replace(" ", "")));
                string[] parts = partsList.ToArray();

                switch (parts[0])
                {
                    case "v":
                        {
                            vertices.Add(new Vector3(SafeParse(parts[1]), SafeParse(parts[2]), SafeParse(parts[3])));
                        }
                        break;
                    case "l":
                        {
                            indices.Add(new Line(int.Parse(parts[1])-1, int.Parse(parts[2])-1));
                        }
                        break;
                }
            }

            // Parse all strands
            List<int> alreadyLoadedIndices = new List<int>(640000);
            List<HairStrandVertex> currentStrandVertices = new List<HairStrandVertex>(64);
            for (int i = 0; i < indices.Count; i++)
            {
                // In order to detect when a new hair starts, we detect if the first index in a line was not added to the mesh already.
                // If it was NOT, we are in a new strand
                if (i != 0 && !alreadyLoadedIndices.Contains(indices[i].index1))
                {
                    // We are in a new hair strand
                    HairStrand hs = new HairStrand();
                    currentStrandVertices[0].isMovable = false;
                    currentStrandVertices.ForEach((sv) =>
                    {
                        hs.vertices.Add(sv);
                    });

                    hs.isGuidanceStrand = true;
                    currentStrands.Add(hs);

                    // Cleanup
                    currentStrandVertices.Clear();
                }

                // Add
                if (!alreadyLoadedIndices.Contains(indices[i].index1))
                {
                    currentStrandVertices.Add(new HairStrandVertex(vertices[indices[i].index1], Vector3.Zero, Vector4.Zero));
                    alreadyLoadedIndices.Add(indices[i].index1);
                }
                if (!alreadyLoadedIndices.Contains(indices[i].index2))
                {
                    currentStrandVertices.Add(new HairStrandVertex(vertices[indices[i].index2], Vector3.Zero, Vector4.Zero));
                    alreadyLoadedIndices.Add(indices[i].index2);
                }
            }

            HairMesh hm = new HairMesh();
            currentStrands.ForEach((item) =>
            {
                hm.strands.Add(item);
            });

            return new HairMesh[] { hm };
        }
Esempio n. 17
0
        public static async Task DetectFaceExtract(IFaceClient client, string url, string recognitionModel)
        {
            List <string> imageFileNames = new List <string>
            {
                "detection1.jpg"           // single female with glasses
                //"detection5.jpg",    // family, woman child man
                //"detection6.jpg"     // elderly couple, male female
            };

            foreach (var imageFileName in imageFileNames)
            {
                IList <DetectedFace> detectedFaces;

                // 取得する画像のurl、ファイル名、その中の情報の指定
                // 分析の結果をdetectedFacesに格納
                detectedFaces = await client.Face.DetectWithUrlAsync($"{url}{imageFileName}",
                                                                     returnFaceAttributes : new List <FaceAttributeType?> {
                    FaceAttributeType.Accessories, FaceAttributeType.Age,
                    FaceAttributeType.Blur, FaceAttributeType.Emotion, FaceAttributeType.Exposure, FaceAttributeType.FacialHair,
                    FaceAttributeType.Gender, FaceAttributeType.Glasses, FaceAttributeType.Hair, FaceAttributeType.HeadPose,
                    FaceAttributeType.Makeup, FaceAttributeType.Noise, FaceAttributeType.Occlusion, FaceAttributeType.Smile
                },
                                                                                                                  // We specify detection model 1 because we are retrieving attributes.
                                                                     detectionModel : DetectionModel.Detection01, // 分析の方法
                                                                     recognitionModel : recognitionModel);        // 出力の方法

                Console.WriteLine($"{detectedFaces.Count} face(s) detected from image `{imageFileName}`.");
                foreach (var face in detectedFaces)
                {
                    Console.WriteLine($"Face attributes for {imageFileName}:");

                    // 顔の向きの表示
                    Console.WriteLine($"Rectangle(Left/Top/Width/Height) : {face.FaceRectangle.Left} {face.FaceRectangle.Top} {face.FaceRectangle.Width} {face.FaceRectangle.Height}");

                    // アクセサリーの表示
                    List <Accessory> accessoriesList = (List <Accessory>)face.FaceAttributes.Accessories;
                    int    count = face.FaceAttributes.Accessories.Count;
                    string accessory; string[] accessoryArray = new string[count];
                    if (count == 0)
                    {
                        accessory = "NoAccessories";
                    }
                    else
                    {
                        for (int i = 0; i < count; ++i)
                        {
                            accessoryArray[i] = accessoriesList[i].Type.ToString();
                        }
                        accessory = string.Join(",", accessoryArray);
                    }
                    Console.WriteLine($"Accessories : {accessory}");


                    // 年齢、画像のぼかし度
                    Console.WriteLine($"Age : {face.FaceAttributes.Age}");
                    Console.WriteLine($"Blur : {face.FaceAttributes.Blur.BlurLevel}");

                    // 表情から感情の分析
                    string  emotionType  = string.Empty;
                    double  emotionValue = 0.0;
                    Emotion emotion      = face.FaceAttributes.Emotion;
                    if (emotion.Anger > emotionValue)
                    {
                        emotionValue = emotion.Anger; emotionType = "Anger";
                    }                                                                                          // 怒り
                    if (emotion.Contempt > emotionValue)
                    {
                        emotionValue = emotion.Contempt; emotionType = "Contempt";
                    }                                                                                                   // 悔しさ
                    if (emotion.Disgust > emotionValue)
                    {
                        emotionValue = emotion.Disgust; emotionType = "Disgust";
                    }                                                                                                // 嫌悪
                    if (emotion.Fear > emotionValue)
                    {
                        emotionValue = emotion.Fear; emotionType = "Fear";
                    }                                                                                       // 恐怖
                    if (emotion.Happiness > emotionValue)
                    {
                        emotionValue = emotion.Happiness; emotionType = "Happiness";
                    }                                                                                                      // 喜び
                    if (emotion.Neutral > emotionValue)
                    {
                        emotionValue = emotion.Neutral; emotionType = "Neutral";
                    }                                                                                                // 無表情
                    if (emotion.Sadness > emotionValue)
                    {
                        emotionValue = emotion.Sadness; emotionType = "Sadness";
                    }                                                                                                // 悲しみ
                    if (emotion.Surprise > emotionValue)
                    {
                        emotionType = "Surprise";
                    }                                              // 驚き
                    Console.WriteLine($"Emotion : {emotionType}"); // 最終的な表情の分析結果

                    // その他の分析情報1
                    Console.WriteLine($"Exposure : {face.FaceAttributes.Exposure.ExposureLevel}");                                                                                                                            // 露出
                    Console.WriteLine($"FacialHair : {string.Format("{0}", face.FaceAttributes.FacialHair.Moustache + face.FaceAttributes.FacialHair.Beard + face.FaceAttributes.FacialHair.Sideburns > 0 ? "Yes" : "No")}"); // 髭
                    Console.WriteLine($"Gender : {face.FaceAttributes.Gender}");                                                                                                                                              // 性別
                    Console.WriteLine($"Glasses : {face.FaceAttributes.Glasses}");                                                                                                                                            // 眼鏡

                    // 髪の毛の色の表示
                    Hair   hair  = face.FaceAttributes.Hair;
                    string color = null;
                    if (hair.HairColor.Count == 0)
                    {
                        if (hair.Invisible)
                        {
                            color = "Invisible";
                        }
                        else
                        {
                            color = "Bald";
                        }
                    }
                    HairColorType returnColor   = HairColorType.Unknown;
                    double        maxConfidence = 0.0f;
                    foreach (HairColor hairColor in hair.HairColor)
                    {
                        if (hairColor.Confidence <= maxConfidence)
                        {
                            continue;
                        }
                        maxConfidence = hairColor.Confidence; returnColor = hairColor.Color; color = returnColor.ToString();
                    }
                    Console.WriteLine($"Hair : {color}");


                    // その他の分析情報2
                    Console.WriteLine($"HeadPose : {string.Format("Pitch: {0}, Roll: {1}, Yaw: {2}", Math.Round(face.FaceAttributes.HeadPose.Pitch, 2), Math.Round(face.FaceAttributes.HeadPose.Roll, 2), Math.Round(face.FaceAttributes.HeadPose.Yaw, 2))}"); // 顔の角度
                    Console.WriteLine($"Makeup : {string.Format("{0}", (face.FaceAttributes.Makeup.EyeMakeup || face.FaceAttributes.Makeup.LipMakeup) ? "Yes" : "No")}");                                                                                      // 化粧
                    Console.WriteLine($"Noise : {face.FaceAttributes.Noise.NoiseLevel}");                                                                                                                                                                      // 粗さ
                    Console.WriteLine($"Occlusion : {string.Format("EyeOccluded: {0}", face.FaceAttributes.Occlusion.EyeOccluded ? "Yes" : "No")} " +
                                      $" {string.Format("ForeheadOccluded: {0}", face.FaceAttributes.Occlusion.ForeheadOccluded ? "Yes" : "No")}   {string.Format("MouthOccluded: {0}", face.FaceAttributes.Occlusion.MouthOccluded ? "Yes" : "No")}");        // 顔の全体の露出度
                    Console.WriteLine($"Smile : {face.FaceAttributes.Smile}");                                                                                                                                                                                 // 笑顔かどうか
                    Console.WriteLine();
                }
            }
        }
Esempio n. 18
0
 public string AssembleAvatarString() => Hair.ToString() + HairColour + "-" + Head.ToString() + HeadColour + "-" + Torso.ToString() + TorsoColour + "-" + Bottoms.ToString() + BottomsColour + "-" + Feet.ToString() + FeetColour;
Esempio n. 19
0
	public HairCondition(bool yes, Hair hair){

		this.yes = yes;
		this.hair = hair;

	}
Esempio n. 20
0
            public void Load(byte[] bytes, int version)
            {
                try
                {
                    using (var reader = new BinaryReader(new MemoryStream(bytes)))
                    {
                        productNo = reader.ReadInt32();

                        int faceShapeCount = reader.ReadInt32();
                        shapeValueFace = new float[faceShapeCount];
                        for (int i = 0; i < faceShapeCount; i++)
                        {
                            shapeValueFace[i] = reader.ReadSingle();
                        }

                        int bodyShapeCount = reader.ReadInt32();
                        shapeValueBody = new float[bodyShapeCount];
                        for (int i = 0; i < bodyShapeCount; i++)
                        {
                            shapeValueBody[i] = reader.ReadSingle();
                        }

                        int hairCount = reader.ReadInt32();
                        hair = new Hair[hairCount];
                        for (int i = 0; i < hairCount; i++)
                        {
                            hair[i]    = new Hair();
                            hair[i].id = reader.ReadInt32();
                            hair[i].color.Load(reader);
                            hair[i].acsColor.Load(reader);
                        }

                        if (2 <= version)
                        {
                            hairType = reader.ReadInt32();
                        }

                        this.headId = reader.ReadInt32();
                        this.skinColor.Load(reader);
                        this.texFaceId     = reader.ReadInt32();
                        this.texTattoo_fId = reader.ReadInt32();
                        this.tattoo_fColor.Load(reader);
                        this.matEyebrowId = reader.ReadInt32();
                        this.eyebrowColor.Load(reader);
                        this.matEyeLId = reader.ReadInt32();
                        this.eyeLColor.Load(reader);
                        this.matEyeRId = reader.ReadInt32();
                        this.eyeRColor.Load(reader);
                        this.eyeWColor.Load(reader);
                        this.texFaceDetailId  = reader.ReadInt32();
                        this.faceDetailWeight = reader.ReadSingle();
                        this.texBodyId        = reader.ReadInt32();
                        this.texTattoo_bId    = reader.ReadInt32();
                        this.tattoo_bColor.Load(reader);
                        this.texBodyDetailId  = reader.ReadInt32();
                        this.bodyDetailWeight = reader.ReadSingle();
                        this.name             = reader.ReadString();
                        this.personality      = reader.ReadInt32();
                        if (3 <= version)
                        {
                            this.voicePitch = reader.ReadSingle();
                        }
                        if (4 <= version)
                        {
                            this.isConcierge = reader.ReadBoolean();
                        }

                        if (this.sex == 0)
                        {
                            this.matBeardId = reader.ReadInt32();
                            this.beardColor.Load(reader);
                        }
                        else
                        {
                            this.texEyeshadowId = reader.ReadInt32();
                            this.eyeshadowColor.Load(reader);
                            this.texCheekId = reader.ReadInt32();
                            this.cheekColor.Load(reader);
                            this.texLipId = reader.ReadInt32();
                            this.lipColor.Load(reader);
                            this.texMoleId = reader.ReadInt32();
                            this.moleColor.Load(reader);
                            this.matEyelashesId = reader.ReadInt32();
                            this.eyelashesColor.Load(reader);
                            this.matEyeHiId = reader.ReadInt32();
                            this.eyeHiColor.Load(reader);
                            this.texSunburnId = reader.ReadInt32();
                            this.sunburnColor.Load(reader);
                            this.matNipId = reader.ReadInt32();
                            this.nipColor.Load(reader);
                            this.matUnderhairId = reader.ReadInt32();
                            this.underhairColor.Load(reader);
                            this.nailColor.Load(reader);
                            this.areolaSize   = reader.ReadSingle();
                            this.bustSoftness = reader.ReadSingle();
                            this.bustWeight   = reader.ReadSingle();
                        }
                    }
                }
                catch (Exception e)
                {
                    System.Diagnostics.Debug.WriteLine(e.Message);
                }
            }
Esempio n. 21
0
        /*
         * Detect faces from URL images
         */
        public static async Task DetectFaceExtract(IFaceClient client, string recognitionModel)
        {
            Console.WriteLine("========Sample of face detection========");

            // Create a list of images
            const string  IMAGE_BASE_URL = "https://csdx.blob.core.windows.net/resources/Face/Images/";
            List <string> imageFileNames = new List <string>
            {
                "detection1.jpg",                                  // single female with glasses
                // "detection2.jpg", // (optional: single man)
                // "detection3.jpg", // (optional: single male construction worker)
                // "detection4.jpg", // (optional: 3 people at cafe, 1 is blurred)
                "detection5.jpg",                                  // black family, woman child man
                "detection6.jpg"                                   // elderly couple, male female
            };

            foreach (var imageFileName in imageFileNames)
            {
                IList <DetectedFace> detectedFaces;

                // Detect faces with all attributes from image url.
                detectedFaces = await client.Face.DetectWithUrlAsync($"{IMAGE_BASE_URL}{imageFileName}",
                                                                     returnFaceAttributes : new List <FaceAttributeType> {
                    FaceAttributeType.Accessories, FaceAttributeType.Age,
                    FaceAttributeType.Blur, FaceAttributeType.Emotion, FaceAttributeType.Exposure, FaceAttributeType.FacialHair,
                    FaceAttributeType.Gender, FaceAttributeType.Glasses, FaceAttributeType.Hair, FaceAttributeType.HeadPose,
                    FaceAttributeType.Makeup, FaceAttributeType.Noise, FaceAttributeType.Occlusion, FaceAttributeType.Smile
                },
                                                                     recognitionModel : recognitionModel);

                Console.WriteLine($"{detectedFaces.Count} face(s) detected from image `{imageFileName}`.");

                // Parse and print all attributes of each detected face.
                foreach (var face in detectedFaces)
                {
                    Console.WriteLine($"Face attributes for {imageFileName}:");

                    // Get bounding box of the faces
                    Console.WriteLine($"Rectangle(Left/Top/Width/Height) : {face.FaceRectangle.Left} {face.FaceRectangle.Top} {face.FaceRectangle.Width} {face.FaceRectangle.Height}");

                    // Get accessories of the faces
                    List <Accessory> accessoriesList = (List <Accessory>)face.FaceAttributes.Accessories;
                    int    count = face.FaceAttributes.Accessories.Count;
                    string accessory; string[] accessoryArray = new string[count];
                    if (count == 0)
                    {
                        accessory = "NoAccessories";
                    }
                    else
                    {
                        for (int i = 0; i < count; ++i)
                        {
                            accessoryArray[i] = accessoriesList[i].Type.ToString();
                        }
                        accessory = string.Join(",", accessoryArray);
                    }
                    Console.WriteLine($"Accessories : {accessory}");

                    // Get face other attributes
                    Console.WriteLine($"Age : {face.FaceAttributes.Age}");
                    Console.WriteLine($"Blur : {face.FaceAttributes.Blur.BlurLevel}");

                    // Get emotion on the face
                    string  emotionType  = string.Empty;
                    double  emotionValue = 0.0;
                    Emotion emotion      = face.FaceAttributes.Emotion;
                    if (emotion.Anger > emotionValue)
                    {
                        emotionValue = emotion.Anger; emotionType = "Anger";
                    }
                    if (emotion.Contempt > emotionValue)
                    {
                        emotionValue = emotion.Contempt; emotionType = "Contempt";
                    }
                    if (emotion.Disgust > emotionValue)
                    {
                        emotionValue = emotion.Disgust; emotionType = "Disgust";
                    }
                    if (emotion.Fear > emotionValue)
                    {
                        emotionValue = emotion.Fear; emotionType = "Fear";
                    }
                    if (emotion.Happiness > emotionValue)
                    {
                        emotionValue = emotion.Happiness; emotionType = "Happiness";
                    }
                    if (emotion.Neutral > emotionValue)
                    {
                        emotionValue = emotion.Neutral; emotionType = "Neutral";
                    }
                    if (emotion.Sadness > emotionValue)
                    {
                        emotionValue = emotion.Sadness; emotionType = "Sadness";
                    }
                    if (emotion.Surprise > emotionValue)
                    {
                        emotionType = "Surprise";
                    }
                    Console.WriteLine($"Emotion : {emotionType}");

                    // Get more face attributes
                    Console.WriteLine($"Exposure : {face.FaceAttributes.Exposure.ExposureLevel}");
                    Console.WriteLine($"FacialHair : {string.Format("{0}", face.FaceAttributes.FacialHair.Moustache + face.FaceAttributes.FacialHair.Beard + face.FaceAttributes.FacialHair.Sideburns > 0 ? "Yes" : "No")}");
                    Console.WriteLine($"Gender : {face.FaceAttributes.Gender}");
                    Console.WriteLine($"Glasses : {face.FaceAttributes.Glasses}");

                    // Get hair color
                    Hair   hair  = face.FaceAttributes.Hair;
                    string color = null;
                    if (hair.HairColor.Count == 0)
                    {
                        if (hair.Invisible)
                        {
                            color = "Invisible";
                        }
                        else
                        {
                            color = "Bald";
                        }
                    }
                    HairColorType returnColor   = HairColorType.Unknown;
                    double        maxConfidence = 0.0f;
                    foreach (HairColor hairColor in hair.HairColor)
                    {
                        if (hairColor.Confidence <= maxConfidence)
                        {
                            continue;
                        }
                        maxConfidence = hairColor.Confidence; returnColor = hairColor.Color; color = returnColor.ToString();
                    }
                    Console.WriteLine($"Hair : {color}");

                    // Get more attributes
                    Console.WriteLine($"HeadPose : {string.Format("Pitch: {0}, Roll: {1}, Yaw: {2}", Math.Round(face.FaceAttributes.HeadPose.Pitch, 2), Math.Round(face.FaceAttributes.HeadPose.Roll, 2), Math.Round(face.FaceAttributes.HeadPose.Yaw, 2))}");
                    Console.WriteLine($"Makeup : {string.Format("{0}", (face.FaceAttributes.Makeup.EyeMakeup || face.FaceAttributes.Makeup.LipMakeup) ? "Yes" : "No")}");
                    Console.WriteLine($"Noise : {face.FaceAttributes.Noise.NoiseLevel}");
                    Console.WriteLine($"Occlusion : {string.Format("EyeOccluded: {0}", face.FaceAttributes.Occlusion.EyeOccluded ? "Yes" : "No")} " +
                                      $" {string.Format("ForeheadOccluded: {0}", face.FaceAttributes.Occlusion.ForeheadOccluded ? "Yes" : "No")}   {string.Format("MouthOccluded: {0}", face.FaceAttributes.Occlusion.MouthOccluded ? "Yes" : "No")}");
                    Console.WriteLine($"Smile : {face.FaceAttributes.Smile}");
                    Console.WriteLine();
                }
            }
        }
Esempio n. 22
0
        public DataLoader()
        {
            Race human = new Race();

            human.DefName = "Human";
            human.Label   = "Human";
            Genders.Add("Female");
            Genders.Add("Male");
            human.BodyType.Add("Male");
            human.BodyType.Add("Female");
            human.BodyType.Add("Average");
            human.BodyType.Add("Thin");
            human.BodyType.Add("Hulk");
            human.BodyType.Add("Fat");
            human.HairsByGender["Female"] = new List <Hair>();
            human.HairsByGender["Male"]   = new List <Hair>();
            foreach (var firstType in new string[] { "Average", "Narrow" })
            {
                foreach (var secondType in new string[] { "Normal", "Pointy", "Wide" })
                {
                    human.HeadType.Add(new CrownType
                    {
                        CrownFirstType = firstType,
                        CrownSubType   = secondType
                    });
                }
            }
            Quality.Add("Awful");
            Quality.Add("Poor");
            Quality.Add("Normal");
            Quality.Add("Good");
            Quality.Add("Excellent");
            Quality.Add("Masterwork");
            Quality.Add("Legendary");

            RaceDictionary[human.DefName] = human;

            ResourceLoader.Load();

            var allXmlFiles = Directory.GetFiles("Data", "*.xml", SearchOption.AllDirectories);

            List <Hair> allHairs = new List <Hair>();

            foreach (var xmlFile in allXmlFiles)
            {
                string[] pathComponents = xmlFile.Split('\\');
                if (!pathComponents[2].Equals("Defs"))
                {
                    continue;
                }

                using (var fileStream = File.OpenRead(xmlFile))
                {
                    var docRoot = XDocument.Load(fileStream).Root;
                    CurrentDocumentPath = xmlFile;
                    var workTypeDefsRoot = docRoot.XPathSelectElements("WorkTypeDef/workTags/..");

                    if (workTypeDefsRoot.Count() != 0)
                    {
                        var workTypeDefs = from workTypeDef in workTypeDefsRoot
                                           select new WorkType
                        {
                            DefName  = workTypeDef.Element("defName").GetValue(),
                            FullName = workTypeDef.Element("gerundLabel").GetValue(),
                            WorkTags = workTypeDef.Element("workTags")
                                       .Elements("li")
                                       .Select(element => element.GetValue()).ToArray()
                        };

                        WorkTypes.AddRange(workTypeDefs);
                    }

                    foreach (var raceVars in docRoot.Descendants("AlienRace.ThingDef_AlienRace"))
                    {
                        Race race = new Race();
                        race.DefName = raceVars.Element("defName").GetValue();
                        race.Label   = raceVars.Element("label").GetValue();
                        var alienraceElement = raceVars.Element("alienrace");
                        if (alienraceElement == null)
                        {
                            alienraceElement = raceVars.Element("alienRace");
                        }
                        race.HairsByGender["Female"] = new List <Hair>();
                        race.HairsByGender["Male"]   = new List <Hair>();
                        foreach (var bodyType in alienraceElement.XPathSelectElements("generalSettings/alienPartGenerator/alienbodytypes/li"))
                        {
                            race.BodyType.Add(bodyType.GetValue());
                        }
                        foreach (var crownType in alienraceElement.XPathSelectElements("generalSettings/alienPartGenerator/aliencrowntypes/li"))
                        {
                            string[] crownStrings = crownType.GetValue().Split('_');
                            race.HeadType.Add(new CrownType
                            {
                                CrownFirstType = crownStrings[0],
                                CrownSubType   = crownStrings[1]
                            });
                        }
                        if (race.HeadType.Count == 0)
                        {
                            race.HeadType.Add(new CrownType
                            {
                                CrownFirstType = "Average",
                                CrownSubType   = "Normal"
                            });
                        }
                        var useGenderedHeads = alienraceElement.XPathSelectElement("generalSettings/alienPartGenerator/UseGenderedHeads");
                        if (useGenderedHeads != null)
                        {
                            race.UseGenderedHeads = Convert.ToBoolean(useGenderedHeads.GetValue());
                        }
                        foreach (var path in alienraceElement.XPathSelectElement("graphicPaths/li").Elements())
                        {
                            race.GraphicPaths[path.Name.ToString().ToLower()] = path.GetValue();
                        }
                        RaceDictionary[race.DefName] = race;
                    }

                    foreach (var hairVars in docRoot.Descendants("HairDef"))
                    {
                        Hair hair = new Hair(
                            hairVars.Element("hairGender").GetValue(),
                            hairVars.Element("label").GetValue(),
                            hairVars.Element("defName").GetValue(),
                            hairVars.XPathSelectElements("hairTags/li"));
                        allHairs.Add(hair);
                    }

                    foreach (var traitDef in docRoot.Descendants("TraitDef"))
                    {
                        var traits = (from trait in traitDef.XPathSelectElements("degreeDatas/li")
                                      select new TraitDef
                        {
                            Def = traitDef.Element("defName").Value,
                            Label = textInfo.ToTitleCase(trait.Element("label").Value),
                            Degree = trait.Element("degree") != null ? trait.Element("degree").Value : "0",
                            Description = trait.Element("description").Value
                        });

                        foreach (var trait in traits)
                        {
                            if (!Traits.ContainsKey(trait.Def + trait.Degree))
                            {
                                Traits.Add(trait.Def + trait.Degree, trait);
                            }
                        }
                    }

                    foreach (var hediffRoot in docRoot.XPathSelectElements("HediffDef/hediffClass/.."))
                    {
                        var parentClass = hediffRoot.Element("hediffClass").Value;
                        var parentName  = hediffRoot.Attribute("Name") != null?hediffRoot.Attribute("Name").Value : "None";

                        Hediff coreHediff;

                        if (!Hediffs.TryGetValue(parentClass, out coreHediff))
                        {
                            Hediffs.Add(parentClass, coreHediff = new Hediff(parentClass, parentName));
                        }

                        var hediffs = (from hediff in docRoot.XPathSelectElements("//HediffDef[boolean(@ParentName) and not(@Abstract)]")
                                       .Where(x => x.Attribute("ParentName").Value == parentName)
                                       select new HediffDef
                        {
                            ParentClass = parentClass,
                            ParentName = hediff.Attribute("ParentName").Value,
                            Def = hediff.Element("defName").Value,
                            Label = textInfo.ToTitleCase(hediff.Element("label").Value),
                        });

                        foreach (var hediff in hediffs)
                        {
                            coreHediff.SubDiffs[hediff.Def] = hediff;
                        }
                    }

                    foreach (var def in docRoot.Descendants("AlienRace.BackstoryDef"))
                    {
                        if (def.Attribute("Abstract") == null || def.Attribute("Abstract").Value != "True")
                        {
                            Backstory backstory = new Backstory
                            {
                                Id           = (string)def.Element("defName"),
                                Title        = (string)def.Element("title"),
                                DisplayTitle = "(AlienRace)" + (string)def.Element("title"),
                                TitleShort   = (string)def.Element("titleShort"),
                                Description  = (string)def.Element("baseDescription"),
                                Slot         = (string)def.Element("slot"),
                                SkillGains   = new Dictionary <string, int>(),
                                WorkDisables = new List <string>()
                            };
                            foreach (var skillGain in def.XPathSelectElements("skillGains/li"))
                            {
                                string defName = (string)skillGain.Element("defName");
                                int    amount  = Convert.ToInt32(skillGain.Element("amount").GetValue());
                                backstory.SkillGains.Add(defName, amount);
                            }
                            foreach (var workDisables in def.XPathSelectElements("workDisables/li"))
                            {
                                backstory.WorkDisables.Add(workDisables.GetValue());
                            }
                            ResourceLoader.Backstories[backstory.Id] = backstory;

                            if (string.IsNullOrEmpty(backstory.Slot))
                            {
                                ResourceLoader.ChildhoodStories.Add(backstory);
                                ResourceLoader.AdulthoodStories.Add(backstory);
                            }
                            else if (backstory.Slot == "Childhood")
                            {
                                ResourceLoader.ChildhoodStories.Add(backstory);
                            }
                            else
                            {
                                ResourceLoader.AdulthoodStories.Add(backstory);
                            }
                        }
                    }

                    foreach (var relationDef in docRoot.XPathSelectElements("PawnRelationDef"))
                    {
                        var pawnRelation = new PawnRelationDef(relationDef);
                        PawnRelationDefs.Add(pawnRelation.DefName, pawnRelation);
                    }

                    foreach (var thingDef in docRoot.XPathSelectElements("ThingDef"))
                    {
                        ThingDef def = new ThingDef(thingDef);
                        if (ThingDefs.TryGetValue(def.Name, out ThingDef value))
                        {
                            value.updateDef(thingDef);
                        }
                        else
                        {
                            ThingDefs.Add(def.Name, def);
                        }
                    }

                    foreach (var bodyDefElement in docRoot.XPathSelectElements("BodyDef"))
                    {
                        BodyDef bodyDef = new BodyDef(bodyDefElement);
                        if (bodyDef.DefName != null)
                        {
                            BodyDefsByDef[bodyDef.DefName] = bodyDef;
                        }
                    }

                    fileStream.Close();
                }
            }

            Dictionary <string, Race> tempRaceDic = RaceDictionary.Values.ToDictionary(x => x.Label.ToLower(), x => x);

            foreach (Hair hair in allHairs)
            {
                List <Race> races = new List <Race>();
                foreach (var hairTags in hair.HairTags)
                {
                    Race race;
                    if (tempRaceDic.TryGetValue(hairTags, out race))
                    {
                        races.Add(race);
                    }
                }
                if (races.Count == 0)
                {
                    races.Add(RaceDictionary["Human"]);
                    if (RaceDictionary.TryGetValue("Alien_Orassan", out var race))
                    {
                        races.Add(race);
                    }
                }

                foreach (var race in races)
                {
                    if (hair.Gender.Equals("Any") || hair.Gender.Contains("Usually"))
                    {
                        foreach (var list in race.HairsByGender.Values.ToList())
                        {
                            list.Add(hair);
                        }
                    }
                    else
                    {
                        List <Hair> hairListForGender;
                        if (race.HairsByGender.TryGetValue(hair.Gender, out hairListForGender))
                        {
                            hairListForGender.Add(hair);
                        }
                    }
                }
            }

            foreach (ThingDef thingDef in ThingDefs.Values)
            {
                if (thingDef.ParentName != null && ThingDefs.TryGetValue(thingDef.ParentName, out ThingDef value))
                {
                    thingDef.Parent = value;
                }
                if (thingDef.DefName != null && !ThingDefsByDefName.ContainsKey(thingDef.DefName))
                {
                    ThingDefsByDefName.Add(thingDef.DefName, thingDef);
                }
                foreach (string stuffPropCat in thingDef.StuffPropsCategories)
                {
                    if (ThingDefsByStuffCategory.TryGetValue(stuffPropCat, out var list))
                    {
                        list.Add(thingDef);
                    }
                    else
                    {
                        List <ThingDef> thingDefs = new List <ThingDef>();
                        thingDefs.Add(thingDef);
                        ThingDefsByStuffCategory.Add(stuffPropCat, thingDefs);
                    }
                }
            }

            ResourceLoader.ChildhoodStories = ResourceLoader.ChildhoodStories.OrderBy(x => x.DisplayTitle).ToList();
            ResourceLoader.AdulthoodStories = ResourceLoader.AdulthoodStories.OrderBy(x => x.DisplayTitle).ToList();
        }
Esempio n. 23
0
 public HabboFigure SetHair(Hair value)
 {
     _hair = value;
     return this;
 }
Esempio n. 24
0
        public static async Task <FaceImage> DetectFaceExtract(IFaceClient client, IFormFile file, string recognitionModel)
        {
            var       stream    = file.OpenReadStream();
            FaceImage faceImage = new FaceImage();

            IList <DetectedFace> detectedFaces;

            // Detect faces with all attributes from image.
            detectedFaces = await client.Face.DetectWithStreamAsync(stream,
                                                                    returnFaceAttributes : new List <FaceAttributeType> {
                FaceAttributeType.Accessories, FaceAttributeType.Age,
                FaceAttributeType.Blur, FaceAttributeType.Emotion, FaceAttributeType.Exposure, FaceAttributeType.FacialHair,
                FaceAttributeType.Gender, FaceAttributeType.Glasses, FaceAttributeType.Hair, FaceAttributeType.HeadPose,
                FaceAttributeType.Makeup, FaceAttributeType.Noise, FaceAttributeType.Occlusion, FaceAttributeType.Smile
            },
                                                                    recognitionModel : recognitionModel);

            faceImage.FileName  = file.FileName;
            faceImage.FaceCount = detectedFaces.Count;

            // Parse all attributes of each detected face.
            List <Attributes> faceAttributes = new List <Attributes>();

            foreach (var face in detectedFaces.Select((value, i) => new { i, value }))
            {
                Attributes attributes = new Attributes();

                attributes.FaceNumber = face.i + 1;

                // Get bounding box of the faces
                attributes.Rectangle.Left   = face.value.FaceRectangle.Left;
                attributes.Rectangle.Top    = face.value.FaceRectangle.Top;
                attributes.Rectangle.Width  = face.value.FaceRectangle.Width;
                attributes.Rectangle.Height = face.value.FaceRectangle.Height;

                // Get accessories of the faces
                List <Accessory> accessoriesList = (List <Accessory>)face.value.FaceAttributes.Accessories;
                int    count = face.value.FaceAttributes.Accessories.Count;
                string accessory; string[] accessoryArray = new string[count];
                if (count == 0)
                {
                    accessory = "NoAccessories";
                }
                else
                {
                    for (int i = 0; i < count; ++i)
                    {
                        accessoryArray[i] = accessoriesList[i].Type.ToString();
                    }
                    accessory = string.Join(",", accessoryArray);
                }

                attributes.Accessories = accessory;

                // Get face other attributes
                attributes.Age  = face.value.FaceAttributes.Age;
                attributes.Blur = face.value.FaceAttributes.Blur.BlurLevel.ToString();

                // Get emotion on the face
                string  emotionType  = string.Empty;
                double  emotionValue = 0.0;
                Emotion emotion      = face.value.FaceAttributes.Emotion;
                if (emotion.Anger > emotionValue)
                {
                    emotionValue = emotion.Anger; emotionType = "Anger";
                }
                if (emotion.Contempt > emotionValue)
                {
                    emotionValue = emotion.Contempt; emotionType = "Contempt";
                }
                if (emotion.Disgust > emotionValue)
                {
                    emotionValue = emotion.Disgust; emotionType = "Disgust";
                }
                if (emotion.Fear > emotionValue)
                {
                    emotionValue = emotion.Fear; emotionType = "Fear";
                }
                if (emotion.Happiness > emotionValue)
                {
                    emotionValue = emotion.Happiness; emotionType = "Happiness";
                }
                if (emotion.Neutral > emotionValue)
                {
                    emotionValue = emotion.Neutral; emotionType = "Neutral";
                }
                if (emotion.Sadness > emotionValue)
                {
                    emotionValue = emotion.Sadness; emotionType = "Sadness";
                }
                if (emotion.Surprise > emotionValue)
                {
                    emotionType = "Surprise";
                }
                attributes.Emotion = emotionType;

                // Get more face attributes
                attributes.Exposure = face.value.FaceAttributes.Exposure.ExposureLevel.ToString();

                attributes.FacialHair = $"{ string.Format("{0}", face.value.FaceAttributes.FacialHair.Moustache + face.value.FaceAttributes.FacialHair.Beard + face.value.FaceAttributes.FacialHair.Sideburns > 0 ? "Yes" : "No")}";
                attributes.Gender     = face.value.FaceAttributes.Gender.ToString();
                attributes.Glasses    = face.value.FaceAttributes.Glasses.ToString();

                // Get hair color
                Hair   hair  = face.value.FaceAttributes.Hair;
                string color = null;
                if (hair.HairColor.Count == 0)
                {
                    if (hair.Invisible)
                    {
                        color = "Invisible";
                    }
                    else
                    {
                        color = "Bald";
                    }
                }
                HairColorType returnColor   = HairColorType.Unknown;
                double        maxConfidence = 0.0f;
                foreach (HairColor hairColor in hair.HairColor)
                {
                    if (hairColor.Confidence <= maxConfidence)
                    {
                        continue;
                    }
                    maxConfidence = hairColor.Confidence; returnColor = hairColor.Color; color = returnColor.ToString();
                }

                attributes.Hair = color;

                // Get more attributes
                attributes.HeadPose.Pitch = Math.Round(face.value.FaceAttributes.HeadPose.Pitch, 2);
                attributes.HeadPose.Roll  = Math.Round(face.value.FaceAttributes.HeadPose.Roll, 2);
                attributes.HeadPose.Yaw   = Math.Round(face.value.FaceAttributes.HeadPose.Yaw, 2);

                attributes.Makeup = $"{string.Format("{0}", (face.value.FaceAttributes.Makeup.EyeMakeup || face.value.FaceAttributes.Makeup.LipMakeup) ? "Yes" : "No")}";
                attributes.Noise  = face.value.FaceAttributes.Noise.NoiseLevel.ToString();

                attributes.Occlusion.EyeOccluded      = face.value.FaceAttributes.Occlusion.EyeOccluded ? true : false;
                attributes.Occlusion.ForeheadOccluded = face.value.FaceAttributes.Occlusion.ForeheadOccluded ? true : false;
                attributes.Occlusion.MouthOccluded    = face.value.FaceAttributes.Occlusion.MouthOccluded ? true : false;

                attributes.Smile = face.value.FaceAttributes.Smile.ToString();

                faceImage.Attributes.Add(attributes);
            }
            return(faceImage);
        }
Esempio n. 25
0
        public static Record CreateRecord(string Tag)
        {
            Record outRecord;

            switch (Tag)
            {
            case "TES4":
                outRecord = new Header();
                break;

            case "GMST":
                outRecord = new GameSetting();
                break;

            case "TXST":
                outRecord = new TextureSet();
                break;

            case "MICN":
                outRecord = new MenuIcon();
                break;

            case "GLOB":
                outRecord = new GlobalVariable();
                break;

            case "CLAS":
                outRecord = new Class();
                break;

            case "FACT":
                outRecord = new Faction();
                break;

            case "HDPT":
                outRecord = new HeadPart();
                break;

            case "HAIR":
                outRecord = new Hair();
                break;

            case "EYES":
                outRecord = new Eyes();
                break;

            case "RACE":
                outRecord = new Race();
                break;

            case "SOUN":
                outRecord = new Sound();
                break;

            case "ASPC":
                outRecord = new AcousticSpace();
                break;

            case "MGEF":
                outRecord = new MagicEffect();
                break;

            case "SCPT":
                outRecord = new Script();
                break;

            case "LTEX":
                outRecord = new LandscapeTexture();
                break;

            case "ENCH":
                outRecord = new ObjectEffect();
                break;

            case "SPEL":
                outRecord = new ActorEffect();
                break;

            case "ACTI":
                outRecord = new ESPSharp.Records.Activator();
                break;

            case "TACT":
                outRecord = new TalkingActivator();
                break;

            case "TERM":
                outRecord = new Terminal();
                break;

            case "ARMO":
                outRecord = new Armor();
                break;

            case "BOOK":
                outRecord = new Book();
                break;

            case "CONT":
                outRecord = new Container();
                break;

            case "DOOR":
                outRecord = new Door();
                break;

            case "INGR":
                outRecord = new Ingredient();
                break;

            case "LIGH":
                outRecord = new Light();
                break;

            case "MISC":
                outRecord = new MiscItem();
                break;

            case "STAT":
                outRecord = new Static();
                break;

            case "SCOL":
                outRecord = new StaticCollection();
                break;

            case "MSTT":
                outRecord = new MoveableStatic();
                break;

            case "PWAT":
                outRecord = new PlaceableWater();
                break;

            case "GRAS":
                outRecord = new Grass();
                break;

            case "TREE":
                outRecord = new Tree();
                break;

            case "FURN":
                outRecord = new Furniture();
                break;

            case "WEAP":
                outRecord = new Weapon();
                break;

            case "AMMO":
                outRecord = new Ammunition();
                break;

            case "NPC_":
                outRecord = new NonPlayerCharacter();
                break;

            case "CREA":
                outRecord = new Creature();
                break;

            case "LVLC":
                outRecord = new LeveledCreature();
                break;

            case "LVLN":
                outRecord = new LeveledNPC();
                break;

            case "KEYM":
                outRecord = new Key();
                break;

            case "ALCH":
                outRecord = new Ingestible();
                break;

            case "IDLM":
                outRecord = new IdleMarker();
                break;

            case "NOTE":
                outRecord = new Note();
                break;

            case "COBJ":
                outRecord = new ConstructibleObject();
                break;

            case "PROJ":
                outRecord = new Projectile();
                break;

            case "LVLI":
                outRecord = new LeveledItem();
                break;

            case "WTHR":
                outRecord = new Weather();
                break;

            case "CLMT":
                outRecord = new Climate();
                break;

            case "REGN":
                outRecord = new Region();
                break;

            case "NAVI":
                outRecord = new NavigationMeshInfoMap();
                break;

            case "DIAL":
                outRecord = new DialogTopic();
                break;

            case "QUST":
                outRecord = new Quest();
                break;

            case "IDLE":
                outRecord = new IdleAnimation();
                break;

            case "PACK":
                outRecord = new Package();
                break;

            case "CSTY":
                outRecord = new CombatStyle();
                break;

            case "LSCR":
                outRecord = new LoadScreen();
                break;

            case "ANIO":
                outRecord = new AnimatedObject();
                break;

            case "WATR":
                outRecord = new Water();
                break;

            case "EFSH":
                outRecord = new EffectShader();
                break;

            case "EXPL":
                outRecord = new Explosion();
                break;

            case "DEBR":
                outRecord = new Debris();
                break;

            case "IMGS":
                outRecord = new ImageSpace();
                break;

            case "IMAD":
                outRecord = new ImageSpaceAdapter();
                break;

            case "FLST":
                outRecord = new FormList();
                break;

            case "PERK":
                outRecord = new Perk();
                break;

            case "BPTD":
                outRecord = new BodyPartData();
                break;

            case "ADDN":
                outRecord = new AddonNode();
                break;

            case "AVIF":
                outRecord = new ActorValueInformation();
                break;

            case "RADS":
                outRecord = new RadiationStage();
                break;

            case "CAMS":
                outRecord = new CameraShot();
                break;

            case "CPTH":
                outRecord = new CameraPath();
                break;

            case "VTYP":
                outRecord = new VoiceType();
                break;

            case "IPCT":
                outRecord = new Impact();
                break;

            case "IPDS":
                outRecord = new ImpactDataSet();
                break;

            case "ARMA":
                outRecord = new ArmorAddon();
                break;

            case "ECZN":
                outRecord = new EncounterZone();
                break;

            case "MESG":
                outRecord = new Message();
                break;

            case "RGDL":
                outRecord = new Ragdoll();
                break;

            case "DOBJ":
                outRecord = new DefaultObjectManager();
                break;

            case "LGTM":
                outRecord = new LightingTemplate();
                break;

            case "MUSC":
                outRecord = new MusicType();
                break;

            case "IMOD":
                outRecord = new ItemMod();
                break;

            case "REPU":
                outRecord = new Reputation();
                break;

            case "RCPE":
                outRecord = new Recipe();
                break;

            case "RCCT":
                outRecord = new RecipeCategory();
                break;

            case "CHIP":
                outRecord = new CasinoChip();
                break;

            case "CSNO":
                outRecord = new Casino();
                break;

            case "LSCT":
                outRecord = new LoadScreenType();
                break;

            case "MSET":
                outRecord = new MediaSet();
                break;

            case "ALOC":
                outRecord = new MediaLocationController();
                break;

            case "CHAL":
                outRecord = new Challenge();
                break;

            case "AMEF":
                outRecord = new AmmoEffect();
                break;

            case "CCRD":
                outRecord = new CaravanCard();
                break;

            case "CMNY":
                outRecord = new CaravanMoney();
                break;

            case "CDCK":
                outRecord = new CaravanDeck();
                break;

            case "DEHY":
                outRecord = new DehydrationStage();
                break;

            case "HUNG":
                outRecord = new HungerStage();
                break;

            case "SLPD":
                outRecord = new SleepDeprivationStage();
                break;

            case "CELL":
                outRecord = new Cell();
                break;

            case "WRLD":
                outRecord = new Worldspace();
                break;

            case "LAND":
                outRecord = new GenericRecord();
                break;

            case "NAVM":
                outRecord = new NavigationMesh();
                break;

            case "INFO":
                outRecord = new DialogResponse();
                break;

            case "REFR":
                outRecord = new Reference();
                break;

            case "ACHR":
                outRecord = new PlacedNPC();
                break;

            case "ACRE":
                outRecord = new PlacedCreature();
                break;

            case "PGRE":
                outRecord = new PlacedGrenade();
                break;

            case "PMIS":
                outRecord = new PlacedMissile();
                break;

            default:
                Console.WriteLine("Encountered unknown record: " + Tag);
                outRecord = new GenericRecord();
                break;
            }

            outRecord.Tag = Tag;

            return(outRecord);
        }
Esempio n. 26
0
 public Rabbit(double Weight, string Name, Hair Hair)
     : base(Weight, Name, Hair)
 {
 }
Esempio n. 27
0
        public HairMesh[] Import(BinaryReader reader, string path, Hair hair, HairImportSettings importSettings)
        {
            reader.Close();
            // Initialize the importer
            string[]          objContent     = File.ReadAllLines(path);
            List <Vector3>    vertices       = new List <Vector3>();
            List <Line>       indices        = new List <Line>();
            List <HairStrand> currentStrands = new List <HairStrand>();

            // Parse all vertices and indices
            for (int i = 0; i < objContent.Length; i++)
            {
                // Get all parts
                List <string> partsList = new List <string>(objContent[i].Split(' '));
                partsList.RemoveAll(x => string.IsNullOrEmpty(x.Replace(" ", "")));
                string[] parts = partsList.ToArray();

                switch (parts[0])
                {
                case "v":
                {
                    vertices.Add(Vector3.Multiply(new Vector3(SafeParse(parts[1]), SafeParse(parts[2]), SafeParse(parts[3])), importSettings.scale));
                }
                break;

                case "l":
                {
                    indices.Add(new Line(int.Parse(parts[1]) - 1, int.Parse(parts[2]) - 1));
                }
                break;
                }
            }

            // Parse all strands
            List <int> alreadyLoadedIndices = new List <int>(640000);
            List <HairStrandVertex> currentStrandVertices = new List <HairStrandVertex>(64);

            for (int i = 0; i < indices.Count; i++)
            {
                // In order to detect when a new hair starts, we detect if the first index in a line was not added to the mesh already.
                // If it was NOT, we are in a new strand
                if (i != 0 && !alreadyLoadedIndices.Contains(indices[i].index1))
                {
                    // We are in a new hair strand
                    HairStrand hs = new HairStrand();
                    currentStrandVertices[0].isMovable = false;
                    currentStrandVertices.ForEach((sv) =>
                    {
                        hs.vertices.Add(sv);
                    });

                    hs.isGuidanceStrand = true;
                    currentStrands.Add(hs);

                    // Cleanup
                    currentStrandVertices.Clear();
                }

                // Add
                if (!alreadyLoadedIndices.Contains(indices[i].index1))
                {
                    currentStrandVertices.Add(new HairStrandVertex(vertices[indices[i].index1], Vector3.Zero, Vector4.Zero));
                    alreadyLoadedIndices.Add(indices[i].index1);
                }
                if (!alreadyLoadedIndices.Contains(indices[i].index2))
                {
                    currentStrandVertices.Add(new HairStrandVertex(vertices[indices[i].index2], Vector3.Zero, Vector4.Zero));
                    alreadyLoadedIndices.Add(indices[i].index2);
                }
            }

            // Shuffle strands
            currentStrands = FormatHelper.Shuffle(currentStrands);

            HairMesh hm = new HairMesh();

            currentStrands.ForEach((item) =>
            {
                hm.strands.Add(item);
            });

            return(new HairMesh[] { hm });
        }
Esempio n. 28
0
 public HabboFigure SetHair(Hair value)
 {
     _hair = value;
     return(this);
 }
Esempio n. 29
0
 public Hair Add(Hair item)
 {
     return(context.Hairs.Add(item));
 }
Esempio n. 30
0
 public void Remove(Hair item)
 {
     context.Hairs.Remove(item);
 }
Esempio n. 31
0
        public virtual HairMesh[] Import(BinaryReader reader, string path, Hair hair, HairImportSettings importSettings)
        {
            // TODO: Implement import settings
            HairMesh[] returnData = null;

            // Load header information
            int numVertices = reader.ReadInt32();
            int numStrands = reader.ReadInt32();

            // maxVerticesPerStrand is what amd calls it
            // Actually this should be vertices per strand, as tressfx needs a uniform vertex count on every strand
            // We will assume that the input file is has a uniform vertex count.
            // If it doesnt, the import will fail.
            int maxVerticesPerStrand = reader.ReadInt32();
            int numGuideHairVertices = reader.ReadInt32();
            int numGuideHairStrands = reader.ReadInt32();
            /*int numFollowHairsPerOneGuideHair = */reader.ReadInt32();

            // Load hair data information
            int[] strandTypes = ReadIntegerArray(reader, numStrands);
            Vector4[] referenceVectors = ReadVector4Array(reader, numVertices);
            Quaternion[] globalRotations = ReadQuaternionArray(reader, numVertices);
            Quaternion[] localRotations = ReadQuaternionArray(reader, numVertices);
            Vector4[] vertices = ReadVector4Array(reader, numVertices);
            Vector4[] tangents = ReadVector4Array(reader, numVertices);

            // Read the triangle vertices
            // Actually those are __NEVER__ used anywhere.
            // So, we are going to skip / ignore them
            ReadVector3Array(reader, numVertices);
            ReadVector3Array(reader, numVertices);
            ReadVector4Array(reader, numVertices);

            float[] thicknessCoefficients = ReadFloatArray(reader, numVertices);
            Vector4[] followRootOffsets = ReadVector4Array(reader, numStrands);
            float[] restLengths = ReadFloatArray(reader, numVertices);

            // Get bounding sphere
            hair.InitializeBoundingSphere(ReadVector3(reader), reader.ReadSingle());

            // Load indices
            int indexTmp = reader.ReadInt32();
            int[] triangleIndices = ReadIntegerArray(reader, indexTmp);
            indexTmp = reader.ReadInt32();
            int[] lineIndices = ReadIntegerArray(reader, indexTmp);

            // Init indices
            hair.InitializeIndices(lineIndices, triangleIndices);

            // Set simulation data
            HairSimulationData simulationData = new HairSimulationData();
            simulationData.followRootOffsets = followRootOffsets.ToList();
            simulationData.globalRotations = globalRotations.ToList();
            simulationData.guideHairStrandCount = numGuideHairStrands;
            simulationData.guideHairVertexCount = numGuideHairVertices;
            simulationData.maxNumVerticesPerStrand = maxVerticesPerStrand;
            simulationData.localRotations = localRotations.ToList();
            simulationData.referenceVectors = referenceVectors.ToList();
            simulationData.strandTypes = strandTypes.ToList();
            simulationData.tangents = tangents.ToList();
            simulationData.thicknessCoefficients = thicknessCoefficients.ToList();
            simulationData.vertices = vertices.ToList();
            simulationData.restLength = restLengths.ToList();

            hair.InitializeSimulationData(simulationData);

            // So, the data is read now.
            // Next, we are going to construct the hair meshes.
            HairMesh[] hairMeshes = new HairMesh[4];

            // Current list "pointer"
            int vertexPointer = 0;
            int strandPointer = 0;

            List<HairStrand> strandReferences = new List<HairStrand>();

            foreach (int meshIndex in strandTypes)
            {
                // Check if we got a valid strand types array
                if (meshIndex < 0 || meshIndex > 3)
                    throw new FormatException("Mesh ids (strand types) < 0 or > 3 are not supported by TressFX!");

                // Get mesh and create it if it doesnt exist
                if (hairMeshes[meshIndex] == null)
                    hairMeshes[meshIndex] = new HairMesh();
                HairMesh mesh = hairMeshes[meshIndex];

                // Create new strand
                HairStrand strand = new HairStrand();
                strandReferences.Add(strand);
                strand.followRootOffset = followRootOffsets[strandPointer];

                if (strand.followRootOffset.x != 0 || strand.followRootOffset.y != 0 || strand.followRootOffset.z != 0)
                {
                    // This is a follow hair
                    strand.guidanceStrand = strandReferences[(int)strand.followRootOffset.w];
                    strand.isGuidanceStrand = false;
                }
                else
                {
                    // This is a guidance hair
                    strand.isGuidanceStrand = true;
                }

                // Read all vertices
                for (int i = 0; i < maxVerticesPerStrand; i++)
                {
                    // Read vertex data
                    // As texcoord we will create a coordinate which projects the hair along the x-axis based on the strand index
                    // and the y-axis based on the vertex index inside of the current strand
                    HairStrandVertex vertex = new HairStrandVertex(new Vector3(vertices[vertexPointer].X, vertices[vertexPointer].Y, vertices[vertexPointer].Z),
                                                    new Vector3(tangents[vertexPointer].X, tangents[vertexPointer].Y, tangents[vertexPointer].Z),
                                                    new Vector4(strandPointer / (float)numStrands, i / (float)maxVerticesPerStrand, 0, 0));

                    // Set movable flag
                    vertex.isMovable = (vertices[vertexPointer].W > 0);

                    // Set simulation data
                    vertex.globalRotation = globalRotations[vertexPointer];
                    vertex.localRotation = localRotations[vertexPointer];
                    vertex.referenceVector = referenceVectors[vertexPointer];
                    vertex.restLength = restLengths[vertexPointer];
                    vertex.thicknessCoefficient = thicknessCoefficients[vertexPointer];

                    // Add to strand
                    strand.vertices.Add(vertex);

                    vertexPointer++;
                }

                // Add strand to mesh
                mesh.strands.Add(strand);

                strandPointer++;
            }

            // Construct return array
            List<HairMesh> meshes = new List<HairMesh>();

            for (int i = 0; i < hairMeshes.Length; i++)
                if (hairMeshes[i] == null)
                {
                    // We're done reading
                    break;
                }
                else
                {
                    // Read the mesh
                    meshes.Add(hairMeshes[i]);
                }

            returnData = hairMeshes.ToArray();

            return returnData;
        }
Esempio n. 32
0
 /// <summary>
 /// Gets if he has bald hair or not
 /// </summary>
 /// <param name="hair"></param>
 /// <returns></returns>
 private HairType GetHairType(Hair hair) =>
 hair.Bald > 90 ? HairType.Bald : HairType.NotBald;
Esempio n. 33
0
        /// <summary>
        /// Opens the hair data (tfxb) at the given path.
        /// </summary>
        /// <param name="path">Path.</param>
        public static void LoadHairData(this TressFXHair ext, Hair hair)
        {
                        #if UNITY_EDITOR
            EditorUtility.DisplayProgressBar("Importing TressFX Hair", "Loading information...", 0);
            HairSimulationData hairSimulationData = hair.hairSimulationData;

            // Load information variables
            ext.m_NumTotalHairVertices          = hairSimulationData.vertexCount;
            ext.m_NumTotalHairStrands           = hairSimulationData.strandCount;
            ext.m_NumOfVerticesPerStrand        = hairSimulationData.maxNumVerticesPerStrand;
            ext.m_NumGuideHairVertices          = hairSimulationData.guideHairVertexCount;
            ext.m_NumGuideHairStrands           = hairSimulationData.guideHairStrandCount;
            ext.m_NumFollowHairsPerOneGuideHair = hairSimulationData.followHairsPerOneGuideHair;

            // Load actual hair data
            EditorUtility.DisplayProgressBar("Importing TressFX Hair", "Loading strandtypes...", 0);
            ext.m_pHairStrandType = hairSimulationData.strandTypes.ToArray();
            EditorUtility.DisplayProgressBar("Importing TressFX Hair", "Loading reference vectors...", 0.05f);
            ext.m_pRefVectors = Vector4Import(hairSimulationData.referenceVectors.ToArray());
            EditorUtility.DisplayProgressBar("Importing TressFX Hair", "Loading global rotations...", 0.15f);
            ext.m_pGlobalRotations = QuaternionsToVector4(QuaternionImport(hairSimulationData.globalRotations.ToArray()));
            EditorUtility.DisplayProgressBar("Importing TressFX Hair", "Loading local rotations...", 0.25f);
            ext.m_pLocalRotations = QuaternionsToVector4(QuaternionImport(hairSimulationData.localRotations.ToArray()));
            EditorUtility.DisplayProgressBar("Importing TressFX Hair", "Loading vertices...", 0.35f);
            ext.m_pVertices = Vector4Import(hairSimulationData.vertices.ToArray());
            EditorUtility.DisplayProgressBar("Importing TressFX Hair", "Loading tangents...", 0.4f);
            ext.m_pTangents = Vector4Import(hairSimulationData.tangents.ToArray());
            EditorUtility.DisplayProgressBar("Importing TressFX Hair", "Loading thickness coefficients...", 0.55f);
            ext.m_pThicknessCoeffs = hairSimulationData.thicknessCoefficients.ToArray();
            EditorUtility.DisplayProgressBar("Importing TressFX Hair", "Loading follow hair root offsets...", 0.65f);
            ext.m_pFollowRootOffset = Vector4Import(hairSimulationData.followRootOffsets.ToArray());
            EditorUtility.DisplayProgressBar("Importing TressFX Hair", "Loading rest lengths...", 0.7f);
            ext.m_pRestLengths = hairSimulationData.restLength.ToArray();

            // Determine how much hair strand types are available
            List <int> strandTypes = new List <int>();
            for (int i = 0; i < ext.m_pHairStrandType.Length; i++)
            {
                if (!strandTypes.Contains(ext.m_pHairStrandType[i]))
                {
                    strandTypes.Add(ext.m_pHairStrandType[i]);
                }
            }

            if (ext.hairPartConfig == null || ext.hairPartConfig.Length != strandTypes.Count)
            {
                ext.hairPartConfig = new HairPartConfig[strandTypes.Count];
            }

            EditorUtility.DisplayProgressBar("Importing TressFX Hair", "Loading bounding sphere...", 0.75f);
            // Load bounding sphere
            ext.m_bSphere = new TressFXBoundingSphere(new Vector3(hair.boundingSphere.center.x, hair.boundingSphere.center.y, hair.boundingSphere.center.z), hair.boundingSphere.radius);

            EditorUtility.DisplayProgressBar("Importing TressFX Hair", "Loading indices...", 0.75f);

            // Read triangle indices
            ext.m_TriangleIndices = hair.triangleIndices;

            // Read line indices
            ext.m_LineIndices = hair.lineIndices;

            // Set texcoords
            ext.m_TexCoords = Vector4Import(hair.texcoords);

            EditorUtility.ClearProgressBar();

            // We are ready!
            Debug.Log("Hair loaded. Vertices loaded: " + ext.m_NumTotalHairVertices + ", Strands: " + ext.m_NumTotalHairStrands + ", Triangle Indices: " + ext.m_TriangleIndices.Length + ", Line Indices: " + ext.m_LineIndices.Length);
                        #endif
        }
Esempio n. 34
0
    public override void Bind()
    {
        Hair s = (Hair)skeleton;

        transfer.BindInt("_NumVertsPerHair", () => s.numVertsPerHair);
    }
Esempio n. 35
0
 public void Export(BinaryWriter writer, string path, Hair hair)
 {
     throw new NotImplementedException("Hair cannot get exported as ASE file");
 }
Esempio n. 36
0
 public Mammal(double Weight, string Name, Hair Hair)
     : base(Weight, Name)
 {
     this.Hair = Hair;
 }
Esempio n. 37
0
        //authenticate the key


        //detection model one
        public static async Task DetectFaceExtract(IFaceClient client, string url, string recognitionModel)
        {
            Console.WriteLine("======== DETECT FACE ========\n======== Detection Mode 1 ======== ");
            Console.WriteLine();



            IList <DetectedFace> detectedFaces;

            detectedFaces = await client.Face.DetectWithUrlAsync(url,
                                                                 returnFaceAttributes : new List <FaceAttributeType?> {
                FaceAttributeType.Accessories, FaceAttributeType.Age,
                FaceAttributeType.Blur, FaceAttributeType.Emotion, FaceAttributeType.Exposure, FaceAttributeType.FacialHair,
                FaceAttributeType.Gender, FaceAttributeType.Glasses, FaceAttributeType.Hair, FaceAttributeType.HeadPose,
                FaceAttributeType.Makeup, FaceAttributeType.Noise, FaceAttributeType.Occlusion, FaceAttributeType.Smile
            },
                                                                 // We specify detection model 1 because we are retrieving attributes.
                                                                 detectionModel : DetectionModel.Detection01,
                                                                 recognitionModel : recognitionModel);

            Console.WriteLine($"{detectedFaces.Count} face detected from the link.");

            foreach (var face in detectedFaces)
            {
                Console.WriteLine($"Face attributes for the link:");

                // Get bounding box of the faces
                Console.WriteLine($"Rectangle(Left/Top/Width/Height) : {face.FaceRectangle.Left} {face.FaceRectangle.Top} {face.FaceRectangle.Width} {face.FaceRectangle.Height}");

                // Get accessories of the faces
                List <Accessory> accessoriesList = (List <Accessory>)face.FaceAttributes.Accessories;
                int    count = face.FaceAttributes.Accessories.Count;
                string accessory; string[] accessoryArray = new string[count];
                if (count == 0)
                {
                    accessory = "NoAccessories";
                }
                else
                {
                    for (int i = 0; i < count; ++i)
                    {
                        accessoryArray[i] = accessoriesList[i].Type.ToString();
                    }
                    accessory = string.Join(",", accessoryArray);
                }
                Console.WriteLine($"Accessories : {accessory}");

                // Get face other attributes
                Console.WriteLine($"Age : {face.FaceAttributes.Age}");
                Console.WriteLine($"Blur : {face.FaceAttributes.Blur.BlurLevel}");

                // Get emotion on the face
                string  emotionType  = string.Empty;
                double  emotionValue = 0.0;
                Emotion emotion      = face.FaceAttributes.Emotion;
                if (emotion.Anger > emotionValue)
                {
                    emotionValue = emotion.Anger; emotionType = "Anger";
                }
                if (emotion.Contempt > emotionValue)
                {
                    emotionValue = emotion.Contempt; emotionType = "Contempt";
                }
                if (emotion.Disgust > emotionValue)
                {
                    emotionValue = emotion.Disgust; emotionType = "Disgust";
                }
                if (emotion.Fear > emotionValue)
                {
                    emotionValue = emotion.Fear; emotionType = "Fear";
                }
                if (emotion.Happiness > emotionValue)
                {
                    emotionValue = emotion.Happiness; emotionType = "Happiness";
                }
                if (emotion.Neutral > emotionValue)
                {
                    emotionValue = emotion.Neutral; emotionType = "Neutral";
                }
                if (emotion.Sadness > emotionValue)
                {
                    emotionValue = emotion.Sadness; emotionType = "Sadness";
                }
                if (emotion.Surprise > emotionValue)
                {
                    emotionType = "Surprise";
                }
                Console.WriteLine($"Emotion : {emotionType}");

                // Get more face attributes
                Console.WriteLine($"Exposure : {face.FaceAttributes.Exposure.ExposureLevel}");
                Console.WriteLine($"FacialHair : {string.Format("{0}", face.FaceAttributes.FacialHair.Moustache + face.FaceAttributes.FacialHair.Beard + face.FaceAttributes.FacialHair.Sideburns > 0 ? "Yes" : "No")}");
                Console.WriteLine($"Gender : {face.FaceAttributes.Gender}");
                Console.WriteLine($"Glasses : {face.FaceAttributes.Glasses}");

                // Get hair color
                Hair   hair  = face.FaceAttributes.Hair;
                string color = null;
                if (hair.HairColor.Count == 0)
                {
                    if (hair.Invisible)
                    {
                        color = "Invisible";
                    }
                    else
                    {
                        color = "Bald";
                    }
                }
                HairColorType returnColor   = HairColorType.Unknown;
                double        maxConfidence = 0.0f;
                foreach (HairColor hairColor in hair.HairColor)
                {
                    if (hairColor.Confidence <= maxConfidence)
                    {
                        continue;
                    }
                    maxConfidence = hairColor.Confidence; returnColor = hairColor.Color; color = returnColor.ToString();
                }
                Console.WriteLine($"Hair : {color}");

                // Get more attributes
                Console.WriteLine($"HeadPose : {string.Format("Pitch: {0}, Roll: {1}, Yaw: {2}", Math.Round(face.FaceAttributes.HeadPose.Pitch, 2), Math.Round(face.FaceAttributes.HeadPose.Roll, 2), Math.Round(face.FaceAttributes.HeadPose.Yaw, 2))}");
                Console.WriteLine($"Makeup : {string.Format("{0}", (face.FaceAttributes.Makeup.EyeMakeup || face.FaceAttributes.Makeup.LipMakeup) ? "Yes" : "No")}");
                Console.WriteLine($"Noise : {face.FaceAttributes.Noise.NoiseLevel}");
                Console.WriteLine($"Occlusion : {string.Format("EyeOccluded: {0}", face.FaceAttributes.Occlusion.EyeOccluded ? "Yes" : "No")} " +
                                  $" {string.Format("ForeheadOccluded: {0}", face.FaceAttributes.Occlusion.ForeheadOccluded ? "Yes" : "No")}   {string.Format("MouthOccluded: {0}", face.FaceAttributes.Occlusion.MouthOccluded ? "Yes" : "No")}");
                Console.WriteLine($"Smile : {face.FaceAttributes.Smile}");
                Console.WriteLine();
            }
        }
Esempio n. 38
0
 public override object GetNew()
 {
     return(Hair.GetNew());
 }
Esempio n. 39
0
 public void Export(BinaryWriter writer, string path, Hair hair)
 {
     throw new NotImplementedException("Hair cannot get exported as ASE file");
 }
Esempio n. 40
0
        public virtual HairMesh[] Import(BinaryReader reader, string path, Hair hair, HairImportSettings importSettings)
        {
            // TODO: Implement import settings
            HairMesh[] returnData = null;

            // Load header information
            int numVertices = reader.ReadInt32();
            int numStrands  = reader.ReadInt32();

            // maxVerticesPerStrand is what amd calls it
            // Actually this should be vertices per strand, as tressfx needs a uniform vertex count on every strand
            // We will assume that the input file is has a uniform vertex count.
            // If it doesnt, the import will fail.
            int maxVerticesPerStrand = reader.ReadInt32();
            int numGuideHairVertices = reader.ReadInt32();
            int numGuideHairStrands  = reader.ReadInt32();

            /*int numFollowHairsPerOneGuideHair = */ reader.ReadInt32();

            // Load hair data information
            int[]        strandTypes      = ReadIntegerArray(reader, numStrands);
            Vector4[]    referenceVectors = ReadVector4Array(reader, numVertices);
            Quaternion[] globalRotations  = ReadQuaternionArray(reader, numVertices);
            Quaternion[] localRotations   = ReadQuaternionArray(reader, numVertices);
            Vector4[]    vertices         = ReadVector4Array(reader, numVertices);
            Vector4[]    tangents         = ReadVector4Array(reader, numVertices);

            // Read the triangle vertices
            // Actually those are __NEVER__ used anywhere.
            // So, we are going to skip / ignore them
            ReadVector3Array(reader, numVertices);
            ReadVector3Array(reader, numVertices);
            ReadVector4Array(reader, numVertices);

            float[]   thicknessCoefficients = ReadFloatArray(reader, numVertices);
            Vector4[] followRootOffsets     = ReadVector4Array(reader, numStrands);
            float[]   restLengths           = ReadFloatArray(reader, numVertices);

            // Get bounding sphere
            hair.InitializeBoundingSphere(ReadVector3(reader), reader.ReadSingle());

            // Load indices
            int indexTmp = reader.ReadInt32();

            int[] triangleIndices = ReadIntegerArray(reader, indexTmp);
            indexTmp = reader.ReadInt32();
            int[] lineIndices = ReadIntegerArray(reader, indexTmp);

            // Init indices
            hair.InitializeIndices(lineIndices, triangleIndices);

            // Set simulation data
            HairSimulationData simulationData = new HairSimulationData();

            simulationData.followRootOffsets       = followRootOffsets.ToList();
            simulationData.globalRotations         = globalRotations.ToList();
            simulationData.guideHairStrandCount    = numGuideHairStrands;
            simulationData.guideHairVertexCount    = numGuideHairVertices;
            simulationData.maxNumVerticesPerStrand = maxVerticesPerStrand;
            simulationData.localRotations          = localRotations.ToList();
            simulationData.referenceVectors        = referenceVectors.ToList();
            simulationData.strandTypes             = strandTypes.ToList();
            simulationData.tangents = tangents.ToList();
            simulationData.thicknessCoefficients = thicknessCoefficients.ToList();
            simulationData.vertices   = vertices.ToList();
            simulationData.restLength = restLengths.ToList();

            hair.InitializeSimulationData(simulationData);

            // So, the data is read now.
            // Next, we are going to construct the hair meshes.
            HairMesh[] hairMeshes = new HairMesh[4];

            // Current list "pointer"
            int vertexPointer = 0;
            int strandPointer = 0;

            List <HairStrand> strandReferences = new List <HairStrand>();

            foreach (int meshIndex in strandTypes)
            {
                // Check if we got a valid strand types array
                if (meshIndex < 0 || meshIndex > 3)
                {
                    throw new FormatException("Mesh ids (strand types) < 0 or > 3 are not supported by TressFX!");
                }

                // Get mesh and create it if it doesnt exist
                if (hairMeshes[meshIndex] == null)
                {
                    hairMeshes[meshIndex] = new HairMesh();
                }
                HairMesh mesh = hairMeshes[meshIndex];

                // Create new strand
                HairStrand strand = new HairStrand();
                strandReferences.Add(strand);
                strand.followRootOffset = followRootOffsets[strandPointer];


                if (strand.followRootOffset.x != 0 || strand.followRootOffset.y != 0 || strand.followRootOffset.z != 0)
                {
                    // This is a follow hair
                    strand.guidanceStrand   = strandReferences[(int)strand.followRootOffset.w];
                    strand.isGuidanceStrand = false;
                }
                else
                {
                    // This is a guidance hair
                    strand.isGuidanceStrand = true;
                }


                // Read all vertices
                for (int i = 0; i < maxVerticesPerStrand; i++)
                {
                    // Read vertex data
                    // As texcoord we will create a coordinate which projects the hair along the x-axis based on the strand index
                    // and the y-axis based on the vertex index inside of the current strand
                    HairStrandVertex vertex = new HairStrandVertex(new Vector3(vertices[vertexPointer].X, vertices[vertexPointer].Y, vertices[vertexPointer].Z),
                                                                   new Vector3(tangents[vertexPointer].X, tangents[vertexPointer].Y, tangents[vertexPointer].Z),
                                                                   new Vector4(strandPointer / (float)numStrands, i / (float)maxVerticesPerStrand, 0, 0));

                    // Set movable flag
                    vertex.isMovable = (vertices[vertexPointer].W > 0);

                    // Set simulation data
                    vertex.globalRotation       = globalRotations[vertexPointer];
                    vertex.localRotation        = localRotations[vertexPointer];
                    vertex.referenceVector      = referenceVectors[vertexPointer];
                    vertex.restLength           = restLengths[vertexPointer];
                    vertex.thicknessCoefficient = thicknessCoefficients[vertexPointer];

                    // Add to strand
                    strand.vertices.Add(vertex);

                    vertexPointer++;
                }

                // Add strand to mesh
                mesh.strands.Add(strand);

                strandPointer++;
            }

            // Construct return array
            List <HairMesh> meshes = new List <HairMesh>();

            for (int i = 0; i < hairMeshes.Length; i++)
            {
                if (hairMeshes[i] == null)
                {
                    // We're done reading
                    break;
                }
                else
                {
                    // Read the mesh
                    meshes.Add(hairMeshes[i]);
                }
            }

            returnData = hairMeshes.ToArray();

            return(returnData);
        }
Esempio n. 41
0
        public static async Task DetectFaceExtract()
        {
            Console.WriteLine("========DETECT FACES========");
            Console.WriteLine();
            var client = AuthenticateService.AuthenticateFaceClient();

            // Create a list of images
            string[] filePaths = Directory.GetFiles(@"D:\Work\Mimobod\dir_001",
                                                    "*", SearchOption.AllDirectories);

            foreach (var filePath in filePaths)
            {
                try
                {
                    byte[] byteData = ParserService.GetImageAsByteArray(filePath);
                    using (var stream = new MemoryStream(byteData))
                    {
                        IList <DetectedFace> detectedFaces;

                        // Detect faces with all attributes from image url.
                        detectedFaces = await client.Face.DetectWithStreamAsync(stream,
                                                                                returnFaceAttributes : new List <FaceAttributeType>
                        {
                            FaceAttributeType.Accessories, FaceAttributeType.Age,
                            FaceAttributeType.Emotion, FaceAttributeType.FacialHair,
                            FaceAttributeType.Gender, FaceAttributeType.Glasses, FaceAttributeType.Hair,
                            FaceAttributeType.Makeup, FaceAttributeType.Smile
                        });

                        Console.WriteLine($"{detectedFaces.Count} face(s) detected from image `{filePath}`.");
                        if (detectedFaces.Count > 0)
                        {
                            var imageIndsex = DbService.SaveImage(byteData);

                            // Parse and print all attributes of each detected face.
                            var faceNumber = 1;
                            foreach (var face in detectedFaces)
                            {
                                // Get accessories of the faces
                                List <Accessory> accessoriesList = (List <Accessory>)face.FaceAttributes.Accessories;
                                int    count = face.FaceAttributes.Accessories.Count;
                                string accessory; string[] accessoryArray = new string[count];
                                if (count == 0)
                                {
                                    accessory = "NoAccessories";
                                }
                                else
                                {
                                    for (int i = 0; i < count; ++i)
                                    {
                                        accessoryArray[i] = accessoriesList[i].Type.ToString();
                                    }
                                    accessory = string.Join(",", accessoryArray);
                                }


                                // Get emotion on the face
                                string  emotionType  = string.Empty;
                                double  emotionValue = 0.0;
                                Emotion emotion      = face.FaceAttributes.Emotion;
                                if (emotion.Anger > emotionValue)
                                {
                                    emotionValue = emotion.Anger; emotionType = "Anger";
                                }
                                if (emotion.Contempt > emotionValue)
                                {
                                    emotionValue = emotion.Contempt; emotionType = "Contempt";
                                }
                                if (emotion.Disgust > emotionValue)
                                {
                                    emotionValue = emotion.Disgust; emotionType = "Disgust";
                                }
                                if (emotion.Fear > emotionValue)
                                {
                                    emotionValue = emotion.Fear; emotionType = "Fear";
                                }
                                if (emotion.Happiness > emotionValue)
                                {
                                    emotionValue = emotion.Happiness; emotionType = "Happiness";
                                }
                                if (emotion.Neutral > emotionValue)
                                {
                                    emotionValue = emotion.Neutral; emotionType = "Neutral";
                                }
                                if (emotion.Sadness > emotionValue)
                                {
                                    emotionValue = emotion.Sadness; emotionType = "Sadness";
                                }
                                if (emotion.Surprise > emotionValue)
                                {
                                    emotionType = "Surprise";
                                }

                                // Get more face attributes
                                var facialHair = string.Format("{0}", face.FaceAttributes.FacialHair.Moustache + face.FaceAttributes.FacialHair.Beard + face.FaceAttributes.FacialHair.Sideburns > 0 ? "Yes" : "No");

                                // Get hair color
                                Hair   hair  = face.FaceAttributes.Hair;
                                string color = null;
                                if (hair.HairColor.Count == 0)
                                {
                                    if (hair.Invisible)
                                    {
                                        color = "Invisible";
                                    }
                                    else
                                    {
                                        color = "Bald";
                                    }
                                }
                                HairColorType returnColor   = HairColorType.Unknown;
                                double        maxConfidence = 0.0f;
                                foreach (HairColor hairColor in hair.HairColor)
                                {
                                    if (hairColor.Confidence <= maxConfidence)
                                    {
                                        continue;
                                    }
                                    maxConfidence = hairColor.Confidence; returnColor = hairColor.Color; color = returnColor.ToString();
                                }

                                DbService.SaveToDatabase(
                                    imageIndsex,
                                    accessory,
                                    face.FaceAttributes.Age,
                                    emotionType,
                                    facialHair,
                                    (int)face.FaceAttributes.Gender,
                                    (int)face.FaceAttributes.Glasses,
                                    color,
                                    face.FaceAttributes.Smile,
                                    faceNumber);
                                faceNumber++;
                            }
                        }
                    }
                }
                catch (Exception)
                {
                    Console.WriteLine("----------------------------------------------------------");
                }
            }
        }
Esempio n. 42
0
        public virtual void Export(BinaryWriter writer, string path, Hair hair)
        {
            // Get simulation data
            HairSimulationData simulationData = hair.hairSimulationData;

            int vertexCount = hair.vertexCount;

            // Write the header
            writer.Write(vertexCount);
            writer.Write(hair.strandCount);
            writer.Write(hair.maxNumVerticesPerStrand);
            writer.Write(simulationData.guideHairVertexCount);
            writer.Write(simulationData.guideHairStrandCount);
            writer.Write(simulationData.followHairsPerOneGuideHair);

            // Write data
            foreach (int strandType in simulationData.strandTypes)
            {
                writer.Write(strandType);
            }

            // Reference vectors
            foreach (Vector4 refVector in simulationData.referenceVectors)
            {
                WriteVector4(writer, refVector);
            }

            // Global rotations
            foreach (Quaternion globalRot in simulationData.globalRotations)
            {
                WriteQuaternion(writer, globalRot);
            }

            // Local rotations
            foreach (Quaternion localRot in simulationData.localRotations)
            {
                WriteQuaternion(writer, localRot);
            }

            // Position vectors
            foreach (Vector4 vertex in simulationData.vertices)
            {
                WriteVector4(writer, vertex);
            }

            // Tangent vectors
            foreach (Vector4 tangent in simulationData.tangents)
            {
                WriteVector4(writer, tangent);
            }

            // Write binary 0 as triangle vertices as they arent used anyway.
            for (int i = 0; i < vertexCount; i++)
            {
                WriteVector3(writer, Vector3.Zero); // Positions
                WriteVector3(writer, Vector3.Zero); // Tangents
                WriteVector4(writer, Vector4.Zero); // Texcoord
            }

            // Thickness coeffs
            foreach (float thicknessCoeff in simulationData.thicknessCoefficients)
            {
                writer.Write(thicknessCoeff);
            }

            // Follow root offsets vectors
            foreach (Vector4 followRootOffset in simulationData.followRootOffsets)
            {
                WriteVector4(writer, followRootOffset);
            }

            // Rest lengths
            foreach (float restLength in simulationData.restLength)
            {
                writer.Write(restLength);
            }

            // Write bounding sphere
            WriteVector3(writer, hair.boundingSphere.center);
            writer.Write(hair.boundingSphere.radius);

            // Triangle indices
            writer.Write(hair.triangleIndices.Length);
            foreach (int triangleIndices in hair.triangleIndices)
            {
                writer.Write(triangleIndices);
            }

            // Line indices
            writer.Write(hair.lineIndices.Length);
            foreach (int lineIndices in hair.lineIndices)
            {
                writer.Write(lineIndices);
            }
        }
Esempio n. 43
0
    private static void UpdateUVs(Config[] configs)
    {
        foreach (var config in configs)
        {
            var armorMeshFolderPath  = "Assets/Character_Editor/Meshes/" + config.folderName + "/Armor/";
            var weaponMeshFolderPath = "Assets/Character_Editor/Meshes/" + config.folderName + "/Weapon/";

            var meshPaths = new Dictionary <int, string>()
            {
                { Arm.GetMerheOrder(MeshType.ArmRight), armorMeshFolderPath + "Armor_Arm/ArmRight" },
                { Arm.GetMerheOrder(MeshType.ArmLeft), armorMeshFolderPath + "Armor_Arm/ArmLeft" },
                { Belt.GetMerheOrder(), armorMeshFolderPath + "Armor_Belt" },
                { BeltAdd.GetMerheOrder(), armorMeshFolderPath + "Armor_BeltAdd" },
                { Hair.GetMerheOrder(), armorMeshFolderPath + "Armor_Hair" },
                { Helm.GetMerheOrder(), armorMeshFolderPath + "Armor_Helm" },
                { Beard.GetMerheOrder(), armorMeshFolderPath + "Armor_Jaw" },
                { FaceFeature.GetMerheOrder(), armorMeshFolderPath + "Armor_Feature" },
                { Leg.GetMerheOrder(MeshType.LegRight), armorMeshFolderPath + "Armor_Leg/LegRight" },
                { Leg.GetMerheOrder(MeshType.LegLeft), armorMeshFolderPath + "Armor_Leg/LegLeft" },
                { Shoulder.GetMerheOrder(MeshType.ShoulderRight), armorMeshFolderPath + "Armor_Shoulder/ShoulderRight" },
                { Shoulder.GetMerheOrder(MeshType.ShoulderLeft), armorMeshFolderPath + "Armor_Shoulder/ShoulderLeft" },
                { Torso.GetMerheOrder(), armorMeshFolderPath + "Armor_Torso" },
                { TorsoAdd.GetMerheOrder(), armorMeshFolderPath + "Armor_TorsoAdd" },
                { Hand.GetMerheOrder(MeshType.HandRight), weaponMeshFolderPath + "HandRight" },
                { Hand.GetMerheOrder(MeshType.HandLeft), weaponMeshFolderPath + "HandLeft" },
            };


            var myList = meshPaths.ToList();
            myList.Sort((pair1, pair2) => pair1.Key.CompareTo(pair2.Key));

            int   atlasSize = 4;
            float uvsStep   = 1f / atlasSize;

            for (int itemNum = 0; itemNum < myList.Count; itemNum++)
            {
                if (!AssetDatabase.IsValidFolder(myList[itemNum].Value))
                {
                    continue;
                }

                var meshGUIDs = AssetDatabase.FindAssets("t:GameObject", new string[] { myList[itemNum].Value });
                for (int meshNum = 0; meshNum < meshGUIDs.Length; meshNum++)
                {
                    var tempMesh = AssetDatabase.LoadAssetAtPath <GameObject>(AssetDatabase.GUIDToAssetPath(meshGUIDs[meshNum]));
                    // Mesh tempMesh = UnityEngine.Object.Instantiate(meshObject);

                    //Update LOD parts for each armor item
                    var armorsParts = tempMesh.GetComponentsInChildren <MeshFilter>();
                    for (var armLOD = 0; armLOD < armorsParts.Length; armLOD++)
                    {
                        if (armorsParts[armLOD] != null)
                        {
                            var mTempMesh = (Mesh)GameObject.Instantiate(armorsParts[armLOD].sharedMesh);

                            //Update UVS for new atlas
                            Vector2[] uvs = mTempMesh.uv;
                            for (int i = 0; i < uvs.Length; i++)
                            {
                                uvs[i] = new Vector2(uvs[i].x / atlasSize + uvsStep * (itemNum % atlasSize),
                                                     uvs[i].y / atlasSize + uvsStep * (atlasSize - 1 - (itemNum / atlasSize)));
                            }

                            mTempMesh.uv = uvs;
                            //assigne the selected LOD Mesh with new UV's to the new mesh to be exported
                            if (!Directory.Exists(myList[itemNum].Value + "/Meshes/"))
                            {
                                Directory.CreateDirectory(myList[itemNum].Value + "/Meshes/");
                            }

                            CreateOrReplaceAsset <Mesh>(mTempMesh,
                                                        myList[itemNum].Value + "/Meshes/" + armorsParts[armLOD].sharedMesh.name + "_New.asset");

                            AssetDatabase.SaveAssets();
                        }
                    }
                }
            }

            var prefabsPath = "Assets/Character_Editor/Prefabs/" + config.folderName;
            var prefabGUIDs = AssetDatabase.FindAssets("t:Prefab", new string[] { prefabsPath });
            for (int prefNum = 0; prefNum < prefabGUIDs.Length; prefNum++)
            {
                var pPath = AssetDatabase.GUIDToAssetPath(prefabGUIDs[prefNum]);
                if (pPath.Contains("/Model/"))
                {
                    var originalPrefab         = AssetDatabase.LoadAssetAtPath <GameObject>(pPath);
                    var originalPrefabInstance = GameObject.Instantiate(originalPrefab);
                    originalPrefabInstance.name = originalPrefab.name;

                    foreach (var filter in originalPrefabInstance.GetComponentsInChildren <MeshFilter>())
                    {
                        var lodMeshPath = AssetDatabase.GetAssetPath(filter.sharedMesh);
                        var index       = lodMeshPath.LastIndexOf("/");
                        if (index != -1)
                        {
                            lodMeshPath = lodMeshPath.Substring(0, index) + "/Meshes/" + filter.sharedMesh.name + "_New.asset";

                            var changedMesh = AssetDatabase.LoadAssetAtPath <Mesh>(lodMeshPath);
                            filter.mesh = changedMesh;

                            var newDirPath  = pPath.Substring(0, pPath.IndexOf("Model/")) + "StaticModel/";
                            var fullDirPath = Application.dataPath.Substring(0, Application.dataPath.Length - 6) + newDirPath;
                            if (Directory.Exists(fullDirPath))
                            {
                                Directory.Delete(fullDirPath, true);
                            }

                            Directory.CreateDirectory(fullDirPath);

                            Object prefab = PrefabUtility.CreateEmptyPrefab(newDirPath + originalPrefabInstance.name + ".prefab");
                            PrefabUtility.ReplacePrefab(originalPrefabInstance, prefab, ReplacePrefabOptions.ConnectToPrefab);

                            AssetDatabase.SaveAssets();
                        }
                    }
                    GameObject.DestroyImmediate(originalPrefabInstance);
                }
            }
        }
    }
Esempio n. 44
0
    // Method
    public void Randomize()
    {
        List<Eyes> eyes = new List<Eyes>();
        foreach (Eyes e in Clothing.Eyes)
            eyes.Add(e);
        this.eyes = eyes[Random.Range(0, eyes.Count - 1)];

        List<Gloves> gloves = new List<Gloves>();
        foreach (Gloves g in Clothing.Gloves)
            gloves.Add(g);
        this.gloves = gloves[Random.Range(0, gloves.Count - 1)];

        List<Pant> pant = new List<Pant>();
        foreach (Pant p in Clothing.Pants)
            pant.Add(p);
        this.pant = pant[Random.Range(0, pant.Count - 1)];

        List<Tshirt> tshirt = new List<Tshirt>();
        foreach (Tshirt t in Clothing.Tshirts)
            tshirt.Add(t);
        this.tshirt = tshirt[Random.Range(0, tshirt.Count - 1)];

        List<Body> body = new List<Body>();
        foreach (Body b in Clothing.Bodies)
            body.Add(b);
        this.body = body[Random.Range(0, body.Count - 1)];

        List<Hair> hair = new List<Hair>();
        foreach (Hair h in Clothing.Hairs)
            hair.Add(h);
        this.hair = hair[Random.Range(0, hair.Count - 1)];

        if (this.hair.GetTypeHair == Hair.TypeHair.Crete)
            this.hat = Hat.NoneHat;
        else
        {
            List<Hat> hat = new List<Hat>();
            foreach (Hat h in Clothing.Hats)
                hat.Add(h);
            this.hat = hat[Random.Range(0, hat.Count - 1)];
        }

        List<Beard> beard = new List<Beard>();
        foreach (Beard b in Clothing.Beards)
            beard.Add(b);
        this.beard = beard[Random.Range(0, beard.Count - 1)];
    }