/// <summary> /// Converts an Ifc File to xBIM if it does not already exists, then converts the geoemtry to Xbim format and profiles the results /// </summary> /// <param name="args"> file[.ifc, xbim]</param> static void Main(string[] args) { if (args.Length < 1) { Console.WriteLine("No Ifc or xBim file specified"); return; } var fileName = args[0]; var mainStopWatch = new Stopwatch(); mainStopWatch.Start(); using (var model = GetModel(fileName)) { if (model != null) { var functionStack = new ConcurrentStack <Tuple <string, double> >(); ReportProgressDelegate progDelegate = delegate(int percentProgress, object userState) { if (percentProgress == -1) { functionStack.Push(new Tuple <string, double>(userState.ToString(), DateTime.Now.TimeOfDay.TotalMilliseconds)); Logger.InfoFormat("Entering - {0}", userState.ToString()); } else if (percentProgress == 101) { Tuple <string, double> func; if (functionStack.TryPop(out func)) { Logger.InfoFormat("Complete in \t\t{0:0.0} ms", DateTime.Now.TimeOfDay.TotalMilliseconds - func.Item2); } } }; var context = new Xbim3DModelContext(model); context.CreateContext(geomStorageType: XbimGeometryType.PolyhedronBinary, progDelegate: progDelegate); mainStopWatch.Stop(); Logger.InfoFormat("Xbim total Compile Time \t\t{0:0.0} ms", mainStopWatch.ElapsedMilliseconds); var wexBimFilename = Path.ChangeExtension(fileName, "wexBIM"); using (var wexBiMfile = new FileStream(wexBimFilename, FileMode.Create, FileAccess.Write)) { using (var wexBimBinaryWriter = new BinaryWriter(wexBiMfile)) { var stopWatch = new Stopwatch(); Logger.InfoFormat("Entering - Create wexBIM"); stopWatch.Start(); context.Write(wexBimBinaryWriter); stopWatch.Stop(); Logger.InfoFormat("Complete - in \t\t{0:0.0} ms", stopWatch.ElapsedMilliseconds); wexBimBinaryWriter.Close(); } wexBiMfile.Close(); } model.Close(); } } Console.WriteLine("Press any key to exit"); Console.Read(); }
/// <summary> /// Set delegate constructor /// </summary> /// <param name="progressFun">Function to pass to delegate</param> public ProgressReporter(ReportProgressDelegate progressFun) : base() { if (progressFun != null) { Progress = progressFun; } }
/// <summary> /// Compresses the directory. /// </summary> /// <param name="dirPath">The dir path.</param> /// <param name="zipFilePath">The zip file path.</param> /// <param name="progress">The progress.</param> public void CompressDirectory(string dirPath, string zipFilePath, ReportProgressDelegate progress) { var files = Directory.GetFiles(dirPath, "*.*", SearchOption.AllDirectories); var dirLen = dirPath[dirPath.Length - 1] == Path.DirectorySeparatorChar ? dirPath.Length : dirPath.Length + 1; using (var outFile = new FileStream(zipFilePath, FileMode.Create, FileAccess.Write, FileShare.None)) { using (var str = new GZipStream(outFile, CompressionMode.Compress)) { foreach (var file in files) { if (progress != null) { var cancel = progress(0, null); if (cancel) { return; } } var relativePath = file.Substring(dirLen); CompressFile(dirPath, relativePath, true, str, progress); } } outFile.Flush(); } }
public override void Persist(IModel model, string fileName, ReportProgressDelegate progDelegate = null) { if (model is EsentModel esentModel) { var fullSourcePath = Path.GetFullPath(esentModel.DatabaseName); var fullTargetPath = Path.GetFullPath(fileName); if (string.Compare(fullSourcePath, fullTargetPath, StringComparison.OrdinalIgnoreCase) == 0) { return; // do nothing - don't save on top of self } } else { throw new ArgumentOutOfRangeException("EsentModelProvider only supports EsentModel"); } // Create a new Esent model for this Model => Model copy var factory = GetFactory(model.SchemaVersion); using (var esentDb = new EsentModel(factory)) { esentDb.CreateFrom(model, fileName, progDelegate); esentDb.Close(); } }
/// <summary> /// Opens the model from STEP21 file. /// </summary> /// <param name="stream">Path to the file</param> /// <param name="streamSize"></param> /// <param name="progDelegate"></param> /// <param name="ignoreTypes">Types to ignore</param> /// <returns>Number of errors in parsing. Always check this to be null or the model might be incomplete.</returns> public virtual int LoadStep21(Stream stream, long streamSize, ReportProgressDelegate progDelegate = null, IEnumerable <string> ignoreTypes = null) { var parser = new XbimP21Scanner(stream, streamSize, ignoreTypes) { AllowMissingReferences = AllowMissingReferences }; if (progDelegate != null) { parser.ProgressStatus += progDelegate; } try { return(LoadStep21(parser)); } catch { throw; } finally { if (progDelegate != null) { parser.ProgressStatus -= progDelegate; } } }
public virtual void SaveAsXml(Stream stream, XmlWriterSettings xmlSettings, XbimXmlSettings xbimSettings = null, configuration configuration = null, ReportProgressDelegate progress = null) { var schema = Header.FileSchema.Schemas.FirstOrDefault(); using (var xmlWriter = XmlWriter.Create(stream, xmlSettings)) { switch (SchemaVersion) { case XbimSchemaVersion.Ifc2X3: var writer3 = new IfcXmlWriter3(); writer3.Write(this, xmlWriter, GetXmlOrderedEntities(schema)); break; case XbimSchemaVersion.Ifc4: var writer4 = new XbimXmlWriter4(XbimXmlSettings.IFC4Add2); writer4.Write(this, xmlWriter, GetXmlOrderedEntities(schema)); break; default: if (xbimSettings == null) { Logger.LogWarning("No xbimsettings set. Defaulting to Ifc4 Add2"); xbimSettings = XbimXmlSettings.IFC4Add2; } var writer = new XbimXmlWriter4(xbimSettings); writer.Write(this, xmlWriter); break; } } }
public void Init(SimulationContext context, List<User> users, ReportProgressDelegate reporter) { List<User> ulRsrpFailUserList; List<User> dlRsrpFailUserList; ICommonChannelMeasure measure = context.ProcessorFactory.BuildCommonChannelMeasure(); ITotalLossMatrix matrix = context.ProcessorFactory.BuildTotalLossMatrix(context.SimulationInfo.SubSysInterface, context.SimulationInfo.Coefficientabc); List<ISimulationUser> userList = this.InitSimulationUser(users); context.DataManager.SimulationUserList = userList; context.DataManager.UlUserNum = 0; context.DataManager.DlUserNum = 0; foreach (SimulationUser user in userList) { this.InitUserState(user, context.DataManager); } matrix.InitUserTotalLossList(userList, context.DataManager.SimulationCarrierList, reporter); context.ProcessorFactory.BuildBestServerCell().DetermineUserServerCell(userList, out dlRsrpFailUserList, out ulRsrpFailUserList); context.DataManager.DlRsrpFailUserList = dlRsrpFailUserList; context.DataManager.UlRsrpFailUserList = ulRsrpFailUserList; //所有用户 List<ISimulationUser> userlist = new List<ISimulationUser>(); foreach (SimulationCarrier carrier in context.DataManager.SimulationCarrierList) { userlist.AddRange(carrier.UlUserList); userlist.AddRange(carrier.DlUserList); } this.InitUsersMIMOClutterGain(userlist, context); this.GetMinAndMaxSinrTarget(userlist); //计算用户的初始的RS sinr,即IntialDlRsSinr measure.CalculateIntialDlRsSinr(userlist); }
public void InitUserTotalLossList(List<ISimulationUser> userList, List<ISimulationCarrier> allCarrierList, ReportProgressDelegate reporter) { Dictionary<int, List<CarrierTotalLoss>> userTotalLossDic = new Dictionary<int, List<CarrierTotalLoss>>(); //这样排列有什么意义没 allCarrierList.Sort(new Comparison<ISimulationCarrier>(this.SortCarrierBySite)); this.initUserTotalLossDic(userList, userTotalLossDic); ISimulationCarrier preCarrier = null; float count = allCarrierList.Count; //用28除是什么意思 float usedCounter = 28f / count; foreach (SimulationCarrier carrier2 in allCarrierList) { this.ClearUserSiteShadowValue(preCarrier, carrier2); List<User> inComputerAreaUsers = this.GetInComputerAreaUsers(userList, carrier2); this.UpdateUserTotalLoss(inComputerAreaUsers, carrier2, userTotalLossDic); if (reporter != null) { reporter(usedCounter); } } this.m_TotalLossCalObj.releaseMediacy(); this.m_TotalLossCalObj = null; GC.Collect(); this.initCarrierListInComputeArea(userList, userTotalLossDic); }
public void CreateFrom(IModel model, string fileName, ReportProgressDelegate progDelegate = null) { Close(); var dbName = Path.ChangeExtension(fileName, "xBIM"); InstanceCache.ImportModel(model, dbName, progDelegate); }
public void IfcStoreSaveAndOpenIfcXml4Test() { int percent = 0; ReportProgressDelegate progDelegate = delegate(int percentProgress, object userState) { percent = percentProgress; }; long count; using (var store = IfcStore.Open("TestFiles\\SampleHouse4.ifc", null, -1, progDelegate)) { count = store.Instances.Count; store.SaveAs("SampleHouse4", StorageType.IfcXml); store.Close(); } using (var store = IfcStore.Open("SampleHouse4.ifcxml", null, -1, progDelegate)) { Assert.IsTrue(count == store.Instances.Count, "Should have same number of instances"); store.Close(); } //now with memory model using (var store = IfcStore.Open("TestFiles\\SampleHouse4.ifc", null, -1, progDelegate)) { count = store.Instances.Count; store.SaveAs("SampleHouse4", StorageType.IfcXml); store.Close(); } using (var store = IfcStore.Open("SampleHouse4.ifcxml")) { Assert.IsTrue(count == store.Instances.Count, "Should have same number of instances"); store.Close(); } Assert.IsTrue(percent == 100); }
public virtual void LoadZip(string file, ReportProgressDelegate progDelegate = null) { using (var stream = File.OpenRead(file)) { LoadZip(stream, progDelegate); } }
/// <summary> /// Saves the model as PART21 file /// </summary> /// <param name="stream">Stream to be used to write the file</param> /// <param name="progress"></param> public virtual void SaveAsStep21(Stream stream, ReportProgressDelegate progress = null) { using (var writer = new StreamWriter(stream)) { SaveAsStep21(writer, progress); } }
/// <summary> /// Opens an IFC file, Ifcxml, IfcZip, xbim from a file path /// </summary> /// <param name="path">the file name of the ifc, ifczip, ifcxml or xbim file to be opened</param> /// <param name="editorDetails">This is only required if the store is opened for editing</param> /// <param name="ifcDatabaseSizeThreshHold">Expressed in MB. If not defined the DefaultIfcDatabaseSizeThreshHold is used, /// IFC files below this size will be opened in memory, above this size a database will be created. If -1 is specified an in memory model will be /// created for all IFC files that are opened. Xbim files are always opened as databases</param> /// <param name="progDelegate"></param> /// <param name="accessMode"></param> /// <param name="codePageOverride"> /// A CodePage that will be used to read implicitly encoded one-byte-char strings. If -1 is specified the default ISO8859-1 /// encoding will be used accoring to the Ifc specification. </param> public static IfcStore Open(string path, XbimEditorCredentials editorDetails = null, double?ifcDatabaseSizeThreshHold = null, ReportProgressDelegate progDelegate = null, XbimDBAccess accessMode = XbimDBAccess.Read, int codePageOverride = -1) { path = Path.GetFullPath(path); if (!Directory.Exists(Path.GetDirectoryName(path) ?? "")) { throw new DirectoryNotFoundException(Path.GetDirectoryName(path) + " directory was not found"); } if (!File.Exists(path)) { throw new FileNotFoundException(path + " file was not found"); } var newStore = new IfcStore(); // we need an instance var ifcVersion = newStore.ModelProvider.GetXbimSchemaVersion(path); if (ifcVersion == XbimSchemaVersion.Unsupported) { throw new FileLoadException(path + " is not a valid IFC file format, ifc, ifcxml, ifczip and xBIM are supported."); } var model = newStore.ModelProvider.Open(path, ifcVersion, ifcDatabaseSizeThreshHold, progDelegate, accessMode, codePageOverride); newStore.AssignModel(model, editorDetails, ifcVersion); return(newStore); }
/// <summary> /// Generates a new project. /// </summary> /// <param name="genatorArguments">The arguments needed to generate the project.</param> /// <param name="progressDelegate">Reports progress for all generator actions.</param> /// <param name="rollbackDelegate">Delegate to ask the user if an action should be rolled back or not.</param> /// <param name="continueAllowedFunc">Delegate to ask the main form if we are allowed to continue.</param> /// <returns>The outcome of the operation.</returns> public GeneratorResult Generate(GeneratorArguments genatorArguments, ReportProgressDelegate progressDelegate, ReportRollBackDelegate rollbackDelegate, Func<bool> continueAllowedFunc) { if (genatorArguments == null) throw new ArgumentNullException("genatorArguments"); if (progressDelegate == null) throw new ArgumentNullException("progressDelegate"); if (rollbackDelegate == null) throw new ArgumentNullException("rollbackDelegate"); if (continueAllowedFunc == null) throw new ArgumentNullException("continueAllowedFunc"); if (genatorArguments.TemplateInformation == null) throw new InvalidOperationException("No template information in Generate method."); arguments = genatorArguments; progress = progressDelegate; rollback = rollbackDelegate; continueAllowed = continueAllowedFunc; progressDelegate(0, "Starting generator"); return GenerateInternal(); }
public static MemoryModel OpenRead(string fileName, ILogger logger, ReportProgressDelegate progressDel = null) { //step21 text file can resolve version in parser if (fileName.IsStepTextFile()) { using (var file = File.OpenRead(fileName)) { return(OpenReadStep21(file, logger, progressDel)); } } var version = GetSchemaVersion(fileName); //an exception is thrown if this fails var ef = GetFactory(version); var model = new MemoryModel(ef, logger); if (fileName.IsStepZipFile()) { model.LoadZip(fileName, progressDel); } else if (fileName.IsStepXmlFile()) { model.LoadXml(fileName, progressDel); } else { throw new FileLoadException($"Unsupported file type extension: {Path.GetExtension(fileName)}"); } return(model); }
public virtual void LoadXml(string path, ReportProgressDelegate progDelegate = null) { using (var file = File.OpenRead(path)) { LoadXml(file, file.Length, progDelegate); } }
/// <summary> /// Reads schema version fron the file on the fly inside the parser so it doesn't need to /// access the file twice. /// </summary> /// <param name="file">Input step21 text file</param> /// <param name="logger">Logger</param> /// <param name="progressDel">Progress delegate</param> /// <returns>New memory model</returns> public static MemoryModel OpenReadStep21(string file, ILogger logger = null, ReportProgressDelegate progressDel = null) { using (var stream = File.OpenRead(file)) { return(OpenReadStep21(stream, logger, progressDel)); } }
internal static void Trim(bool stripEdids, bool stripRefs, string In, string Out, ReportProgressDelegate del) { Plugin p=new Plugin(In, false); del("Editing plugin"); Queue<Rec> queue=new Queue<Rec>(p.Records); while(queue.Count>0) { if(queue.Peek() is Record) { Record r=(Record)queue.Dequeue(); if(stripEdids) { //if(r.SubRecords.Count>0&&r.SubRecords[0].Name=="EDID") r.SubRecords.RemoveAt(0); for(int i=0;i<r.SubRecords.Count;i++) { //if(r.SubRecords[i].Name=="SCTX") r.SubRecords.RemoveAt(i--); } } } else { GroupRecord gr=(GroupRecord)queue.Dequeue(); if(gr.ContentsType!="GMST") { foreach(Rec r in gr.Records) queue.Enqueue(r); } } } del("Generating new esm"); //deflater=new ICSharpCode.SharpZipLib.Zip.Compression.Deflater(9); BinaryWriter bw=new BinaryWriter(File.Create(Out)); p.SaveData(bw); /*foreach(Rec r in p.Records) { if(r is GroupRecord) WriteGroup(bw, (GroupRecord)r); else WriteRecord(bw, (Record)r); }*/ bw.Close(); }
/// <summary> /// Dispose /// </summary> public void Dispose() { if (_progress != null) { ProgressStatus -= _progress; _progress = null; } }
/// <summary> /// Opens the model from STEP21 file. /// </summary> /// <param name="file">Path to the file</param> /// <param name="progDelegate"></param> /// <returns>Number of errors in parsing. Always check this to be null or the model might be incomplete.</returns> public virtual int LoadStep21(string file, ReportProgressDelegate progDelegate = null) { using (var stream = File.OpenRead(file)) { var result = LoadStep21(stream, stream.Length, progDelegate); return(result); } }
/// <summary> /// Saves a model as a STEP IFC file /// </summary> /// <param name="model"></param> /// <param name="stream"></param> /// <param name="progDelegate"></param> public static void SaveAsIfc(this IModel model, Stream stream, ReportProgressDelegate progDelegate = null) { using (TextWriter tw = new StreamWriter(stream)) { Part21Writer.Write(model, tw, model.Metadata, null, progDelegate); tw.Flush(); } }
/// <summary> /// Constructor /// </summary> public COBieXBimSerialiser(string fileName, ReportProgressDelegate progressHandler) { string fileNameDB = Path.ChangeExtension(fileName, ".xBIM"); XBimContext = new COBieXBimContext(XbimModel.CreateModel(fileNameDB), progressHandler); XBimContext.IsMerge = false; FileName = fileName; MergeGeometryOnly = true; }
public COBieContext(ReportProgressDelegate progressHandler = null) : this() { if (progressHandler != null) { _progress = progressHandler; this.ProgressStatus += progressHandler; } }
/// <summary> /// You can use this function to open IFC model from a <see cref="Stream"/>. /// You need to know file type (IFC, IFCZIP, IFCXML) and schema type (IFC2x3 or IFC4) to be able to use this function. /// If you don't know, you should the overloaded <see cref="Open(string, XbimEditorCredentials, double?, ReportProgressDelegate, XbimDBAccess, int)"/> /// method which takes file paths as an argument, and can automatically detect schema and file type. /// If are opening an *.xbim file you should also use the path-based overload because Esent database needs to operate /// on the file and this function will have to create temporal file if it is not a file stream. /// If the input is a FileStream, be aware this method may call <see cref="Stream.Close"/> on it to keep exclusive access. /// </summary> /// <param name="stream">Stream of data</param> /// <param name="dataType">Type of data (*.ifc, *.ifcxml, *.ifczip)</param> /// <param name="schema">IFC schema (IFC2x3, IFC4). Other schemas are not supported by this class.</param> /// <param name="modelType">Type of model to be used. You can choose between EsentModel and MemoryModel</param> /// <param name="editorDetails">Optional details. You should always pass these if you are going to change the data.</param> /// <param name="accessMode">Access mode to the stream. This is only important if you choose EsentModel. MemoryModel is completely in memory so this is not relevant</param> /// <param name="progDelegate">Progress reporting delegate</param> /// <param name="codePageOverride"> /// A CodePage that will be used to read implicitly encoded one-byte-char strings. If -1 is specified the default ISO8859-1 /// encoding will be used accoring to the Ifc specification. </param> /// <returns></returns> public static IfcStore Open(Stream stream, StorageType dataType, XbimSchemaVersion schema, XbimModelType modelType, XbimEditorCredentials editorDetails = null, XbimDBAccess accessMode = XbimDBAccess.Read, ReportProgressDelegate progDelegate = null, int codePageOverride = -1) { var newStore = new IfcStore(); var model = newStore.ModelProvider.Open(stream, dataType, schema, modelType, accessMode, progDelegate, codePageOverride); newStore.AssignModel(model, editorDetails, schema); return(newStore); }
/// <summary> /// Instantiates a new IIfcToCOBieLiteUkExchanger class. /// </summary> public IfcToCoBieExpressExchanger(IfcStore source, IModel target, ReportProgressDelegate reportProgress = null, OutPutFilters filter = null, string configFile = null, EntityIdentifierMode extId = EntityIdentifierMode.IfcEntityLabels, SystemExtractionMode sysMode = SystemExtractionMode.System | SystemExtractionMode.Types, bool classify = false) : base(source, target) { ReportProgress.Progress = reportProgress; //set reporter Helper = new COBieExpressHelper(this, ReportProgress, filter, configFile, extId, sysMode); Helper.Init(); _classify = classify; }
public COBieXBimContext(IfcStore model, ReportProgressDelegate progressHandler = null) : this(model) { if (progressHandler != null) { _progress = progressHandler; this.ProgressStatus += progressHandler; } }
public bool SaveAs(string outputFileName, StorageType?storageType = null, ReportProgressDelegate progress = null, IDictionary <int, int> map = null) { try { if (!storageType.HasValue) { storageType = outputFileName.StorageType(); } if (storageType.Value == StorageType.Invalid) { var ext = Path.GetExtension(outputFileName); if (string.IsNullOrWhiteSpace(ext)) { throw new XbimException("Invalid file type, no extension specified in file " + outputFileName); } throw new XbimException("Invalid file extension " + ext.ToUpper() + " in file " + outputFileName); } if (storageType.Value == StorageType.Xbim && DatabaseName != null) //make a copy { var srcFile = DatabaseName; if (string.Compare(srcFile, outputFileName, true, CultureInfo.InvariantCulture) == 0) { throw new XbimException("Cannot save file to the same name, " + outputFileName); } var deleteOnClose = _deleteOnClose; var accessMode = InstanceCache.AccessMode; try { _deleteOnClose = false; //regardless we need to keep it to copy it Close(); File.Copy(srcFile, outputFileName); if (deleteOnClose) { File.Delete(srcFile); } srcFile = outputFileName; return(true); } catch (Exception e) { throw new XbimException("Failed to save file as outputFileName", e); } finally { Open(srcFile, accessMode); } } InstanceCache.SaveAs(storageType.Value, outputFileName, progress, map); return(true); } catch (Exception e) { throw new XbimException(string.Format("Failed to Save file as {0}\n{1}", outputFileName, e.Message), e); } }
/// <summary> /// Constructor /// </summary> /// <param name="progressHandler">Report Delegate</param> public FederateCOBie(ReportProgressDelegate progressHandler = null) { if (progressHandler != null) { _progress = progressHandler; this.ProgressStatus += progressHandler; } cOBieProgress = new COBieProgress(this); ErrorRowStartIndex = ErrorRowIndexBase.RowTwo; //default for excel sheet }
/// <summary> /// Constructor /// </summary> public COBieXBimSerialiser(string fileName, ReportProgressDelegate progressHandler) { var fileNameDB = Path.ChangeExtension(fileName, ".xBIM"); XBimContext = new COBieXBimContext(IfcStore.Create(fileNameDB, null, XbimSchemaVersion.Ifc2X3), progressHandler) { IsMerge = false }; FileName = fileName; MergeGeometryOnly = true; }
public MainForm() : base() { InitializeComponent(); Alert = new AlertDelegate(AlertMethod); Exit = new ExitDelegate(ExitMethod); FatalExit = new FatalExitDelegate(FatalExitMethod); Log = new LogDelegate(LogMethod); ReportProgress = new ReportProgressDelegate(ReportProgressMethod); Info = new InfoDelegate(InfoMethod); logfile = File.OpenWrite(Path.GetDirectoryName(Application.ExecutablePath) + "\\cuetoogg.log.txt"); }
//Needed Geometry to test, but Steve's comment on "need to resolve generate geometry" may see GenerateGeometry change private void GenerateGeometry(COBieContext context) { //now convert the geometry XbimModel model = context.Model; int total = (int)model.Instances.CountOf <IfcProduct>(); ReportProgressDelegate progDelegate = delegate(int percentProgress, object userState) { context.UpdateStatus("Creating Geometry File", total, (total * percentProgress / 100)); }; XbimMesher.GenerateGeometry(model, null, progDelegate); }
/// <summary> /// Opens a model from the provided path, inferring model implementation based on format and model size /// </summary> /// <param name="path">Path to the model file, in any support IFC or XBIM format</param> /// <param name="schemaVersion"></param> /// <param name="ifcDatabaseSizeThreshHold"></param> /// <param name="progDelegate"></param> /// <param name="accessMode"></param> /// <param name="codePageOverride"></param> /// <returns></returns> public override IModel Open(string path, XbimSchemaVersion schemaVersion, double?ifcDatabaseSizeThreshHold = null, ReportProgressDelegate progDelegate = null, XbimDBAccess accessMode = XbimDBAccess.Read, int codePageOverride = -1) { var storageType = path.StorageType(); if (storageType == StorageType.Xbim) //open the XbimFile { var model = CreateEsentModel(schemaVersion, codePageOverride); model.Open(path, accessMode, progDelegate); return(model); } else //it will be an IFC file if we are at this point { var fInfo = new FileInfo(path); double ifcMaxLength = (ifcDatabaseSizeThreshHold ?? DefaultIfcDatabaseSizeThreshHoldMb) * 1024 * 1024; // we need to make an Esent database, if ifcMaxLength<0 we use in memory if (ifcMaxLength >= 0 && fInfo.Length > ifcMaxLength) { var tmpFileName = Path.GetTempFileName(); var model = CreateEsentModel(schemaVersion, codePageOverride); // We delete the XBIM on close as the consumer is not controlling the generation of the XBIM file if (model.CreateFrom(path, tmpFileName, progDelegate, keepOpen: true, deleteOnClose: true)) { return(model); } throw new FileLoadException(path + " file was not a valid IFC format"); } else //we can use a memory model { var model = CreateMemoryModel(schemaVersion); if (storageType.HasFlag(StorageType.IfcZip) || storageType.HasFlag(StorageType.Zip) || storageType.HasFlag(StorageType.StpZip)) { model.LoadZip(path, progDelegate); } else if (storageType.HasFlag(StorageType.Ifc) || storageType.HasFlag(StorageType.Stp)) { model.LoadStep21(path, progDelegate); } else if (storageType.HasFlag(StorageType.IfcXml)) { model.LoadXml(path, progDelegate); } // if we are looking at a memory model loaded from a file it might be safe to fix the file name in the // header with the actual file loaded FileInfo f = new FileInfo(path); model.Header.FileName.Name = f.FullName; return(model); } } }
/// <summary> /// Instantiates a new IIfcToCOBieLiteUkExchanger class. /// </summary> public IfcToCoBieExpressExchanger(IModel source, IModel target, ReportProgressDelegate reportProgress = null, OutputFilters filter = null, string configFile = null, EntityIdentifierMode extId = EntityIdentifierMode.IfcEntityLabels, SystemExtractionMode sysMode = SystemExtractionMode.System | SystemExtractionMode.Types, bool classify = false) : base(source, target) { // make sure there are some loggers in the models target.Logger = target.Logger ?? NullLogger.Instance; source.Logger = source.Logger ?? NullLogger.Instance; ReportProgress.Progress = reportProgress; //set reporter Helper = new COBieExpressHelper(this, ReportProgress, target.Logger, filter, configFile, extId, sysMode); Helper.Init(); _classify = classify; }
public SilentForm() : base() { InitializeComponent(); Alert = new AlertDelegate(AlertMethod); Exit = new ExitDelegate(ExitMethod); FatalExit = new FatalExitDelegate(FatalExitMethod); Log = new LogDelegate(LogMethod); ReportProgress = new ReportProgressDelegate(ReportProgressMethod); Info = new InfoDelegate(InfoMethod); logfile=File.OpenWrite(Path.GetDirectoryName(Application.ExecutablePath)+"\\cuetoogg.log.txt"); }
public virtual void SaveAsStep21Zip(Stream stream, ReportProgressDelegate progress = null) { using (var zipStream = new ZipArchive(stream, ZipArchiveMode.Update)) { var schema = EntityFactory.SchemasIds.FirstOrDefault(); var ext = schema != null && schema.StartsWith("IFC") ? ".ifc" : ".stp"; var newEntry = zipStream.CreateEntry($"data{ext}"); using (var writer = newEntry.Open()) { SaveAsStep21(writer, progress); } } }
internal static void Trim(bool stripEdids, bool stripRefs, string In, string Out, ReportProgressDelegate del) { var p = new Plugin(In, false); del("Editing plugin"); var queue = new Queue<Rec>(p.Records); while (queue.Count > 0) { if (queue.Peek() is Record) { queue.Dequeue(); } else { var gr = (GroupRecord) queue.Dequeue(); if (gr.ContentsType != "GMST") { foreach (var r in gr.Records) { queue.Enqueue(r); } } } } del("Generating new esm"); //deflater=new ICSharpCode.SharpZipLib.Zip.Compression.Deflater(9); var bw = new BinaryWriter(File.Create(Out)); p.SaveData(bw); /*foreach(Rec r in p.Records) { if(r is GroupRecord) WriteGroup(bw, (GroupRecord)r); else WriteRecord(bw, (Record)r); }*/ bw.Close(); }
/// <summary> /// Use this function on a Xbim Model that has just been creted from IFC content /// This will create the default 3D mesh geometry for all IfcProducts and add it to the model /// </summary> /// <param name="model"></param> public static void GenerateGeometry(XbimModel model, ILogger Logger = null, ReportProgressDelegate progDelegate = null, IEnumerable<IfcProduct> toMesh = null) { //Create the geometry engine by reflection to allow dynamic loading of different binary platforms (32, 64 etc) Assembly assembly = AssemblyResolver.GetModelGeometryAssembly(); if (assembly == null) { if (Logger != null) { #if DEBUG Logger.Error("Failed to load Xbim.ModelGeometry.OCCd.dll Please ensure it is installed correctly"); #else Logger.Error("Failed to load Xbim.ModelGeometry.OCC.dll Please ensure it is installed correctly"); #endif } return; } IXbimGeometryEngine engine = (IXbimGeometryEngine)assembly.CreateInstance("Xbim.ModelGeometry.XbimGeometryEngine"); engine.Init(model); if (engine == null) { if (Logger != null) { #if DEBUG Logger.Error("Failed to create Xbim Geometry engine. Please ensure Xbim.ModelGeometry.OCCd.dll is installed correctly"); #else Logger.Error("Failed to create Xbim Geometry engine. Please ensure Xbim.ModelGeometry.OCC.dll is installed correctly"); #endif } return; } //now convert the geometry IEnumerable<IfcProduct> toDraw; if (toMesh != null) toDraw = toMesh; else toDraw = model.InstancesLocal.OfType<IfcProduct>().Where(t => !(t is IfcFeatureElement)); //List<IfcProduct> toDraw = new List<IfcProduct>(); // toDraw.Add(model.Instances[513489] as IfcProduct); if (!toDraw.Any()) return; //othing to do TransformGraph graph = new TransformGraph(model); //create a new dictionary to hold maps ConcurrentDictionary<int, Object> maps = new ConcurrentDictionary<int, Object>(); //add everything that may have a representation graph.AddProducts(toDraw); //load the products as we will be accessing their geometry ConcurrentDictionary<int, MapData> mappedModels = new ConcurrentDictionary<int, MapData>(); ConcurrentQueue<MapRefData> mapRefs = new ConcurrentQueue<MapRefData>(); ConcurrentDictionary<int, int[]> written = new ConcurrentDictionary<int, int[]>(); int tally = 0; int percentageParsed = 0; int total = graph.ProductNodes.Values.Count; try { //use parallel as this improves the OCC geometry generation greatly ParallelOptions opts = new ParallelOptions(); opts.MaxDegreeOfParallelism = 16; XbimRect3D bounds = XbimRect3D.Empty; double deflection = model.ModelFactors.DeflectionTolerance; #if DOPARALLEL Parallel.ForEach<TransformNode>(graph.ProductNodes.Values, opts, node => //go over every node that represents a product #else foreach (var node in graph.ProductNodes.Values) #endif { IfcProduct product = node.Product(model); try { IXbimGeometryModel geomModel = engine.GetGeometry3D(product, maps); if (geomModel != null) //it has geometry { XbimMatrix3D m3d = node.WorldMatrix(); if (geomModel.IsMap) //do not process maps now { MapData toAdd = new MapData(geomModel, m3d, product); if (!mappedModels.TryAdd(geomModel.RepresentationLabel, toAdd)) //get unique rep mapRefs.Enqueue(new MapRefData(toAdd)); //add ref } else { int[] geomIds; XbimGeometryCursor geomTable = model.GetGeometryTable(); XbimLazyDBTransaction transaction = geomTable.BeginLazyTransaction(); if (written.TryGetValue(geomModel.RepresentationLabel, out geomIds)) { byte[] matrix = m3d.ToArray(true); short? typeId = IfcMetaData.IfcTypeId(product); foreach (var geomId in geomIds) { geomTable.AddMapGeometry(geomId, product.EntityLabel, typeId.Value, matrix, geomModel.SurfaceStyleLabel); } } else { XbimTriangulatedModelCollection tm = geomModel.Mesh(deflection); XbimRect3D bb = tm.Bounds; byte[] matrix = m3d.ToArray(true); short? typeId = IfcMetaData.IfcTypeId(product); geomIds = new int[tm.Count + 1]; geomIds[0] = geomTable.AddGeometry(product.EntityLabel, XbimGeometryType.BoundingBox, typeId.Value, matrix, bb.ToDoublesArray(), 0, geomModel.SurfaceStyleLabel); bb = XbimRect3D.TransformBy(bb, m3d); if (bounds.IsEmpty) bounds = bb; else bounds.Union(bb); short subPart = 0; foreach (XbimTriangulatedModel b in tm) { geomIds[subPart + 1] = geomTable.AddGeometry(product.EntityLabel, XbimGeometryType.TriangulatedMesh, typeId.Value, matrix, b.Triangles, subPart, b.SurfaceStyleLabel); subPart++; } // Debug.Assert(written.TryAdd(geomModel.RepresentationLabel, geomIds)); Interlocked.Increment(ref tally); if (progDelegate != null) { int newPercentage = Convert.ToInt32((double)tally / total * 100.0); if (newPercentage > percentageParsed) { percentageParsed = newPercentage; progDelegate(percentageParsed, "Meshing"); } } } transaction.Commit(); model.FreeTable(geomTable); } } else { // store a transform only if no geomtery is available XbimGeometryCursor geomTable = model.GetGeometryTable(); XbimLazyDBTransaction transaction = geomTable.BeginLazyTransaction(); XbimMatrix3D m3dtemp = node.WorldMatrix(); byte[] matrix = m3dtemp.ToArray(true); short? typeId = IfcMetaData.IfcTypeId(product); geomTable.AddGeometry(product.EntityLabel, XbimGeometryType.TransformOnly, typeId.Value, matrix, new byte[] {}); transaction.Commit(); model.FreeTable(geomTable); Interlocked.Increment(ref tally); if (progDelegate != null) { int newPercentage = Convert.ToInt32((double)tally / total * 100.0); if (newPercentage > percentageParsed) { percentageParsed = newPercentage; progDelegate(percentageParsed, "Meshing"); } } } } catch (Exception e1) { String message = String.Format("Error Triangulating product geometry of entity #{0} - {1}", product.EntityLabel, product.GetType().Name ); if (Logger != null) Logger.Error(message, e1); } } #if DOPARALLEL ); #endif graph = null; // Debug.WriteLine(tally); #if DOPARALLEL //now sort out maps again in parallel Parallel.ForEach<KeyValuePair<int, MapData>>(mappedModels, opts, map => #else foreach (var map in mappedModels) #endif { IXbimGeometryModel geomModel = map.Value.Geometry; XbimMatrix3D m3d = map.Value.Matrix; IfcProduct product = map.Value.Product; //have we already written it? int[] writtenGeomids = new int[0]; if (!written.TryAdd(geomModel.RepresentationLabel, writtenGeomids)) { //make maps mapRefs.Enqueue(new MapRefData(map.Value)); //add ref } else { m3d = XbimMatrix3D.Multiply(geomModel.Transform, m3d); WriteGeometry(model, written, geomModel, ref bounds, m3d, product, deflection); } Interlocked.Increment(ref tally); if (progDelegate != null) { int newPercentage = Convert.ToInt32((double)tally / total * 100.0); if (newPercentage > percentageParsed) { percentageParsed = newPercentage; progDelegate(percentageParsed, "Meshing"); } } map.Value.Clear(); //release any native memory we are finished with this } #if DOPARALLEL ); #endif //clear up maps mappedModels.Clear(); XbimGeometryCursor geomMapTable = model.GetGeometryTable(); XbimLazyDBTransaction mapTrans = geomMapTable.BeginLazyTransaction(); foreach (var map in mapRefs) //don't do this in parallel to avoid database thrashing as it is very fast { int[] geomIds; if (!written.TryGetValue(map.RepresentationLabel, out geomIds)) { if (Logger != null) Logger.WarnFormat("A geometry mapped reference (#{0}) has been found that has no base geometry", map.RepresentationLabel); } else { byte[] matrix = map.Matrix.ToArray(true); foreach (var geomId in geomIds) { geomMapTable.AddMapGeometry(geomId, map.EntityLabel, map.EntityTypeId, matrix, map.SurfaceStyleLabel); } mapTrans.Commit(); mapTrans.Begin(); } Interlocked.Increment(ref tally); if (progDelegate != null) { int newPercentage = Convert.ToInt32((double)tally / total * 100.0); if (newPercentage > percentageParsed) { percentageParsed = newPercentage; progDelegate(percentageParsed, "Meshing"); } } if (tally % 100 == 100) { mapTrans.Commit(); mapTrans.Begin(); } } mapTrans.Commit(); // Store model regions in the database. // all regions are stored for the project in one row and need to be desirialised to XbimRegionCollection before being enumerated on read. // // todo: bonghi: currently geometry labels of partitioned models are not stored, only their bounding box and count are. // mapTrans.Begin(); XbimRegionCollection regions = PartitionWorld(model, bounds); IfcProject project = model.IfcProject; int projectId = 0; if (project != null) projectId = Math.Abs(project.EntityLabel); geomMapTable.AddGeometry(projectId, XbimGeometryType.Region, IfcMetaData.IfcTypeId(typeof(IfcProject)), XbimMatrix3D.Identity.ToArray(), regions.ToArray()); mapTrans.Commit(); model.FreeTable(geomMapTable); if (progDelegate != null) { progDelegate(0, "Ready"); } } catch (Exception e2) { if (Logger != null) Logger.Warn("General Error Triangulating geometry", e2); } finally { } }
public static void Trim(IntPtr hwnd, string In, string Out, ReportProgressDelegate del) { NativeMethods.ddsInit(hwnd); var br = new BinaryReader(File.OpenRead(In), Encoding.Default); var bw = new BinaryWriter(File.Create(Out), Encoding.Default); var sb = new StringBuilder(64); var inf = new Inflater(); bool Compressed, SkipName; if (br.ReadInt32() != 0x00415342) { throw new Exception("Invalid bsa"); } var version = br.ReadUInt32(); bw.Write(0x00415342); bw.Write(version); bw.Write(br.ReadInt32()); var flags = br.ReadUInt32(); if ((flags & 0x004) > 0) { Compressed = true; flags ^= 0x4; } else { Compressed = false; } if ((flags & 0x100) > 0 && version == 0x68) { SkipName = true; } else { SkipName = false; } flags ^= 0x2; var FolderCount = br.ReadInt32(); var FileCount = br.ReadInt32(); bw.Write(flags); bw.Write(FolderCount); bw.Write(FileCount); bw.Write(br.ReadInt32()); bw.Write(br.ReadInt32()); bw.Write(br.ReadInt32()); var folderFileCount = new int[FolderCount]; for (var i = 0; i < FolderCount; i++) { bw.Write(br.ReadInt64()); folderFileCount[i] = br.ReadInt32(); bw.Write(folderFileCount[i]); bw.Write(br.ReadInt32()); } var fileLengths = new int[FileCount]; var offsetOffsets = new long[FileCount]; var fileOffsets = new uint[FileCount]; var parsefiles = new bool[FileCount]; var file = 0; for (var i = 0; i < FolderCount; i++) { var len = br.ReadByte(); bw.Write(len); sb.Length = 0; while (--len > 0) { var c = br.ReadChar(); sb.Append(c); bw.Write(c); } br.ReadByte(); bw.Write((byte) 0); var parse = true; if (sb.ToString().StartsWith("textures\\interface\\")) { parse = false; } for (var j = 0; j < folderFileCount[i]; j++) { bw.Write(br.ReadUInt64()); offsetOffsets[file] = br.BaseStream.Position; fileLengths[file] = br.ReadInt32(); bw.Write(fileLengths[file]); fileOffsets[file] = br.ReadUInt32(); bw.Write(fileOffsets[file]); parsefiles[file] = parse; file++; } } for (var i = 0; i < FileCount; i++) { sb.Length = 0; while (true) { var c = (char) br.ReadByte(); //bw.Write(c); if (c == '\0') { break; } sb.Append(c); } if (!sb.ToString().EndsWith(".dds", StringComparison.OrdinalIgnoreCase)) { parsefiles[i] = false; } } for (var i = 0; i < FileCount; i++) { if ((i%100) == 0) { del("Processing file " + i + " of " + FileCount); } br.BaseStream.Position = fileOffsets[i]; var offset = bw.BaseStream.Position; var add = 0; if (SkipName) { var len = br.ReadByte(); bw.Write(len); bw.Write(br.ReadBytes(len + 1)); add = len + 2; } var compressed2 = Compressed; if ((fileLengths[i] & (1 << 30)) != 0) { compressed2 = !compressed2; fileLengths[i] ^= (1 << 30); } if (!compressed2) { var bytes = new byte[fileLengths[i]]; br.Read(bytes, 0, fileLengths[i]); Commit(bw, offsetOffsets[i], bytes, offset, add, parsefiles[i]); } else { var uncompressed = new byte[br.ReadUInt32()]; var compressed = new byte[fileLengths[i] - 4]; br.Read(compressed, 0, fileLengths[i] - 4); inf.Reset(); inf.SetInput(compressed); inf.Inflate(uncompressed); Commit(bw, offsetOffsets[i], uncompressed, offset, add, parsefiles[i]); } } br.Close(); bw.Close(); NativeMethods.ddsClose(); }
public COBieXBimContext(XbimModel model, ReportProgressDelegate progressHandler = null) : this(model) { if (progressHandler != null) { _progress = progressHandler; this.ProgressStatus += progressHandler; } }
public void InitUserTotalLossList(List<ISimulationUser> userList, List<ISimulationCarrier> allCarrierList, ReportProgressDelegate reporter) { Dictionary<string, List<CarrierTotalLoss>> userTotalLossDic = new Dictionary<string, List<CarrierTotalLoss>>(); allCarrierList.Sort(new Comparison<ISimulationCarrier>(this.SortCarrierBySite)); initUserTotalLossDic(userList, allCarrierList,userTotalLossDic); ISimulationCarrier preCarrier = null; float count = allCarrierList.Count; //用28除是什么意思 float usedCounter = 28f / count; List<SimulationUser> relayUserList = new List<SimulationUser>(); foreach (SimulationCarrier carrier1 in allCarrierList) { relayUserList.AddRange(carrier1.UlRelayUserList); } foreach (SimulationCarrier carrier2 in allCarrierList) { this.ClearUserSiteShadowValue(preCarrier, carrier2); Dictionary<bool, List<User>> userDic = GetInComputerAreaUsers(userList, relayUserList,carrier2); List<RelayCell> relayCells = GetInComputerAreaRCs(carrier2, relayUserList); UpdateUserTotalLoss(userDic,relayCells, carrier2, userTotalLossDic); if (reporter != null) { reporter(usedCounter); } } this.m_TotalLossCalObj.releaseMediacy(); this.m_TotalLossCalObj = null; GC.Collect(); this.initCarrierListInComputeArea(userList, allCarrierList, userTotalLossDic); }