public Wall(int x, int y, WallType wallType)
        {
            this.x = x;
            this.y = y;

            if(wallType == WallType.Brick)
            {
                spriteWidth = 20;
                spriteHeight = 20;

                offset = 2;
            }
            else
            {
                spriteWidth = 40;
                spriteHeight = 40;

                isDestroyable = false;
            }

            sourceRect = new Rectangle(spriteWidth * 16 * offset, spriteHeight, spriteWidth, spriteHeight);

            rectangle = new Rectangle(x, y, spriteWidth, spriteHeight); //needed for collision updates

            isStatic = true;
        }
        public override void Deserialize(IntVector3 position, SerializedObject serializedObject)
        {
            this.Type = (WallType) serializedObject.Properties[0];
            this.rotation = (Rotation) serializedObject.Properties[1];

            SpawnWall(this.Type, position, this.rotation);
        }
Exemple #3
0
 public WallUnit(World world, int x, int y, WallType wallType)
     : base(world, WorldLaw.DefaultUnitCreationSpeed,
     WorldLaw.DefaultEnemyLifeCount)
 {
     WallUnitType = wallType;
     SetLocation(x, y);
 }
Exemple #4
0
 public WallUnit(World world, Point point, WallType wallType)
     : base(world, WorldLaw.DefaultUnitCreationSpeed,
     WorldLaw.DefaultEnemyLifeCount)
 {
     WallUnitType = wallType;
     SetLocation(point.X, point.Y);
 }
Exemple #5
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Wall"/> class.
 /// </summary>
 /// <param name="width">The width.</param>
 /// <param name="height">The height.</param>
 /// <param name="color">The color.</param>
 /// <param name="wallTypeEnum">Type of the wall.</param>
 public Wall(int width, int height, Color color, WallType.WallTypeEnum wallTypeEnum)
 {
     Height = height;
       Width = width;
       WallColor = color;
       WallType = wallTypeEnum;
 }
Exemple #6
0
    void ChangeWallInDirection(Facing direction, WallType newType)
    {
        GrabTilesFromSelection();

        string prefabPath = "";
        Wall newWall = null;

        switch(newType) {
            case WallType.Basic:
                prefabPath = "Assets/Prefabs/Walls/Basic Wall.prefab";
                break;
            case WallType.Laser:
                prefabPath = "Assets/Prefabs/Walls/Laser Wall.prefab";
                break;
            default:
                Debug.Log("No path for replacement prefab!");
                break;
        }

        var prefab = Resources.LoadAssetAtPath(prefabPath, typeof(Wall));

        if (null == prefab) {
            Debug.Log("Replacement prefab not found!");
            return;
        }

        foreach (Tile tile in selectedTiles) {
            Wall wallToChange = tile.adjacentWalls[(int)direction];

            if (null == wallToChange) {
                Debug.Log("Wall doesn't exist in that direction!");
                continue;
            }

            if (wallToChange.wallType == newType) {
                Debug.Log("Existing wall is already this type.");
                continue;
            }

            newWall = (Wall)GameObject.Instantiate(prefab, wallToChange.transform.position, wallToChange.transform.rotation);
            newWall.transform.parent = wallToChange.transform.parent;
            newWall.facing = wallToChange.facing;
            newWall.adjacentTiles = wallToChange.adjacentTiles;
            newWall.Setup();
            TileVisualizer.instance.SetVisualizationForWall(newWall);

            foreach (Tile adjTile in wallToChange.adjacentTiles) {
                if (adjTile.adjacentWalls[(int)direction] == wallToChange) {
                    adjTile.adjacentWalls[(int)direction] = newWall;
                }
                if (adjTile.adjacentWalls[(int)Utils.UTurnFacing(direction)] == wallToChange) {
                    adjTile.adjacentWalls[(int)Utils.UTurnFacing(direction)] = newWall;
                }
            }

            DestroyImmediate(wallToChange.gameObject);
        }
    }
        public LabyrinthUnit(Game game, int posX, int posY, int indexX, int indexY, WallType wallType)
            : base(game)
        {
            Wall = wallType;

            TopLeftPosition = new Vector2(posX, posY);
            _topRightPosition = new Vector2(posX + Length, posY);
            _bottomLeftPosition = new Vector2(posX, posY + Length);

            SetCurrentPosition();

            _indexX = indexX;
            _indexY = indexY;
        }
Exemple #8
0
 /// <summary>
 /// Another constructor for the WallTile.
 /// Chooses random decorations for the wall.
 /// </summary>
 /// <param name="parent"></param>
 /// <param name="r">A random used to choose the deco.</param>
 public WallTile(object parent, Random r)
     : base(parent)
 {
     if (r.Next(100) > 80)
     {
         _type = Backend.WallType.Deco1;
     }
     if (r.Next(100) > 80)
     {
         _type = Backend.WallType.Deco3;
     }
     if (r.Next(100) > 80)
     {
         _type = Backend.WallType.Deco2;
     }
 }
Exemple #9
0
        public Wall(Vertices vertices, WallType type, PlayWindow playWindow)
        {
            _playWindow = playWindow;

            _thickness = 100.0f;

            Vertices wallVertices = SimplifyTools.CollinearSimplify(vertices);
            _body = BodyFactory.CreateLoopShape(_playWindow.World, VerticesToSimUnits(wallVertices));
            _body.CollisionCategories = Category.All;
            _body.CollidesWith = Category.All;

            _basicEffect = new BasicEffect(_playWindow.GraphicsDevice);
            _basicEffect.TextureEnabled = true;
            _basicEffect.Texture = _wallTexture;

            InitDrawVertices(wallVertices, type);
        }
Exemple #10
0
 public Block(Block b)
 {
     id = b.id;
     color = b.color;
     edges = new List<Edge>();
     behaviors = new List<Behavior>();
     scales = b.scales;
     depth = b.depth;
     type = b.type;
     foreach (Edge e in b.edges)
     {
         edges.Add(new Edge(e));
     }
     foreach (Behavior be in b.behaviors)
     {
         behaviors.Add(new Behavior(be));
     }
 }
Exemple #11
0
 public Door(Vector2 position, World world, float width, float height, float density, WallType type, Direction d)
     : base(position, world, width, height, density, type, d)
 {
     this.type = type;
     textureString = "solitudeWallDoor";
     if (type == WallType.Grip)
     {
         textureString = "solitudeGripDoor";
     }
     direction = d;
     switch (d)
     {
         case Direction.Up: body.Rotation = (float)(3 * Math.PI / 2); break;
         case Direction.Down: body.Rotation = (float)(Math.PI / 2); break;
         case Direction.Left: body.Rotation = (float)Math.PI; break;
         case Direction.Right: body.Rotation = 0; break;
     }
     //body.Rotation = (float)((int)d * (Math.PI / 2));
 }
Exemple #12
0
        public static void FillNode(TreeNode nd, WallType Type, dsWall dsWall, int ID)
        {
            switch (Type)
            {
                case WallType.Wall:
                    nd.Tag = new Wall(dsWall, ID);
                    break;
                case WallType.Arc:
                    nd.Tag = new WallArc(dsWall, ID);
                    break;
                case WallType.Line:
                    nd.Tag = new WallLine(dsWall, ID);
                    break;
                case WallType.Corner:
                    nd.Tag = new WallCorner(dsWall, ID);
                    break;
            }

            nd.Text = (nd.Tag as WallSection).FullName;
            nd.ImageKey = (nd.Tag as WallSection).Type.ToString();
            nd.SelectedImageKey = (nd.Tag as WallSection).Type.ToString();
        }
Exemple #13
0
 public static GameObject GetWall(WallType type)
 {
     switch (type) {
     case WallType.OneByZero:
         return GameObject.Instantiate(GameManager.Instance.wallSmallPrefab, Vector3.zero, Quaternion.identity) as GameObject;
     case WallType.TwoByOne:
         return GameObject.Instantiate(GameManager.Instance.wallLargePrefab, Vector3.zero, TWO_BY_ONE_QUAT) as GameObject;
     case WallType.OneByOne:
         return GameObject.Instantiate(GameManager.Instance.wallMediumPrefab, Vector3.zero, ONE_BY_ONE_QUAT) as GameObject;
     case WallType.OneByTwo:
         return GameObject.Instantiate(GameManager.Instance.wallLargePrefab, Vector3.zero, ONE_BY_TWO_QUAT) as GameObject;
     case WallType.ZeroByOne:
         return GameObject.Instantiate(GameManager.Instance.wallSmallPrefab, Vector3.zero, ZERO_BY_ONE_QUAT) as GameObject;
     case WallType.OneByTwoFlipped:
         return GameObject.Instantiate(GameManager.Instance.wallLargePrefab, Vector3.zero, ONE_BY_TWO_FLIPPED_QUAT) as GameObject;
     case WallType.OneByOneFlipped:
         return GameObject.Instantiate(GameManager.Instance.wallMediumPrefab, Vector3.zero, ONE_BY_ONE_FLIPPED_QUAT) as GameObject;
     case WallType.TwoByOneFlipped:
         return GameObject.Instantiate(GameManager.Instance.wallLargePrefab, Vector3.zero, TWO_BY_ONE_FLIPPED_QUAT) as GameObject;
     default:
         return null;
         break;
     }
 }
Exemple #14
0
        public Wall(Vector2 position, World world, float width, float height, float density, WallType t, Direction d)
            : base(position, world, width, height)
        {
            body.Rotation = 0;

            if (d == Direction.Up || d == Direction.Down) // Up or down
            {
                body.Rotation = (float)Math.PI / 2;
            }

            body.BodyType = BodyType.Static;
            //world.AddBody(body);
            fixture = FixtureFactory.CreateRectangle(width, height, density, Vector2.Zero, body, null);
            fixture.OnCollision += new OnCollisionEventHandler(OnCollision);
            type = t;
            this.width = width;
            this.height = height;

            drawRectangle = new Rectangle(0, 0, (int)width, (int)height);
            switch (type){
                case WallType.Smooth:
                    textureString = /*TextureStatic.Get(*/"solitudeWallSmooth";      break;
                case WallType.HandHold:
                    textureString = /*TextureStatic.Get(*/"solitudeWallHandHold";    break;
                case WallType.Grip:
                    textureString = /*TextureStatic.Get(*/"solitudeWallGrip";        break;
                case WallType.Metal:
                    textureString = /*TextureStatic.Get(*/"solitudeWallMetal";       break;
                case WallType.Hot:
                    textureString = /*TextureStatic.Get(*/"solitudeWallHot";         break;
                case WallType.Cold:
                    textureString = /*TextureStatic.Get(*/"solitudeWallCold";        break;
                case WallType.Spike:
                    textureString = /*TextureStatic.Get(*/"solitudeWallSpike";       break;
            }
        }
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            // Path of file
            string filePath = null;

            // Using Windows form to get file path
            using (Data form = new Data())
            {
                OpenFileDialog browserDialog = new OpenFileDialog();
                browserDialog.ShowDialog();
                if (browserDialog.FileName != null)
                {
                    filePath = browserDialog.FileName;
                }
                else
                {
                    return(Result.Cancelled);
                }
            }


            // Get Dxf document
            DxfDocument document = DxfDocument.Load(filePath);

            // Get Revit UI document
            UIDocument uIDocument = commandData.Application.ActiveUIDocument;

            // Get Revit document
            Document rvtDocument = uIDocument.Document;

            //Get Level of revit file
            List <Level> levels = new FilteredElementCollector(rvtDocument)
                                  .OfCategory(BuiltInCategory.OST_Levels)
                                  .WhereElementIsNotElementType().Cast <Level>().ToList();

            // Get Wall Type
            var wallType = new FilteredElementCollector(rvtDocument)
                           .OfCategory(BuiltInCategory.OST_Walls)
                           .WhereElementIsElementType()
                           .Cast <WallType>()
                           .FirstOrDefault();


            // Get Layers of dxf file
            List <Layer> layers = document.Layers.ToList();

            // Declear variables
            string base_level_name = null;

            string top_level_name = null;

            string column_layer = null;

            string wall_layer = null;

            string floor_layer = null;

            // Get Data from user by form
            using (Data form = new Data())
            {
                // Set dxf layers to comboBoxs
                form.ComboBox_wall_layer.Items.AddRange(layers.Select(layer => (object)layer).ToArray());

                form.ComboBox_col_layer.Items.AddRange(layers.Select(layer => (object)layer).ToArray());

                form.ComboBox_floor_layer.Items.AddRange(layers.Select(layer => (object)layer).ToArray());

                // Set levels to ComboBoxs
                form.ComboBox_base_level.Items.AddRange(levels.Select(l => (object)l.Name).ToArray());

                form.ComboBox_top_level.Items.AddRange(levels.Select(l => (object)l.Name).ToArray());

                form.ShowDialog();


                if (form.DialogResult == System.Windows.Forms.DialogResult.Cancel)
                {
                    return(Result.Cancelled);
                }
                else if (form.Button_ok.DialogResult == System.Windows.Forms.DialogResult.OK)
                {
                    //Get Data from ComboBoxs

                    base_level_name = form.ComboBox_base_level.SelectedItem.ToString();

                    top_level_name = form.ComboBox_top_level.SelectedItem.ToString();

                    wall_layer = form.ComboBox_wall_layer.SelectedItem.ToString();

                    column_layer = form.ComboBox_col_layer.SelectedItem.ToString();

                    floor_layer = form.ComboBox_floor_layer.SelectedItem.ToString();
                }
            }

            // Get Data of vertix and its layer by sending document and layers
            Dxf_Vertices vertices = new Dxf_Vertices(document, column_layer, wall_layer, floor_layer);

            // Get Column Vertix
            Dxf_Column columns = new Dxf_Column(vertices);

            // Get Walls Vertix
            Dxf_Wall walls = new Dxf_Wall(vertices);

            // Get Floor Vertix
            Dxf_Floor floor = new Dxf_Floor(vertices);



            RVT_Col rVT_Col = new RVT_Col(columns.Points);

            RVT_Wall rVT_Wall = new RVT_Wall(walls.Walls_center);

            RVT_Floor rVT_Floor = new RVT_Floor(floor.Floor_boundary);



            Level base_level = GetLEVEL(rvtDocument, base_level_name);

            Level top_level = GetLEVEL(rvtDocument, top_level_name);

            FamilySymbol symbol;

            using (Transaction t = new Transaction(rvtDocument, "Load"))
            {
                t.Start();

                bool ff = rvtDocument.LoadFamily($"{Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)}\\Concrete-Rectangular-Column.rfa");

                symbol = new FilteredElementCollector(rvtDocument).OfClass(typeof(FamilySymbol))
                         .WhereElementIsElementType()
                         .Cast <FamilySymbol>()
                         .First(x => x.Name == "12 x 18");

                symbol.Activate();

                t.Commit();
            }


            using (Transaction t = new Transaction(rvtDocument, "Create "))
            {
                t.Start();


                WallType newWallType = CreateWallType(rvtDocument, wallType, 300);

                rVT_Col.CreateColumns(rvtDocument, symbol, base_level, top_level);

                rVT_Wall.CreateWalls(rvtDocument, newWallType, base_level, top_level);

                rVT_Floor.CreateFloor(rvtDocument, top_level);

                t.Commit();
            }

            return(Result.Succeeded);
        }
