Пример #1
0
        public CADComponent(CyPhy.Component cyphycomp, string ProjectDirectory, bool size2fit = false, string format = "Creo")
        {
            Type = CADDataType.Component;
            StructuralInterfaceNodes = new Dictionary<string, StructuralInterfaceConstraint>();
            DisplayID = cyphycomp.Attributes.InstanceGUID;
            Id = cyphycomp.ID;
            GraphvizID = UtilityHelpers.CleanString2(cyphycomp.ID, 50, "-");
            AVMID = cyphycomp.Attributes.AVMID;
            RevID = "";
            VersionID = cyphycomp.Attributes.Version;
            CADFormat = format;
            Name = cyphycomp.Name;
            CadParameters = new List<CADParameter>();
            ModelType = "Part";
            Size2Fit = size2fit;
            MaterialName = "";
            CyPhyModelPath = cyphycomp.GetDirectoryPath(ProjectDirectory: ProjectDirectory);
            Classification = cyphycomp.Attributes.Classifications;
            HyperLink = cyphycomp.ToHyperLink();

            CreateStructuralInterfaceEquivalent(cyphycomp);

            AddManufacturingParameters(cyphycomp);

            var specialinstr = cyphycomp.Children.ParameterCollection.Where(p => p.Name.ToUpper() == SpecialInstrParamStr);
            if (specialinstr.Any())
            {
                SpecialInstructions = specialinstr.First().Attributes.Value.Replace("\"", "");
            }

            // META-3555 hack
            if (cyphycomp.Children.CADModelCollection.Any())
            {
                foreach (var datum in cyphycomp.Children.CADModelCollection.First().Children.CADDatumCollection)
                {
                    if (datum.Name == "FRONT" || datum.Name == "TOP" || datum.Name == "RIGHT")
                    {
                        SpecialDatums.Add(new Datum(datum, "", false));
                    }
                }
            }

            foreach (var prop in cyphycomp.Children.PropertyCollection)
            {
                if (prop.Name.StartsWith("METADATA."))
                {
                    MetaData.Add(prop.Name.Substring(9), prop.Attributes.Value);
                }
            }
        }
        private bool FindMatchingDatums(CyPhy.CADDatum datum,
                                        CyPhy.CADModel cadmodel,
                                        Dictionary<string, DataRep.Datum> featuremap)
        {
            string cadmodel_id = cadmodel.ID;
            string alignment = "ALIGN";
            string orientation = "NONE";


            if (datum.Kind == "Surface")
            {
                alignment = (datum as CyPhy.Surface).Attributes.Alignment.ToString();
                if (alignment=="MATE")
                    Logger.Instance.AddLogMessage("MATE alignment is used on surface: " + datum.ToHyperLink() + ". This construct is obsolete, please set up the connection as ALIGN.", Severity.Warning);
            }

            CadDatumTraversal traversal = new CadDatumTraversal(datum,
                                                                cadmodel_id);

            if (traversal.datumFound.Count > 0)
            {
                if (traversal.datumFound.Count > 1)
                {
                    Logger.Instance.AddLogMessage("Connector datum connected to multiple datums in the same CADModel [" + datum.Path + "]", Severity.Error);
                    return true; // Error
                }

                // META-3232
                /*
                DataRep.Datum datumRep = new DataRep.Datum(traversal.datumFound.First().Attributes.DatumName,
                                                           datum.Kind,
                                                           this.ParentInstanceGUID, guide);
                */
                bool guide = datum.Attributes.DefinitionNotes.Contains("GUIDE");
                if (guide)
                {
                    Logger.Instance.AddLogMessage("Datum is using old guide format. Please use the attribute 'IsGuide'. [" + datum.Path + "]", Severity.Error);
                    return true; // Error
                }
                guide |= datum.Attributes.IsGuide;
                DataRep.Datum datumRep = new DataRep.Datum(traversal.datumFound.First(),
                                                           this.ParentInstanceGUID, guide);

                if (datum.Kind == "Surface")
                {
                    if (traversal.ReverseMap)
                        orientation = "SIDE_B";
                    else
                        orientation = "SIDE_A";
                }

                if (datum.Kind == "CoordinateSystem")
                {
                    alignment = "CSYS";
                }

                datumRep.Alignment = alignment;
                datumRep.Orientation = orientation;

                if (!featuremap.ContainsKey(datum.Name))
                {
                    featuremap[datum.Name] = datumRep;
                }
            }

            return false;
        }
