Esempio n. 1
0
        static void Main(string[] args)
        {
            try
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                var currentDomain = AppDomain.CurrentDomain;
                currentDomain.AssemblyResolve += LoadSubLibs;

                ProgramCore.CurrentProgram = ProgramCore.ProgramMode.PrintAhead;
                ProgramCore.paypalHelper   = new TruePaypalHelper();
                ProgramCore.IsFreeVersion  = File.Exists(Path.Combine(Application.StartupPath, "bin", "rh_Saqr.dlib"));

                //   var objectCreator = new ObjCreator();
                //   objectCreator.CreateObj(2, "ph4ea4veilnuswyq2viwbm1m","","", "", "", "", "", "", "", "", "", "",0,0,0,0, "test");

                ProgramCore.MainForm = new frmMain(args.Length == 0 ? string.Empty : args[0]);
                Application.Run(ProgramCore.MainForm);
            }
            catch (Exception e)
            {
                ProgramCore.EchoToLog(e);
                MessageBox.Show(e.Message + Environment.NewLine + e.StackTrace, e.Message);
            }
        }
Esempio n. 2
0
        public Dictionary <Guid, PartMorphInfo> LoadPartsMorphInfo(string path, RenderMesh renderMesh)
        {
            var          vertexPositions = new List <float>();
            List <float> tmp             = null;
            List <uint>  uitmp           = null;
            var          vertices        = new List <Vector3>();

            var objModel = ObjLoader.LoadObjFile(path);

            if (objModel == null)
            {
                ProgramCore.EchoToLog(string.Format("Can't load obj model '{0}'", path), EchoMessageType.Error);
                return(null);
            }

            var a      = new Vector3(99999.0f, 99999.0f, 99999.0f);
            var b      = new Vector3(-99999.0f, -99999.0f, -99999.0f);
            var result = new Dictionary <Guid, PartMorphInfo>();

            foreach (var modelGroup in objModel.Groups) // one group - one mesh
            {
                vertexPositions.Clear();

                foreach (var face in modelGroup.Value.Faces) //  combine all meshes in group - to one mesh.
                {
                    GetObjFace(face, objModel, ref vertexPositions, ref tmp, ref tmp,
                               ref tmp, ref tmp, ref uitmp);
                }
                vertices.Clear();
                for (int i = 0; i < vertexPositions.Count; i += 3)
                {
                    vertices.Add(new Vector3(vertexPositions[i], vertexPositions[i + 1], vertexPositions[i + 2]));
                }


                PartMorphInfo morphInfo = null;
                float         scale     = ProgramCore.PluginMode &&
                                          ProgramCore.MainForm.ctrlRenderControl.pickingController.ObjExport != null
                    ? ProgramCore.MainForm.ctrlRenderControl.pickingController.ObjExport.Scale
                    : 1.0f;
                var part =
                    renderMesh.Parts.FirstOrDefault(
                        p =>
                        (p.Name.ToLower().Contains(modelGroup.Value.Name.ToLower()) || modelGroup.Value.Name.ToLower().Contains(p.Name.ToLower())) &&
                        PartMorphInfo.CreatePartMorphInfo(vertices, p, scale, out morphInfo));
                if (part != null)
                {
                    result.Add(part.Guid, morphInfo);
                    GetAABB(ref a, ref b, vertices);
                }
            }
            foreach (var r in result)
            {
                MoveToPosition(ref r.Value.PointsMorph, a, b, Vector3.Zero);
            }
            return(result);
        }
Esempio n. 3
0
        public static void FindCenter(List <Vector3> list, String text)
        {
            Vector3 min, max;
            var     center = MeshUtils.Helpers.MeshUtils.FindCenter(list, out min, out max);

            ProgramCore.EchoToLog(String.Format("{0} Center: {1}; {2}; {3}; Min: {4}; {5}; {6}; Max: {7}; {8}; {9};",
                                                text, center.X, center.Y, center.Z,
                                                min.X, min.Y, min.Z,
                                                max.X, max.Y, max.Z), EchoMessageType.Information);
        }
Esempio n. 4
0
        private void CheckError()
        {
            var error = GL.GetError();

            if (error != ErrorCode.NoError)
            {
                ProgramCore.EchoToLog(error.ToString(), EchoMessageType.Error);
                throw new Exception(error.ToString());
            }
        }
Esempio n. 5
0
        public bool SetUniformLocation(String name)
        {
            var location = GL.GetUniformLocation(shader, name);

            if (location == -1) // -1 = fail
            {
                ProgramCore.EchoToLog(String.Format("SetUniformLocation error: {0}", name), EchoMessageType.Error);
            }

            uniforms.Add(name, location);
            return(true);
        }
Esempio n. 6
0
        public void SetObjectAABB(Vector3 A, Vector3 B)
        {
            ProgramCore.EchoToLog("_delta: " + _delta.ToString(), IO.EchoMessageType.Information);

            Scale = (DefaultB.Y - DefaultA.Y) / (B.Y - A.Y);

            // Vector3 DefaultCenter = (DefaultA + DefaultB) * 0.5f;
            //Vector3 Center = (A + B) * 0.5f;

            float MinY = A.Y * Scale;

            _delta.Y = DefaultA.Y - MinY;

            ProgramCore.EchoToLog("_delta: " + _delta.ToString(), IO.EchoMessageType.Information);
        }