Exemple #16
0
 public bool Contains(WallType wall)
 {
     return (wallMask & (1 << ((byte)wall - 1))) > 0;
 }
Exemple #17
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Application   app   = uiapp.Application;
            Document      doc   = uidoc.Document;

            // Open source project

            Document docHasFamily = app.OpenDocumentFile(
                _source_project_path);

            // Find system family to copy, e.g. using a named wall type

            WallType wallType = null;

            //WallTypeSet wallTypes = docHasFamily.WallTypes; // 2013

            FilteredElementCollector wallTypes
                = new FilteredElementCollector(docHasFamily) // 2014
                  .OfClass(typeof(WallType));

            int i = 0;

            foreach (WallType wt in wallTypes)
            {
                string name = wt.Name;

                Debug.Print("  {0} {1}", ++i, name);

                if (name.Equals(_wall_type_name))
                {
                    wallType = wt;
                    break;
                }
            }

            if (null == wallType)
            {
                message = string.Format(
                    "Cannot find source wall type '{0}'"
                    + " in source document '{1}'. ",
                    _wall_type_name, _source_project_path);

                return(Result.Failed);
            }

            // Create a new wall type in current document

            using (Transaction t = new Transaction(doc))
            {
                t.Start("Transfer Wall Type");

                WallType newWallType = null;

                //WallTypeSet wallTypes = doc.WallTypes; // 2013

                wallTypes = new FilteredElementCollector(doc)
                            .OfClass(typeof(WallType)); // 2014

                foreach (WallType wt in wallTypes)
                {
                    if (wt.Kind == wallType.Kind)
                    {
                        newWallType = wt.Duplicate(_wall_type_name)
                                      as WallType;

                        Debug.Print(string.Format(
                                        "New wall type '{0}' created.",
                                        _wall_type_name));

                        break;
                    }
                }

                // Assign parameter values from source wall type:

#if COPY_INDIVIDUAL_PARAMETER_VALUE
                // Example: individually copy the "Function" parameter value:

                BuiltInParameter bip      = BuiltInParameter.FUNCTION_PARAM;
                string           function = wallType.get_Parameter(bip).AsString();
                Parameter        p        = newWallType.get_Parameter(bip);
                p.Set(function);
#endif // COPY_INDIVIDUAL_PARAMETER_VALUE

                Parameter p = null;

                foreach (Parameter p2 in newWallType.Parameters)
                {
                    Definition d = p2.Definition;

                    if (p2.IsReadOnly)
                    {
                        Debug.Print(string.Format(
                                        "Parameter '{0}' is read-only.", d.Name));
                    }
                    else
                    {
                        p = wallType.get_Parameter(d);

                        if (null == p)
                        {
                            Debug.Print(string.Format(
                                            "Parameter '{0}' not found on source wall type.",
                                            d.Name));
                        }
                        else
                        {
                            if (p.StorageType == StorageType.ElementId)
                            {
                                // Here you have to find the corresponding
                                // element in the target document.

                                Debug.Print(string.Format(
                                                "Parameter '{0}' is an element id.",
                                                d.Name));
                            }
                            else
                            {
                                if (p.StorageType == StorageType.Double)
                                {
                                    p2.Set(p.AsDouble());
                                }
                                else if (p.StorageType == StorageType.String)
                                {
                                    p2.Set(p.AsString());
                                }
                                else if (p.StorageType == StorageType.Integer)
                                {
                                    p2.Set(p.AsInteger());
                                }
                                Debug.Print(string.Format(
                                                "Parameter '{0}' copied.", d.Name));
                            }
                        }
                    }

                    // Note:
                    // If a shared parameter parameter is attached,
                    // you need to create the shared parameter first,
                    // then copy the parameter value.
                }

                // If the system family type has some other properties,
                // you need to copy them as well here. Reflection can
                // be used to determine the available properties.

                MemberInfo[] memberInfos = newWallType.GetType()
                                           .GetMembers(BindingFlags.GetProperty);

                foreach (MemberInfo m in memberInfos)
                {
                    // Copy the writable property values here.
                    // As there are no property writable for
                    // Walltype, I ignore this process here.
                }
                t.Commit();
            }
            return(Result.Succeeded);
        }
Exemple #18
0
 public Wall(Segment seg_, WallType type_)
 {
     seg = seg_;
     type = type_;
 }
Exemple #19
0
    public void BuildWall(ref Vec2i index, int count, WallType type, bool reverse)
    {
        if (reverse) {
            index -= wallOffsets[(int)type] * count;
        }

        BuildWall(index, count, type);

        if (!reverse) {
            index += wallOffsets[(int)type] * count;
        }
    }
        void RoomFinish(UIDocument uiDoc, Transaction tx)
        {
            Document doc = uiDoc.Document;

            tx.Start(Tools.LangResMan.GetString("roomFinishes_transactionName", Tools.Cult));

            //Load the selection form
            RoomsFinishesControl userControl = new RoomsFinishesControl(uiDoc);

            userControl.InitializeComponent();

            if (userControl.ShowDialog() == true)
            {
                //Select wall types
                WallType plinte      = userControl.SelectedWallType;
                WallType newWallType = userControl.DuplicatedWallType;

                //Get all finish properties
                double height = userControl.BoardHeight;

                //Select Rooms in model
                IEnumerable <Room> modelRooms = userControl.SelectedRooms;

                Dictionary <ElementId, ElementId> skirtingDictionary = new Dictionary <ElementId, ElementId>();
                List <KeyValuePair <Wall, Wall> > addedWalls         = new List <KeyValuePair <Wall, Wall> >();

                //Loop on all rooms to get boundaries
                foreach (Room currentRoom in modelRooms)
                {
                    ElementId roomLevelId = currentRoom.LevelId;

                    SpatialElementBoundaryOptions opt = new SpatialElementBoundaryOptions();
                    opt.SpatialElementBoundaryLocation = SpatialElementBoundaryLocation.Finish;

                    IList <IList <Autodesk.Revit.DB.BoundarySegment> > boundarySegmentArray = currentRoom.GetBoundarySegments(opt);
                    if (null == boundarySegmentArray)  //the room may not be bound
                    {
                        continue;
                    }

                    foreach (IList <Autodesk.Revit.DB.BoundarySegment> boundarySegArr in boundarySegmentArray)
                    {
                        if (0 == boundarySegArr.Count)
                        {
                            continue;
                        }
                        else
                        {
                            foreach (Autodesk.Revit.DB.BoundarySegment boundarySegment in boundarySegArr)
                            {
                                //Check if the boundary is a room separation lines
                                Element boundaryElement = doc.GetElement(boundarySegment.ElementId);

                                if (boundaryElement == null)
                                {
                                    continue;
                                }

                                Categories categories            = doc.Settings.Categories;
                                Category   RoomSeparetionLineCat = categories.get_Item(BuiltInCategory.OST_RoomSeparationLines);

                                if (boundaryElement.Category.Id != RoomSeparetionLineCat.Id)
                                {
                                    Wall      currentWall       = Wall.Create(doc, boundarySegment.GetCurve(), newWallType.Id, roomLevelId, height, 0, false, false);
                                    Parameter wallJustification = currentWall.get_Parameter(BuiltInParameter.WALL_KEY_REF_PARAM);
                                    wallJustification.Set(2);

                                    skirtingDictionary.Add(currentWall.Id, boundarySegment.ElementId);
                                }
                            }
                        }
                    }
                }

                FailureHandlingOptions options = tx.GetFailureHandlingOptions();

                options.SetFailuresPreprocessor(new PlintePreprocessor());
                // Now, showing of any eventual mini-warnings will be postponed until the following transaction.
                tx.Commit(options);

                tx.Start(Tools.LangResMan.GetString("roomFinishes_transactionName", Tools.Cult));

                List <ElementId> addedIds = new List <ElementId>(skirtingDictionary.Keys);
                foreach (ElementId addedSkirtingId in addedIds)
                {
                    if (doc.GetElement(addedSkirtingId) == null)
                    {
                        skirtingDictionary.Remove(addedSkirtingId);
                    }
                }

                Wall.ChangeTypeId(doc, skirtingDictionary.Keys, plinte.Id);

                //Join both wall
                if (userControl.JoinWall)
                {
                    foreach (ElementId skirtingId in skirtingDictionary.Keys)
                    {
                        Wall skirtingWall = doc.GetElement(skirtingId) as Wall;

                        if (skirtingWall != null)
                        {
                            Parameter wallJustification = skirtingWall.get_Parameter(BuiltInParameter.WALL_KEY_REF_PARAM);
                            wallJustification.Set(3);
                            Wall baseWall = doc.GetElement(skirtingDictionary[skirtingId]) as Wall;

                            if (baseWall != null)
                            {
                                JoinGeometryUtils.JoinGeometry(doc, skirtingWall, baseWall);
                            }
                        }
                    }
                }

                doc.Delete(newWallType.Id);

                tx.Commit();
            }
            else
            {
                tx.RollBack();
            }
        }
        public frmWall(Wall wall)
        {
            InitializeComponent();
            _wall                  = wall;
            _level                 = wall.Level;
            _wallType              = _wall.WallType;
            _building              = _level.Building;
            _levelList             = _building.LevelList;
            _wallTypeList          = _building.WallTypeList;
            _tmpStartPoint         = (Point2D)_wall.StartPoint.Clone();
            _tmpEndPoint           = (Point2D)_wall.EndPoint.Clone();
            _tmpVertSpacingSetting = (BarSpacingSettings)_wall.VertSpacingSetting.Clone();
            _tmpHorSpacingSetting  = (BarSpacingSettings)_wallType.HorSpacingSetting.Clone();

            tbName.Text                  = _wall.Name;
            tbStartCoord.Text            = _wall.StartPoint.PointText();
            tbEndCoord.Text              = _wall.EndPoint.PointText();
            nudConcreteStartOffset.Value = _wall.ConcreteStartOffset;
            nudConcreteEndOffset.Value   = _wall.ConcreteEndOffset;
            cbRewriteHeight.Checked      = _wall.ReWriteHeight;
            nudHeight.Value              = _wall.Height;
            if (_wall.OverrideVertSpacing)
            {
                tbVertSpacing.Text = _wall.VertSpacingSetting.SpacingText();
            }
            else
            {
                tbVertSpacing.Text = _wall.WallType.VertSpacingSetting.SpacingText();
            }
            if (_wall.OverrideHorSpacing)
            {
                tbHorSpacing.Text = _wall.HorSpacingSetting.SpacingText();
            }
            else
            {
                tbHorSpacing.Text = _wall.WallType.HorSpacingSetting.SpacingText();
            }
            cbOverrideVertSpacing.Checked     = _wall.OverrideVertSpacing;
            cbOverrideHorSpacing.Checked      = _wall.OverrideHorSpacing;
            nudReinforcementStartOffset.Value = _wall.ReiforcementStartOffset;
            nudReinforcementEndOffset.Value   = _wall.ReiforcementEndOffset;
            int Counter = 0;

            foreach (Level levelItem in _levelList)
            {
                cbLevels.Items.Add(levelItem.Name);
                if (ReferenceEquals(levelItem, _level))
                {
                    cbLevels.SelectedIndex = Counter;
                }
                Counter++;
            }
            Counter = 0;
            foreach (WallType wallTypeItem in _wallTypeList)
            {
                cbWallTypes.Items.Add(wallTypeItem.Name);
                if (ReferenceEquals(wallTypeItem, _wallType))
                {
                    cbWallTypes.SelectedIndex = Counter;
                }
                Counter++;
            }
        }
