/// <summary> /// Set a property /field value, if a transaction is active it is transacted and undoable, if the owner supports INotifyPropertyChanged, the required events will be raised /// </summary> /// <typeparam name = "TProperty"></typeparam> /// The property type to be set /// <param name = "field"></param> /// The field to be set /// <param name = "newValue"></param> /// The value to set the field to /// <param name = "setter"></param> /// The function to set and unset the field /// <param name = "notifyPropertyName"></param> /// A list of property names of the owner to raise notification on internal static void SetModelValue <TProperty>(IPersistIfcEntity target, ref TProperty field, TProperty newValue, ReversibleInstancePropertySetter <TProperty> setter, string notifyPropertyName) { //The object must support Property Change Notification so notify ISupportChangeNotification iPropChanged = target as ISupportChangeNotification; if (iPropChanged != null) { Transaction.AddPropertyChange(setter, field, newValue); #if SupportActivation target.Activate(true); #endif iPropChanged.NotifyPropertyChanging(notifyPropertyName); field = newValue; iPropChanged.NotifyPropertyChanged(notifyPropertyName); } else { throw new Exception( string.Format( "Request to Notify Property Changes on type {0} that does not support ISupportChangeNotification", target.GetType().Name)); } }
public static IfcPropertySingleValue SetPropertySingleValue(this Xbim.Ifc2x3.Kernel.IfcTypeObject obj, string pSetName, string propertyName, IfcValue value) { IfcPropertySet pset = GetPropertySet(obj, pSetName); IfcPropertySingleValue property = null; IModel model = null; if (pset == null) { //if (value == null) return; IPersistIfcEntity ent = obj as IPersistIfcEntity; model = ent != null? ent.ModelOf : obj.ModelOf; pset = model.Instances.New <IfcPropertySet>(); pset.Name = pSetName; obj.AddPropertySet(pset); } //change existing property of the same name from the property set IfcPropertySingleValue singleVal = GetPropertySingleValue(obj, pSetName, propertyName); if (singleVal != null) { property = singleVal; singleVal.NominalValue = value; } else { //if (value == null) return; IPersistIfcEntity ent = obj as IPersistIfcEntity; model = ent != null ? ent.ModelOf : obj.ModelOf; property = model.Instances.New <IfcPropertySingleValue>(psv => { psv.Name = propertyName; psv.NominalValue = value; }); pset.HasProperties.Add(property); } return(property); }
internal bool AppliesTo(IPersistIfcEntity SelectedEntity) { IfcType ifcType = IfcMetaData.IfcType(ConceptRoot.applicableRootEntity.ToUpperInvariant()); IfcType seltype = IfcMetaData.IfcType(SelectedEntity); return(ifcType == seltype || ifcType.IfcSubTypes.Contains(seltype)); }
public static IModel ModelOf(IPersistIfcEntity instance) { #if SupportActivation if (instance.ModelOf != null) { return(instance.ModelOf); } else #endif if (instance == _lastAccessedInstance) { return(_lastAccessedModel); } if (_lastAccessedModel != null && _lastAccessedModel.ContainsInstance(instance)) //try this first to improve performance { _lastAccessedInstance = instance; return(_lastAccessedModel); } else { foreach (IModel model in _models.Where(m => m != _lastAccessedModel)) { if (model.ContainsInstance(instance)) { _lastAccessedModel = model; _lastAccessedInstance = instance; return(model); } } } throw new ArgumentException( "Failure in ModelManager.ModelOf, the instance is in none of the current models", "instance"); }
/// <summary> /// If the type has indexed attributes, this returns a set of unique values for the specified IPersistIfcEntity /// </summary> /// <param name="ent"></param> /// <returns></returns> internal IEnumerable <int> GetIndexedValues(IPersistIfcEntity ent) { if (IndexedProperties == null) { return(Enumerable.Empty <int>()); } HashSet <int> keys = new HashSet <int>(); foreach (var prop in IndexedProperties) { object o = prop.GetValue(ent, null); if (null != o && typeof(IPersistIfcEntity).IsAssignableFrom(o.GetType())) { int h = ((IPersistIfcEntity)o).EntityLabel; keys.Add(h); //normally there are only one or two keys so don't worry about performance of contains on a list } else if (null != o && typeof(ExpressEnumerable).IsAssignableFrom(o.GetType())) { foreach (var obj in (ExpressEnumerable)o) { int h = ((IPersistIfcEntity)obj).EntityLabel; keys.Add(h); //normally there are only one or two keys so don't worry about performance of contains on a list } } } return(keys); }
public static void AddElements(this MeshGeometry3D m, IPersistIfcEntity item, XbimMatrix3D wcsTransform) { var fromModel = item.ModelOf as XbimModel; if (fromModel == null || !(item is IfcProduct)) { return; } switch (fromModel.GeometrySupportLevel) { case 2: var context = new Xbim3DModelContext(fromModel); var productShape = context.ShapeInstancesOf((IfcProduct)item) .Where(s => s.RepresentationType != XbimGeometryRepresentationType.OpeningsAndAdditionsExcluded) .ToList(); if (!productShape.Any() && item is IfcFeatureElement) { productShape = context.ShapeInstancesOf((IfcProduct)item) .Where( s => s.RepresentationType == XbimGeometryRepresentationType.OpeningsAndAdditionsExcluded) .ToList(); } if (!productShape.Any()) { return; } foreach (var shapeInstance in productShape) { IXbimShapeGeometryData shapeGeom = context.ShapeGeometry(shapeInstance.ShapeGeometryLabel); switch ((XbimGeometryType)shapeGeom.Format) { case XbimGeometryType.PolyhedronBinary: m.Read(shapeGeom.ShapeData, XbimMatrix3D.Multiply(shapeInstance.Transformation, wcsTransform)); break; case XbimGeometryType.Polyhedron: m.Read(((XbimShapeGeometry)shapeGeom).ShapeData, XbimMatrix3D.Multiply(shapeInstance.Transformation, wcsTransform)); break; } } break; case 1: var xm3d = new XbimMeshGeometry3D(); var geomDataSet = fromModel.GetGeometryData(item.EntityLabel, XbimGeometryType.TriangulatedMesh); foreach (var geomData in geomDataSet) { var gd = geomData.TransformBy(wcsTransform); xm3d.Add(gd); } m.Add(xm3d); break; } }
public IfcForwardReference(int referenceEntityLabel, short referencingProperty, IPersistIfcEntity referencingEntity) { ReferenceEntityLabel = referenceEntityLabel; ReferencingPropertyId = referencingProperty; ReferencingEntity = referencingEntity; }
/// <summary> /// Constructs an entry for a completely new instance of a type, offset == 0, Type == typeof entity /// </summary> public XbimIndexEntry(long entityLabel, IPersistIfcEntity entity) { _entityLabel = entityLabel; _offset = 0; _type = entity.GetType(); _entityRef = null; Entity = entity; }
public void Clear(string identifier) { FixVariableName(ref identifier); if (IsDefined(identifier)) _data[identifier] = new IPersistIfcEntity[] { }; else throw new ArgumentException(identifier + " is not defined;"); }
public IEnumerable <IPersistIfcEntity> GetEntities(string variable) { FixVariableName(ref variable); IEnumerable <IPersistIfcEntity> result = new IPersistIfcEntity[] { }; _data.TryGetValue(variable, out result); return(result); }
public static XbimMaterialProvider GetDefaultMaterial(IPersistIfcEntity obj) { if (obj != null) { return(GetDefaultMaterial(obj.GetType().Name)); } return(null); }
/// <summary> /// /// </summary> /// <param name="model"></param> /// <returns></returns> public IEnumerable <int> Run(XbimModel model) { foreach (var label in _entityLabelsToParse) { if (_transverse) { yield return(label); } else if (_queryCommand.Trim() == "") { yield return(label); } var entity = model.Instances[label]; if (entity != null) { IfcType ifcType = IfcMetaData.IfcType(entity); // directs first SquareBracketIndexer sbi = new SquareBracketIndexer(_queryCommand); var prop = ifcType.IfcProperties.Where(x => x.Value.PropertyInfo.Name == sbi.Property).FirstOrDefault().Value; if (prop == null) // otherwise test inverses { prop = ifcType.IfcInverses.Where(x => x.PropertyInfo.Name == sbi.Property).FirstOrDefault(); } if (prop != null) { object propVal = prop.PropertyInfo.GetValue(entity, null); if (propVal != null) { if (prop.IfcAttribute.IsEnumerable) { IEnumerable <object> propCollection = propVal as IEnumerable <object>; if (propCollection != null) { propCollection = sbi.GetItem(propCollection); foreach (var item in propCollection) { IPersistIfcEntity pe = item as IPersistIfcEntity; if (pe != null) { yield return(pe.EntityLabel); } } } } else { IPersistIfcEntity pe = propVal as IPersistIfcEntity; if (pe != null && sbi.Index < 1) // index is negative (not specified) or 0 { yield return(pe.EntityLabel); } } } } } } }
public XbimIndexEntry AddNew <T>(out IPersistIfcEntity newEntity) { newEntity = (IPersistIfcEntity)Activator.CreateInstance <T>(); XbimIndexEntry entry = new XbimIndexEntry(NextLabel, newEntity); IList <XbimIndexEntry> entryList = this as IList <XbimIndexEntry>; entryList.Add_Reversible(entry); return(entry); }
/// <summary> /// Converts a XbimInstanceHandle into an XbimInstance, this is NOT and undoable action /// </summary> /// <param name="model"></param> /// <param name="handle"></param> /// <returns></returns> internal IPersistIfcEntity CreateEntity(IModel model, XbimInstanceHandle handle) { IPersistIfcEntity entity = (IPersistIfcEntity)Activator.CreateInstance(handle.EntityType); entity.Bind(model, (handle.EntityLabel * -1)); //a negative handle determines that the attributes of this entity have not been loaded yet XbimInstance inst = new XbimInstance(entity, handle.FileOffset); this[handle.EntityLabel] = inst; return(entity); }
/// <summary> /// Adds an entity, assumes a valid transaction is running /// </summary> /// <param name="toWrite"></param> internal void AddEntity(IPersistIfcEntity toWrite) { MemoryStream ms = new MemoryStream(); BinaryWriter bw = new BinaryWriter(ms); toWrite.WriteEntity(bw); IfcType ifcType = IfcMetaData.IfcType(toWrite); AddEntity(toWrite.EntityLabel, ifcType.TypeId, ifcType.GetIndexedValues(toWrite), ms.ToArray(), ifcType.IndexedClass); }
public XbimIndexEntry AddNew(Type type, out IPersistIfcEntity newEntity, long label) { newEntity = (IPersistIfcEntity)Activator.CreateInstance(type); XbimIndexEntry entry = new XbimIndexEntry(label, newEntity); IList <XbimIndexEntry> entryList = this as IList <XbimIndexEntry>; entryList.Add_Reversible(entry); _highestLabel = Math.Max(label, _highestLabel); return(entry); }
public static bool EvaluatePropertyValue(IPersistIfcEntity element, string pSetName, NameRule pSetNameRule, string propertyName, NameRule propNameRule, string value, ValueRule valueRule) { Dictionary<IfcLabel, Dictionary<IfcIdentifier, IfcValue>> allProperties = null; if (string.IsNullOrEmpty(propertyName)) return false; //properties could be defined in IfcTypeObject as HasProperties IfcTypeObject typeObject = element as IfcTypeObject; if (typeObject != null) { allProperties = typeObject.GetAllPropertySingleValues(); } //or properties could be defined in IfcObject in IsDefinedBy IfcObject ifcObject = element as IfcObject; if (ifcObject != null) { allProperties = ifcObject.GetAllPropertySingleValues(); } //or properties could be defined for material as ExtendedMaterialProperties IfcMaterial material = element as IfcMaterial; if (material != null) { allProperties = material.GetAllPropertySingleValues(); } //getting properties is not supported otherwise if (allProperties != null) { foreach (var p in allProperties) { //if pSetName is null all property sets are inspected if (pSetName != null) { if (!IsRightName(pSetName, p.Key, pSetNameRule)) { continue; } } foreach (var prop in p.Value) { //if name is not specified all values are returned if (IsRightName(propertyName, prop.Key, propNameRule)) { Type t = ((ExpressType)(prop.Value)).UnderlyingSystemType; Expression right = XbimQueryFactory.PromoteToConstant(t, value); Expression left = XbimQueryFactory.PromoteToConstant(t, prop.Value.ToString()); //todo: this should be more sofisticated than 'ToString()' Expression eval = CreateValueExpression(left, right, valueRule); return Expression.Lambda<Func<bool>>(eval).Compile()(); } } } } return false; }
public void Write(XbimModel model, TextWriter output, IDictionary <int, int> map = null) { _written = new HashSet <long>(); output.Write(HeaderAsString(model.Header ?? new IfcFileHeader(IfcFileHeader.HeaderCreationMode.InitWithXbimDefaults))); foreach (XbimInstanceHandle item in model.InstanceHandles /*.Types.OrderBy(t=>t.Name)*/) { IPersistIfcEntity entity = model.GetInstanceVolatile(item); entity.WriteEntity(output, map); } output.WriteLine("ENDSEC;"); output.WriteLine("END-ISO-10303-21;"); }
public static void AddElements(this MeshGeometry3D m, IPersistIfcEntity item, XbimMatrix3D wcsTransform) { var fromModel = item.ModelOf as XbimModel; if (fromModel == null || !(item is IfcProduct)) return; switch (fromModel.GeometrySupportLevel) { case 2: var context = new Xbim3DModelContext(fromModel); var productShape = context.ShapeInstancesOf((IfcProduct) item) .Where(s => s.RepresentationType != XbimGeometryRepresentationType.OpeningsAndAdditionsExcluded) .ToList(); if (!productShape.Any() && item is IfcFeatureElement) { productShape = context.ShapeInstancesOf((IfcProduct) item) .Where( s => s.RepresentationType == XbimGeometryRepresentationType.OpeningsAndAdditionsExcluded) .ToList(); } if (!productShape.Any()) return; foreach (var shapeInstance in productShape) { IXbimShapeGeometryData shapeGeom = context.ShapeGeometry(shapeInstance.ShapeGeometryLabel); switch ((XbimGeometryType) shapeGeom.Format) { case XbimGeometryType.PolyhedronBinary: m.Read(shapeGeom.ShapeData, XbimMatrix3D.Multiply(shapeInstance.Transformation, wcsTransform)); break; case XbimGeometryType.Polyhedron: m.Read(((XbimShapeGeometry) shapeGeom).ShapeData, XbimMatrix3D.Multiply(shapeInstance.Transformation, wcsTransform)); break; } } break; case 1: var xm3d = new XbimMeshGeometry3D(); var geomDataSet = fromModel.GetGeometryData(item.EntityLabel, XbimGeometryType.TriangulatedMesh); foreach (var geomData in geomDataSet) { var gd = geomData.TransformBy(wcsTransform); xm3d.Add(gd); } m.Add(xm3d); break; } }
public void Set(string variable, IPersistIfcEntity entity) { FixVariableName(ref variable); if (entity == null && IsDefined(variable)) { Clear(variable); } else { Set(variable, new IPersistIfcEntity[] { entity }); } }
public void Clear(string identifier) { FixVariableName(ref identifier); if (IsDefined(identifier)) { _data[identifier] = new IPersistIfcEntity[] { } } ; else { throw new ArgumentException(identifier + " is not defined;"); } }
private static void OnSelectedEntityChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { XbimTreeview view = d as XbimTreeview; if (view != null && e.NewValue is IPersistIfcEntity) { view.UnselectAll(); IPersistIfcEntity newVal = (IPersistIfcEntity)(e.NewValue); if (newVal != null) { view.Select(newVal); } } }
public static StringCollection SummaryString(this IPersistIfcEntity entity) { StringCollection sc = new StringCollection(); sc.Add("Entity\t = #" + entity.EntityLabel); if (entity is IfcRoot) { IfcRoot root = entity as IfcRoot; sc.Add("Guid\t = " + root.GlobalId); sc.Add("Type\t = " + root.GetType().Name); sc.Add("Name\t = " + (root.Name.HasValue ? root.Name.Value.ToString() : root.ToString())); } return(sc); }
/// <summary> /// Gets the geometry of an entity building it up from layers. /// </summary> /// <param name="entity">The entity instance</param> public IXbimMeshGeometry3D GetMeshGeometry3D(IPersistIfcEntity entity, short modelId) { var geometry = new XbimMeshGeometry3D(); IModel m = entity.ModelOf; foreach (var layer in Layers) { // an entity model could be spread across many layers (e.g. in case of different materials) if (layer.Model == m) { geometry.Add(layer.GetVisibleMeshGeometry3D(entity.EntityLabel, modelId)); } } return(geometry); }
private static IModel GetModel(IfcRoot root) { IModel model = null; IPersistIfcEntity persist = root as IPersistIfcEntity; if (persist != null) { model = persist.ModelOf; } if (model == null) { model = root.ModelOf; } return(model); }
public static void SetPropertyTableItemValue(this Xbim.Ifc2x3.Kernel.IfcTypeObject obj, string pSetName, string propertyTableName, IfcValue definingValue, IfcValue definedValue, IfcUnit definingUnit, IfcUnit definedUnit) { IfcPropertySet pset = GetPropertySet(obj, pSetName); IModel model = null; if (pset == null) { IPersistIfcEntity ent = obj as IPersistIfcEntity; model = ent != null ? ent.ModelOf : obj.ModelOf; pset = model.Instances.New <IfcPropertySet>(); pset.Name = pSetName; obj.AddPropertySet(pset); } IfcPropertyTableValue table = GetPropertyTableValue(obj, pSetName, propertyTableName); if (table == null) { IPersistIfcEntity ent = obj as IPersistIfcEntity; model = ent != null ? ent.ModelOf : obj.ModelOf; table = model.Instances.New <IfcPropertyTableValue>(tb => { tb.Name = propertyTableName; }); pset.HasProperties.Add(table); table.DefinedUnit = definedUnit; table.DefiningUnit = definingUnit; } if (table.DefiningUnit != definingUnit || table.DefinedUnit != definedUnit) { throw new Exception("Inconsistent definition of the units in the property table."); } IfcValue itemValue = GetPropertyTableItemValue(obj, pSetName, propertyTableName, definingValue); if (itemValue != null) { itemValue = definedValue; } else { table.DefiningValues.Add(definingValue); table.DefinedValues.Add(definedValue); //check of integrity if (table.DefinedValues.Count != table.DefiningValues.Count) { throw new Exception("Inconsistent state of the property table. Number of defined and defining values are not the same."); } } }
protected override void OnSelectionChanged(System.Windows.Controls.SelectionChangedEventArgs e) { base.OnSelectionChanged(e); if (e.AddedItems.Count > 0) { IPersistIfcEntity p = ((IXbimViewModel)(e.AddedItems[0])).Entity; IPersistIfcEntity p2 = SelectedEntity; if (p2 == null) { SelectedEntity = p; } else if (!(p.ModelOf == p2.ModelOf && p.EntityLabel == p2.EntityLabel)) { SelectedEntity = p; } } }
private void Write(XbimModel model, int handle, XmlWriter output, int pos = -1) { if (_written.Contains(handle)) //we have already done it { return; } //int nextId = _written.Count + 1; _written.Add(handle); IPersistIfcEntity entity = model.GetInstanceVolatile(handle); //load either the cache or a volatile version of the entity IfcType ifcType = IfcMetaData.IfcType(entity); output.WriteStartElement(ifcType.Type.Name); output.WriteAttributeString("id", string.Format("i{0}", handle)); if (pos > -1) //we are writing out a list element { output.WriteAttributeString("pos", pos.ToString()); } IEnumerable <IfcMetaProperty> toWrite; if (WriteInverses) { List <IfcMetaProperty> l = new List <IfcMetaProperty>(ifcType.IfcProperties.Values); l.AddRange(ifcType.IfcInverses); toWrite = l; } else { toWrite = ifcType.IfcProperties.Values; } foreach (IfcMetaProperty ifcProperty in toWrite) //only write out persistent attributes, ignore inverses { if (ifcProperty.IfcAttribute.State != IfcAttributeState.DerivedOverride) { Type propType = ifcProperty.PropertyInfo.PropertyType; object propVal = ifcProperty.PropertyInfo.GetValue(entity, null); WriteProperty(model, ifcProperty.PropertyInfo.Name, propType, propVal, entity, output, -1, ifcProperty.IfcAttribute); } } output.WriteEndElement(); }
private IXbimViewModel FindUnderContainingSpace(IPersistIfcEntity newVal, IfcProduct p) { var ContainingSpace = p.IsContainedIn().FirstOrDefault(); if (ContainingSpace != null) { var ContainingSpaceView = FindItemBreadthFirst(ContainingSpace); if (ContainingSpaceView != null) { var found = FindItemDepthFirst(ContainingSpaceView, newVal); if (found != null) { return(found); } } } return(null); }
/// <summary> /// Creates and returns a new instance of Type t, sets the label to the specificed value. /// This is a reversabel operation /// /// </summary> /// <param name="t"></param> /// <returns></returns> public IPersistIfcEntity New(Type t) { IPersistIfcEntity entity = cache.CreateNew(t); if (typeof(IfcRoot).IsAssignableFrom(t)) { if (_ownerHistoryAddObject == null) //create an owner history object if it is nor already available { _ownerHistoryAddObject = (IfcOwnerHistory)cache.CreateNew(typeof(IfcOwnerHistory)); _ownerHistoryAddObject.ChangeAction = IfcChangeActionEnum.ADDED; _ownerHistoryAddObject.OwningApplication = DefaultOwningApplication; _ownerHistoryAddObject.OwningUser = DefaultOwningUser; } ((IfcRoot)entity).OwnerHistory = _ownerHistoryAddObject; } return(entity); }
private void DataRebind(IPersistIfcEntity entity) { if (_entity != null && !_preventHistory) { _history.Push(_entity); UpdateButtonBack(); } Clear(); //remove any bindings _entity = null; if (entity != null) { _entity = entity; FillTabValues(TheTabs.SelectedItem as TabItem); } else { _entity = null; } }
public IXbimViewModel FindItemDepthFirst(IXbimViewModel node, IPersistIfcEntity entity) { if (IsMatch(node, entity)) { // node.IsExpanded = true; // commented because of new Highlighting mechanisms return(node); } foreach (var child in node.Children) { IXbimViewModel res = FindItemDepthFirst(child, entity); if (res != null) { // node.IsExpanded = true; //commented because of new Highlighting mechanisms return(res); } } return(null); }
public IXbimViewModel FindItemBreadthFirst(IPersistIfcEntity entity) { Queue<IXbimViewModel> queue = new Queue<IXbimViewModel>(); foreach (var item in HierarchySource.OfType<IXbimViewModel>()) { queue.Enqueue(item); } IXbimViewModel current = queue.Dequeue(); while (current != null) { if (IsMatch(current, entity)) { return current; } foreach (var item in current.Children) { queue.Enqueue(item); } current = queue.Dequeue(); } return null; }
public static void WriteEntity(this IPersistIfcEntity entity, BinaryWriter entityWriter) { IfcType ifcType = IfcMetaData.IfcType(entity); // entityWriter.Write(Convert.ToByte(P21ParseAction.NewEntity)); entityWriter.Write(Convert.ToByte(P21ParseAction.BeginList)); foreach (IfcMetaProperty ifcProperty in ifcType.IfcProperties.Values) //only write out persistent attributes, ignore inverses { if (ifcProperty.IfcAttribute.State == IfcAttributeState.DerivedOverride) { entityWriter.Write(Convert.ToByte(P21ParseAction.SetOverrideValue)); } else { Type propType = ifcProperty.PropertyInfo.PropertyType; object propVal = ifcProperty.PropertyInfo.GetValue(entity, null); WriteProperty(propType, propVal, entityWriter); } } entityWriter.Write(Convert.ToByte(P21ParseAction.EndList)); entityWriter.Write(Convert.ToByte(P21ParseAction.EndEntity)); }
/// <summary> /// If the type has indexed attributes, this returns a set of unique values for the specified IPersistIfcEntity /// </summary> /// <param name="ent"></param> /// <returns></returns> internal IEnumerable<int> GetIndexedValues(IPersistIfcEntity ent) { if (IndexedProperties == null) return Enumerable.Empty<int>(); HashSet<int> keys = new HashSet<int>(); foreach (var prop in IndexedProperties) { object o = prop.GetValue(ent, null); if (null!=o && typeof(IPersistIfcEntity).IsAssignableFrom(o.GetType())) { int h = Math.Abs(((IPersistIfcEntity)o).EntityLabel); keys.Add(h); //normally there are only one or two keys so don't worry about performance of contains on a list } else if (null != o && typeof(ExpressEnumerable).IsAssignableFrom(o.GetType())) { foreach (var obj in (ExpressEnumerable)o) { int h = Math.Abs(((IPersistIfcEntity)obj).EntityLabel); keys.Add(h); //normally there are only one or two keys so don't worry about performance of contains on a list } } } return keys; }
private bool EvaluateTypeCondition(IPersistIfcEntity input, Func<IPersistIfcEntity, bool> function) { var obj = input as IfcObject; if (obj == null) return false; var defObj = obj.GetDefiningType(); if (defObj == null) return false; return function(defObj); }
private static PropertyInfo GetAttributeInfo(string name, IPersistIfcEntity entity) { Type type = entity.GetType(); return type.GetProperty(name, BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.Public); }
private bool EvaluateTypeObjectType(IPersistIfcEntity input, Type type, Tokens condition) { IfcObject obj = input as IfcObject; if (obj == null) return false; var typeObj = obj.GetDefiningType(); //null variant if (typeObj == null || type == null) { try { return EvaluateNullCondition(typeObj, type, condition); } catch (Exception e) { Scanner.yyerror(e.Message); return false; } } switch (condition) { case Tokens.OP_EQ: return typeObj.GetType() == type; case Tokens.OP_NEQ: return typeObj.GetType() != type; default: Scanner.yyerror("Unexpected Token in this function. Only OP_EQ or OP_NEQ expected."); return false; } }
private static void SetMaterial(IPersistIfcEntity entity, IfcMaterialSelect material, AbstractScanner<ValueType, LexLocation> scanner) { if (entity == null || material == null) return; var materialSelect = material as IfcMaterialSelect; if (materialSelect == null) { scanner.yyerror(material.GetType() + " can't be used as a material"); return; } var root = entity as IfcRoot; if (root == null) { scanner.yyerror(root.GetType() + " can't have a material assigned."); return; } IModel model = material.ModelOf; var matSet = material as IfcMaterialLayerSet; if (matSet != null) { var element = root as IfcElement; if (element != null) { var usage = model.Instances.New<IfcMaterialLayerSetUsage>(mlsu => { mlsu.DirectionSense = IfcDirectionSenseEnum.POSITIVE; mlsu.ForLayerSet = matSet; mlsu.LayerSetDirection = IfcLayerSetDirectionEnum.AXIS1; mlsu.OffsetFromReferenceLine = 0; }); var rel = model.Instances.New<IfcRelAssociatesMaterial>(r => { r.RelatedObjects.Add_Reversible(root); r.RelatingMaterial = usage; }); return; } } var matUsage = material as IfcMaterialLayerSetUsage; if (matUsage != null) { var typeElement = root as IfcElementType; if (typeElement != null) { //change scope to the layer set for the element type. It will be processed in a standard way than materialSelect = matUsage.ForLayerSet; } } //find existing relation var matRel = model.Instances.Where<IfcRelAssociatesMaterial>(r => r.RelatingMaterial == materialSelect).FirstOrDefault(); if (matRel == null) //create new if none exists matRel = model.Instances.New<IfcRelAssociatesMaterial>(r => r.RelatingMaterial = materialSelect); //insert only if it is not already there if (!matRel.RelatedObjects.Contains(root)) matRel.RelatedObjects.Add_Reversible(root); }
private void SetAttribute(IPersistIfcEntity input, string attrName, object newVal) { if (input == null) return; var attr = GetAttributeInfo(attrName, input); SetValue(attr, input, newVal); }
private bool EvaluateValueCondition(IPersistIfcEntity input, string propertyName, object value, Tokens condition) { //try to get attribute var attr = GetAttributeValue(propertyName, input); var prop = attr as IfcValue; //try to get property if attribute doesn't exist if (prop == null) prop = GetPropertyValue(propertyName, input); return EvaluateValue(prop, value, condition); }
private void SetAttributeOrProperty(IPersistIfcEntity input, string attrName, object newVal) { //try to set attribute as a priority var attr = GetAttributeInfo(attrName, input); if (attr != null) SetValue(attr, input, newVal); else //set property if no such an attribute exist SetProperty(input, attrName, newVal); }
/// <summary> /// Writes the in memory data of the entity to a stream /// </summary> /// <param name = "entityStream"></param> /// <param name = "entityWriter"></param> /// <param name = "item"></param> private static int WriteEntityToSteam(MemoryStream entityStream, BinaryWriter entityWriter, IPersistIfcEntity item) { entityWriter.Seek(0, SeekOrigin.Begin); entityWriter.Write((int)0); item.WriteEntity(entityWriter); int len = Convert.ToInt32(entityStream.Position); entityWriter.Seek(0, SeekOrigin.Begin); entityWriter.Write(len); entityWriter.Seek(0, SeekOrigin.Begin); return len; }
public XbimParserState(IPersistIfcEntity entity) { _currentInstance = new Part21Entity(entity); _processStack.Push(_currentInstance); }
private static bool EvaluateThicknessCondition(IPersistIfcEntity input, double thickness, Tokens condition) { IfcRoot root = input as IfcRoot; if (input == null) return false; double? value = null; var materSel = root.GetMaterial(); IfcMaterialLayerSetUsage usage = materSel as IfcMaterialLayerSetUsage; if (usage != null) if (usage.ForLayerSet != null) value = usage.ForLayerSet.MaterialLayers.Aggregate(0.0, (current, layer) => current + layer.LayerThickness); IfcMaterialLayerSet set = materSel as IfcMaterialLayerSet; if (set != null) value = set.TotalThickness; if (value == null) return false; switch (condition) { case Tokens.OP_EQ: return thickness.AlmostEquals(value ?? 0); case Tokens.OP_NEQ: return !thickness.AlmostEquals(value ?? 0); case Tokens.OP_GT: return value > thickness; case Tokens.OP_LT: return value < thickness; case Tokens.OP_GTE: return value >= thickness; case Tokens.OP_LTQ: return value <= thickness; default: throw new ArgumentException("Unexpected value of the condition"); } }
private static bool EvaluateMaterialCondition(IPersistIfcEntity input, string materialName, Tokens condition) { IfcRoot root = input as IfcRoot; if (root == null) return false; IModel model = root.ModelOf; var materialRelations = model.Instances.Where<IfcRelAssociatesMaterial>(r => r.RelatedObjects.Contains(root)); List<string> names = new List<string>(); foreach (var mRel in materialRelations) { names.AddRange(GetMaterialNames(mRel.RelatingMaterial)); } //convert to lower case for (int i = 0; i < names.Count; i++) names[i] = names[i].ToLower(); switch (condition) { case Tokens.OP_EQ: return names.Contains(materialName.ToLower()); case Tokens.OP_NEQ: return !names.Contains(materialName.ToLower()); case Tokens.OP_CONTAINS: foreach (var name in names) { if (name.Contains(materialName.ToLower())) return true; } break; case Tokens.OP_NOT_CONTAINS: foreach (var name in names) { if (name.Contains(materialName.ToLower())) return false; } break; default: throw new ArgumentOutOfRangeException("Unexpected Token value."); } return false; }
private static bool EvaluateGroupCondition(IPersistIfcEntity input, Func<IPersistIfcEntity, bool> function) { foreach (var item in GetGroups(input)) { if (function(item)) return true; } return false; }
private void SetProperty(IPersistIfcEntity entity, string name, object newVal) { //try to get existing property object pObject = null; var pInfo = GetPropertyInfo(name, entity, out pObject); if (pInfo != null) { SetValue(pInfo, pObject, newVal); } //create new property if no such a property or quantity exists else { //try to get the name of the pSet if it is encoded in there var split = name.Split(new[] { "\n" }, StringSplitOptions.RemoveEmptyEntries); string pSetName = null; if (split.Count() == 2) { pSetName = split[0]; name = split[1]; } //prepare potential objects IfcObject obj = entity as IfcObject; IfcTypeObject typeObj = entity as IfcTypeObject; IfcMaterial material = entity as IfcMaterial; //set new property in specified or default property set pSetName = pSetName ?? Defaults.DefaultPSet; IfcValue val = null; if (newVal != null) val = CreateIfcValueFromBasicValue(newVal, name); if (obj != null) { obj.SetPropertySingleValue(pSetName, name, val); } else if (typeObj != null) { typeObj.SetPropertySingleValue(pSetName, name, val); } else if (material != null) { material.SetExtendedSingleValue(pSetName, name, val); } } }
public void Set(string variable, IPersistIfcEntity entity) { FixVariableName(ref variable); if (entity == null && IsDefined(variable)) Clear(variable); else Set(variable, new IPersistIfcEntity[] { entity }); }
private static object GetAttributeValue(string name, IPersistIfcEntity entity) { PropertyInfo pInfo = GetAttributeInfo(name, entity); if (pInfo == null) return null; return pInfo.GetValue(entity, null); }
public IEnumerable<IPersistIfcEntity> GetEntities(string variable) { FixVariableName(ref variable); IEnumerable<IPersistIfcEntity> result = new IPersistIfcEntity[] { }; _data.TryGetValue(variable, out result); return result; }
private static IEnumerable<IfcGroup> GetGroups(IPersistIfcEntity input) { IModel model = input.ModelOf; var obj = input as IfcObjectDefinition; if (obj != null) { var rels = model.Instances.Where<IfcRelAssignsToGroup>(r => r.RelatedObjects.Contains(input)); foreach (var rel in rels) { yield return rel.RelatingGroup; //recursive search for upper groups in the hierarchy foreach (var gr in GetGroups(rel.RelatingGroup)) { yield return gr; } } } }
private static IEnumerable<int> ReportProp(TextHighliter sb, string IndentationHeader, IPersistIfcEntity entity, IfcMetaProperty prop, bool Verbose) { List<int> RetIds = new List<int>(); string propName = prop.PropertyInfo.Name; Type propType = prop.PropertyInfo.PropertyType; string ShortTypeName = CleanPropertyName(propType.FullName); object propVal = prop.PropertyInfo.GetValue(entity, null); if (propVal == null) propVal = "<null>"; if (prop.IfcAttribute.IsEnumerable) { IEnumerable<object> propCollection = propVal as IEnumerable<object>; propVal = propVal.ToString() + " [not an enumerable]"; if (propCollection != null) { propVal = "<empty>"; int iCntProp = 0; foreach (var item in propCollection) { iCntProp++; if (iCntProp == 1) propVal = ReportPropValue(item, ref RetIds); else { if (iCntProp == 2) { propVal = "\r\n" + IndentationHeader + " " + propVal; } propVal += "\r\n" + IndentationHeader + " " + ReportPropValue(item, ref RetIds); } } } } else propVal = ReportPropValue(propVal, ref RetIds); if (Verbose) sb.AppendFormat(IndentationHeader + "- {0} ({1}): {2}", propName, // 0 ShortTypeName, // 1 propVal // 2 ); else { if ((string)propVal != "<null>" && (string)propVal != "<empty>") { sb.AppendFormat(IndentationHeader + "- {0}: {1}", propName, // 0 propVal // 1 ); } } return RetIds; }
private static PropertyInfo GetPropertyInfo(string name, IPersistIfcEntity entity, out object propertyObject) { //try to get the name of the pSet if it is encoded in there var split = name.Split(new[] { "\n" }, StringSplitOptions.RemoveEmptyEntries); string pSetName = null; if (split.Count() == 2) { pSetName = split[0]; name = split[1]; } var specificPSet = pSetName != null; List<IfcPropertySet> pSets = null; IEnumerable<IfcExtendedMaterialProperties> pSetsMaterial = null; IEnumerable<IfcElementQuantity> elQuants = null; IfcPropertySingleValue property = null; IfcPhysicalSimpleQuantity quantity = null; IfcPropertySet ps = null; IfcElementQuantity eq = null; IfcExtendedMaterialProperties eps = null; IfcObject obj = entity as IfcObject; if (obj != null) { if (specificPSet) { ps = obj.GetPropertySet(pSetName); eq = obj.GetElementQuantity(pSetName); } pSets = ps == null ? obj.GetAllPropertySets() : new List<IfcPropertySet>(){ps}; elQuants = eq == null ? obj.GetAllElementQuantities() : new List<IfcElementQuantity>() { eq }; } IfcTypeObject typeObj = entity as IfcTypeObject; if (typeObj != null) { if (specificPSet) { ps = typeObj.GetPropertySet(pSetName); eq = typeObj.GetElementQuantity(pSetName); } pSets = ps == null ? typeObj.GetAllPropertySets() : new List<IfcPropertySet>() { ps }; elQuants = eq == null ? typeObj.GetAllElementQuantities() : new List<IfcElementQuantity>() { eq}; } IfcMaterial material = entity as IfcMaterial; if (material != null) { if (specificPSet) eps = material.GetExtendedProperties(pSetName); pSetsMaterial = eps == null ? material.GetAllPropertySets() : new List<IfcExtendedMaterialProperties>() { eps }; } if (pSets != null) foreach (var pSet in pSets) { foreach (var prop in pSet.HasProperties) { if (prop.Name.ToString().ToLower() == name.ToLower()) property = prop as IfcPropertySingleValue; } } if (pSetsMaterial != null) foreach (var pSet in pSetsMaterial) { foreach (var prop in pSet.ExtendedProperties) { if (prop.Name.ToString().ToLower() == name.ToLower()) property = prop as IfcPropertySingleValue; } } if (elQuants != null) foreach (var quant in elQuants) { foreach (var item in quant.Quantities) { if (item.Name.ToString().ToLower() == name.ToLower()) quantity = item as IfcPhysicalSimpleQuantity; } } //set property if (property != null) { propertyObject = property; return property.GetType().GetProperty("NominalValue"); } //set simple quantity else if (quantity != null) { PropertyInfo info = null; var qType = quantity.GetType(); switch (qType.Name) { case "IfcQuantityLength": info = qType.GetProperty("LengthValue"); break; case "IfcQuantityArea": info = qType.GetProperty("AreaValue"); break; case "IfcQuantityVolume": info = qType.GetProperty("VolumeValue"); break; case "IfcQuantityCount": info = qType.GetProperty("CountValue"); break; case "IfcQuantityWeight": info = qType.GetProperty("WeightValue"); break; case "IfcQuantityTime": info = qType.GetProperty("TimeValue"); break; default: throw new NotImplementedException(); } if (info != null) { propertyObject = quantity; return info; } } propertyObject = null; return null; }
private static IfcValue GetPropertyValue(string name, IPersistIfcEntity entity) { object pObject = null; var pInfo = GetPropertyInfo(name, entity, out pObject); if (pInfo == null) return null; var result = pInfo.GetValue(pObject, null); return result as IfcValue; }
private static bool IsOfType(Type type, IPersistIfcEntity entity) { return type.IsAssignableFrom(entity.GetType()); }
private bool EvaluateSpatialCondition(IPersistIfcEntity input, Tokens op, Tokens condition, IEnumerable<IfcProduct> right) { IfcProduct left = input as IfcProduct; if (left == null) { Scanner.yyerror(input.GetType().Name + " can't have a spatial condition."); return false; } switch (condition) { case Tokens.NORTH_OF: break; case Tokens.SOUTH_OF: break; case Tokens.WEST_OF: break; case Tokens.EAST_OF: break; case Tokens.ABOVE: break; case Tokens.BELOW: break; case Tokens.SPATIALLY_EQUALS: break; case Tokens.DISJOINT: break; case Tokens.INTERSECTS: break; case Tokens.TOUCHES: break; case Tokens.CROSSES: break; case Tokens.WITHIN: break; case Tokens.SPATIALLY_CONTAINS: break; case Tokens.OVERLAPS: break; case Tokens.RELATE: break; default: break; } throw new NotImplementedException(); }
private bool EvaluateTypeObjectName(IPersistIfcEntity input, string typeName, Tokens condition) { IfcObject obj = input as IfcObject; if (obj == null) return false; var type = obj.GetDefiningType(); //null variant if (type == null) { return false; } switch (condition) { case Tokens.OP_EQ: return type.Name == typeName; case Tokens.OP_NEQ: return type.Name != typeName; case Tokens.OP_CONTAINS: return type.Name.ToString().ToLower().Contains(typeName.ToLower()); case Tokens.OP_NOT_CONTAINS: return !type.Name.ToString().ToLower().Contains(typeName.ToLower()); default: Scanner.yyerror("Unexpected Token in this function. Only equality or containment expected."); return false; } }