Esempio n. 7
0
        public bool Create(List <float> vertexPositions, List <float> vertexNormals,
                           List <float> vertexTextureCoordinates, List <float> vertexBoneIndices, List <float> vertexBoneWeights,
                           List <uint> indices, string texturePath, string alphaTexturePath)
        {
            Material.DiffuseTextureMap     = texturePath;
            Material.TransparentTextureMap = alphaTexturePath;
            NumIndices = indices.Count;

#if WEB_APP
#else
            GL.GenBuffers(1, out VertexBuffer);
            GL.GenBuffers(1, out IndexBuffer);

            GL.BindBuffer(BufferTarget.ElementArrayBuffer, IndexBuffer);
            GL.BufferData(BufferTarget.ElementArrayBuffer, new IntPtr(indices.Count * sizeof(uint)), indices.ToArray(), BufferUsageHint.DynamicDraw);


            ProgramCore.EchoToLog($"IndexBuffer Size: {indices.Count}", EchoMessageType.Information);

            var error = GL.GetError();
            if (error != ErrorCode.NoError)
            {
                throw new Exception(error.ToString());
            }
#endif

            vertexArray = new Vertex[vertexPositions.Count / 3];
            for (var i = 0; i < vertexPositions.Count / 3; i++)
            {
                var index = i * 3;
                vertexArray[i].Position = new Vector3(vertexPositions[index], vertexPositions[index + 1], vertexPositions[index + 2]);
                vertexArray[i].Normal   = new Vector3(vertexNormals[index], vertexNormals[index + 1], vertexNormals[index + 2]);
                vertexArray[i].TexCoord = new Vector2(vertexTextureCoordinates[i * 2], 1.0f - vertexTextureCoordinates[i * 2 + 1]);
                vertexArray[i].Color    = Vector4.One;
            }

            vertexBoneIndicsArray = vertexBoneIndices.ToArray();
            vertexBoneWeightArray = vertexBoneWeights.ToArray();

#if WEB_APP
#else
            UpdateBuffer();
#endif
            UpdatePointIndices();

            return(true);
        }
Esempio n. 8
0
        /// <summary> Copy dir with all files in them </summary>
        /// <param name="sourceDirName">Source directory path</param>
        /// <param name="destDirName">Destination directory path</param>
        /// <param name="copySubDirs">Copy subfolders</param>
        public static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
        {
            var dir  = new DirectoryInfo(sourceDirName);
            var dirs = dir.GetDirectories();

            // If the source directory does not exist, throw an exception.
            if (!dir.Exists)
            {
                ProgramCore.EchoToLog("Source directory does not exist or could not be found: " + sourceDirName, EchoMessageType.Warning);
                return;
            }

            // If the destination directory does not exist, create it.
            if (!Directory.Exists(destDirName))
            {
                Directory.CreateDirectory(destDirName);
            }


            // Get the file contents of the directory to copy.
            var files = dir.GetFiles();

            foreach (var file in files)
            {
                // Create the path to the new copy of the file.
                var temppath = Path.Combine(destDirName, file.Name);

                // Copy the file.
                file.CopyTo(temppath, false);
            }

            // If copySubDirs is true, copy the subdirectories.
            if (copySubDirs)
            {
                foreach (var subdir in dirs)
                {
                    // Create the subdirectory.
                    var temppath = Path.Combine(destDirName, subdir.Name);

                    // Copy the subdirectories.
                    DirectoryCopy(subdir.FullName, temppath, copySubDirs);
                }
            }
        }
Esempio n. 9
0
        static void Main(string[] args)
        {
            try
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                var currentDomain = AppDomain.CurrentDomain;
                currentDomain.AssemblyResolve += LoadSubLibs;

                ProgramCore.CurrentProgram    = ProgramCore.ProgramMode.FaceAge2_Partial;
                ProgramCore.IsTutorialVisible = false;
                ProgramCore.MainForm          = new frmMain(args.Length == 0 ? string.Empty : args[0]);
                Application.Run(ProgramCore.MainForm);
            }
            catch (Exception e)
            {
                ProgramCore.EchoToLog(e);
                MessageBox.Show(e.Message + Environment.NewLine + e.StackTrace, e.Message);
            }
        }
