示例#1
1
        public void Export(string filePath)
        {
            PalletProperties palletProperties = _palletSolution.Analysis.PalletProperties;

            COLLADA model = new COLLADA();
            // asset
            model.asset = new asset()
            {
                created = DateTime.Now,
                modified = DateTime.Now
            };
            model.asset.keywords = "StackBuilder Pallet Case";
            model.asset.title = _palletSolution.Title;
            model.asset.unit = new assetUnit() { name = "millimeters", meter = 0.001 };
            model.asset.up_axis = UpAxisType.Z_UP;

            library_images images = new library_images();
            library_materials materials = new library_materials();
            library_effects effects = new library_effects();
            library_geometries geometries = new library_geometries();
            library_nodes nodes = new library_nodes();
            library_cameras cameras = new library_cameras();
            library_animations animations = new library_animations();
            library_visual_scenes scenes = new library_visual_scenes();

            COLLADAScene colladaScene = new COLLADAScene();

            model.Items = new Object[] { images, materials, effects, geometries, nodes, cameras, animations, scenes };
            model.scene = colladaScene;

            // colors and materials
            List<effect> listEffects = new List<effect>();
            List<material> listMaterials = new List<material>();
            List<image> listImages = new List<image>();

            // effects
            effect effectPallet;
            material materialPallet;
            CreateMaterial(palletProperties.Color, null, null, "Pallet", out effectPallet, out materialPallet);
            listEffects.Add(effectPallet);
            listMaterials.Add(materialPallet);

            Box box = new Box(0, _palletSolution.Analysis.BProperties);

            // build list of effects / materials / images
            uint faceIndex = 0;
            foreach (Face face in box.Faces)
            {
                // build texture image if any
                string textureName = null;
                if (face.HasBitmap)
                {
                    textureName = string.Format("textureFace_{0}", faceIndex);
                    string texturePath = System.IO.Path.Combine(
                        System.IO.Path.GetDirectoryName(filePath)
                        , textureName + ".jpg");

                    double dimX = 0.0, dimY = 0.0;

                    switch (faceIndex)
                    {
                        case 0: dimX = box.Width; dimY = box.Height; break;
                        case 1: dimX = box.Width; dimY = box.Height; break;
                        case 2: dimX = box.Length; dimY = box.Height; break;
                        case 3: dimX = box.Length; dimY = box.Height; break;
                        case 4: dimX = box.Length; dimY = box.Width; break;
                        case 5: dimX = box.Length; dimY = box.Width; break;
                        default: break;
                    }
                    face.ExtractFaceBitmap(dimX, dimY, _bmpWidth, texturePath);
                    // create image
                    listImages.Add(
                        new image()
                        {
                            id = textureName + ".jpg",
                            name = textureName + ".jpg",
                            Item = @".\" + textureName + @".jpg"
                        }
                    );
                }
                material materialCase;
                effect effectCase;
                CreateMaterial(face.ColorFill, textureName, "0", string.Format("Case{0}", faceIndex), out effectCase, out materialCase);
                listEffects.Add(effectCase);
                listMaterials.Add(materialCase);

                ++faceIndex;
            }

            // add to image list
            images.image = listImages.ToArray();

            // case lines material
            effect effectCaseLines;
            material materialCaseLines;
            CreateMaterial(Color.Black, null, null, "CaseLines", out effectCaseLines, out materialCaseLines);
            listEffects.Add(effectCaseLines);
            listMaterials.Add(materialCaseLines);
            effects.effect = listEffects.ToArray();
            materials.material = listMaterials.ToArray();

            // geometries
            geometry geomPallet = new geometry() { id = "palletGeometry", name = "palletGeometry" };
            geometry geomCase = new geometry() { id = "caseGeometry", name = "caseGeometry" };
            geometries.geometry = new geometry[] { geomPallet, geomCase };
            // pallet
            mesh meshPallet = CreatePalletMesh(palletProperties);
            geomPallet.Item = meshPallet;
            // case
            mesh meshCase = CreateCaseMesh(_palletSolution.Analysis.BProperties as BoxProperties);
            geomCase.Item = meshCase;
            // library_animations
            animation animationMain = new animation() { id = "animationMain_ID", name = "animationMain" };
            animations.animation = new animation[] { animationMain };

            List<object> listAnimationSource = new List<object>();

            // library_visual_scenes
            visual_scene mainScene = new visual_scene() { id = "MainScene", name = "MainScene" };
            scenes.visual_scene = new visual_scene[] { mainScene };

            List<node> sceneNodes = new List<node>();
            sceneNodes.Add(new node()
            {
                id = "PalletNode",
                name = "PalletNode",
                instance_geometry = new instance_geometry[]
                {
                    new instance_geometry()
                    {
                        url = "#palletGeometry",
                        bind_material = new bind_material()
                        {
                            technique_common = new instance_material[]
                            {
                                new instance_material()
                                {
                                    symbol="materialPallet",
                                    target=string.Format("#{0}", materialPallet.id)
                                }
                            }
                        }
                    }
                }
            });
            uint caseIndex = 0;
            foreach (ILayer layer in _palletSolution)
            {
                BoxLayer bLayer = layer as BoxLayer;
                if (null == bLayer) continue;

                foreach (BoxPosition bp in bLayer)
                {
                    Vector3D translation = bp.Position;
                    Vector3D rotations = bp.Transformation.Rotations;

                    node caseNode = new node()
                    {
                        id = string.Format("CaseNode_{0}_ID", caseIndex),
                        name = string.Format("CaseNode_{0}", caseIndex),
                        ItemsElementName = new ItemsChoiceType2[]
                        {
                            ItemsChoiceType2.translate,
                            ItemsChoiceType2.rotate,
                            ItemsChoiceType2.rotate,
                            ItemsChoiceType2.rotate
                        },
                        Items = new object[]
                        {
                            new TargetableFloat3()
                            {
                                Values = new double[] { translation.X, translation.Y, translation.Z },
                                sid = "t",
                            },
                            new rotate()
                            {
                                Values = new double[] { 1.0, 0.0, 0.0, rotations.X },
                                sid = "rx"
                            },
                            new rotate()
                            {
                                Values = new double[] { 0.0, 1.0, 0.0, rotations.Y },
                                sid = "ry"
                            },
                            new rotate()
                            {
                                Values = new double[] { 0.0, 0.0, 1.0, rotations.Z },
                                sid = "rz"
                            } 
                        },

                        instance_geometry = new instance_geometry[]
                        {
                            new instance_geometry()
                            {
                                url="#caseGeometry",
                                bind_material = new bind_material()
                                {
                                    technique_common = new instance_material[]
                                    {
                                        new instance_material() { symbol="materialCase0", target="#material_Case0_ID" },
                                        new instance_material() { symbol="materialCase1", target="#material_Case1_ID" },
                                        new instance_material() { symbol="materialCase2", target="#material_Case2_ID" },
                                        new instance_material() { symbol="materialCase3", target="#material_Case3_ID" },
                                        new instance_material() { symbol="materialCase4", target="#material_Case4_ID" },
                                        new instance_material() { symbol="materialCase5", target="#material_Case5_ID" },
                                        new instance_material() { symbol="materialCaseLines", target="#material_CaseLines_ID"}
                                    }
                                }
                            }
                        }
                    };
                    sceneNodes.Add(caseNode);

                    // animations
                    CreateAnimation(caseIndex, (uint)_palletSolution.CaseCount, listAnimationSource, bp);

                    // increment case index
                    ++caseIndex;
                }
            }

            // add nodes
            mainScene.node = sceneNodes.ToArray();

            animationMain.Items = listAnimationSource.ToArray();

            // library_cameras
            camera cameraCamera = new camera() { id = "Camera-Camera", name = "Camera-Camera" };
            cameraOpticsTechnique_commonPerspective cameraPerspective = new cameraOpticsTechnique_commonPerspective()
            {
                znear = new TargetableFloat() { sid = "znear", Value = 1.0 },
                zfar = new TargetableFloat() { sid = "zfar", Value = 10000.0 }
            };
            cameraCamera.optics = new cameraOptics() { technique_common = new cameraOpticsTechnique_common() { Item = cameraPerspective } };
            cameras.camera = new camera[] { cameraCamera };

            // colladaScene
            colladaScene.instance_visual_scene = new InstanceWithExtra() { url = "#MainScene" };

            model.Save(filePath);
            model.Save(System.IO.Path.ChangeExtension(filePath, "xml"));
        }