Exemple #22
0
 /// <summary>
 /// Set the necessary data which support the wall creation
 /// </summary>
 /// <param name="startPoint">the start point of the wall</param>
 /// <param name="endPoint">the end point of the wall</param>
 /// <param name="level">the level which the wall base on</param>
 /// <param name="type">the type of the wall</param>
 public void SetNecessaryData(Autodesk.Revit.DB.XYZ startPoint, Autodesk.Revit.DB.XYZ endPoint, Level level, WallType type)
 {
     m_startPoint  = startPoint; // start point
     m_endPoint    = endPoint;   // end point
     m_createlevel = level;      // the level information
     m_createType  = type;       // the wall type
 }
Exemple #23
0
        /// <summary>
        /// Cumulate the compound wall layer volumes for the given wall.
        /// </summary>
        void GetWallLayerVolumes(
            Wall wall,
            ref MapLayerToVolume totalVolumes)
        {
            WallType wt = wall.WallType;

            //CompoundStructure structure= wt.CompoundStructure; // 2011
            CompoundStructure structure = wt.GetCompoundStructure(); // 2012

            //CompoundStructureLayerArray layers = structure.Layers; // 2011
            IList <CompoundStructureLayer> layers = structure.GetLayers(); // 2012

            //int i, n = layers.Size; // 2011
            int i, n = layers.Count; // 2012

            double area      = GetWallParameter(wall, _bipArea);
            double volume    = GetWallParameter(wall, _bipVolume);
            double thickness = wt.Width;

            string desc = Util.ElementDescription(wall);

            Debug.Print(
                "{0} with thickness {1}"
                + " and volume {2}"
                + " has {3} layer{4}{5}",
                desc,
                Util.MmString(thickness),
                Util.RealString(volume),
                n, Util.PluralSuffix(n),
                Util.DotOrColon(n));

            // volume for entire wall:

            string key = wall.WallType.Name;

            totalVolumes.Cumulate(key, volume);

            // volume for compound wall layers:

            if (0 < n)
            {
                i = 0;
                double total = 0.0;
                double layerVolume;
                foreach (CompoundStructureLayer
                         layer in layers)
                {
                    key = wall.WallType.Name + " : "
                          + layer.Function;

                    //layerVolume = area * layer.Thickness; // 2011
                    layerVolume = area * layer.Width; // 2012

                    totalVolumes.Cumulate(key, layerVolume);
                    total += layerVolume;

                    Debug.Print(
                        "  Layer {0}: function {1}, "
                        + "thickness {2}, volume {3}",
                        ++i, layer.Function,
                        Util.MmString(layer.Width),
                        Util.RealString(layerVolume));
                }

                Debug.Print("Wall volume = {0},"
                            + " total layer volume = {1}",
                            Util.RealString(volume),
                            Util.RealString(total));

                if (!Util.IsEqual(volume, total))
                {
                    Debug.Print("Wall host volume parameter"
                                + " value differs from sum of all layer"
                                + " volumes: {0}",
                                volume - total);
                }
            }
        }
 public void SetType(IntVector2 coordinates, WallType type)
 {
     mazeData[coordinates.x, coordinates.z] = type;
 }
Exemple #25
0
 public Wall(WallType typeOfWall)
 {
     this.Type       = PartType.Walls;
     this.TypeOfWall = typeOfWall;
 }
Exemple #26
0
 private void AddCorner(ComplexPoly poly, Vector3 start, Vector3 end, Vector3 center, CornerType type, WallType wallType = WallType.None)
 {
     center = nudge(start, end, center);
     switch (type)
     {
         case CornerType.Diamond:
             break;
         case CornerType.Square:
             poly.AddLineSegment(start, center, end);
             AddWallMesh(wallType, start, center, end);
             return;
         case CornerType.Rounded:
             poly.AddLineSegment(
                 start,
                 (start + center) / 2,
                 (end + center) / 2,
                 end);
             AddWallMesh(wallType,
                 start,
                 (start + center) / 2,
                 (end + center) / 2,
                 end);
             return;
         default:
             break;
     }
     poly.AddLineSegment(start, end);
     AddWallMesh(wallType, start, end);
 }
Exemple #27
0
 void AddWallMesh(WallType wallType, params Vector3[] points)
 {
     switch (wallType)
     {
         case WallType.Floor:
             AddWallMesh(GameMap.floorHeight, 0, points);
             break;
         case WallType.Wall:
             AddWallMesh(GameMap.tileHeight, GameMap.floorHeight, points);
             break;
         case WallType.Both:
             AddWallMesh(GameMap.tileHeight, 0, points);
             break;
         default:
             break;
     }
 }
Exemple #28
0
 public Wall(int x, int y, Location currentLocation, WallType type) : base(x, y, currentLocation, true, true, true)
 {
     this.type = type;
 }
Exemple #29
0
 /// <summary>
 /// Constructor instantiates the position in the base
 /// </summary>
 public Wall(int x, int y, WallType type) : base(x, y)
 {
     this.Type = type;
 }