Esempio n. 10
0
        public List <DynamicRenderMesh> AddMehes(string path, MeshType type, bool fromDragAndDrop, ManType manType, string animationPath, bool needExporter)
        {
            var result = new List <DynamicRenderMesh>();

            var objModel = ObjLoader.LoadObjFile(path, needExporter);

            if (objModel == null)
            {
                ProgramCore.EchoToLog(string.Format("Can't load obj model '{0}'", path), EchoMessageType.Error);
                return(result);
            }

            switch (type)
            {
            case MeshType.Hair:
            {
                var fi           = new FileInfo(path);
                var objModelNull = ObjLoader.LoadObjFile(Path.Combine(fi.DirectoryName, fi.Name.Replace(fi.Extension, string.Format("_null{0}", fi.Extension))));
                if (objModelNull != null &&
                    (objModelNull.Groups.Count != objModel.Groups.Count ||
                     objModel.Vertices.Count != objModelNull.Vertices.Count))
                {
                    //  objModel.TextureCoords.Count != objModelNull.TextureCoords.Count))
                    objModelNull = null;
                }

                result = LoadHairMeshes(objModel, objModelNull, fromDragAndDrop, manType, MeshType.Hair);
                foreach (var renderMesh in result)
                {
                    HairMeshes.Add(renderMesh);
                }
                break;
            }

            case MeshType.Accessory:
                return(objModel.accessoryByHeadShop ? LoadSpecialAccessoryMesh(objModel) : new List <DynamicRenderMesh> {
                    LoadAccessoryMesh(objModel)
                });

            case MeshType.Head:
            {
                var tempPluginTexture = string.Empty;
                if (ProgramCore.PluginMode)
                {
                    var folderPath = Path.Combine(Application.StartupPath, "Models\\Model", manType.GetObjDirPath());
                    switch (ProgramCore.Project.ManType)
                    {
                    case ManType.Male:
                        tempPluginTexture = Path.Combine(folderPath, "Maps", "RyNevio_faceB.jpg");
                        break;

                    case ManType.Female:
                        tempPluginTexture = Path.Combine(folderPath, "Maps", "RyBelle_face.jpg");
                        break;

                    case ManType.Child:
                        tempPluginTexture = Path.Combine(folderPath, "Maps", "AC_KidsRRHBy.jpg");
                        break;

                    default:
                        tempPluginTexture = Path.Combine(Application.StartupPath, "Plugin", "fsRndColor.png");
                        break;
                    }
                }

                foreach (var mesh in HeadMeshes)
                {
                    mesh.Destroy();
                }
                HeadMeshes.Clear();

                var objModelFull = animationPath == string.Empty ? null : ObjLoader.LoadObjFile(animationPath);
                if (objModelFull != null &&
                    (objModelFull.Groups.Count != objModel.Groups.Count ||
                     objModel.Vertices.Count != objModelFull.Vertices.Count ||
                     objModel.TextureCoords.Count != objModelFull.TextureCoords.Count))
                {
                    objModelFull = null;
                }
                LastTriangleIndex = 0;
                result            = LoadHairMeshes(objModel, objModelFull, fromDragAndDrop, manType, MeshType.Head);
                var meshPartInfos = new List <MeshPartInfo>();
                var a             = new Vector3(99999.0f, 99999.0f, 99999.0f);
                var b             = new Vector3(-99999.0f, -99999.0f, -99999.0f);
                foreach (var renderMesh in result)
                {
                    HeadMeshes.Add(renderMesh);

                    if (ProgramCore.PluginMode && ProgramCore.MainForm.PluginUvGroups.Contains(renderMesh.Material.Name))
                    {
                        if (string.IsNullOrEmpty(renderMesh.Material.DiffuseTextureMap))
                        {
                            renderMesh.Material.DiffuseTextureMap = tempPluginTexture;
                        }
                        else if (!File.Exists(renderMesh.Material.DiffuseTextureMap))
                        {
                            renderMesh.Material.DiffuseTextureMap = tempPluginTexture;
                        }
                    }

                    var meshPartInfo = new MeshPartInfo
                    {
                        VertexPositions        = renderMesh.GetVertices(),
                        TextureCoords          = renderMesh.GetTexCoords(),
                        PartName               = renderMesh.Title,
                        Color                  = renderMesh.Material.DiffuseColor,
                        Texture                = renderMesh.Material.Texture,
                        TransparentTexture     = renderMesh.Material.TransparentTexture,
                        TextureName            = renderMesh.Material.DiffuseTextureMap,
                        TransparentTextureName = renderMesh.Material.TransparentTextureMap
                    };                          // создаем инфу о голове. для работы с headshop
                    GetAABB(ref a, ref b, meshPartInfo.VertexPositions);
                    meshPartInfos.Add(meshPartInfo);
                }
                Vector3 dv = Vector3.Zero;
                foreach (var meshPartInfo in meshPartInfos)
                {
                    dv = MoveToPosition(ref meshPartInfo.VertexPositions, a, b, Vector3.Zero);
                    ProgramCore.MainForm.ctrlRenderControl.headMeshesController.CreateMeshPart(meshPartInfo);
                }

                ObjExport = objModel.ObjExport;
                if (ObjExport != null)
                {
                    ObjExport.Delta = -dv;
                }
                ProgramCore.MainForm.ctrlRenderControl.headMeshesController.FinishCreating();

                // ProgramCore.MainForm.ctrlRenderControl.headMeshesController.InitializeTexturing(HeadController.GetDots(ProgramCore.Project.ManType), HeadController.GetIndices(ProgramCore.Project.ManType));
                break;
            }

            default:
                return(result);
            }
            return(result);
        }