示例#2
0
        static CL.COLLADA NewCollada()
        {
            var dae = new CL.COLLADA();

            dae.asset             = new CL.asset();
            dae.asset.created     = dae.asset.modified = DateTime.Now;
            dae.asset.contributor = new CL.assetContributor[] {
                new CL.assetContributor()
                {
                    author         = "LancerEdit User",
                    authoring_tool = "LancerEdit"
                }
            };
            return(dae);
        }
示例#3
0
        public KSPPartAttrib(TextReader stream)
        {
            int lineIdx = 0;
            String line;

            Regex r = new Regex(@"((\s)*(?<Key>([^\=^\s^\n]+))[\s^\n] \= (\s)*(?<Value>([^\n^\s]+(\n){0,1})))",RegexOptions.Compiled | RegexOptions.ExplicitCapture);

            List<String[]> extraLines = new List<string[]>();

            while ((line = stream.ReadLine()) != "")
            {
                lineIdx++;

                if (line.Substring(0, 1) == "//")
                    continue;

                var match = r.Match(line);

                var key = match.Groups["Key"].Value;
                var val = match.Groups["Value"].Value;

                switch (key.Trim())
                {
                    case "name":
                        name = val;
                        break;
                    case "module":
                        if (!Enum.TryParse<KSPPartModule>(val, out module))
                        {
                            throw new Exception(String.Format("Module string '{0}' could not be parsed into a module known to this program. (Line {1})", val, lineIdx));
                        }
                        break;
                    case "author":
                        author = val;
                        break;
                    case "mesh":
                        mesh = COLLADA.Load(val);
                        break;
                    case "scale":
                        try
                        {
                            scale = Double.Parse(val.Trim());
                        }
                        catch (Exception e)
                        {
                            throw new Exception(String.Format("scale string '{0}' could not be parsed into a double value. (Line {1})", val, lineIdx),e);
                        }
                        break;
                    case "texture":
                        texture = val;
                        break;
                    case "specPower":
                        try
                        {
                            specPower = Double.Parse(val.Trim());
                        }
                        catch (Exception e)
                        {
                            throw new Exception(String.Format("specPower string '{0}' could not be parsed into a double value. (Line {1})", val, lineIdx), e);
                        }
                        break;
                    case "rimFalloff":
                        try
                        {
                            rimFalloff = Double.Parse(val.Trim());

                        }
                        catch (Exception e)
                        {
                            throw new Exception(String.Format("rimFalloff string '{0}' could not be parsed into a double value. (Line {1})", val, lineIdx), e);
                        }
                        break;
                    case "alphaCutoff":
                        try
                        {
                            alphaCutoff = Double.Parse(val.Trim());
                        }
                        catch (Exception e)
                        {
                            throw new Exception(String.Format("alphaCutoff string '{0}' could not be parsed into a double value. (Line {1})", val, lineIdx), e);
                        }
                        break;
                    case "iconCenter":
                        var comps = val.Split(',');
                        try
                        {
                            double x = Double.Parse(comps[0].Trim());
                            double y = Double.Parse(comps[1].Trim());
                            double z = Double.Parse(comps[2].Trim());

                            iconCenter = new Point3() { x = x, y = y, z = z };
                        }
                        catch (Exception e)
                        {
                            throw new Exception(String.Format("iconCenter string '{0}' could not be parsed into doubles. (Line {1})", val, lineIdx), e);
                        }
                        break;
                    case "cost":
                        try
                        {
                            cost = Int32.Parse(val.Trim());
                        }
                        catch (Exception e)
                        {
                            throw new Exception(String.Format("cost string '{0}' could not be parsed into Int32. (Line {1})", val, lineIdx), e);
                        }
                        break;
                    case "category":
                        try
                        {
                            category = Int32.Parse(val.Trim());
                        }
                        catch (Exception e)
                        {
                            throw new Exception(String.Format("category string '{0}' could not be parsed into Int32. (Line {1})", val, lineIdx), e);
                        }
                        break;
                    case "subcategory":
                        try
                        {
                            subcategory = Int32.Parse(val.Trim());
                        }
                        catch (Exception e)
                        {
                            throw new Exception(String.Format("subcategory string '{0}' could not be parsed into Int32. (Line {1})", val, lineIdx), e);
                        }
                        break;
                    case "title":
                        title = val;
                        break;
                    case "manufacturer":
                        manufacturer = val;
                        break;
                    case "description":
                        description = val;
                        break;
                    case "attachRules":
                        try
                        {
                            comps = val.Split(',');

                            attachmentStack = (comps[0].Trim() == "1");
                            attachmentSurf = (comps[1].Trim() == "1");
                            attachmentAllowStack = (comps[2].Trim() == "1");
                            attachmentAllowSurf = (comps[3].Trim() == "1");
                            attachmentAllowCollision = (comps[4].Trim() == "1");
                        }
                        catch (Exception e)
                        {
                            throw new Exception(String.Format("attachRules string '{0}' could not be parsed into valid attachment rules. (Line {1})", val, lineIdx), e);
                        }
                        break;
                    case "mass":
                        try
                        {
                            mass = Double.Parse(val.Trim());
                        }
                        catch (Exception e)
                        {
                            throw new Exception(String.Format("mass string '{0}' could not be parsed into a double value. (Line {1})", val, lineIdx), e);
                        }
                        break;
                    case "dragModelType":
                        dragModelType = val;
                        break;
                    case "maximum_drag":
                        try
                        {
                            maximum_drag = Double.Parse(val.Trim());
                        }
                        catch (Exception e)
                        {
                            throw new Exception(String.Format("maximum_drag string '{0}' could not be parsed into a double value. (Line {1})", val, lineIdx), e);
                        }
                        break;
                    case "minimum_drag":
                        try
                        {
                            minimum_drag = Double.Parse(val.Trim());
                        }
                        catch (Exception e)
                        {
                            throw new Exception(String.Format("minimum_drag string '{0}' could not be parsed into a double value. (Line {1})", val, lineIdx), e);
                        }
                        break;
                    case "angularDrag ":
                        try
                        {
                            angularDrag = Double.Parse(val.Trim());
                        }
                        catch (Exception e)
                        {
                            throw new Exception(String.Format("angularDrag string '{0}' could not be parsed into a double value. (Line {1})", val, lineIdx), e);
                        }
                        break;
                    case "crashTolerance":
                        try
                        {
                            crashTolerance = Double.Parse(val.Trim());
                        }
                        catch (Exception e)
                        {
                            throw new Exception(String.Format("crashTolerance string '{0}' could not be parsed into a double value. (Line {1})", val, lineIdx), e);
                        }
                        break;
                    case "maxTemp":
                        try
                        {
                            maxTemp = Double.Parse(val.Trim());
                        }
                        catch (Exception e)
                        {
                            throw new Exception(String.Format("maxTemp string '{0}' could not be parsed into a double value. (Line {1})", val, lineIdx), e);
                        }
                        break;
                    default:
                        if (val.Substring(0,4) == "node")
                        {
                            try{
                            comps = val.Split(',');

                            double x = Double.Parse(comps[0].Trim());
                            double y = Double.Parse(comps[1].Trim());
                            double z = Double.Parse(comps[2].Trim());

                            double vx = Double.Parse(comps[3].Trim());
                            double vy = Double.Parse(comps[4].Trim());
                            double vz = Double.Parse(comps[5].Trim());

                            nodeDefinitions.Add(new KSPAttribNodeDefinition() { Name = key, Position = new Point3() { x = x, y = y, z = z }, UpVector = new Point3() { x = vx, y = vy, z = vz } });
                            }
                            catch (Exception e)
                        {
                            throw new Exception(String.Format("node string '{0}' ({2}) could not be parsed into doubles. (Line {1})", val, lineIdx, key), e);
                        }
                        }
                        else if (val.Trim() != "")
                        {
                            extraLines.Add(new string[] { key, val });
                        }
                        break;
                }

            }
            switch (module)
            {
                case KSPPartModule.AdvSASModule:
                    break;
                case KSPPartModule.FuelLine:
                    break;
                case KSPPartModule.FuelTank:
                    break;
                case KSPPartModule.LiquidEngine:
                    break;
                case KSPPartModule.CommandPod:
                    break;
                case KSPPartModule.Parachutes:
                    break;
                case KSPPartModule.RadialDecoupler:
                    break;
                case KSPPartModule.RCSModule:
                    break;
                case KSPPartModule.RCSFuelTank:
                    break;
                case KSPPartModule.SASModule:
                    break;
                case KSPPartModule.SolidRocket:
                    break;
                case KSPPartModule.Decoupler:
                    break;
                case KSPPartModule.Strut:
                    break;
                case KSPPartModule.StrutConnector:
                    break;
                case KSPPartModule.Winglet:
                    break;
                case KSPPartModule.ControlSurface:
                    break;
                default:
                    throw new Exception(String.Format("No specific part parser for module '{0}'. Well, that's awkward. (We're in KSPEdit.Model.KSPPartAttrib btw, if you feel like reporting this)", module.ToString()));
                    break;
            }
        }