Exemple #30
0
        private WallData GetWallTypes()
        {
            List <WallType> wallElemTypes = _doc.CollectTypes <WallType>(BuiltInCategory.OST_Walls);

            // Getting the categories from the indices
            string[] mainMaterialCat   = TerminusFieldSplit(countItParams.MainMaterial_T);
            string[] baseMaterialCat   = TerminusFieldSplit(countItParams.BaseMaterial_T);
            string[] accentMaterialCat = TerminusFieldSplit(countItParams.AccentMaterial_T);

            // Getting the colors from the categories
            string[] mainMaterialColor   = TerminusFieldSplit(countItParams.MainMaterialColor_T);
            string[] baseMaterialColor   = TerminusFieldSplit(countItParams.BaseMaterialColor_T);
            string[] accentMaterialColor = TerminusFieldSplit(countItParams.AccentMaterialColor_T);

            string[] mMatColRange = GetColor(mainMaterialColor[0]);
            string[] bMatColRange = GetColor(baseMaterialColor[0]);
            string[] aMatColRange = GetColor(accentMaterialColor[0]);

            WallType mainWallType   = null;
            WallType baseWallType   = null;
            WallType accentWallType = null;

            string mainMatCatDefault    = null;
            string mainMatCatColDefault = null;
            string baseMatCatDefault    = null;
            string baseMatCatColDefault = null;

            foreach (WallType type in wallElemTypes)
            {
                // Get the main material & color
                if (mainMaterialCat[0] != null && type.Name.Contains(mainMaterialCat[0]))
                {
                    mainMatCatDefault = mainMaterialCat[0];

                    if (mMatColRange[0] != null && type.Name.Contains(mMatColRange[0]))
                    {
                        mainMatCatColDefault = mMatColRange[0];
                        mainWallType         = type;
                    }
                }

                // Get the base material & color
                if (baseMaterialCat[0] != null && type.Name.Contains(baseMaterialCat[0]))
                {
                    baseMatCatDefault = baseMaterialCat[0];

                    if (bMatColRange[0] != null && type.Name.Contains(bMatColRange[0]))
                    {
                        baseMatCatColDefault = bMatColRange[0];
                        baseWallType         = type;
                    }
                }

                // Get the accent material & color
                if (accentMaterialCat[0] != null && type.Name.Contains(accentMaterialCat[0]))
                {
                    if (aMatColRange[0] != null && type.Name.Contains(aMatColRange[0]))
                    {
                        accentWallType = type;
                    }
                }
            }

            return(new WallData(mainWallType, baseWallType, accentWallType,
                                mainMatCatDefault, mainMatCatColDefault, baseMatCatDefault, baseMatCatColDefault));
        }
        public ItemType GetItemTypeFromWallType(WallType wallType)
        {
            if ((int)wallType < TerrariaUtils.WallType_Min || (int)wallType > TerrariaUtils.WallType_Max)
            throw new ArgumentException(string.Format("The given item type {0} is invalid.", wallType), "wallType");

              if (TerrariaItems.wallTypesItemTypes == null) {
            TerrariaItems.wallTypesItemTypes = new ItemType[TerrariaUtils.WallType_Max + 1];

            for (int i = TerrariaUtils.ItemType_Min; i < TerrariaUtils.WallType_Max + 1; i++) {
              Item dummyItem = new Item();
              dummyItem.netDefaults(i);
              if (!string.IsNullOrEmpty(dummyItem.name) && dummyItem.createWall != -1)
            TerrariaItems.wallTypesItemTypes[dummyItem.createWall] = (ItemType)i;
            }
              }

              return TerrariaItems.wallTypesItemTypes[(int)wallType];
        }
        public static void SlopedWallTest(
            ExternalCommandData revit)
        {
            Document massDoc = revit.Application.Application.NewFamilyDocument(
                @"C:\ProgramData\Autodesk\RAC 2012\Family Templates\English_I\Conceptual Mass\Mass.rft");

            Transaction transaction = new Transaction(massDoc);

            transaction.SetName("TEST");
            transaction.Start();

            ExternalCommandData cdata = revit;

            Autodesk.Revit.ApplicationServices.Application app = revit.Application.Application;
            app = revit.Application.Application;

            // Create one profile
            ReferenceArray ref_ar = new ReferenceArray();

            Autodesk.Revit.DB.XYZ ptA = new XYZ(0, 0, 0);
            XYZ        ptB            = new XYZ(0, 30, 0);
            ModelCurve modelcurve     = MakeLine(revit.Application, ptA, ptB, massDoc);

            ref_ar.Append(modelcurve.GeometryCurve.Reference);

            ptA        = new XYZ(0, 30, 0);
            ptB        = new XYZ(2, 30, 0);
            modelcurve = MakeLine(revit.Application, ptA, ptB, massDoc);
            ref_ar.Append(modelcurve.GeometryCurve.Reference);

            ptA        = new XYZ(2, 30, 0);
            ptB        = new XYZ(2, 0, 0);
            modelcurve = MakeLine(revit.Application, ptA, ptB, massDoc);
            ref_ar.Append(modelcurve.GeometryCurve.Reference);

            ptA        = new XYZ(2, 0, 0);
            ptB        = new XYZ(0, 0, 0);
            modelcurve = MakeLine(revit.Application, ptA, ptB, massDoc);
            ref_ar.Append(modelcurve.GeometryCurve.Reference);

            // The extrusion form direction
            XYZ  direction = new XYZ(-6, 0, 50);
            Form form      = massDoc.FamilyCreate.NewExtrusionForm(true, ref_ar, direction);

            transaction.Commit();

            if (File.Exists(@"C:\TestFamily.rfa"))
            {
                File.Delete(@"C:\TestFamily.rfa");
            }

            massDoc.SaveAs(@"C:\TestFamily.rfa");

            if (!revit.Application.ActiveUIDocument.Document.LoadFamily(@"C:\TestFamily.rfa"))
            {
                throw new Exception("DID NOT LOAD FAMILY");
            }

            Family family = null;

            foreach (Element el in new FilteredElementCollector(
                         revit.Application.ActiveUIDocument.Document).WhereElementIsNotElementType().ToElements())
            {
                if (el is Family)
                {
                    if (((Family)el).Name.ToUpper().Trim().StartsWith("TEST"))
                    {
                        family = (Family)el;
                    }
                }
            }

            FamilySymbol fs = null;

            foreach (FamilySymbol sym in family.Symbols)
            {
                fs = sym;
            }

            // Create a family instance.
            revit.Application.ActiveUIDocument.Document.Create.NewFamilyInstance(
                new XYZ(0, 0, 0), fs, revit.Application.ActiveUIDocument.Document.ActiveView.Level,
                StructuralType.NonStructural);

            WallType wallType = null;

            foreach (WallType wt in revit.Application.ActiveUIDocument.Document.WallTypes)
            {
                if (FaceWall.IsWallTypeValidForFaceWall(revit.Application.ActiveUIDocument.Document, wt.Id))
                {
                    wallType = wt;
                    break;
                }
            }

            foreach (Element el in new FilteredElementCollector(
                         revit.Application.ActiveUIDocument.Document).WhereElementIsNotElementType().ToElements())
            {
                if (el is FamilyInstance)
                {
                    if (((FamilyInstance)el).Symbol.Family.Name.ToUpper().StartsWith("TEST"))
                    {
                        Options options = revit.Application.Application.Create.NewGeometryOptions();
                        options.ComputeReferences = true;
                        options.View = revit.Application.ActiveUIDocument.Document.ActiveView;
                        GeometryElement geoel = el.get_Geometry(options);

                        // Attempt to create a slopped wall from the geometry.
                        for (int i = 0; i < geoel.Objects.Size; i++)
                        {
                            if (geoel.Objects.get_Item(i) is Solid)
                            {
                                Solid solid = (Solid)geoel.Objects.get_Item(i);
                                for (int j = 0; j < solid.Faces.Size; j++)
                                {
                                    try
                                    {
                                        if (solid.Faces.get_Item(i).Reference != null)
                                        {
                                            FaceWall.Create(revit.Application.ActiveUIDocument.Document,
                                                            wallType.Id, WallLocationLine.CoreCenterline,
                                                            solid.Faces.get_Item(i).Reference);
                                        }
                                    }
                                    catch (System.Exception e)
                                    {
                                        System.Windows.Forms.MessageBox.Show(e.Message);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
Exemple #33
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Application   app   = uiapp.Application;
            Document      doc   = uidoc.Document;


            // Open source project
            Document docHasFamily = app.OpenDocumentFile(_source_project_path);

            // Find system family to copy, e.g. using a named wall type
            WallType _selectedWallType = null;

            FilteredElementCollector wallTypes
                = new FilteredElementCollector(docHasFamily) // 2014
                  .OfClass(typeof(WallType));

            int i = 0;



            foreach (WallType wt in wallTypes)
            {
                //Add the wall type to the list
                m_data.Add(wt.Name);
            }

            //show the form and get a value back from it
            //See this page for example: https://stackoverflow.com/questions/5233502/how-to-return-a-value-from-a-form-in-c
            using (var f = new frmListDialog(m_data))
            {
                var result = f.ShowDialog();
                if (result == System.Windows.Forms.DialogResult.OK)
                {
                    _selectedWallTypeName = f.ReturnValue1; //values preserved after close

                    //loop thru and find the wall type the matches the name
                    foreach (WallType wt in wallTypes)
                    {
                        if (wt.Name == _selectedWallTypeName)
                        {
                            //if its a match then...
                            _selectedWallType = wt;
                            //_selectedWallTypeName = wt.Name;
                        }
                    }
                }
            }



            //foreach( WallType wt in wallTypes )
            //{
            //  string name = wt.Name;

            //  Debug.Print( "  {0} {1}", ++i, name );

            //  if( name.Equals( _selectedWallTypeName ) )
            //  {
            //    _selectedWallType = wt;
            //    break;
            //  }
            //}

            //if( null == _selectedWallType )
            //{
            //  message = string.Format(
            //    "Cannot find source wall type '{0}'"
            //    + " in source document '{1}'. ",
            //    _selectedWallTypeName, _source_project_path );

            //  return Result.Failed;
            //}



            // Create a new wall type in current document

            using (Transaction t = new Transaction(doc))
            {
                t.Start("Transfer Wall Type");

                WallType newWallType = null;

                wallTypes = new FilteredElementCollector(doc).OfClass(typeof(WallType)); // 2014

                foreach (WallType wt in wallTypes)
                {
                    if (wt.Kind == _selectedWallType.Kind)
                    {
                        newWallType = wt.Duplicate(_selectedWallTypeName) as WallType;

                        TaskDialog.Show("New wall type '{0}' created.", "Wall type " + _selectedWallTypeName + "created.");

                        break;
                    }
                }

                // Assign parameter values from source wall type:

#if COPY_INDIVIDUAL_PARAMETER_VALUE
                // Example: individually copy the "Function" parameter value:

                BuiltInParameter bip      = BuiltInParameter.FUNCTION_PARAM;
                string           function = wallType.get_Parameter(bip).AsString();
                Parameter        p        = newWallType.get_Parameter(bip);
                p.Set(function);
#endif // COPY_INDIVIDUAL_PARAMETER_VALUE

                Parameter p = null;

                foreach (Parameter p2 in newWallType.Parameters)
                {
                    Definition d = p2.Definition;

                    if (p2.IsReadOnly)
                    {
                        Debug.Print(string.Format(
                                        "Parameter '{0}' is read-only.", d.Name));
                    }
                    else
                    {
                        p = _selectedWallType.get_Parameter(d);

                        if (null == p)
                        {
                            Debug.Print(string.Format(
                                            "Parameter '{0}' not found on source wall type.",
                                            d.Name));
                        }
                        else
                        {
                            if (p.StorageType == StorageType.ElementId)
                            {
                                // Here you have to find the corresponding
                                // element in the target document.

                                Debug.Print(string.Format(
                                                "Parameter '{0}' is an element id.",
                                                d.Name));
                            }
                            else
                            {
                                if (p.StorageType == StorageType.Double)
                                {
                                    p2.Set(p.AsDouble());
                                }
                                else if (p.StorageType == StorageType.String)
                                {
                                    p2.Set(p.AsString());
                                }
                                else if (p.StorageType == StorageType.Integer)
                                {
                                    p2.Set(p.AsInteger());
                                }


                                Debug.Print(string.Format(
                                                "Parameter '{0}' copied.", d.Name));
                            }
                        }
                    }

                    // Note:
                    // If a shared parameter parameter is attached,
                    // you need to create the shared parameter first,
                    // then copy the parameter value.
                }

                // If the system family type has some other properties,
                // you need to copy them as well here. Reflection can
                // be used to determine the available properties.

                MemberInfo[] memberInfos = newWallType.GetType()
                                           .GetMembers(BindingFlags.GetProperty);

                foreach (MemberInfo m in memberInfos)
                {
                    // Copy the writable property values here.
                    // As there are no property writable for
                    // Walltype, I ignore this process here.
                }
                t.Commit();
            }
            return(Result.Succeeded);
        }
Exemple #34
0
        /// <summary>
        /// Creates a creator from DoorWindowInfo.
        /// </summary>
        /// <param name="exporterIFC">The exporter.</param>
        /// <param name="doorWindowInfo">The DoorWindowInfo.</param>
        /// <param name="instanceHandle">The instance handle.</param>
        /// <param name="levelId">The level id.</param>
        /// <returns>The creator.</returns>
        public static DoorWindowDelayedOpeningCreator Create(ExporterIFC exporterIFC, DoorWindowInfo doorWindowInfo, IFCAnyHandle instanceHandle, ElementId levelId)
        {
            if (exporterIFC == null || doorWindowInfo == null)
            {
                return(null);
            }

            DoorWindowDelayedOpeningCreator doorWindowDelayedOpeningCreator = null;

            if (doorWindowInfo.HasRealWallHost)
            {
                Document       doc     = doorWindowInfo.HostObject.Document;
                Wall           wall    = doorWindowInfo.HostObject as Wall;
                FamilyInstance famInst = doorWindowInfo.InsertInstance;
                ElementId      hostId  = wall != null ? wall.Id : ElementId.InvalidElementId;
                ElementId      instId  = famInst != null ? famInst.Id : ElementId.InvalidElementId;

                doorWindowDelayedOpeningCreator                           = new DoorWindowDelayedOpeningCreator();
                doorWindowDelayedOpeningCreator.HostId                    = hostId;
                doorWindowDelayedOpeningCreator.InsertId                  = instId;
                doorWindowDelayedOpeningCreator.PosHingeSide              = doorWindowInfo.PosHingeSide;
                doorWindowDelayedOpeningCreator.DoorWindowHnd             = instanceHandle;
                doorWindowDelayedOpeningCreator.LevelId                   = levelId;
                doorWindowDelayedOpeningCreator.CreatedFromDoorWindowInfo = true;

                WallType wallType      = doc.GetElement(wall.GetTypeId()) as WallType;
                double   unScaledWidth = ((wallType != null) && (wallType.Kind != WallKind.Curtain)) ? wallType.Width : 0.0;
                if (!MathUtil.IsAlmostZero(unScaledWidth))
                {
                    IFCAnyHandle openingHnd = exporterIFC.GetDoorWindowOpeningHandle(instId);
                    if (IFCAnyHandleUtil.IsNullOrHasNoValue(openingHnd))
                    {
                        XYZ       cutDir  = null;
                        CurveLoop cutLoop = null;
                        try
                        {
                            cutLoop = ExporterIFCUtils.GetInstanceCutoutFromWall(wall.Document, wall, famInst, out cutDir);
                        }
                        catch
                        {
                            cutLoop = null;
                            // Couldn't create opening for door in wall - report as error in log when we create log file.
                        }

                        if (cutLoop != null)
                        {
                            if (doorWindowDelayedOpeningCreator.ExtrusionData == null)
                            {
                                doorWindowDelayedOpeningCreator.ExtrusionData = new List <IFCExtrusionData>();
                            }

                            IFCExtrusionData extrusionData = new IFCExtrusionData();
                            extrusionData.ExtrusionDirection    = cutDir;
                            extrusionData.ScaledExtrusionLength = UnitUtil.ScaleLength(unScaledWidth);
                            extrusionData.AddLoop(cutLoop);
                            doorWindowDelayedOpeningCreator.ScaledHostWidth = UnitUtil.ScaleLength(unScaledWidth);
                            doorWindowDelayedOpeningCreator.ExtrusionData.Add(extrusionData);
                            doorWindowDelayedOpeningCreator.HasValidGeometry = true;
                        }
                        else
                        {
                            // Couldn't create opening for door in wall - report as error in log when we create log file.
                        }
                    }
                }
            }

            return(doorWindowDelayedOpeningCreator);
        }
Exemple #35
0
        public async Task DeleteWallAsync(int wallId, UserAndOrganizationDto userOrg, WallType type)
        {
            var wall = await _wallsDbSet
                       .Include(x => x.Moderators)
                       .Include(x => x.Members)
                       .Include(x => x.Posts)
                       .Include(x => x.Posts.Select(y => y.Comments))
                       .FirstOrDefaultAsync(x => x.Id == wallId &&
                                            x.OrganizationId == userOrg.OrganizationId &&
                                            x.Type == type);

            if (wall == null)
            {
                throw new ValidationException(ErrorCodes.ContentDoesNotExist);
            }

            var hasPermission = await _permissionService.UserHasPermissionAsync(userOrg, AdministrationPermissions.Wall);

            var isWallModerator = wall.Moderators.Any(x => x.UserId == userOrg.UserId) || hasPermission;

            if (!isWallModerator)
            {
                throw new UnauthorizedException();
            }

            _wallsDbSet.Remove(wall);
            await _uow.SaveChangesAsync(userOrg.UserId);
        }
Exemple #36
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIDocument uidoc   = commandData.Application.ActiveUIDocument;
            Document   doc     = commandData.Application.ActiveUIDocument.Document;
            View       view    = uidoc.ActiveView;
            ElementId  levelid = view.GenLevel.Id;

            bool iscontinue = true;

            do
            {
                List <Element> eles = new List <Element>();
                try
                {
                    eles = GetSelected(uidoc);
                }
                catch
                {
                    iscontinue = false;
                    continue;
                }
                if (eles == null)
                {
                    TaskDialog.Show("wrong", "选择的符号线的数量不为2.");  continue;
                }


                //get line_closer & line_farther
                Line line1 = (eles[0] as DetailLine).GeometryCurve as Line;
                Line line2 = (eles[1] as DetailLine).GeometryCurve as Line;
                if (line1 == null || line2 == null)
                {
                    TaskDialog.Show("wrong", "仅支持直线."); continue;
                }
                Line line1unbound = (eles[0] as DetailLine).GeometryCurve as Line;
                line1unbound.MakeUnbound();
                Line line2unbound = (eles[1] as DetailLine).GeometryCurve as Line;
                line2unbound.MakeUnbound();
                //get distance from origin
                IntersectionResult result1   = line1unbound.Project(new XYZ(-1000 / 304.8, -1000 / 304.8, line1.GetEndPoint(0).Z));
                double             distance1 = result1.Distance;
                IntersectionResult result2   = line2unbound.Project(new XYZ(-1000 / 304.8, -1000 / 304.8, line2.GetEndPoint(0).Z));
                double             distance2 = result2.Distance;
                if (IsAlmostEqual(distance1, distance2))
                {
                    TaskDialog.Show("wrong", "两条线间距太小."); continue;
                }
                Line line_closer          = null;
                Line line_farther         = null;
                Line line_closer_unbound  = null;
                Line line_farther_unbound = null;
                if (distance1 > distance2)
                {
                    line_closer          = line2;
                    line_farther         = line1;
                    line_closer_unbound  = line2unbound;
                    line_farther_unbound = line1unbound;
                }
                else
                {
                    line_closer          = line1;
                    line_farther         = line2;
                    line_closer_unbound  = line1unbound;
                    line_farther_unbound = line2unbound;
                }

                //Determine parallel
                XYZ  dir1       = line_closer.Direction;
                XYZ  dir2       = line_farther.Direction;
                bool isparallel = dir1.IsAlmostEqualTo(dir2) || dir1.IsAlmostEqualTo(-dir2);
                if (!isparallel)
                {
                    TaskDialog.Show("wrong", "请选择平行的线."); continue;
                }

                //get points
                //makeunbound
                XYZ startpoint_closerline  = line_closer.GetEndPoint(0);
                XYZ endpoint_closerline    = line_closer.GetEndPoint(1);
                XYZ startpoint_fartherline = line_farther.GetEndPoint(0);
                XYZ endpoint_fartherline   = line_farther.GetEndPoint(1);

                //get width of wall
                IntersectionResult intersection = line_closer_unbound.Project(startpoint_fartherline);
                double             distance     = intersection.Distance;
                XYZ  point_intersection         = intersection.XYZPoint;
                Line normalline    = Line.CreateBound(point_intersection, startpoint_fartherline);
                XYZ  normallinedir = normalline.Direction;

                //offset
                Line wallline = null;
                if (line_closer.Length > line_farther.Length)
                {
                    wallline = OffsetLine(line_closer, normallinedir, distance / 2);
                }
                else
                {
                    wallline = OffsetLine(line_farther, -normallinedir, distance / 2);
                }

                //get material
                FilteredElementCollector materialcollector = new FilteredElementCollector(doc);
                materialcollector.OfCategory(BuiltInCategory.OST_Materials).OfClass(typeof(Material));
                IEnumerable <Material> materials = from ele in materialcollector
                                                   let material = ele as Material
                                                                  where material.Name == "BRIK"
                                                                  select material;
                if (materials.Count() == 0)
                {
                    TaskDialog.Show("wrong", "未找到BRIK材质"); continue;
                }
                ElementId materialid = materials.First().Id;

                //get walltype
                FilteredElementCollector walltypecollector = new FilteredElementCollector(doc);
                walltypecollector.OfClass(typeof(WallType)).OfCategory(BuiltInCategory.OST_Walls).WhereElementIsElementType();
                IEnumerable <WallType> walltypes = from element in walltypecollector
                                                   let walltypetemp                       = element as WallType
                                                                                 let para = walltypetemp.get_Parameter(BuiltInParameter.WALL_ATTR_WIDTH_PARAM)
                                                                                            where walltypetemp.Name.Contains("A-WALL-INTR")
                                                                                            where walltypetemp.Kind == WallKind.Basic
                                                                                            //  where para.AsDouble() == distance
                                                                                            where IsAlmostEqual(para.AsDouble(), distance)
                                                                                            select walltypetemp;
                if (walltypecollector.Count() == 0)
                {
                    TaskDialog.Show("wrong", "请先随意新建一个类型."); continue;
                }
                WallType typetemp = null;
                foreach (WallType type in walltypecollector)
                {
                    if (type.Kind == WallKind.Basic)
                    {
                        typetemp = type; break;
                    }
                }
                if (typetemp == null)
                {
                    TaskDialog.Show("wrong", "请先随意新建一个内墙类型."); continue;
                }
                WallType walltype = null;
                if (walltypes.Count() == 0)
                {
                    TaskDialog.Show("wrong", "未找到合适的类型,将新建一个类型");
                    using (Transaction createwalltype = new Transaction(doc))
                    {
                        createwalltype.Start("新建墙类型");

                        walltype = typetemp.Duplicate("A-WALL-INTR-" + Convert.ToInt32((distance * 304.8)).ToString()) as WallType;
                        CompoundStructure compoundstructure = CompoundStructure.CreateSingleLayerCompoundStructure(MaterialFunctionAssignment.Structure, distance, materialid);
                        walltype.SetCompoundStructure(compoundstructure);

                        createwalltype.Commit();
                    }
                }
                else
                {
                    walltype = walltypes.First();
                }


                //transaction

                using (Transaction transaction = new Transaction(doc))
                {
                    transaction.Start("生成墙");

                    Wall wall = Wall.Create(doc, wallline, walltype.Id, levelid, 10, 0, false, false);

                    transaction.Commit();
                }
            }while (iscontinue);



            return(Result.Succeeded);
        }
Exemple #37
0
    public int GetWalls(out WallType wall0, out WallType wall1)
    {
        wall0 = WallType.None;
        wall1 = WallType.None;
        bool firstSet = false;

        int count = 0;

        for (int i = 0; i < 8; i++) {
            if (((wallMask >> i) & 1) > 0) {
                count++;
                if (!firstSet) {
                    wall0 = (WallType)(i + 1);
                    firstSet = true;
                } else {
                    wall1 = (WallType)(i + 1);
                }
            }
        }

        return count;
    }
Exemple #38
0
    public void SpawnWall(WallType type, WallLocation location, GameObject owner)
    {
        GameObject WallObject;

        switch (type)
        {
        default:
        case WallType.None:
            return;

        case WallType.BarbedWire:
            WallObject = Instantiate(WireFencePrefab) as GameObject;
            break;

        case WallType.BrickWall:
            WallObject = Instantiate(BrickWallPrefab) as GameObject;
            break;

        case WallType.WoodWall:
            WallObject = Instantiate(WoodWallPrefab) as GameObject;
            break;
        }

        var WallScript = WallObject.GetComponent <WallScript>();

        WallScript.betweenA = owner.GetComponent <HexTile>().Coordinate;
        WallScript.betweenB = GetBetween(WallScript.betweenA, location)[1];

        WallObject.transform.SetParent(owner.transform);

        switch (location)
        {
        default:
        case WallLocation.Upper:
            WallObject.transform.localPosition = new Vector3(-0.8683267f, 0f);
            break;

        case WallLocation.Lower:
            WallObject.transform.localPosition = new Vector3(0.8683267f, 0f);
            break;

        case WallLocation.UpperLeft:
            WallObject.transform.localPosition = new Vector3(-0.4341633f, 0.7519927f);
            WallObject.transform.localRotation = Quaternion.Euler(0f, 0f, -60f);
            break;

        case WallLocation.LowerRight:
            WallObject.transform.localPosition = new Vector3(0.4341633f, -0.7519927f);
            WallObject.transform.localRotation = Quaternion.Euler(0f, 0f, -60f);
            break;

        case WallLocation.UpperRight:
            WallObject.transform.localPosition = new Vector3(-0.4341624f, -0.7519927f);
            WallObject.transform.localRotation = Quaternion.Euler(0f, 0f, -120f);
            break;

        case WallLocation.LowerLeft:
            WallObject.transform.localPosition = new Vector3(0.4341624f, 0.7519927f);
            WallObject.transform.localRotation = Quaternion.Euler(0f, 0f, -120f);
            break;
        }
    }
Exemple #39
0
 public WallUnit(World world, WallType wallType)
     : base(world, WorldLaw.DefaultUnitCreationSpeed,
     WorldLaw.DefaultEnemyLifeCount)
 {
     WallUnitType = wallType;
 }
        private void SpawnWall(WallType type, IntVector3 position, Rotation rotation)
        {
            var prefabs = registry.WallObjectHelper.Prefabs;

            if (!prefabs.ContainsKey(type)) {
                Logger.Warn("Could not load prefab for type {0}.", type);
                return;
            }

            var prefab = prefabs[type].Spawn();
            prefab.transform.position = position.ToVector3();

            this.goReference = prefab;
            this.Type = type;

            SetRotation(rotation);
            Logger.Info("Spawned wall {0} at {1} {2}.", type, position, this.goReference.transform.eulerAngles);
        }
Exemple #41
0
        private NewlyCreatedPostDTO MapNewlyCreatedPostToDto(Post post, UserDto user, WallType wallType)
        {
            var newlyCreatedPostDto = new NewlyCreatedPostDTO
            {
                Id          = post.Id,
                MessageBody = post.MessageBody,
                PictureId   = post.PictureId,
                Created     = post.Created,
                CreatedBy   = post.CreatedBy,
                User        = user,
                WallType    = wallType,
                WallId      = post.WallId
            };

            return(newlyCreatedPostDto);
        }
    private void populateMaze()
    {
        //SetType(0, 1, WallType.Floor);
        IntVector2 pos = new IntVector2(0, 0);

        for (; pos.x < size.x; pos.x++)
        {
            pos.z = 0;
            for (; pos.z < size.z; pos.z++)
            {
                WallType type = GetType(pos);
                if (type == WallType.SolidWall || type == WallType.PermanentWall)
                {
                    createPrefab <MazeWall>(pos, dir, wallPrefab);
                }
                if (type == WallType.Door)
                {
                    createPrefab <MazeDoor>(pos, dir, doorPrefab);
                    createPrefabMaterial <MazeFloor>(pos, floorPrefab, 1);
                }
                if (type == WallType.TreasureChest)
                {
                    createPrefab <TreasureChest>(pos, dir, treasurePrefab);
                    createPrefabMaterial <MazeFloor>(pos, floorPrefab, 1);
                    if (hasCeiling)
                    {
                        createPrefab <MazeCeiling>(pos, ceilingPrefab);
                    }
                }
                if (type == WallType.LootRoom)
                {
                    createPrefabMaterial <MazeFloor>(pos, floorPrefab, 1);
                    if (hasCeiling)
                    {
                        createPrefab <MazeCeiling>(pos, ceilingPrefab);
                    }
                }
                if (type == WallType.Floor)
                {
                    createPrefab <MazeFloor>(pos, dir, floorPrefab);
                    if (hasCeiling)
                    {
                        createPrefab <MazeCeiling>(pos, ceilingPrefab);
                    }
                    if (pos.x != doorEntrance.x && pos.z != doorEntrance.z)
                    {
                        if (rollRandom(7))
                        {
                            createPrefab <MazeVine>(pos, vinePrefab);
                            createPrefab <MazeDoor>(pos, doorPrefab);
                            randomlyAddCoin(pos, 1.5f, 10);
                        }
                        else if (mazeNum >= 2 && rollRandom(5))
                        {
                            //CALC THE ORIENTATION
                            MazeDirection facing = MazeDirection.East;
                            createPrefab <MazeBreakable>(pos, facing, breakablePrefab);
                        }
                        else if (mazeNum >= 4 && rollRandom(5))
                        {
                            createPrefab <MazeJumpObstacle>(pos, jumpPrefab);
                            randomlyAddCoin(pos, 4.5f, 10);
                        }
                        else if (mazeNum >= 6 && rollRandom(5))
                        {
                            createPrefab <MazePushObstacle>(pos, pushPrefab);
                        }
                        else
                        {
                            randomlyAddCoin(pos, 1.5f, 10);
                        }
                    }
                }
            }
        }
    }
Exemple #43
0
 private void AddStraight(ComplexPoly poly, Vector3 a, Vector3 b, WallType wallType = WallType.None)
 {
     poly.AddLineSegment(a, b);
     AddWallMesh(wallType, a, b);
 }
        /// <summary>
        /// try to create a wall. if failed, keep this dialog,
        /// otherwise, close it.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void okButton_Click(object sender, EventArgs e)
        {
            try
            {
                Document document = m_commandData.Application.ActiveUIDocument.Document;
                double   x, y, z;
                Autodesk.Revit.DB.XYZ sPoint;

                //try to convert string to double, and return without closing dialog if failed
                if (Double.TryParse(this.spXTextBox.Text, out x) &&
                    Double.TryParse(this.spYTextBox.Text, out y) &&
                    Double.TryParse(this.spZTextBox.Text, out z))
                {
                    sPoint = new Autodesk.Revit.DB.XYZ(x, y, z);
                }
                else
                {
                    TaskDialog.Show("Revit", "Failed to get the start point.");
                    return;
                }

                //try to convert string to double, and return without closing dialog if failed
                Autodesk.Revit.DB.XYZ ePoint;
                if (Double.TryParse(this.epXTextBox.Text, out x) &&
                    Double.TryParse(this.epYTextBox.Text, out y) &&
                    Double.TryParse(this.epZTextBox.Text, out z))
                {
                    ePoint = new Autodesk.Revit.DB.XYZ(x, y, z);
                }
                else
                {
                    TaskDialog.Show("Revit", "Failed to get the end point.");
                    return;
                }

                if (sPoint.IsAlmostEqualTo(ePoint))
                {
                    TaskDialog.Show("Revit", "The start point and end point cannot have the same location.");
                    return;
                }

                Autodesk.Revit.DB.Line line = Line.CreateBound(sPoint, ePoint);

                Level    level    = this.levelsComboBox.SelectedItem as Level;
                WallType wallType = this.wallTypesComboBox.SelectedItem as WallType;

                //check whether parameters used to create wall are not null
                if (null == line)
                {
                    TaskDialog.Show("Revit", "Create line failed.");
                    return;
                }

                if (null == level || null == wallType)
                {
                    TaskDialog.Show("Revit", "Please select a level and a wall type.");
                    return;
                }

                m_createdWall = Wall.Create(document, line, wallType.Id, level.Id, 10, 0, true, true);
                document.Regenerate();
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            catch (Exception ex)
            {
                TaskDialog.Show("Revit", ex.Message);
            }
        }
Exemple #45
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elementSet)
        {
            Document doc = commandData.Application.ActiveUIDocument.Document;

            List <string> liste = new List <string>();

            Form1 form             = new Form1(doc);
            bool  RoomName         = false;
            bool  RoomWalls        = false;
            bool  RoomFurniture    = false;
            bool  RoomDoors        = false;
            bool  RoomAddFurniture = false;
            bool  RoomFinishes     = false;

            if (form.DialogResult == System.Windows.Forms.DialogResult.Cancel)
            {
                return(Result.Cancelled);
            }

            if (DialogResult.OK == form.ShowDialog())
            {
                //Nom du paramètre de type "oui/non" permettant de détecter les locaux confidentiels
                string param = "G6_Confidentiel";
                //Nom des éléments pour le remplacement des familles
                string wall_type       = "XXXX";
                string door_type       = "XXXX_P:XXXX";
                string furniture_type  = "XXXX_M:XXXX";
                string plumbing_type   = "XXXX_S:XXXX";
                string furniture_param = "Dimension";
                string plumbing_param  = "Dimension";
                //Valeur attribuée aux paramètres cryptés
                string change = "XXXX";
                //Clé de décryptage
                List <string> key    = new List <string>();
                string        phase  = "Nouvelle construction";
                string        phase2 = "New Construction";

                ElementId    levelID       = null;
                FamilySymbol door_fs       = null;
                FamilySymbol furniture_fs  = null;
                FamilySymbol plumbing_fs   = null;
                ElementId    eid           = null;
                Line         newWallLine_2 = null;
                List <Curve> curves        = new List <Curve>();
                int          count         = 0;
                Random       rnd           = new Random();
                int          Offset        = rnd.Next(4, 6);
                double       random        = rnd.NextDouble() * Offset;
                //double random = Offset;

                using (Transaction t = new Transaction(doc, "Crypter la maquette"))
                {
                    t.Start();
                    RoomName         = form.RoomName();
                    RoomWalls        = form.RoomWalls();
                    RoomFurniture    = form.RoomFurniture();
                    RoomDoors        = form.RoomDoors();
                    RoomAddFurniture = form.RoomAddFurnitures();
                    RoomFinishes     = form.RoomFinishes();
                    //Sélection du type de porte de remplacement
                    FamilySymbol fs = (from element in new FilteredElementCollector(doc).OfClass(typeof(FamilySymbol)).OfCategory(BuiltInCategory.OST_Doors).Cast <FamilySymbol>()
                                       where element.Family.Name + ":" + element.Name == door_type
                                       select element).ToList <FamilySymbol>().First();
                    door_fs = fs;
                    //Sélection du type de mobilier de remplacement
                    FamilySymbol fs_furniture = (from element in new FilteredElementCollector(doc).OfClass(typeof(FamilySymbol)).OfCategory(BuiltInCategory.OST_Furniture).Cast <FamilySymbol>()
                                                 where element.Family.Name + ":" + element.Name == furniture_type
                                                 select element).ToList <FamilySymbol>().First();
                    furniture_fs = fs_furniture;
                    //Sélection du type de sanitaire de remplacement
                    FamilySymbol fs_plumbing = (from element in new FilteredElementCollector(doc).OfClass(typeof(FamilySymbol)).OfCategory(BuiltInCategory.OST_PlumbingFixtures).Cast <FamilySymbol>()
                                                where element.Family.Name + ":" + element.Name == plumbing_type
                                                select element).ToList <FamilySymbol>().First();
                    plumbing_fs = fs_plumbing;
                    //Sélection du type de mur de remplacement
                    WallType walltype = (from element in new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Walls).WhereElementIsElementType()
                                         where element.Name == wall_type
                                         select element).Cast <WallType>().ToList <WallType>().First();
                    eid = walltype.Id;
                    //Remplacement du mobilier
                    if (RoomFurniture == true)
                    {
                        foreach (FamilyInstance furniture_instance in new FilteredElementCollector(doc).OfClass(typeof(FamilyInstance)).OfCategory(BuiltInCategory.OST_Furniture).Cast <FamilyInstance>())
                        {
                            if (furniture_instance.Room != null && furniture_instance.Room.LookupParameter(param).AsInteger() == 1)
                            {
                                try
                                {
                                    string original = furniture_instance.Name;
                                    furniture_instance.Symbol = furniture_fs;
                                    Random rd = new Random();
                                    double random_dimension = 0.5 + rd.NextDouble();
                                    furniture_instance.LookupParameter(furniture_param).Set(UnitUtils.ConvertToInternalUnits(random_dimension, DisplayUnitType.DUT_METERS));
                                    key.Add("F;" + furniture_instance.Id.ToString() + ";" + original + ";" + furniture_instance.Room.Id.ToString() + ";" + furniture_instance.Room.Name);
                                }
                                catch
                                {
                                }
                            }
                        }
                        foreach (FamilyInstance plumbing_instance in new FilteredElementCollector(doc).OfClass(typeof(FamilyInstance)).OfCategory(BuiltInCategory.OST_PlumbingFixtures).Cast <FamilyInstance>())
                        {
                            if (plumbing_instance.Room != null && plumbing_instance.Room.LookupParameter(param).AsInteger() == 1)
                            {
                                string original = plumbing_instance.Name;
                                plumbing_instance.Symbol = plumbing_fs;
                                Random rd = new Random();
                                double random_dimension = 0.5 + rd.NextDouble();
                                plumbing_instance.LookupParameter(plumbing_param).Set(UnitUtils.ConvertToInternalUnits(random_dimension, DisplayUnitType.DUT_METERS));
                                key.Add("P;" + plumbing_instance.Id.ToString() + ";" + original + ";" + plumbing_instance.Room.Id.ToString() + ";" + plumbing_instance.Room.Name);
                            }
                        }
                    }
                    //Lister les pièces confidentielles et appartenant à la phase désignée
                    List <Room> rooms = (from element in new FilteredElementCollector(doc).OfClass(typeof(SpatialElement)).OfCategory(BuiltInCategory.OST_Rooms).Cast <Room>()
                                         where element.LookupParameter(param).AsInteger() == 1 &&
                                         (element.get_Parameter(BuiltInParameter.ROOM_PHASE).AsValueString() == phase || element.get_Parameter(BuiltInParameter.ROOM_PHASE).AsValueString() == phase2)
                                         select element).ToList <Room>();
                    //Première boucle sur les pièces confidentielles pour renseigner la clé
                    foreach (Room r in rooms)
                    {
                        Parameter     name   = r.get_Parameter(BuiltInParameter.ROOM_NAME);
                        Parameter     number = r.get_Parameter(BuiltInParameter.ROOM_NUMBER);
                        Parameter     floor  = r.get_Parameter(BuiltInParameter.ROOM_FINISH_FLOOR);
                        LocationPoint lp     = r.Location as LocationPoint;
                        XYZ           point  = lp.Point;
                        //Ajout des valeurs de paramètres initiaux à la clé de déchiffrement
                        key.Add("R;" + r.Id.ToString() + ";" + name.AsString() + ";" + number.AsString() + ";" + floor.AsString() + ";" + point.X + ";" + point.Y + ";" + point.Z);
                    }

                    //Deuxième boucle sur les pièces confidentielles pour modifier paramètres et géométrie
                    foreach (Room r in rooms)
                    {
                        Parameter     name   = r.get_Parameter(BuiltInParameter.ROOM_NAME);
                        Parameter     number = r.get_Parameter(BuiltInParameter.ROOM_NUMBER);
                        Parameter     floor  = r.get_Parameter(BuiltInParameter.ROOM_FINISH_FLOOR);
                        LocationPoint lp     = r.Location as LocationPoint;
                        XYZ           point  = lp.Point;
                        //Remplacement des valeurs de paramètres des pièces par le code
                        if (RoomName == true)
                        {
                            name.Set(change);
                            number.Set(change + count.ToString());
                        }
                        if (RoomFinishes == true)
                        {
                            floor.Set(change);
                        }
                        //Incrémentation du nombre de pièces cryptées
                        count += 1;
                        //Retrouver les limites des pièces
                        IList <IList <Autodesk.Revit.DB.BoundarySegment> > segments = r.GetBoundarySegments(new SpatialElementBoundaryOptions());
                        int             segments_number   = 0;
                        int             boundaries_number = 0;
                        BoundarySegment bd0 = null;
                        BoundarySegment bd1 = null;
                        BoundarySegment bd2 = null;

                        if (null != segments)  //la pièce peut ne pas être fermée
                        {
                            foreach (IList <Autodesk.Revit.DB.BoundarySegment> segmentList in segments)
                            {
                                segments_number += 1;
                                foreach (Autodesk.Revit.DB.BoundarySegment boundarySegment in segmentList)
                                {
                                    boundaries_number += 1;
                                    if (boundaries_number == 1)
                                    {
                                        bd0 = boundarySegment;
                                    }
                                    if (boundaries_number == 3)
                                    {
                                        bd1 = boundarySegment;
                                    }
                                    if (boundaries_number == 4)
                                    {
                                        bd2 = boundarySegment;
                                    }
                                    //Retrouver l'élément qui forme la limite de pièce
                                    Element elt = r.Document.GetElement(boundarySegment.ElementId);
                                    //Déterminer si cet élément est un mur
                                    bool isWall = false;
                                    if (elt as Wall != null)
                                    {
                                        isWall = true;
                                    }
                                    //Si c'est un mur, continuer
                                    if (isWall == true)
                                    {
                                        Wall      wall     = elt as Wall;
                                        Parameter function = wall.WallType.get_Parameter(BuiltInParameter.FUNCTION_PARAM);
                                        //Ne traiter que les murs intérieurs
                                        if (function.AsValueString() == "Interior" || function.AsValueString() == "Intérieur")
                                        {
                                            if (RoomDoors == true)
                                            {
                                                //Changer les types de portes
                                                IList <ElementId> inserts = (wall as HostObject).FindInserts(true, true, true, true);
                                                foreach (ElementId id in inserts)
                                                {
                                                    Element e = doc.GetElement(id);
                                                    try
                                                    {
                                                        FamilyInstance fi = e as FamilyInstance;
                                                        if (fi.get_Parameter(BuiltInParameter.PHASE_CREATED).AsValueString() == phase || fi.get_Parameter(BuiltInParameter.PHASE_CREATED).AsValueString() == phase2)
                                                        {
                                                            string original = fi.Name;
                                                            fi.Symbol = door_fs;
                                                            LocationPoint doorPoint = fi.Location as LocationPoint;
                                                            XYZ           pt        = doorPoint.Point;
                                                            key.Add("D;" + fi.Id.ToString() + ";" + original + ";" + pt.X + ";" + pt.Y + ";" + pt.Z);
                                                        }
                                                    }
                                                    catch
                                                    {
                                                    }
                                                }
                                            }
                                            //Récupérer les points de départ et d'extrémité des murs
                                            LocationCurve wallLine  = wall.Location as LocationCurve;
                                            XYZ           endPoint0 = wallLine.Curve.GetEndPoint(0);
                                            XYZ           endPoint1 = wallLine.Curve.GetEndPoint(1);
                                            //Ajout des coordonnées initiales des murs à la clé de déchiffrement
                                            key.Add("W;" + wall.Id.ToString() + ";" + wall.WallType.Name + ";" + endPoint0.X.ToString() + ";" + endPoint0.Y.ToString() + ";" + endPoint1.X.ToString() + ";" + endPoint1.Y.ToString());
                                            levelID = wall.LevelId;
                                            //Changer le type des murs
                                            if (RoomWalls == true)
                                            {
                                                wall.ChangeTypeId(eid);
                                            }
                                        }
                                    }
                                }
                            }

                            if (RoomAddFurniture == true && r.Area > UnitUtils.ConvertToInternalUnits(7, DisplayUnitType.DUT_SQUARE_METERS))
                            {
                                //Créer de nouveaux meubles de façon aléatoire dans les pièces confidentielles
                                Random rd        = new Random();
                                int    offset    = rnd.Next(0, 10);
                                XYZ    new_point = new XYZ(point.X + offset * 0.5, point.Y + offset * 0.3, point.Z);
                                if (offset > 1 && offset < 9)
                                {
                                    FamilyInstance nf = doc.Create.NewFamilyInstance(new_point, furniture_fs, r.Level, StructuralType.NonStructural);
                                    key.Add("NF;" + nf.Id.ToString());
                                }
                            }
                        }
                    }

                    SaveFileDialog saveFileDialog1 = new SaveFileDialog();
                    saveFileDialog1.Title            = "Choisir le chemin du fichier de chiffrement";
                    saveFileDialog1.Filter           = "Fichier texte (*.txt)|*.txt";
                    saveFileDialog1.RestoreDirectory = true;

                    DialogResult result = saveFileDialog1.ShowDialog();
                    if (result == System.Windows.Forms.DialogResult.OK)
                    {
                        string txt_filename = saveFileDialog1.FileName;
                        if (File.Exists(txt_filename))
                        {
                            File.Delete(txt_filename);
                        }
                        //Ecrire dans le fichier clé
                        using (StreamWriter sw = new StreamWriter(txt_filename))
                        {
                            foreach (string s in key)
                            {
                                sw.WriteLine(s);
                            }
                        }
                        //Process.Start(txt_filename);
                    }
                    t.Commit();
                    return(Result.Succeeded);
                }
            }
            return(Result.Succeeded);
        }
 private int WallBonus(WallType? wallType, WallType reference)
 {
     if (!wallType.HasValue) { return 0; }
     if (wallType.Value == reference) { return ContinueWallBonus; }
     if (wallType.Value == WallType.OuterWall) { return BranchWallBonus; }
     return 0;
 }
Exemple #47
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elementSet)
        {
            Document      doc = commandData.Application.ActiveUIDocument.Document;
            List <string> key = new List <string>();

            using (Transaction t = new Transaction(doc, "Décrypter la maquette"))
            {
                t.Start();

                OpenFileDialog openFileDialog1 = new OpenFileDialog();
                openFileDialog1.Title            = "Sélectionner la clé de déchiffrement";
                openFileDialog1.Filter           = "Fichier texte (*.txt)|*.txt";
                openFileDialog1.RestoreDirectory = true;

                DialogResult result = openFileDialog1.ShowDialog();
                if (result == System.Windows.Forms.DialogResult.OK)
                {
                    string txt_filename = openFileDialog1.FileName;
                    //Lire le fichier Clé.txt
                    int              counter = 0;
                    string           line;
                    List <ElementId> to_delete = new List <ElementId>();

                    System.IO.StreamReader file0 = new System.IO.StreamReader(txt_filename);
                    while ((line = file0.ReadLine()) != null)
                    {
                        key.Add(line);
                        string[] list = line.Split(';');
                        //Supprimer les murs et mobiliers crées
                        if (line.StartsWith("NW;"))
                        {
                            Wall wall = (from element in new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Walls).WhereElementIsNotElementType()
                                         where element.Id.ToString() == list[1]
                                         select element).Cast <Wall>().ToList <Wall>().First();
                            to_delete.Add(wall.Id);
                        }
                        if (line.StartsWith("NF;"))
                        {
                            FamilyInstance nf = (from element in new FilteredElementCollector(doc).OfClass(typeof(FamilyInstance)).OfCategory(BuiltInCategory.OST_Furniture)
                                                 where element.Id.ToString() == list[1]
                                                 select element).Cast <FamilyInstance>().ToList <FamilyInstance>().First();
                            to_delete.Add(nf.Id);
                        }
                        counter++;
                    }
                    file0.Close();

                    foreach (ElementId eid in to_delete)
                    {
                        doc.Delete(eid);
                    }

                    //Récupérer les valeurs de paramètre initiales pour les murs, à partir du fichier Clé.txt
                    System.IO.StreamReader file = new System.IO.StreamReader(txt_filename);
                    while ((line = file.ReadLine()) != null)
                    {
                        key.Add(line);
                        string[] list = line.Split(';');
                        if (line.StartsWith("W;"))
                        {
                            Wall wall = (from element in new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Walls).WhereElementIsNotElementType()
                                         where element.Id.ToString() == list[1]
                                         select element).Cast <Wall>().ToList <Wall>().First();
                            WallType walltype = (from element in new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Walls).WhereElementIsElementType()
                                                 where element.Name == list[2]
                                                 select element).Cast <WallType>().ToList <WallType>().First();
                            wall.ChangeTypeId(walltype.Id);
                            LocationCurve wallLine    = wall.Location as LocationCurve;
                            XYZ           endPoint2   = wallLine.Curve.GetEndPoint(0);
                            XYZ           endPoint3   = wallLine.Curve.GetEndPoint(1);
                            XYZ           endPoint0   = new XYZ(Convert.ToDouble(list[3]), Convert.ToDouble(list[4]), endPoint2.Z);
                            XYZ           endPoint1   = new XYZ(Convert.ToDouble(list[5]), Convert.ToDouble(list[6]), endPoint3.Z);
                            Line          newWallLine = Line.CreateBound(endPoint0, endPoint1);
                            wallLine.Curve = newWallLine;
                        }

                        if (line.StartsWith("D;"))
                        {
                            FamilyInstance door = (from element in new FilteredElementCollector(doc).OfClass(typeof(FamilyInstance)).OfCategory(BuiltInCategory.OST_Doors)
                                                   where element.Id.ToString() == list[1] select element).Cast <FamilyInstance>().ToList <FamilyInstance>().First();
                            FamilySymbol door_type = (from element in new FilteredElementCollector(doc).OfClass(typeof(FamilySymbol)).OfCategory(BuiltInCategory.OST_Doors)
                                                      where element.Name == list[2] select element).Cast <FamilySymbol>().ToList <FamilySymbol>().First();
                            door.Symbol = door_type;
                            XYZ           point = new XYZ(Convert.ToDouble(list[3]), Convert.ToDouble(list[4]), Convert.ToDouble(list[5]));
                            LocationPoint lp    = door.Location as LocationPoint;
                            lp.Point = point;
                        }

                        if (line.StartsWith("F;"))
                        {
                            FamilyInstance furniture = (from element in new FilteredElementCollector(doc).OfClass(typeof(FamilyInstance)).OfCategory(BuiltInCategory.OST_Furniture)
                                                        where element.Id.ToString() == list[1] select element).Cast <FamilyInstance>().ToList <FamilyInstance>().First();
                            FamilySymbol furniture_type = (from element in new FilteredElementCollector(doc).OfClass(typeof(FamilySymbol)).OfCategory(BuiltInCategory.OST_Furniture)
                                                           where element.Name == list[2] select element).Cast <FamilySymbol>().ToList <FamilySymbol>().First();
                            furniture.Symbol = furniture_type;
                        }

                        if (line.StartsWith("P;"))
                        {
                            FamilyInstance plumbing = (from element in new FilteredElementCollector(doc).OfClass(typeof(FamilyInstance)).OfCategory(BuiltInCategory.OST_PlumbingFixtures)
                                                       where element.Id.ToString() == list[1] select element).Cast <FamilyInstance>().ToList <FamilyInstance>().First();
                            FamilySymbol plumbing_type = (from element in new FilteredElementCollector(doc).OfClass(typeof(FamilySymbol)).OfCategory(BuiltInCategory.OST_PlumbingFixtures)
                                                          where element.Name == list[2] select element).Cast <FamilySymbol>().ToList <FamilySymbol>().First();
                            plumbing.Symbol = plumbing_type;
                        }

                        if (line.StartsWith("R;"))
                        {
                            Room r = (from element in new FilteredElementCollector(doc).OfClass(typeof(SpatialElement)).OfCategory(BuiltInCategory.OST_Rooms)
                                      where element.Id.ToString() == list[1] select element).Cast <Room>().ToList <Room>().First();
                            Parameter name   = r.get_Parameter(BuiltInParameter.ROOM_NAME);
                            Parameter number = r.get_Parameter(BuiltInParameter.ROOM_NUMBER);
                            Parameter floor  = r.get_Parameter(BuiltInParameter.ROOM_FINISH_FLOOR);
                            name.Set(list[2]);
                            number.Set(list[3]);
                            floor.Set(list[4]);
                            LocationPoint lp = r.Location as LocationPoint;
                            XYZ           previousLocation = new XYZ(Convert.ToDouble(list[5]), Convert.ToDouble(list[6]), lp.Point.Z);
                            lp.Point = previousLocation;
                        }
                        counter++;
                    }
                    file.Close();
                }
                t.Commit();
            }

            return(Result.Succeeded);
        }
 private WallType InvertType(WallType type)
 {
     return(type == WallType.Center ? WallType.Side : WallType.Center);
 }
Exemple #49
0
    public void BuildWall(ref Vec2i index, int count, WallType type)
    {
        BuildWall(index, count, type);

        index += wallOffsets[(int)type] * count;
    }
Exemple #50
0
 public bool IsWall(WallType type, int coord)
 {
     return(type == WallType.Vertical ? _verticalWalls.Contains(coord) : _horizontalWalls.Contains(coord));
 }
Exemple #51
0
    public void BuildWall(Vec2i index, int count, WallType type)
    {
        VesselTile tile;

        for (int i = 0; i < count; i++) {

            if (IsWallLegal(index, type)) {

                tile = TryGetTile(index);
                if (tile == null) {
                    tile = new VesselTile();
                    SetTile(index, tile);
                }

                tile.wallMask |= (byte)(1 << ((byte)type - 1));
                tile.wallNode = true;

                index += wallOffsets[(byte)type];

                tile = TryGetTile(index);
                if (tile == null) {
                    tile = new VesselTile();
                    SetTile(index, tile);
                }
                tile.wallNode = true;
            } else {
                index += wallOffsets[(byte)type];
            }
        }
    }
 public void ByName_NullArgument()
 {
     Assert.Throws(typeof(ArgumentNullException), () => WallType.ByName(null));
 }
    void UpdateWallChecks()
    {
        _wallAboveHandHeight = false;
        _wallAtHandHeight = false;
        _wallAtCrotchHeight = false;

        Vector3 offset = offsets.handOffsetP1;
        offset.x *= _direction.x;

        Vector3 checkDirection = (offsets.handOffsetP2 - offsets.handOffsetP1) * _direction.x;

        Ray handRay = new Ray( _transform.position + offset, checkDirection );
        // if there's a wall at hand height

        Debug.DrawLine( handRay.origin, handRay.origin + handRay.direction * _ledgeGrabDistance, Color.red );

        RaycastHit info;
        if ( Physics.Raycast( handRay, out info, _ledgeGrabDistance, _groundLayerMask ) )
        {
            _wallAtHandHeight = true;
            if ( info.transform.tag == "ClimbableWall" )
            {
                _wallTypeAtHand = WallType.Climbable;
            }
            else
            {
                _wallTypeAtHand = WallType.Normal;
            }

            _wallNormal = info.normal;
            _wallIntersectPoint = info.point;

            offset = offsets.aboveHandOffset;
            offset.x *= _direction.x;

            Ray aboveHandRay = new Ray( _transform.position + offset, checkDirection );

            Debug.DrawLine( aboveHandRay.origin, aboveHandRay.origin + aboveHandRay.direction * _ledgeGrabDistance, Color.cyan );
            if ( !Physics.Raycast( aboveHandRay, out info, _ledgeGrabDistance, _groundLayerMask ) )
            {
                Vector3 newPos = _transform.position;

                newPos.x = info.point.x;
                Vector3 testPos = aboveHandRay.origin;
                testPos.x = newPos.x + _direction.x * 0.05f;

                if ( Physics.Raycast( testPos, Vector3.down, out info, offsets.aboveHandOffset.y - offsets.handOffsetP1.y, _groundLayerMask ) )
                {
                    newPos.y = info.point.y;
                }
                else
                {
                    Debug.LogWarning("Couldn't find Y position of ledge");
                }

                _ledgePosition = newPos;
            }
            else
            {
                _wallAboveHandHeight = true;
            }

            offset = offsets.crotchOffset;
            offset.x *= _direction.x;

            Ray crotchRay = new Ray( _transform.position + offset, checkDirection );
            Debug.DrawLine( crotchRay.origin, crotchRay.origin + crotchRay.direction * _ledgeGrabDistance, Color.magenta );
            if ( Physics.Raycast( crotchRay, out info, _ledgeGrabDistance, _groundLayerMask ) )
            {
                _wallAtCrotchHeight = true;
            }
        }
        else
        {
            _wallAtHandHeight = false;
        }
    }
Exemple #54
0
        /// <summary>
        /// Here is a part or our code to start a Revit command.
        /// The aim of the code is to set a wall type current in the Revit property window.
        /// We only start up the wall command with the API and let the user do the drawing of the wall.
        /// This solution can also be used to launch other Revit commands.
        /// </summary>
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Application   app   = uiapp.Application;
            Document      doc   = uidoc.Document;

            IntPtr hRvt = uiapp.MainWindowHandle; // 2019

            // Name of target wall type that we want to use:

            string wallTypeName = "Generic - 203";

            WallType wallType = GetFirstWallTypeNamed(
                doc, wallTypeName);

            Wall wall = GetFirstWallUsingType(
                doc, wallType);

            // Select the wall in the UI

            //uidoc.Selection.Elements.Add( wall ); // 2014

            List <ElementId> ids = new List <ElementId>(1);

            ids.Add(wall.Id);
            uidoc.Selection.SetElementIds(ids); // 2015

            //if( 0 == uidoc.Selection.Elements.Size ) // 2014

            if (0 == uidoc.Selection.GetElementIds().Count) // 2015
            {
                // No wall with the correct wall type found

                FilteredElementCollector collector
                    = new FilteredElementCollector(doc);

                Level ll = collector
                           .OfClass(typeof(Level))
                           .FirstElement() as Level;

                // place a new wall with the
                // correct wall type in the project

                //Line geomLine = app.Create.NewLineBound( XYZ.Zero, new XYZ( 2, 0, 0 ) ); // 2013
                Line geomLine = Line.CreateBound(XYZ.Zero, new XYZ(2, 0, 0)); // 2014

                Transaction t = new Transaction(
                    doc, "Create dummy wall");

                t.Start();

                //Wall nw = doc.Create.NewWall( geomLine, // 2012
                //  wallType, ll, 1, 0, false, false );

                Wall nw = Wall.Create(doc, geomLine, // 2013
                                      wallType.Id, ll.Id, 1, 0, false, false);

                t.Commit();

                // Select the new wall in the project

                //uidoc.Selection.Elements.Add( nw ); // 2014

                ids.Clear();
                ids.Add(nw.Id);
                uidoc.Selection.SetElementIds(ids); // 2015

                // Start command create similar. In the
                // property menu, our wall type is set current

                Press.Keys(hRvt, "CS");

                // Select the new wall in the project,
                // so we can delete it

                //uidoc.Selection.Elements.Add( nw ); // 2014

                ids.Clear();
                ids.Add(nw.Id);
                uidoc.Selection.SetElementIds(ids); // 2015

                // Erase the selected wall (remark:
                // doc.delete(nw) may not be used,
                // this command will undo)

                Press.Keys(hRvt, "DE");

                // Start up wall command

                Press.Keys(hRvt, "WA");
            }
            else
            {
                // The correct wall is already selected:

                Press.Keys(hRvt, "CS"); // Start "create similar"
            }
            return(Result.Succeeded);
        }