Esempio n. 11
0
        public static ObjItem LoadObjFile(string filePath, bool needExporter)
        {
            var result = new ObjItem(needExporter);
            var fi     = new FileInfo(filePath);

            if (!fi.Exists)
            {
                return(null);
            }

            using (var sr = new StreamReader(fi.FullName, Encoding.Default))
            {
                var currentGroup = default(ObjGroup);
                CheckAndAttachDefaultGroup(ref currentGroup, ref result);

                var index         = 0;
                var lastGroupName = String.Empty;

                if (ProgramCore.PluginMode)
                {
                    var folderPath = Path.Combine(Application.StartupPath, "Models\\Model", ProgramCore.Project.ManType.GetObjDirPath());
                    switch (ProgramCore.Project.ManType)
                    {
                    case ManType.Male:
                        LoadMtlib(Path.Combine(folderPath, "Male.mtl"), ref result);
                        break;

                    case ManType.Female:
                        LoadMtlib(Path.Combine(folderPath, "Fem.mtl"), ref result);
                        break;

                    case ManType.Child:
                        LoadMtlib(Path.Combine(folderPath, "Child.mtl"), ref result);
                        break;
                    }
                }

                while (!sr.EndOfStream)
                {
                    var currentLine = sr.ReadLine();

                    if (String.IsNullOrWhiteSpace(currentLine) || currentLine[0] == '#')
                    {
                        if (currentLine == "#Accessories")
                        {
                            result.accessoryByHeadShop = true;
                        }
                        else if (currentLine == "#HeadShop Model")
                        {
                            result.modelByHeadShop = true;
                        }
                        continue;
                    }

                    var fields = currentLine.Trim().Split(null, 2);
                    if (fields.Length < 2)
                    {
                        ProgramCore.EchoToLog(String.Format("Bad obj file format. File: '{0}'", fi.FullName), EchoMessageType.Warning);
                        continue;
                    }

                    var keyword = fields[0].Trim().ToLower();
                    var data    = fields[1].Trim();

                    switch (keyword)
                    {
                    case "v":           // verticles
                        var vertex = ParseVector3(data);
                        result.Vertices.Add(vertex);
                        if (needExporter)
                        {
                            result.ObjExport.Vertices.Add(vertex);
                        }
                        break;

                    case "vt":          // texture coords
                        var textureCoord = ParseTextureCoords(data);
                        result.TextureCoords.Add(textureCoord);
                        if (needExporter)
                        {
                            result.ObjExport.TexCoords.Add(textureCoord);
                        }
                        break;

                    case "vn":          // normals
                        var normal = ParseVector3(data);
                        result.Normals.Add(normal);
                        if (needExporter)
                        {
                            result.ObjExport.Normals.Add(normal);
                        }
                        break;

                    case "f":          // faces
                        var face = ParceFace(data);
                        if (needExporter)
                        {
                            face.ObjExportIndex = result.ObjExport.Faces.Count;
                            result.ObjExport.Faces.Add(new ObjExportFace(face.Count, face.Vertices));
                        }
                        currentGroup.AddFace(face);
                        index++;
                        break;

                    case "g":          // start group
                        if (needExporter)
                        {
                            lastGroupName = data;
                            if (result.ObjExport.MaterialsGroups.Count > 0)
                            {
                                result.ObjExport.MaterialsGroups.Last().Groups.Last().EndFaceIndex = index - 1;
                                result.ObjExport.MaterialsGroups.Last().Groups.Add(new ObjExportGroup
                                {
                                    Group          = data,
                                    StartFaceIndex = index
                                });
                            }
                        }
                        break;

                    case "mtllib":      //parse mtl file
                        var path = Path.Combine(fi.DirectoryName, data);
                        LoadMtlib(path, ref result);
                        break;

                    case "usemtl":
                        if (needExporter)
                        {
                            if (result.ObjExport.MaterialsGroups.Count > 0)
                            {
                                result.ObjExport.MaterialsGroups.Last().Groups.Last().EndFaceIndex = index - 1;
                            }
                            result.ObjExport.MaterialsGroups.Add(new ObjExportMaterial
                            {
                                Material = data,
                                Groups   = new List <ObjExportGroup>
                                {
                                    new ObjExportGroup
                                    {
                                        Group          = lastGroupName,
                                        StartFaceIndex = index
                                    }
                                }
                            });
                        }

                        var         lowerData   = data.ToLower();
                        var         materialKey = result.Materials.Keys.SingleOrDefault(x => x == lowerData);
                        ObjMaterial material;
                        if (materialKey == null)                            // if can't parse mtl, create default group
                        {
                            material = new ObjMaterial(lowerData);
                            result.Materials.Add(lowerData, material);
                        }
                        else
                        {
                            material = result.Materials[materialKey];
                        }

                        if (result.Groups.ContainsKey(material))
                        {
                            currentGroup = result.Groups[material];
                        }
                        else
                        {
                            currentGroup = new ObjGroup(material.Name);
                            result.Groups.Add(material, currentGroup);
                        }
                        break;
                    }
                }
                if (result.ObjExport != null && result.ObjExport.MaterialsGroups.Count > 0 && needExporter)
                {
                    result.ObjExport.MaterialsGroups.Last().Groups.Last().EndFaceIndex = index - 1;
                }
            }
            return(result);
        }