示例#4
0
 public DAELoader(string modelFileName)
     : base(modelFileName)
 {
     m_COLLADAModel = COLLADA.Load(modelFileName);
 }
示例#5
0
        public GameObject Load(string inputFile)
        {
            COLLADA model = COLLADA.Load(inputFile);

            // parent directory
            string parentDir = Directory.GetParent(inputFile).FullName;

            // (image id, texture)
            Dictionary <string, Texture2D> textureDict = new Dictionary <string, Texture2D>();
            // (effect id, material)
            Dictionary <string, Material> effectDict = new Dictionary <string, Material>();
            // (material id, effect id)
            Dictionary <string, string> materialDict = new Dictionary <string, string>();

            // (geom id, mesh)
            Dictionary <string, Mesh> geomDict = new Dictionary <string, Mesh>();
            // (geom id, materilas)
            Dictionary <string, List <string> > geomMatDict = new Dictionary <string, List <string> >();

            // root game object for mesh file
            GameObject unityObj = new GameObject("mesh");

            // Iterate on libraries
            foreach (var item in model.Items)
            {
                if (item is library_images)
                {
                    // image libraries -> effectDict
                    var lib_image = item as library_images;
                    if (lib_image == null || lib_image.image == null)
                    {
                        continue;
                    }

                    foreach (var image in lib_image.image)
                    {
                        var imagePath = Path.Combine(parentDir, image.Item as string);

                        // load image
                        byte[]    byteArray = File.ReadAllBytes(imagePath);
                        Texture2D texture   = new Texture2D(2, 2);
                        bool      isLoaded  = texture.LoadImage(byteArray);
                        if (!isLoaded)
                        {
                            // TODO error
                        }
                        textureDict.Add(image.id, texture);
                    }
                }
                else if (item is library_effects)
                {
                    // effect libraries -> effectDict
                    var lib_effect = item as library_effects;
                    if (lib_effect == null || lib_effect.effect == null)
                    {
                        continue;
                    }

                    foreach (var eff in lib_effect.effect)
                    {
                        var name = eff.id;
                        if (eff.Items == null)
                        {
                            continue;
                        }

                        foreach (var it in eff.Items)
                        {
                            var profile = it as effectFx_profile_abstractProfile_COMMON;

                            Dictionary <string, string> surfaceDict = new Dictionary <string, string>();
                            Dictionary <string, string> samplerDict = new Dictionary <string, string>();

                            if (it.Items != null)
                            {
                                foreach (var it2 in it.Items)
                                {
                                    var newparam = it2 as common_newparam_type;
                                    if (newparam.Item is fx_surface_common)
                                    {
                                        var surface = newparam.Item as fx_surface_common;
                                        surfaceDict.Add(newparam.sid, surface.init_from[0].Value);
                                    }
                                    else if (newparam.Item is fx_sampler2D_common)
                                    {
                                        var sampler = newparam.Item as fx_sampler2D_common;
                                        samplerDict.Add(newparam.sid, sampler.source);
                                    }
                                }
                            }

                            var phong = profile.technique.Item as effectFx_profile_abstractProfile_COMMONTechniquePhong;
                            if (phong.diffuse.Item is common_color_or_texture_typeColor)
                            {
                                // color
                                var diffuse = phong.diffuse.Item as common_color_or_texture_typeColor;

                                if (diffuse != null)
                                {
                                    Material material = new Material(Shader.Find("Standard"));
                                    Color    color    = new Color(
                                        (float)diffuse.Values[0],
                                        (float)diffuse.Values[1],
                                        (float)diffuse.Values[2],
                                        (float)diffuse.Values[3]
                                        );
                                    material.color = color;

                                    effectDict.Add(name, material);
                                }
                            }
                            else if (phong.diffuse.Item is common_color_or_texture_typeTexture)
                            {
                                // texture
                                var diffuse = phong.diffuse.Item as common_color_or_texture_typeTexture;

                                if (diffuse != null)
                                {
                                    var texture = diffuse.texture;

                                    if (samplerDict.ContainsKey(texture))
                                    {
                                        var surface = samplerDict[texture];
                                        if (surfaceDict.ContainsKey(surface))
                                        {
                                            var textureName = surfaceDict[surface];
                                            if (textureDict.ContainsKey(textureName))
                                            {
                                                Material material = new Material(Shader.Find("Standard"));
                                                material.SetTexture("_MainTex", textureDict[textureName]);
                                                effectDict.Add(name, material);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                else if (item is library_materials)
                {
                    // material libraries -> materialDict
                    var material = item as library_materials;
                    if (material == null || material.material == null)
                    {
                        continue;
                    }

                    foreach (var mat in material.material)
                    {
                        materialDict.Add(mat.id, mat.instance_effect.url.Substring(1));
                    }
                }
                else if (item is library_geometries)
                {
                    // geometry libraries -> geomDict
                    var geometries = item as library_geometries;
                    if (geometries == null || geometries.geometry == null)
                    {
                        continue;
                    }

                    // Dictionary stores source arrays
                    Dictionary <string, double[]>      sourceDict       = new Dictionary <string, double[]>();
                    Dictionary <string, VertexSources> vertexSourceDict = new Dictionary <string, VertexSources>();

                    // Iterate on geomerty in library_geometries
                    foreach (var geom in geometries.geometry)
                    {
                        // converted as vector3
                        List <Vector3> vertexList = new List <Vector3>();
                        List <Vector3> normalList = new List <Vector3>();
                        List <Vector2> uvList     = new List <Vector2>();
                        List <int[]>   idxList    = new List <int[]>();

                        // submesh
                        int           numSubmesh   = 0;
                        List <string> subMaterials = new List <string>();

                        var mesh = geom.Item as mesh;
                        if (mesh == null)
                        {
                            continue;
                        }

                        foreach (var source in mesh.source)
                        {
                            var float_array = source.Item as float_array;
                            if (float_array == null)
                            {
                                continue;
                            }

                            sourceDict.Add(source.id, float_array.Values);
                        }

                        // Add vertex of mesh to list
                        foreach (var input in mesh.vertices.input)
                        {
                            if (input.semantic == "POSITION")
                            {
                                VertexSources vs = new VertexSources();
                                vs.positionId = input.source.Substring(1);
                                vertexSourceDict.Add(mesh.vertices.id, vs);
                            }
                            else if (input.semantic == "NORMAL")
                            {
                                VertexSources vs = new VertexSources();
                                vs.normalId = input.source.Substring(1);
                                vertexSourceDict.Add(mesh.vertices.id, vs);
                            }
                        }

                        if (mesh.Items == null)
                        {
                            continue;
                        }

                        // triangle or polylist
                        foreach (var meshItem in mesh.Items)
                        {
                            int indexStride   = 1;
                            int posOffset     = 0;
                            int normalOffset  = 0;
                            int uvOffset      = 0;
                            int numIndices    = 0;
                            int curNumIndices = 0;

                            // source name
                            string positionSourceName = "";
                            string normalSourceName   = "";
                            string uvSourceName       = "";

                            // current indices
                            List <int> currIdxList = new List <int>();

                            // triangles
                            if (meshItem is triangles)
                            {
                                var triangles = meshItem as triangles;
                                var inputs    = triangles.input;

                                int count = (int)triangles.count;

                                foreach (var input in inputs)
                                {
                                    // offset
                                    int offset = (int)input.offset;
                                    if (offset + 1 > indexStride)
                                    {
                                        indexStride = offset + 1;
                                    }

                                    // source
                                    string sourceName = input.source.Substring(1);

                                    if (input.semantic == "VERTEX")
                                    {
                                        VertexSources vs = vertexSourceDict[sourceName];
                                        if (!string.IsNullOrEmpty(vs.positionId))
                                        {
                                            positionSourceName = vs.positionId;
                                            posOffset          = offset;
                                        }
                                        else if (string.IsNullOrEmpty(vs.normalId))
                                        {
                                            normalSourceName = vs.normalId;
                                            normalOffset     = offset;
                                        }
                                    }
                                    else if (input.semantic == "NORMAL")
                                    {
                                        normalSourceName = sourceName;
                                        normalOffset     = offset;
                                    }
                                    else if (input.semantic == "TEXCOORD")
                                    {
                                        uvSourceName = sourceName;
                                        uvOffset     = offset;
                                    }
                                }

                                numIndices = count * 3;

                                // parse index from p
                                currIdxList = triangles.p.Split(' ').Select(Int32.Parse).ToList();

                                // material
                                string materialName = triangles.material;
                                if (!string.IsNullOrEmpty(materialName) && materialDict.ContainsKey(materialName))
                                {
                                    subMaterials.Add(materialName);
                                }

                                // Increment submesh count
                                numSubmesh += 1;
                            }

                            // vertex
                            List <double> positionFloatArray = new List <double>();
                            if (sourceDict.ContainsKey(positionSourceName))
                            {
                                positionFloatArray = sourceDict[positionSourceName].ToList();
                            }

                            // normal
                            List <double> normalFloatArray = new List <double>();
                            if (sourceDict.ContainsKey(normalSourceName))
                            {
                                normalFloatArray = sourceDict[normalSourceName].ToList();
                            }

                            // uv
                            List <double> uvFloatArray = new List <double>();
                            if (sourceDict.ContainsKey(uvSourceName))
                            {
                                uvFloatArray = sourceDict[uvSourceName].ToList();
                            }

                            // add to list
                            int indexOffset = vertexList.Count;

                            for (int i = 0; i < (int)numIndices; i++)
                            {
                                int posIndex    = currIdxList[i * indexStride + posOffset];
                                int normalIndex = currIdxList[i * indexStride + normalOffset];
                                int uvIndex     = currIdxList[i * indexStride + uvOffset];

                                if (model.asset.up_axis == UpAxisType.Y_UP)
                                {
                                    vertexList.Add(new Vector3(
                                                       -(float)positionFloatArray[posIndex * 3],
                                                       (float)positionFloatArray[posIndex * 3 + 1],
                                                       (float)positionFloatArray[posIndex * 3 + 2]
                                                       ));

                                    if (normalFloatArray.Count > 0 && (normalFloatArray.Count > normalIndex))
                                    {
                                        normalList.Add(new Vector3(
                                                           -(float)normalFloatArray[normalIndex * 3],
                                                           (float)normalFloatArray[normalIndex * 3 + 1],
                                                           (float)normalFloatArray[normalIndex * 3 + 2]
                                                           ));
                                    }
                                    else
                                    {
                                        // Add dummy normal for debugging
                                        normalList.Add(new Vector3(
                                                           0,
                                                           0,
                                                           0
                                                           ));
                                    }
                                }
                                else if (model.asset.up_axis == UpAxisType.Z_UP)
                                {
                                    vertexList.Add(new Vector3(
                                                       -(float)positionFloatArray[posIndex * 3],
                                                       (float)positionFloatArray[posIndex * 3 + 2],
                                                       -(float)positionFloatArray[posIndex * 3 + 1]
                                                       ));

                                    if (normalFloatArray.Count > 0 && (normalFloatArray.Count > normalIndex))
                                    {
                                        normalList.Add(new Vector3(
                                                           -(float)normalFloatArray[normalIndex * 3],
                                                           (float)normalFloatArray[normalIndex * 3 + 2],
                                                           -(float)normalFloatArray[normalIndex * 3 + 1]
                                                           ));
                                    }
                                    else
                                    {
                                        // Add dummy normal for debugging
                                        normalList.Add(new Vector3(
                                                           0,
                                                           0,
                                                           0
                                                           ));
                                    }
                                }

                                if (uvFloatArray.Count > 0)
                                {
                                    uvList.Add(new Vector2(
                                                   (float)uvFloatArray[uvIndex * 2],
                                                   (float)uvFloatArray[uvIndex * 2 + 1]
                                                   ));
                                }
                            }

                            // indices
                            int[] currIndices = new int[numIndices];
                            for (int i = 0; i < numIndices; i += 3)
                            {
                                currIndices[i + 0] = i + 2 + indexOffset;
                                currIndices[i + 1] = i + 1 + indexOffset;
                                currIndices[i + 2] = i + 0 + indexOffset;
                            }

                            if (numIndices != 0)
                            {
                                idxList.Add(currIndices);
                            }
                            curNumIndices += numIndices;
                        }

                        // Add mesh to sub-gameobject
                        Mesh unityMesh = new Mesh();
                        unityMesh.vertices     = vertexList.ToArray();
                        unityMesh.normals      = normalList.ToArray();
                        unityMesh.subMeshCount = numSubmesh;
                        for (int i = 0; i < idxList.Count; i++)
                        {
                            unityMesh.SetTriangles(idxList[i], i);
                        }

                        if (uvList.Count > 0)
                        {
                            unityMesh.uv = uvList.ToArray();
                        }

                        geomDict.Add(geom.id, unityMesh);
                        geomMatDict.Add(geom.id, subMaterials);
                    }
                }
                else if (item is library_visual_scenes)
                {
                    var visual_scenes = item as library_visual_scenes;
                    if (visual_scenes == null)
                    {
                        continue;
                    }

                    foreach (var vis in visual_scenes.visual_scene)
                    {
                        foreach (var node in vis.node)
                        {
                            if (node.instance_geometry == null)
                            {
                                continue;
                            }

                            Quaternion quat = Quaternion.identity;
                            Vector3    pos  = Vector3.zero;

                            if (node.Items != null)
                            {
                                foreach (var item2 in node.Items)
                                {
                                    var matrix = item2 as matrix;
                                    if (matrix == null)
                                    {
                                        continue;
                                    }

                                    Matrix4x4 unityMatrix = new Matrix4x4();
                                    unityMatrix.SetColumn(0, new Vector4(
                                                              (float)matrix.Values[0],
                                                              (float)matrix.Values[4],
                                                              (float)matrix.Values[8],
                                                              (float)matrix.Values[12]
                                                              ));
                                    unityMatrix.SetColumn(1, new Vector4(
                                                              (float)matrix.Values[1],
                                                              (float)matrix.Values[5],
                                                              (float)matrix.Values[9],
                                                              (float)matrix.Values[13]
                                                              ));
                                    unityMatrix.SetColumn(2, new Vector4(
                                                              (float)matrix.Values[2],
                                                              (float)matrix.Values[6],
                                                              (float)matrix.Values[10],
                                                              (float)matrix.Values[14]
                                                              ));
                                    unityMatrix.SetColumn(3, new Vector4(
                                                              (float)matrix.Values[3],
                                                              (float)matrix.Values[7],
                                                              (float)matrix.Values[11],
                                                              (float)matrix.Values[15]
                                                              ));

                                    quat = Quaternion.LookRotation(unityMatrix.GetColumn(2), unityMatrix.GetColumn(1));
                                    pos  = unityMatrix.GetColumn(3);
                                }
                            }

                            foreach (var geom in node.instance_geometry)
                            {
                                var url = geom.url.Substring(1);

                                if (geomDict.ContainsKey(url))
                                {
                                    var unityMesh = geomDict[url];

                                    // Create sub-gameobject
                                    var unitySubObj = new GameObject(geom.name);
                                    unitySubObj.AddComponent <MeshFilter>();
                                    unitySubObj.AddComponent <MeshRenderer>();
                                    unitySubObj.AddComponent <MeshCollider>();
                                    unitySubObj.GetComponent <MeshFilter>().mesh = unityMesh;

                                    // local transform
                                    unitySubObj.transform.SetParent(unityObj.transform, true);
                                    if (model.asset.up_axis == UpAxisType.Z_UP)
                                    {
                                        unitySubObj.transform.localRotation = new Quaternion(0.7071f, 0, 0, 0.7071f);
                                    }
                                    ObjectController.SetTransform(unitySubObj, pos, quat);

                                    // material
                                    var materials = geomMatDict[url];
                                    if (materials.Count > 0)
                                    {
                                        List <Material> unityMaterials = new List <Material>();
                                        foreach (var mat in materials)
                                        {
                                            if (!materialDict.ContainsKey(mat))
                                            {
                                                continue;
                                            }

                                            var eff = materialDict[mat];
                                            if (effectDict.ContainsKey(eff))
                                            {
                                                unityMaterials.Add(effectDict[eff]);
                                            }
                                        }
                                        unitySubObj.GetComponent <Renderer>().materials = unityMaterials.ToArray();
                                    }
                                }
                            }
                        }
                    }
                }
            }

            return(unityObj);
        }
示例#6
0
 public COLLADA ToCollada(string[] textures)
 {
     COLLADA result = new COLLADA
     {
         version = VersionType.Item140,
         asset = new asset
         {
             contributor = new assetContributor[] { new assetContributor() { authoring_tool = "SAModel" } },
             created = DateTime.UtcNow,
             modified = DateTime.UtcNow
         }
     };
     List<object> libraries = new List<object>();
     List<image> images = new List<image>();
     if (textures != null)
     {
         for (int i = 0; i < textures.Length; i++)
         {
             images.Add(new image
             {
                 id = "image_" + (i + 1).ToString(NumberFormatInfo.InvariantInfo),
                 name = "image_" + (i + 1).ToString(NumberFormatInfo.InvariantInfo),
                 Item = textures[i] + ".png"
             });
         }
     }
     libraries.Add(new library_images { image = images.ToArray() });
     List<material> materials = new List<material>();
     List<effect> effects = new List<effect>();
     List<geometry> geometries = new List<geometry>();
     List<string> visitedAttaches = new List<string>();
     node node = AddToCollada(materials, effects, geometries, visitedAttaches, textures != null);
     libraries.Add(new library_materials { material = materials.ToArray() });
     libraries.Add(new library_effects { effect = effects.ToArray() });
     libraries.Add(new library_geometries { geometry = geometries.ToArray() });
     libraries.Add(new library_visual_scenes
     {
         visual_scene = new visual_scene[]
         {
             new visual_scene
             {
                 id = "RootNode",
                 node = new node[] { node }
             }
         }
     });
     result.Items = libraries.ToArray();
     result.scene = new COLLADAScene { instance_visual_scene = new InstanceWithExtra { url = "#RootNode" } };
     return result;
 }
示例#7
0
    private void SaveMeshes()
    {
        COLLADA exportScene = new COLLADA();

        List<geometry> geometryList = new List<geometry>();

        //if(testMesh!= null)
        //{
        //    geometry geo = COLLADA.MeshToGeometry(testMesh);
        //    if (geo != null)
        //        geometryList.Add(geo);
        //}

        foreach (Mesh mesh in blocks)
        {
            if (mesh != null)
            {
                geometry geo = (COLLADA.MeshToGeometry(mesh));
                if (geo != null)
                    geometryList.Add(geo);
            }
        }
        foreach (Mesh mesh in stencilBlocks)
        {
            if (mesh != null)
            {
                geometry geo = (COLLADA.MeshToGeometry(mesh));
                if (geo != null)
                    geometryList.Add(geo);
            }
        }
        foreach (Mesh mesh in transparentBlocks)
        {
            if (mesh != null)
            {
                geometry geo = (COLLADA.MeshToGeometry(mesh));
                if (geo != null)
                    geometryList.Add(geo);
            }
        }
        foreach (Mesh mesh in liquidBlocks)
        {
            if (mesh != null)
            {
                geometry geo = (COLLADA.MeshToGeometry(mesh));
                if (geo != null)
                    geometryList.Add(geo);
            }
        }

        library_geometries geometryLib = new library_geometries();
        geometryLib.geometry = geometryList.ToArray();

        library_visual_scenes visualSceneLib = new library_visual_scenes();
        visual_scene visualScene = new visual_scene();

        visualSceneLib.visual_scene = new visual_scene[1];
        visualSceneLib.visual_scene[0] = visualScene;

        visualScene.id = "Map";
        visualScene.name = "Map";
        visualScene.node = new node[geometryList.Count];
        for (int i = 0; i < geometryList.Count; i++)
        {
            node thisNode = new node();
            visualScene.node[i] = thisNode;
            geometry thisGeometry = geometryList[i];
            thisNode.id = thisGeometry.id.Remove(thisGeometry.id.Length - 4);
            thisNode.name = thisGeometry.name.Remove(thisGeometry.name.Length - 6);
            thisNode.sid = thisNode.id;

            thisNode.Items = new object[1];
            thisNode.Items[0] = COLLADA.ConvertMatrix(Matrix4x4.identity);

            thisNode.instance_geometry = new instance_geometry[1];
            thisNode.instance_geometry[0] = new instance_geometry();
            thisNode.instance_geometry[0].url = "#" + thisGeometry.id;
            thisNode.ItemsElementName = new ItemsChoiceType2[1];
            thisNode.ItemsElementName[0] = ItemsChoiceType2.matrix;
        }

        COLLADAScene sceneInstance = new COLLADAScene();
        sceneInstance.instance_visual_scene = new InstanceWithExtra();
        sceneInstance.instance_visual_scene.url = "#" + visualScene.id;

        exportScene.scene = sceneInstance;

        exportScene.Items = new object[2];
        exportScene.Items[0] = geometryLib;
        exportScene.Items[1] = visualSceneLib;

        asset assetHeader = new asset();
        assetHeader.unit = new assetUnit();
        assetHeader.unit.meter = 1;
        assetHeader.unit.name = "meter";
        assetHeader.up_axis = UpAxisType.Y_UP;

        exportScene.asset = assetHeader;

        if (File.Exists("Map.dae"))
            File.Delete("Map.dae");
        exportScene.Save("Map.dae");

        Texture2D mainTex = (Texture2D)basicTerrainMaterial.GetTexture("_MainTex");

        Color[] mainTexPixels = mainTex.GetPixels();
        Color[] diffusePixels = new Color[mainTexPixels.Length];
        Color[] roughnessPixels = new Color[mainTexPixels.Length];

        for(int i = 0; i < mainTexPixels.Length; i++)
        {
            diffusePixels[i] = new Color(mainTexPixels[i].r, mainTexPixels[i].g, mainTexPixels[i].b, 1.0f);
            roughnessPixels[i] = new Color(mainTexPixels[i].a, mainTexPixels[i].a, mainTexPixels[i].a, 1.0f);
        }

        Texture2D diffuseTex = new Texture2D(mainTex.width, mainTex.height);
        Texture2D roughnessTex = new Texture2D(mainTex.width, mainTex.height);

        diffuseTex.SetPixels(diffusePixels);
        roughnessTex.SetPixels(roughnessPixels);

        diffuseTex.Apply();
        roughnessTex.Apply();

        byte[] diffuseBytes = diffuseTex.EncodeToPNG();
        byte[] roughnessBytes = roughnessTex.EncodeToPNG();

        File.WriteAllBytes("pattern.png", diffuseBytes);
        File.WriteAllBytes("specular.png", roughnessBytes);

        Texture2D bumpMap = (Texture2D)basicTerrainMaterial.GetTexture("_BumpMap");

        Color[] bumpMapPixels = bumpMap.GetPixels();
        Color[] normalMapPixels = new Color[bumpMapPixels.Length];
        Color[] ambientMapPixels = new Color[bumpMapPixels.Length];
        Color[] alphaMapPixels = new Color[bumpMapPixels.Length];

        for (int i = 0; i < bumpMapPixels.Length; i++)
        {
            normalMapPixels[i] = new Color(bumpMapPixels[i].a, bumpMapPixels[i].g, Mathf.Sqrt(1 - ((bumpMapPixels[i].a * 2 - 1) * (bumpMapPixels[i].a * 2 - 1)) + ((bumpMapPixels[i].g * 2 - 1) * (bumpMapPixels[i].g * 2 - 1))));
            ambientMapPixels[i] = new Color(bumpMapPixels[i].r, bumpMapPixels[i].r, bumpMapPixels[i].r, 1.0f);
            alphaMapPixels[i] = new Color(bumpMapPixels[i].b, bumpMapPixels[i].b, bumpMapPixels[i].b, 1.0f);
        }

        Texture2D normalTex = new Texture2D(bumpMap.width, bumpMap.height);
        Texture2D ambientTex = new Texture2D(bumpMap.width, bumpMap.height);
        Texture2D alphaTex = new Texture2D(bumpMap.width, bumpMap.height);

        normalTex.SetPixels(normalMapPixels);
        ambientTex.SetPixels(ambientMapPixels);
        alphaTex.SetPixels(alphaMapPixels);

        normalTex.Apply();
        ambientTex.Apply();
        alphaTex.Apply();

        byte[] normalBytes = normalTex.EncodeToPNG();
        byte[] ambientBytes = ambientTex.EncodeToPNG();
        byte[] alphaBytes = alphaTex.EncodeToPNG();

        File.WriteAllBytes("normal.png", normalBytes);
        File.WriteAllBytes("occlusion.png", ambientBytes);
        File.WriteAllBytes("alpha.png", alphaBytes);

        Debug.Log("Saved map!");
    }