Exemple #55
0
        /// <summary>
        /// This function takes an XmlReader the was created from a WALL element in the main file,
        /// It then creates a new wall and adds it to the List<Wall>
        /// </summary>
        /// <param name="wallReader">
        /// The XML Reader object created from a wall subtree in the ParseLevel() method
        /// </param>
        private void ParseWall(XmlReader wallReader)
        {
            //a point to hold the location from where we add the wall
            Point wallLocation = new Point();

            //a Walltype to hold the type, set the default to hard
            WallType wt = WallType.Hard;

            //a Wallshape to hold the shape, default is vertical line
            WallShape ws = WallShape.l;

            //a string to hold text data parsed from the file
            string tempString = "";

            //width and height variables
            int width = 0, height = 0;

            //read to the end
            while (wallReader.Read())
            {
                //check the node type
                switch (wallReader.NodeType)
                {
                ///*******************************************************
                ///Here we parse the WALL subelements into their own parts
                ///*******************************************************
                case XmlNodeType.Element:
                    //check the tag name and perform the necessary action on it
                    switch (wallReader.Name)
                    {
                    //get the starting X location of the wall
                    case "X":
                        wallLocation.X = wallReader.ReadElementContentAsInt();
                        break;

                    //get the starting Y location of the wall
                    case "Y":
                        wallLocation.Y = wallReader.ReadElementContentAsInt();
                        break;

                    //Get the wall type as a string, and then assign the appropriate type based on
                    //the string
                    case "TYPE":
                        tempString = wallReader.ReadElementContentAsString();
                        if (tempString == "WEAK")
                        {
                            wt = WallType.Weak;
                        }
                        break;

                    //Get the shape type. Call the SetWallShape function. It returns the appropriate enum WallShape
                    case "SHAPE":
                        tempString = wallReader.ReadElementContentAsString();
                        ws         = SetWallShape(tempString);
                        break;

                    //Get the width of the wall
                    case "WIDTH":
                        width = wallReader.ReadElementContentAsInt() * Tilesize;
                        break;

                    //Get the height of the wall
                    case "HEIGHT":
                        height = wallReader.ReadElementContentAsInt() * Tilesize;
                        //add the walls once we reach the end
                        AddWalls(wallLocation, wt, ws, width, height);
                        break;
                    }
                    break;
                }
            }
        }
 public void SetType(int x, int z, WallType type)
 {
     mazeData[x, z] = type;
 }
        private void Stream(ArrayList data, WallType wallType)
        {
            data.Add(new Snoop.Data.ClassSeparator(typeof(WallType)));

             data.Add(new Snoop.Data.Double("Width", wallType.Width));
             data.Add(new Snoop.Data.String("Kind", wallType.Kind.ToString()));
        }
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication app = commandData.Application;
            Document      doc = app.ActiveUIDocument.Document;