Esempio n. 12
0
        public static List <DynamicRenderMesh> LoadHairMeshes(ObjItem objModel, ObjItem objModelNull, bool fromDragAndDrop, ManType manType, MeshType meshType, ref int lastTriangle)
        {
            var result                   = new List <DynamicRenderMesh>();
            var vertexPositions          = new List <float>();
            var vertexNormals            = new List <float>();
            var vertexTextureCoordinates = new List <float>();
            var vertexBoneIndices        = new List <float>();
            var vertexBoneWeights        = new List <float>();
            var indeces                  = new List <uint>();

            var vertexPositionsNull          = new List <float>();
            var vertexNormalsNull            = new List <float>();
            var vertexTextureCoordinatesNull = new List <float>();
            var vertexBoneIndicesNull        = new List <float>();
            var vertexBoneWeightsNull        = new List <float>();
            var indecesNull = new List <uint>();

            var groupsNull = objModelNull == null ? new Dictionary <ObjMaterial, ObjGroup> .Enumerator() : objModelNull.Groups.GetEnumerator();

            ObjGroup groupNull;

            foreach (var modelGroup in objModel.Groups)          // one group - one mesh
            {
                vertexPositions.Clear();
                vertexNormals.Clear();
                vertexTextureCoordinates.Clear();
                vertexBoneIndices.Clear();
                vertexBoneWeights.Clear();
                indeces.Clear();

                foreach (var face in modelGroup.Value.Faces)          //  combine all meshes in group - to one mesh.
                {
                    GetObjFace(face, objModel, ref vertexPositions, ref vertexNormals, ref vertexTextureCoordinates, ref vertexBoneWeights, ref vertexBoneIndices, ref indeces, ref lastTriangle);
                }

                var renderMesh = new DynamicRenderMesh(meshType);
                renderMesh.groupName = modelGroup.Value.Name;

                if (!objModel.modelByHeadShop)
                {
                    for (var i = 0; i < vertexPositions.Count / 3; i++)
                    {
                        vertexPositions[i * 3 + 1] = vertexPositions[i * 3 + 1] - 0.0060975609f;
                    }
                }

                ProgramCore.EchoToLog(String.Format("RenderMesh: {0}", modelGroup.Value.Name), EchoMessageType.Information);
                ProgramCore.EchoToLog(
                    String.Format("renderMesh.Create: {0}, {1}, {2}, {3}, {4}", vertexPositions.Count,
                                  vertexTextureCoordinates.Count, vertexBoneIndices.Count, vertexBoneWeights.Count, indeces.Count),
                    EchoMessageType.Information);

                if (renderMesh.Create(vertexPositions, vertexTextureCoordinates, vertexBoneIndices, vertexBoneWeights, indeces, string.Empty, string.Empty))
                {
                    if (objModelNull != null)
                    {
                        groupsNull.MoveNext();
                        groupNull = groupsNull.Current.Value;
                        vertexPositionsNull.Clear();
                        vertexNormalsNull.Clear();
                        vertexTextureCoordinatesNull.Clear();
                        vertexBoneWeightsNull.Clear();
                        vertexBoneIndicesNull.Clear();
                        indecesNull.Clear();
                        foreach (var face in groupNull.Faces)
                        {
                            GetObjFace(face, objModelNull, ref vertexPositionsNull, ref vertexNormalsNull, ref vertexTextureCoordinatesNull, ref vertexBoneWeightsNull, ref vertexBoneIndicesNull, ref indecesNull, ref lastTriangle);
                        }
                        renderMesh.SetNullPoints(vertexPositionsNull, vertexNormalsNull, vertexTextureCoordinatesNull);
                    }

                    renderMesh.Title    = modelGroup.Key.Name == "default" ? string.Empty : modelGroup.Key.Name;
                    renderMesh.Material = modelGroup.Key;
                    renderMesh.Material.DiffuseColor = new Vector4(modelGroup.Key.DiffuseColor.X, modelGroup.Key.DiffuseColor.Y, modelGroup.Key.DiffuseColor.Z, modelGroup.Key.Transparency);

                    if (!string.IsNullOrEmpty(modelGroup.Key.DiffuseTextureMap))
                    {
                        renderMesh.Material.DiffuseTextureMap = modelGroup.Key.DiffuseTextureMap;
                    }
                    if (!string.IsNullOrEmpty(modelGroup.Key.TransparentTextureMap))
                    {
                        renderMesh.Material.TransparentTextureMap = modelGroup.Key.TransparentTextureMap;
                    }

                    var scale = meshType == MeshType.Head ? GetHeadScale(manType) : GetHairScale(manType);                       // перегруз сделан потому, что на этапе загрузки проекта самого проекта еще может не быть. поэтому лучше передавать

#if WEB_APP
                    scale *= ProgramCore.Project.RenderMainHelper.headMeshesController.RenderMesh.MorphScale;
#endif

                    renderMesh.Transform = Matrix4.CreateScale(scale);

                    var center = Vector3.Zero;
                    var count  = vertexPositions.Count / 3;
                    for (var i = 0; i < count; i++)
                    {
                        center.X += vertexPositions[i * 3] * scale;
                        center.Y += vertexPositions[i * 3 + 1] * scale;
                        center.Z += vertexPositions[i * 3 + 2] * scale;
                    }

                    if (fromDragAndDrop)
                    {
                        center /= count;
                        renderMesh.Transform       = Matrix4.CreateScale(scale);
                        renderMesh.Transform[3, 0] = -center.X;
                        renderMesh.Transform[3, 1] = -center.Y;
                        renderMesh.Transform[3, 2] = -center.Z;

                        renderMesh.Position = center;
                    }

                    if (vertexTextureCoordinates.Count > 0 && vertexTextureCoordinates.All(x => x == 0))
                    {
                        renderMesh.UpdateTextureCoordinates(0, 1);
                    }

                    if (renderMesh.vertexArray.Length > 0)
                    {
                        result.Add(renderMesh);
                    }
                }
            }
            return(result);
        }