Пример #3
0
        private static bool AddFace(CyPhy.Face face, List<KeyValuePair<string, string>> featureList, out CADGeometry.FeatureTypeEnum type)
        {
            int ptCnt = face.Children.PointCollection.Count(),
                surfCnt = face.Children.SurfaceCollection.Count();

            type = CADGeometry.FeatureTypeEnum.POINT;
            if ((ptCnt + surfCnt) > 1)
            {
                // insert error message
                Logger.Instance.AddLogMessage(String.Format("Face geometry must contain a ReferencePoint or a ReferenceSurface: {0}", face.ToHyperLink()), Severity.Error);
                return false;
            }

            if (ptCnt > 0)          // Plane
            {
                type = CADGeometry.FeatureTypeEnum.POINT;
                CyPhy.Point point = face.Children.PointCollection.First();
                if (CreateFeatureFromPoint(point,
                                           featureList))
                    return true;
                else
                {
                    Logger.Instance.AddLogMessage(String.Format("Face geometry's ReferencePoint must connect to a Point datum inside a CADModel: {0}", face.ToHyperLink()), Severity.Error);
                    return false;
                }

            }

            if (surfCnt > 0)        // Surface
            {
                type = CADGeometry.FeatureTypeEnum.SURFACE;
                CyPhy.Surface surface = face.Children.SurfaceCollection.First();
                if (CreateFeatureFromPoint(surface,
                                           featureList))
                    return true;
                else
                {
                    Logger.Instance.AddLogMessage(String.Format("Face geometry's ReferenceSurface must connect to a Surface datum inside a CADModel: {0}", face.ToHyperLink()), Severity.Error);
                    return false;
                }
            }

            return false;

        }
 private void WarnUserAboutMissingFiles(CyPhy.Component component)
 {
     Logger.WriteWarning(string.Format(@"Warning: copied component {0} contains resource children, but
                                         its path is empty or invalid; its backing files are likely
                                         missing and should be copied manually.", component.ToHyperLink()));
 }
Пример #5
0
        private static bool AddPolygon(CyPhy.Polygon polygon, List<KeyValuePair<string, string>> featureList)
        {
            bool status = true;
            List<CyPhy.OrdinalPoint> ordinalPt = polygon.Children.OrdinalPointCollection.OrderBy(x => x.Attributes.PolygonOrdinalPosition).ToList();
            if (ordinalPt.Count < 3)
                return false;

            foreach (var item in ordinalPt)
            {
                if (!CreateFeatureFromPoint(item,
                                       featureList))
                {
                    Logger.Instance.AddLogMessage(String.Format("Polygon geometry's OrdinalPoint must connect to a Point datum inside a CADModel: {0}", polygon.ToHyperLink()), Severity.Error);
                    return false;
                }
            }

            return status;
        }
Пример #6
0
        private static bool AddExtrusion(CyPhy.Extrusion extrusion, List<KeyValuePair<string, string>> featureList)           // only extrusion with polygon is supported
        {
            if (extrusion.Children.PolygonCollection.Any())
            {
                CyPhy.Polygon polygon = extrusion.Children.PolygonCollection.FirstOrDefault();
                if (polygon != null)
                {
                    AddPolygon(polygon,
                               featureList);
                    List<MgaFCO> height = FindByRole((extrusion.Impl as MgaModel), "ExtrusionHeight");
                    if (height.Count < 1)
                    {
                        Logger.Instance.AddLogMessage(String.Format("Extrusion geometry must contain exactly 1 ExtrusionHeight point: {0}", extrusion.ToHyperLink()), Severity.Error);
                        return false;
                    }

                    CyPhy.Point offset = CyPhyClasses.Point.Cast(height[0]);
                    if (CreateFeatureFromPoint(offset,
                                           featureList))
                        return true;
                    else
                    {
                        Logger.Instance.AddLogMessage(String.Format("Extrusion geometry's ExtrusionHeight must connect to a Point datum inside a CADModel: {0}", extrusion.ToHyperLink()), Severity.Error);
                        return false;
                    }
                }
            }

            return false;
        }
Пример #7
0
        private static bool AddSphere(CyPhy.Sphere sphere, List<KeyValuePair<string, string>> featureList)
        {
            List<MgaFCO> centerPts = new List<MgaFCO>();
            centerPts = FindByRole((sphere.Impl as MgaModel), "SphereCenter");
            List<MgaFCO> edgePts = new List<MgaFCO>();
            edgePts = FindByRole((sphere.Impl as MgaModel), "SphereEdge");

            if (centerPts.Count != 1 || edgePts.Count != 1)
            {
                Logger.Instance.AddLogMessage(String.Format("Sphere geometry must contain 1 SphereEdge and 1 SphereCenter: {0}", sphere.ToHyperLink()), Severity.Error);
                return false;
            }

            CyPhy.Point centerPt = CyPhyClasses.Point.Cast(centerPts[0]);
            if (!CreateFeatureFromPoint(centerPt,
                                   featureList))
            {
                Logger.Instance.AddLogMessage(String.Format("Sphere geometry's SphereCenter point must connect to a Point datum inside a CADModel: {0}", sphere.ToHyperLink()), Severity.Error);
                return false;
            }

            CyPhy.Point edge = CyPhyClasses.Point.Cast(edgePts[0]);
            if (!CreateFeatureFromPoint(edge,
                                   featureList))
            {
                Logger.Instance.AddLogMessage(String.Format("Sphere geometry's SphereEdge point must connect to a Point datum inside a CADModel: {0}", sphere.ToHyperLink()), Severity.Error);
                return false;
            }

            return true;
        }
Пример #8
0
        private static bool AddCircle(CyPhy.Circle circle, List<KeyValuePair<string, string>> featureList)
        {
            bool status = true;

            List<MgaFCO> edgePts = new List<MgaFCO>();
            edgePts = FindByRole((circle.Impl as MgaModel), "CircleEdge");
            List<MgaFCO> centerPts = new List<MgaFCO>();
            centerPts = FindByRole((circle.Impl as MgaModel), "CircleCenter");

            if (centerPts.Count != 1 || edgePts.Count != 2)
            {
                Logger.Instance.AddLogMessage(String.Format("Circle geometry must contain 2 CircleEdge and 1 CircleCenter points: {0}", circle.ToHyperLink()), Severity.Error);
                return false;
            }


            CyPhy.Point centerPt = CyPhyClasses.Point.Cast(centerPts[0]);
            CyPhy.Point edge1 = CyPhyClasses.Point.Cast(edgePts[0]);
            CyPhy.Point edge2 = CyPhyClasses.Point.Cast(edgePts[1]);

            // Should be checked
            /*if (edge1.Guid.Equals(edge2.Guid))
            {
                Logger.Instance.AddLogMessage(String.Format("Circle is defined by equivalend edge points. These 2 points must be different to be able to identify a plane: {0}", circle.ToHyperLink()), Severity.Error);
                return false;
            }*/

            if (!CreateFeatureFromPoint(centerPt,
                                   featureList))
            {
                Logger.Instance.AddLogMessage(String.Format("Circle geometry's CircleCenter point must connect to a Point datum inside a CADModel: {0}", circle.ToHyperLink()), Severity.Error);
                return false;
            }
            if (!CreateFeatureFromPoint(edge1,
                                   featureList))
            {
                Logger.Instance.AddLogMessage(String.Format("Circle geometry's CircleEdge point must connect to a Point datum inside a CADModel: {0}", circle.ToHyperLink()), Severity.Error);
                return false;
            }

            if (!CreateFeatureFromPoint(edge2,
                                   featureList))
            {
                Logger.Instance.AddLogMessage(String.Format("Circle geometry's CircleEdge point must connect to a Point datum inside a CADModel: {0}", circle.ToHyperLink()), Severity.Error);
                return false;
            }

            return status;
        }
Пример #9
0
        private static bool AddCylinder(CyPhy.Cylinder cylinder,
                                 List<KeyValuePair<string, string>> featureList)
        {
            bool status = true;
            if (cylinder != null)
            {
                // start, end, radius
                MgaModel cylinderMga = cylinder.Impl as MgaModel;
                List<MgaFCO> startPts = new List<MgaFCO>();
                startPts = FindByRole(cylinderMga, "CylinderStart");
                List<MgaFCO> endPts = new List<MgaFCO>();
                endPts = FindByRole(cylinderMga, "CylinderEnd");
                List<MgaFCO> radiusPts = new List<MgaFCO>();
                radiusPts = FindByRole(cylinderMga, "CylinderRadius");

                if (startPts.Count != 1 || endPts.Count != 1 || radiusPts.Count != 1)
                {
                    Logger.Instance.AddLogMessage(String.Format("Cylinder geometry must contain 1 CylinderStart, 1 CylinderEnd, and 1 CylinderRadius: {0}", cylinder.ToHyperLink()), Severity.Error);
                    return false;
                }

                CyPhy.Point startPt = CyPhyClasses.Point.Cast(startPts[0]);
                if (!CreateFeatureFromPoint(startPt,
                                       featureList))
                {
                    Logger.Instance.AddLogMessage(String.Format("Cylinder geometry's CylinderStart point must connect to a Point datum inside a CADModel: {0}", cylinder.ToHyperLink()), Severity.Error);
                    return false;
                }
                CyPhy.Point endPt = CyPhyClasses.Point.Cast(endPts[0]);
                if (!CreateFeatureFromPoint(endPt,
                                       featureList))
                {
                    Logger.Instance.AddLogMessage(String.Format("Cylinder geometry's CylinderEnd point must connect to a Point datum inside a CADModel: {0}", cylinder.ToHyperLink()), Severity.Error);
                    return false;
                }
                CyPhy.Point radiusPt = CyPhyClasses.Point.Cast(radiusPts[0]);
                if (!CreateFeatureFromPoint(radiusPt,
                                       featureList))
                {
                    Logger.Instance.AddLogMessage(String.Format("Cylinder geometry's CylinderRadius point must connect to a Point datum inside a CADModel: {0}", cylinder.ToHyperLink()), Severity.Error);
                    return false;
                }
            }
            else
                status = false;

            //var height = (extrusion.Impl as MgaModel).ChildFCOs.Cast<MgaFCO>().Where(x => x.MetaRole.Name == "ExtrusionHeight").FirstOrDefault();

            return status;
        }
        private bool CallCyberInterpreter(CyPhy.CyberModel cyberModel)
        {
            bool success = true;

            string cyberModelPath = string.Empty;

            // checks
            if (string.IsNullOrWhiteSpace(cyberModel.Attributes.FileRef))
            {
                this.Logger.WriteError("[Cyber] Model filename attribute is empty: {0}", cyberModel.ToHyperLink());
                return false;
            }

            if (Path.IsPathRooted(cyberModel.Attributes.FileRef))
            {
                cyberModelPath = cyberModel.Attributes.FileRef;
            }
            else
            {
                cyberModelPath = Path.Combine(this.mainParameters.ProjectDirectory, cyberModel.Attributes.FileRef);
            }

            string cyberModelMgaPath = string.Empty;
            string cyberModelXmePath = string.Empty;
            bool requiresImport = false;

            cyberModelMgaPath = Path.GetFileNameWithoutExtension(cyberModelPath) + ".mga";
            cyberModelXmePath = Path.GetFileNameWithoutExtension(cyberModelPath) + ".xme";

            if (Path.GetExtension(cyberModelPath) == ".mga")
            {
                if (File.Exists(cyberModelMgaPath) == false)
                {
                    requiresImport = true;
                    if (File.Exists(cyberModelXmePath) == false)
                    {
                        this.Logger.WriteError("[Cyber] Model filename does not exist: {0} {1}", cyberModel.ToHyperLink(), cyberModelPath);
                        return false;
                    }
                }
            }
            else if (Path.GetExtension(cyberModelPath) == ".xme")
            {
                requiresImport = true;
                if (File.Exists(cyberModelXmePath) == false)
                {
                    this.Logger.WriteError("[Cyber] Model filename does not exist: {0} {1}", cyberModel.ToHyperLink(), cyberModelPath);
                    return false;
                }
            }
            else
            {
                this.Logger.WriteError("[Cyber] Model filename attribute has unknown extension (valid: [mga|xme]): {0} {1}", cyberModel.ToHyperLink(), Path.GetExtension(cyberModelPath));
                return false;
            }

            MgaProject cyberProject = new MgaProject();

            if (requiresImport)
            {
                // FIXME: this will throw an exception if xme is referenced mga exists and it is being used.
                MgaUtils.ImportXME(cyberModelXmePath, cyberModelMgaPath);
            }

            try
            {
                bool ro_mode;

                // FIXME: any race conditions here???
                // FIXME: for SoT we need to copy the referenced xme/mgas
                cyberProject.Open("MGA=" + cyberModelMgaPath, out ro_mode);
                string cyberComponentPath = "";

                if (cyberModel.Attributes.FilePathWithinResource.Contains('.'))
                {
                    cyberComponentPath = cyberModel.Attributes.FilePathWithinResource.Substring(cyberModel.Attributes.FilePathWithinResource.IndexOf('.')).Replace(".", "/@");
                }

                this.Logger.WriteInfo("[Cyber] {0} --> {1}", cyberModel.Attributes.FilePathWithinResource, cyberComponentPath);

                var terr = cyberProject.BeginTransactionInNewTerr();

                MgaFCO currentObj = cyberProject.ObjectByPath[cyberComponentPath] as MgaFCO;

                cyberProject.AbortTransaction();
                terr.Destroy();

                if (currentObj == null)
                {
                    this.Logger.WriteError("[Cyber] Referenced cyber object was not found in model: {0} {1} {2}", cyberModel.ToHyperLink(), cyberModelPath, cyberModel.Attributes.FilePathWithinResource);
                    return false;
                }

                // Cyber model type and interpreter progid map. Each cyber model type has a different interpreter.
                Dictionary<CyPhyClasses.CyberModel.AttributesClass.ModelType_enum, string> interpreterMap =
                    new Dictionary<CyPhyClasses.CyberModel.AttributesClass.ModelType_enum, string>()
                {
                    //{ CyPhyClasses.CyberModel.AttributesClass.ModelType_enum.ESMoL, ""},
                    //{ CyPhyClasses.CyberModel.AttributesClass.ModelType_enum.SignalFlow, ""},
                    { CyPhyClasses.CyberModel.AttributesClass.ModelType_enum.Simulink, "MGA.Interpreter.Cyber2SLC_CodeGen" }
                };
                // call appropriate Cyber interpreter
                Type tCyber = Type.GetTypeFromProgID(interpreterMap[cyberModel.Attributes.ModelType]);
                if (tCyber == null)
                {
                    this.Logger.WriteError("[Cyber] Cannot instantiate Cyber interpreter: {0} {1}", cyberModel.ToHyperLink(), interpreterMap[cyberModel.Attributes.ModelType]);
                }
                IMgaComponentEx cyberCodeGenerator = Activator.CreateInstance(tCyber) as IMgaComponentEx;

                cyberCodeGenerator.Initialize(cyberProject);
                var cyberOutputDir = Path.Combine(this.mainParameters.OutputDirectory, Modelica.CodeGenerator.MainPackage);
                Directory.CreateDirectory(cyberOutputDir);
                cyberCodeGenerator.ComponentParameter["output_dir"] = cyberOutputDir;
                cyberCodeGenerator.ComponentParameter["automation"] = "true";
                cyberCodeGenerator.ComponentParameter["console_messages"] = "off";
                this.Logger.WriteInfo("Generating code for Cyber [{0}] elements...", cyberModel.Attributes.ModelType);
                System.Windows.Forms.Application.DoEvents();
                MgaFCOs selectedobjs = (MgaFCOs)Activator.CreateInstance(Type.GetTypeFromProgID("Mga.MgaFCOs"));
                cyberCodeGenerator.InvokeEx(cyberProject, currentObj, selectedobjs, 128);
                this.Logger.WriteInfo("Cyber [{0}] code generation is done.", cyberModel.Attributes.ModelType);
                System.Windows.Forms.Application.DoEvents();
            }
            catch (Exception ex)
            {
                this.Logger.WriteError("Cyber exception occured: {0}", ex);

                success = false;
            }

            return success;
        }
Пример #11
0
        private bool CallCyberInterpreter(CyPhy.CyberModel cyberModel)
        {
            bool success = true;

            string cyberModelPath = string.Empty; 

            // get the path to the cyber model file
            // first, the right way (using resources)
            CyPhy.UsesResource uses_conn = null;
            CyPhy.Resource res = null;

            CyPhy.Component parent_comp = cyberModel.ParentContainer as CyPhy.Component;

            if (cyberModel.SrcConnections.UsesResourceCollection != null
                && cyberModel.SrcConnections.UsesResourceCollection.Count() != 0)
            {
                uses_conn = cyberModel.SrcConnections.UsesResourceCollection.First();
                res = uses_conn.SrcEnd as CyPhy.Resource;
            }
            else if (cyberModel.DstConnections.UsesResourceCollection != null
                      && cyberModel.DstConnections.UsesResourceCollection.Count() != 0)
            {
                uses_conn = cyberModel.DstConnections.UsesResourceCollection.First();
                res = uses_conn.DstEnd as CyPhy.Resource;
            }

            if (res != null)
            {
                cyberModelPath = Path.Combine(parent_comp.Attributes.Path, res.Attributes.Path);
            }
            else
            {
                uses_conn = null;
            }
            
            if (uses_conn == null)
            {

                // failing that, do it the wrong way by getting the fileref attribute value

                // checks
                if (string.IsNullOrWhiteSpace(cyberModel.Attributes.FileRef))
                {
                    this.Logger.WriteError("[Cyber] Model filename attribute is empty: {0}", cyberModel.ToHyperLink());
                    return false;
                }

                if (Path.IsPathRooted(cyberModel.Attributes.FileRef))
                {
                    cyberModelPath = cyberModel.Attributes.FileRef;
                }
                else
                {
                    cyberModelPath = Path.Combine(this.mainParameters.ProjectDirectory, cyberModel.Attributes.FileRef);
                }
            }

            string cyberModelMgaPath = string.Empty;
            string cyberModelXmePath = string.Empty;
            bool requiresImport = false;

            cyberModelMgaPath = Path.GetFileNameWithoutExtension(cyberModelPath) + ".mga";
            cyberModelXmePath = Path.GetFileNameWithoutExtension(cyberModelPath) + ".xme";

            if (Path.GetExtension(cyberModelPath) == ".mga")
            {
                if (File.Exists(cyberModelMgaPath) == false)
                {
                    requiresImport = true;
                    if (File.Exists(cyberModelXmePath) == false)
                    {
                        this.Logger.WriteError("[Cyber] Model filename does not exist: {0} {1}", cyberModel.ToHyperLink(), cyberModelPath);
                        return false;
                    }
                }
            }
            else if (Path.GetExtension(cyberModelPath) == ".xme")
            {
                requiresImport = true;
                if (File.Exists(cyberModelXmePath) == false)
                {
                    this.Logger.WriteError("[Cyber] Model filename does not exist: {0} {1}", cyberModel.ToHyperLink(), cyberModelPath);
                    return false;
                }
            }
            else
            {
                this.Logger.WriteError("[Cyber] Model filename attribute has unknown extension (valid: [mga|xme]): {0} {1}", cyberModel.ToHyperLink(), Path.GetExtension(cyberModelPath));
                return false;
            }

            MgaProject cyberProject = new MgaProject();

            if (requiresImport)
            {
                // FIXME: this will throw an exception if xme-referenced mga exists and it is being used.
                MgaUtils.ImportXME(cyberModelXmePath, cyberModelMgaPath);
            }

            try
            {
                bool ro_mode;

                // FIXME: any race conditions here???
                // FIXME: for SoT we need to copy the referenced xme/mgas
                cyberProject.Open("MGA=" + cyberModelMgaPath, out ro_mode);
                string cyberComponentPath = "";

                if (cyberModel.Attributes.FilePathWithinResource.Contains('.'))
                {
                    cyberComponentPath = cyberModel.Attributes.FilePathWithinResource.Substring(cyberModel.Attributes.FilePathWithinResource.IndexOf('.')).Replace(".", "/@");
                }

                this.Logger.WriteInfo("[Cyber] {0} --> {1}", cyberModel.Attributes.FilePathWithinResource, cyberComponentPath);

                var terr = cyberProject.BeginTransactionInNewTerr();

                MgaFCO currentObj = cyberProject.ObjectByPath[cyberComponentPath] as MgaFCO;

                cyberProject.AbortTransaction();
                terr.Destroy();

                if (currentObj == null)
                {
                    this.Logger.WriteError("[Cyber] Referenced cyber object was not found in model: {0} {1} {2}", cyberModel.ToHyperLink(), cyberModelPath, cyberModel.Attributes.FilePathWithinResource);
                    return false;
                }

                // Cyber model type and interpreter progid map. Each cyber model type has a different interpreter.
                Dictionary<CyPhyClasses.CyberModel.AttributesClass.ModelType_enum, string> interpreterMap =
                    new Dictionary<CyPhyClasses.CyberModel.AttributesClass.ModelType_enum, string>()
                {
                    //{ CyPhyClasses.CyberModel.AttributesClass.ModelType_enum.ESMoL, ""},
                    //{ CyPhyClasses.CyberModel.AttributesClass.ModelType_enum.SignalFlow, ""},
                    { CyPhyClasses.CyberModel.AttributesClass.ModelType_enum.Simulink, "MGA.Interpreter.Cyber2SLC_CodeGen" }
                };
                // call appropriate Cyber interpreter
                Type tCyber = Type.GetTypeFromProgID(interpreterMap[cyberModel.Attributes.ModelType]);
                if (tCyber == null)
                {
                    this.Logger.WriteError("[Cyber] Cannot instantiate Cyber interpreter: {0} {1}", cyberModel.ToHyperLink(), interpreterMap[cyberModel.Attributes.ModelType]);
                }
                IMgaComponentEx cyberCodeGenerator = Activator.CreateInstance(tCyber) as IMgaComponentEx;

                cyberCodeGenerator.Initialize(cyberProject);
                string cyberOutputDir = Path.Combine(this.mainParameters.OutputDirectory, Modelica.CodeGenerator.MainPackage);
                Directory.CreateDirectory(cyberOutputDir);
                cyberCodeGenerator.ComponentParameter["output_dir"] = cyberOutputDir;
                cyberCodeGenerator.ComponentParameter["automation"] = "true";
                cyberCodeGenerator.ComponentParameter["console_messages"] = "off";
                this.Logger.WriteInfo("Generating code for Cyber [{0}] elements... to directory {1}", cyberModel.Attributes.ModelType, cyberOutputDir);
                System.Windows.Forms.Application.DoEvents();
                MgaFCOs selectedobjs = (MgaFCOs)Activator.CreateInstance(Type.GetTypeFromProgID("Mga.MgaFCOs"));
                cyberCodeGenerator.InvokeEx(cyberProject, currentObj, selectedobjs, 128);
                this.Logger.WriteInfo("Cyber [{0}] code generation is done.", cyberModel.Attributes.ModelType);
                System.Windows.Forms.Application.DoEvents();

                // Copy files referred by resource objects
                string cyber_manifest_filename = parent_comp.Name + ".cyber.json";
                Dictionary<string, string> comp_resources = new Dictionary<string, string>();
                foreach (CyPhy.Resource resource in parent_comp.Children.ResourceCollection)
                {
                    FileInfo resource_path = new FileInfo(Path.Combine(parent_comp.Attributes.Path, resource.Attributes.Path));
                    string final_path;

                    if (resource_path.DirectoryName == null || resource_path.DirectoryName == string.Empty)
                    {
                        final_path = "Cyber";
                    }
                    else
                    {
                        final_path = resource_path.DirectoryName.Split(Path.DirectorySeparatorChar).Last();
                    }
                    //DirectoryInfo resource_directory = resource_path.Directory;

                    //string res_path = Path.Combine(cyberModel.Path, resource.Attributes.Path);
                    //string[] path_parts = res_path.Split('\\');
                    //string[] path_only = path_parts.Take(path_parts.Length - 1).ToArray();
                    
                    string new_path = Path.Combine( cyberOutputDir, final_path );
                    Logger.WriteInfo("[Cyber] resource_path.DirectoryName == string.Empty, new_path is {0}", new_path);
                    
                    System.IO.Directory.CreateDirectory(new_path);
                    string dest_filename = Path.Combine(new_path, resource_path.Name);
                    Logger.WriteInfo("[Cyber] dest_filename is {0}", dest_filename);
                    // TODO: Little bit hacky hard-coding the wait time
                    //int counter = 0;
                    //while ((IsFileReady(resource_path.FullName) != true)) && (counter < 10))
                    //{
                    //    System.Threading.Thread.Sleep(2000);
                    //    counter++;
                    //}

                    if (IsFileReady(resource_path.FullName) == true)
                    {
                        Logger.WriteInfo("[Cyber] copying file {0} to file {1}", resource_path.FullName, dest_filename);
                        System.IO.File.Copy(resource_path.FullName, dest_filename, true);
                        comp_resources[resource.Attributes.ID] = Path.Combine(final_path, resource_path.Name );
                    }
                    else
                    {
                        Logger.WriteError("[Cyber] Cannot access file for copying: {0}", dest_filename);
                    }
                    
                }

                string json_resources = Newtonsoft.Json.JsonConvert.SerializeObject(comp_resources);
                System.IO.File.WriteAllText(Path.Combine(cyberOutputDir, cyber_manifest_filename), json_resources);
            }
            catch (Exception ex)
            {
                this.Logger.WriteError("Cyber exception occured: {0}", ex);

                success = false;
            }

            return success;
        }