#if _2011
            //
            // code for the Revit 2011 API:
            //
            Debug.Assert(false,
                         "Currently, no new wall layer can be created, because"
                         + "there is no creation method available for it.");

            foreach (WallType wallType in doc.WallTypes)
            {
                if (0 < wallType.CompoundStructure.Layers.Size)
                {
                    CompoundStructureLayer oldLayer
                        = wallType.CompoundStructure.Layers.get_Item(0);

                    WallType newWallType
                        = wallType.Duplicate("NewWallType") as WallType;

                    CompoundStructure structure
                        = newWallType.CompoundStructure;

                    CompoundStructureLayerArray layers
                        = structure.Layers;


                    // from here on, nothing works, as expected:
                    // in the Revir 2010 API, we could call the constructor
                    // even though it is for internal use only.
                    // in 2011, it is not possible to call it either.

                    CompoundStructureLayer newLayer = null;
                    //  = new CompoundStructureLayer(); // for internal use only

                    newLayer.DeckProfile = oldLayer.DeckProfile;
                    //newLayer.DeckUsage = oldLayer.DeckUsage; // read-only
                    //newLayer.Function = oldLayer.Function; // read-only
                    newLayer.Material  = oldLayer.Material;
                    newLayer.Thickness = oldLayer.Thickness;
                    newLayer.Variable  = oldLayer.Variable;
                    layers.Append(newLayer);
                }
            }