Esempio n. 13
0
        public List <DynamicRenderMesh> AddMehes(string path, MeshType type, bool fromDragAndDrop, GenesisType genesisType, ManType manType, string animationPath, bool needExporter, bool isOpenSmile)
        {
            var result = new List <DynamicRenderMesh>();

            var objModel = ObjLoader.LoadObjFile(path, needExporter, isOpenSmile);

            if (objModel == null)
            {
                ProgramCore.EchoToLog($"Can't load obj model '{path}'", EchoMessageType.Error);
                return(result);
            }

            var lastTriangle = 0;

            switch (type)
            {
            case MeshType.Hair:
            {
                var fi           = new FileInfo(path);
                var objModelNull = ObjLoader.LoadObjFile(Path.Combine(fi.DirectoryName, fi.Name.Replace(fi.Extension, string.Format("_null{0}", fi.Extension))), isOpenSmile);
                if (objModelNull != null &&
                    (objModelNull.Groups.Count != objModel.Groups.Count ||
                     objModel.Vertices.Count != objModelNull.Vertices.Count))
                {
                    //  objModel.TextureCoords.Count != objModelNull.TextureCoords.Count))
                    objModelNull = null;
                }

                result = LoadHairMeshes(objModel, objModelNull, fromDragAndDrop, manType, MeshType.Hair, ref lastTriangle);
                foreach (var renderMesh in result)
                {
                    HairMeshes.Add(renderMesh);
                }
                break;
            }

            case MeshType.Accessory:

                if (objModel.accessoryByHeadShop)
                {
                    result.AddRange(LoadSpecialAccessoryMesh(objModel));
                }
                else
                {
                    var accessories = new List <DynamicRenderMesh> {
                        LoadAccessoryMesh(objModel)
                    };
                    foreach (var accessory in accessories)
                    {
                        AccesoryMeshes.Add(accessory);
                    }

                    result.AddRange(accessories);
                }
                break;

            case MeshType.Head:
            {
                var tempPluginTexture      = string.Empty;
                var topPoint               = 11.98351f;
                int tempPluginTextureIndex = 0;
                if (ProgramCore.PluginMode)
                {
                    var folderPath = Path.Combine(Application.StartupPath, "Models", "Model", genesisType.GetGenesisPath(), manType.GetObjDirPath(isOpenSmile));
                    switch (ProgramCore.Project.ManType)
                    {
                    case ManType.Male:
                        switch (ProgramCore.Project.GenesisType)
                        {
                        case GenesisType.Genesis2:
                            tempPluginTexture = Path.Combine(folderPath, "Maps", "RyNevio_faceB.jpg");
                            break;

                        case GenesisType.Genesis3:
                            tempPluginTexture = Path.Combine(folderPath, "Maps", "RyEddie_face_1001.jpg");
                            break;

                        case GenesisType.Genesis8:
                            tempPluginTexture = Path.Combine(folderPath, "Maps", "G8MBaseFaceMapD01_1001.jpg");
                            break;
                        }
                        break;

                    case ManType.Female:
                        switch (ProgramCore.Project.GenesisType)
                        {
                        case GenesisType.Genesis2:
                            tempPluginTexture = Path.Combine(folderPath, "Maps", "V5BreeHeadM.jpg");
                            break;

                        case GenesisType.Genesis3:
                            tempPluginTexture = Path.Combine(folderPath, "Maps", "RyJeane_face_1001.jpg");
                            break;

                        case GenesisType.Genesis8:
                            tempPluginTexture = Path.Combine(folderPath, "Maps", "G8FBaseFaceMapD_1001.jpg");
                            break;
                        }
                        break;

                    case ManType.Child:
                        tempPluginTexture = Path.Combine(folderPath, "Maps", "AC_KidsRRHBy.jpg");
                        break;

                    default:
                        tempPluginTexture = Path.Combine(Application.StartupPath, "Plugin", "fsRndColor.png");
                        break;
                    }
                    tempPluginTextureIndex = ProgramCore.MainForm.ctrlRenderControl.GetTexture(tempPluginTexture);
                }


                float scale = 1.0f;
                switch (ProgramCore.Project.ManType)
                {
                case ManType.Male:
                    topPoint = 11.98351f;
                    break;

                case ManType.Female:
                    topPoint = 11.61f;
                    break;

                case ManType.Child:
                    //scale = 0.85f;
                    topPoint = 9.759598f;
                    break;
                }

                var objModelFull = animationPath == string.Empty ? null : ObjLoader.LoadObjFile(animationPath, isOpenSmile);
                if (objModelFull != null &&
                    (objModelFull.Groups.Count != objModel.Groups.Count ||
                     objModel.Vertices.Count != objModelFull.Vertices.Count ||
                     objModel.TextureCoords.Count != objModelFull.TextureCoords.Count))
                {
                    objModelFull = null;
                }

                var meshPartInfos = LoadHeadMeshes(objModel, fromDragAndDrop, manType, scale, ref lastTriangle);
                ObjExport = objModel.ObjExport;

                //if (ProgramCore.PluginMode)
                {
                    ObjExport.DefaultA = new Vector3(99999.0f, 99999.0f, 99999.0f);
                    ObjExport.DefaultB = new Vector3(-99999.0f, -99999.0f, -99999.0f);

                    foreach (var meshPartInfo in meshPartInfos)
                    {
                        GetAABB(ref ObjExport.DefaultA, ref ObjExport.DefaultB, meshPartInfo.VertexPositions);
                    }
                }

                if (ProgramCore.PluginMode && isOpenSmile)
                {
                    PluginMorphToSmile(meshPartInfos, genesisType, manType, scale);
                }

                //result = LoadHairMeshes(objModel, objModelFull, fromDragAndDrop, manType, MeshType.Head);
                //var meshPartInfos = new List<MeshPartInfo>();
                var a = new Vector3(99999.0f, 99999.0f, 99999.0f);
                var b = new Vector3(-99999.0f, -99999.0f, -99999.0f);
                foreach (var meshPartInfo in meshPartInfos)
                {
                    if (ProgramCore.PluginMode && ProgramCore.MainForm.PluginUvGroups.Contains(meshPartInfo.MaterialName))
                    {
                        if (string.IsNullOrEmpty(meshPartInfo.TextureName) || !File.Exists(meshPartInfo.TextureName))
                        {
                            meshPartInfo.TextureName = tempPluginTexture;
                            meshPartInfo.Texture     = tempPluginTextureIndex;
                        }
                    }
                    GetAABB(ref a, ref b, meshPartInfo.VertexPositions);
                }
                var dv = Vector3.Zero;
                foreach (var meshPartInfo in meshPartInfos)
                {                   // ПОТЕНЦИАЛЬНО ОПАСНОЕ МЕСТО! В случае улетания башки - AlignByTOp сделать для всех, кроме плагина. Для него оставить MoveToPosition
#if (WEB_APP)
                    dv = AlignByTop(ref meshPartInfo.VertexPositions, a, b, topPoint);
#else
                    dv = MoveToPosition(ref meshPartInfo.VertexPositions, a, b, Vector3.Zero);
#endif
                    ProgramCore.Project.RenderMainHelper.headMeshesController.CreateMeshPart(ProgramCore.Project.GenesisType, meshPartInfo);
                }

                if (ObjExport != null)
                {
                    ObjExport.Delta = -dv;
                }
                ProgramCore.Project.RenderMainHelper.headMeshesController.FinishCreating();

                return(null);
                // ProgramCore.Project.RenderMainHelper.headMeshesController.InitializeTexturing(HeadController.GetDots(ProgramCore.Project.ManType), HeadController.GetIndices(ProgramCore.Project.ManType));
            }

            default:
                return(result);
            }

            foreach (var item in result)
            {
                item.Path = path;
            }

            return(result);
        }