#endif // _2011

            using (Transaction t = new Transaction(doc))
            {
                t.Start("Create New Wall Layer");

                //WallTypeSet wallTypes = doc.WallTypes; // 2013

                FilteredElementCollector wallTypes
                    = new FilteredElementCollector(doc)
                      .OfClass(typeof(WallType)); // 2014

                foreach (WallType wallType in wallTypes)
                {
                    if (0 < wallType.GetCompoundStructure().GetLayers().Count)
                    {
                        CompoundStructureLayer oldLayer
                            = wallType.GetCompoundStructure().GetLayers()[0];

                        WallType newWallType
                            = wallType.Duplicate("NewWallType") as WallType;

                        CompoundStructure structure
                            = newWallType.GetCompoundStructure();

                        IList <CompoundStructureLayer> layers
                            = structure.GetLayers();

                        // in Revit 2012, we can create a new layer:

                        double width = 0.1;
                        MaterialFunctionAssignment function = oldLayer.Function;
                        ElementId materialId = oldLayer.MaterialId;

                        CompoundStructureLayer newLayer
                            = new CompoundStructureLayer(width, function, materialId);

                        layers.Add(newLayer);
                        structure.SetLayers(layers);
                        newWallType.SetCompoundStructure(structure);
                    }
                }
                t.Commit();
            }
            return(Result.Succeeded);
        }
        /// <summary>
        /// Return the first wall found that
        /// uses the given wall type.
        /// </summary>
        static Wall GetFirstWallUsingType(
            Document doc,
            WallType wallType)
        {
            // built-in parameter storing this
              // wall's wall type element id:

              BuiltInParameter bip
            = BuiltInParameter.ELEM_TYPE_PARAM;

              ParameterValueProvider provider
            = new ParameterValueProvider(
              new ElementId( bip ) );

              FilterNumericRuleEvaluator evaluator
            = new FilterNumericEquals();

              FilterRule rule = new FilterElementIdRule(
            provider, evaluator, wallType.Id );

              ElementParameterFilter filter
            = new ElementParameterFilter( rule );

              FilteredElementCollector collector
            = new FilteredElementCollector( doc )
              .OfClass( typeof( Wall ) )
              .WherePasses( filter );

              return collector.FirstElement() as Wall;
        }