Esempio n. 14
0
        public static ObjItem LoadObjFile(string filePath, bool needExporter, bool isOpenSmile)
        {
            var result = new ObjItem(needExporter);           

#if WEB_APP
            var request = (FtpWebRequest)FtpWebRequest.Create(filePath);
            request.Credentials = new NetworkCredential(FTPHelper.Login, FTPHelper.Password);

            request.Method = WebRequestMethods.Ftp.DownloadFile;

            var ftpResponse = (FtpWebResponse)request.GetResponse();

            byte[] buffer = new byte[16 * 1024];
            using (var ftpStream = ftpResponse.GetResponseStream())
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    int read;
                    while ((read = ftpStream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        ms.Write(buffer, 0, read);
                    }
                    ms.Position = 0;
                    ms.Flush();
                    using (var sr = new StreamReader(ms, Encoding.Default))
#else

                 var fi = new FileInfo(filePath);
                if (!fi.Exists)
                    return null;
                    using (var sr = new StreamReader(fi.FullName, Encoding.Default))
#endif
                    {
                        var currentGroup = default(ObjGroup);
                        CheckAndAttachDefaultGroup(ref currentGroup, ref result);

                        var index = 0;
                        var lastGroupName = String.Empty;

                        if (ProgramCore.PluginMode)
                        {
                            var folderPath = Path.Combine(Application.StartupPath, "Models", "Model", ProgramCore.Project.GenesisType.GetGenesisPath(), ProgramCore.Project.ManType.GetObjDirPath(isOpenSmile));
                            switch (ProgramCore.Project.ManType)
                            {
                                case ManType.Male:
                                    LoadMtlib(Path.Combine(folderPath, "Male.mtl"), ref result);
                                    break;
                                case ManType.Female:
                                    LoadMtlib(Path.Combine(folderPath, "Fem.mtl"), ref result);
                                    break;
                                case ManType.Child:
                                    LoadMtlib(Path.Combine(folderPath, "Child.mtl"), ref result);
                                    break;
                            }
                        }

                        while (!sr.EndOfStream)
                        {
                            var currentLine = sr.ReadLine();

                            if (String.IsNullOrWhiteSpace(currentLine) || currentLine[0] == '#')
                            {
                                if (currentLine == "#Accessories")
                                    result.accessoryByHeadShop = true;
                                else if (currentLine == "#HeadShop Model")
                                    result.modelByHeadShop = true;
                                continue;
                            }

                            var fields = currentLine.Trim().Split(null, 2);
                            if (fields.Length < 2)
                            {
#if WEB_APP
#else
                                ProgramCore.EchoToLog(String.Format("Bad obj file format. File: '{0}'", fi.FullName), EchoMessageType.Warning);
#endif
                                continue;
                            }

                            var keyword = fields[0].Trim().ToLower();
                            var data = fields[1].Trim();

                            switch (keyword)
                            {
                                case "v":       // verticles
                                    var vertex = ParseVector3(data);
                                    result.Vertices.Add(vertex);
                                    if (needExporter)
                                        result.ObjExport.Vertices.Add(vertex);
                                    break;
                                case "vt":      // texture coords
                                    var textureCoord = ParseTextureCoords(data);
                                    result.TextureCoords.Add(textureCoord);
                                    if (needExporter)
                                        result.ObjExport.TexCoords.Add(textureCoord);
                                    break;
                                case "vn":      // normals
                                    var normal = ParseVector3(data);
                                    result.Normals.Add(normal);
                                    if (needExporter)
                                        result.ObjExport.Normals.Add(normal);
                                    break;
                                case "f":      // faces
                                    var face = ParceFace(data);
                                    if (needExporter)
                                    {
                                        face.ObjExportIndex = result.ObjExport.Faces.Count;
                                        result.ObjExport.Faces.Add(new ObjExportFace(face.Count, face.Vertices));
                                    }
                                    currentGroup.AddFace(face);
                                    index++;
                                    break;
                                case "g":      // start group
                                    if (needExporter)
                                    {
                                        lastGroupName = data;
                                        if (result.ObjExport.MaterialsGroups.Count > 0)
                                        {
                                            result.ObjExport.MaterialsGroups.Last().Groups.Last().EndFaceIndex = index - 1;
                                            result.ObjExport.MaterialsGroups.Last().Groups.Add(new ObjExportGroup
                                            {
                                                Group = data,
                                                StartFaceIndex = index
                                            });
                                        }
                                    }
                                    break;
                                case "mtllib":  //parse mtl file
#if WEB_APP
                                    if (ProgramCore.Project != null)
                                    {
                                        var path = ProgramCore.Project.HeadModelPath.Replace(".obj", ".mtl");
                                        switch (ProgramCore.Project.ManType)
                                        {
                                            case ManType.Male:
                                                LoadMtlib(path, ref result);
                                                break;
                                            case ManType.Female:
                                                LoadMtlib(path, ref result);
                                                break;
                                            case ManType.Child:
                                                LoadMtlib(path, ref result);
                                                break;
                                        }
                                    }
#else
                                    var path = Path.Combine(fi.DirectoryName, data);
                                    LoadMtlib(path, ref result);
#endif
                                    break;
                                case "usemtl":
                                    if (needExporter)
                                    {
                                        if (result.ObjExport.MaterialsGroups.Count > 0)
                                            result.ObjExport.MaterialsGroups.Last().Groups.Last().EndFaceIndex = index - 1;
                                        result.ObjExport.MaterialsGroups.Add(new ObjExportMaterial
                                        {
                                            Material = data,
                                            Groups = new List<ObjExportGroup>
                                        {
                                            new ObjExportGroup
                                            {
                                                Group = lastGroupName,
                                                StartFaceIndex = index
                                            }
                                        }
                                        });
                                    }

                                    var lowerData = data.ToLower();
                                    var materialKey = result.Materials.Keys.SingleOrDefault(x => x == lowerData);
                                    ObjMaterial material;
                                    if (materialKey == null)                        // if can't parse mtl, create default group
                                    {
                                        material = new ObjMaterial(lowerData);
                                        result.Materials.Add(lowerData, material);
                                    }
                                    else
                                        material = result.Materials[materialKey];

                                    if (result.Groups.ContainsKey(material))
                                        currentGroup = result.Groups[material];
                                    else
                                    {
                                        currentGroup = new ObjGroup(material.Name);
                                        result.Groups.Add(material, currentGroup);
                                    }
                                    break;
                            }
                        }
                        if (result.ObjExport != null && result.ObjExport.MaterialsGroups.Count > 0 && needExporter)
                            result.ObjExport.MaterialsGroups.Last().Groups.Last().EndFaceIndex = index - 1;
                    }
#if WEB_APP
                }
            }
#endif
            return result;
        }