Exemple #60
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication app   = commandData.Application;
            UIDocument    uidoc = app.ActiveUIDocument;
            Document      doc   = uidoc.Document;
            //ElementSet a = uidoc.Selection.Elements; // 2014
            ICollection <ElementId> ids = uidoc.Selection.GetElementIds(); // 2015

            const string newWallTypeName = "NewWallType_with_Width_doubled";

            using (Transaction t = new Transaction(doc))
            {
                t.Start("Duplicate Wall Type");

                foreach (ElementId id in ids)
                {
                    Wall wall = doc.GetElement(id) as Wall;

                    if (null != wall)
                    {
                        WallType wallType = wall.WallType;

                        WallType newWallType = wallType.Duplicate(
                            newWallTypeName) as WallType;

                        //CompoundStructureLayerArray layers = newWallType.CompoundStructure.Layers; // 2011
                        IList <CompoundStructureLayer> layers = newWallType.GetCompoundStructure().GetLayers(); // 2012

                        foreach (CompoundStructureLayer layer in layers)
                        {
                            // double each layer thickness:

                            //layer.Thickness *= 2.0; // 2011

                            layer.Width *= 2.0; // 2012
                        }
                        // assign the new wall type back to the wall:

                        wall.WallType = newWallType;

                        // only process the first wall, if one was selected:

                        break;
                    }
                }
                t.Commit();
            }
            return(Result.Succeeded);

            #region Assign colour
#if ASSIGN_COLOUR
            ElementSet elemset = doc.Selection.Elements;

            foreach (Element e in elemset)
            {
                FamilyInstance inst = e as FamilyInstance;

                // get the symbol and duplicate it:
                FamilySymbol dupSym = inst.Symbol.Duplicate(
                    "D1") as FamilySymbol;

                // access the material:
                ElementId matId = dupSym.get_Parameter(
                    "Material").AsElementId();

                Material mat = doc.GetElement(ref matId)
                               as Autodesk.Revit.Elements.Material;

                // change the color of this material:
                mat.Color = new Color(255, 0, 0);

                // assign the new symbol to the instance:
                inst.Symbol = dupSym;
#endif // ASSIGN_COLOUR
            #endregion // Assign colour
        }
    }