public async Task <IActionResult> Edit(int?id, FlatViewImage pvm)
        {
            Flat flat = await _context.Flat.FindAsync(id);

            flat.OwnerName   = pvm.OwnerName;
            flat.PhoneNumber = pvm.PhoneNumber;
            flat.Description = pvm.Description;
            flat.Price       = pvm.Price;

            if (pvm.Image != null)
            {
                byte[] imageData = null;
                // считываем переданный файл в массив байтов
                using (var binaryReader = new BinaryReader(pvm.Image.OpenReadStream()))
                {
                    imageData = binaryReader.ReadBytes((int)pvm.Image.Length);
                }
                // установка массива байтов
                flat.Image = imageData;
            }
            if (id != null)
            {
                _context.Flat.Update(flat);
                await _context.SaveChangesAsync();

                return(RedirectToAction("Index"));
                //flat = await _context.Flat.FirstOrDefaultAsync(p => p.RoomID == id);
                //if (flat != null)
                //    return View(flat);
            }
            return(NotFound());
        }
        public async Task TestDeleteChoreCorrectUserAsync()
        {
            // Arrange
            var chore = new Chore
            {
                Title        = "dishes",
                Description  = "do the dishes",
                AssignedUser = await _userRepository.Get(1),    // Chore has to be assigned to a real user
                DueDate      = new DateTime(2020, 04, 04),
                Completed    = false,
                Recurring    = true,
            };

            Chore result = await _choresRepository.Add(chore);

            int id = result.Id;

            int  userId     = 1; // as initialised in HttpContextHelper
            User activeUser = await _userRepository.Get(userId);

            Flat userFlat = activeUser.Flat;

            userFlat.Chores.Add(result);
            await _flatRepository.Update(userFlat);

            // Act
            var response = await _choreController.DeleteChore(id);

            // Assert
            Assert.IsInstanceOf <OkResult>(response);
            Assert.Null(await _choresRepository.Get(id));
        }
Example #3
0
        private void AddComponent(Flat c)
        {
            var component = Flat.GetComponentLieIn(c);
            var room      = component as Flat;

            if (room != null)
            {
                component.Add(new Room(new Rectangle()
                {
                    Location = c.Rectangle.Location,
                    Height   = c.Rectangle.Height,
                    Width    = c.Rectangle.Width
                }));
            }
            else if (component is Room)
            {
                component.Add(new Furniture(new Rectangle()
                {
                    Location = c.Rectangle.Location,
                    Height   = c.Rectangle.Height,
                    Width    = c.Rectangle.Width
                }));
            }
            else
            {
                errorLds.Text = "You can't add this shape";
            }
            Draw();
            PrintTree();
        }
Example #4
0
        /// <summary>
        ///     Отсечение лишних квартир. Два правила:
        ///         а) Количество квартир на этажах одинаковое
        ///         б) Площадь секции не превышает 500м2
        ///     Стараемся отбрасывать самые маленькие однокомнатные, так как их проще встроить в новую модель.
        ///     Алгоритм в лоб:
        ///         Сначала работаем с правилом б. Отсекаем лишние
        ///         Проверяем на выполнение правила а
        /// </summary>
        public static Building ToSeverExcessFlats(Building building)
        {
            // Общая нежилая площадь = Лестничная клетка + коридор
            var generalSquare = Math.Round(Constraints.EntrywayLength * Constraints.WidthFlat[4] + Constraints.MaxSquareCorridor, 2);

            building.Flats = building.Flats.OrderBy(a => a.InputSquare).ToList();

            var listSquares = Flat.ReceiveListCastSquares(building.Flats);

            // Суммарная допустимая жилая площадь
            var livingSquare = (Constraints.MaxSquareSection - generalSquare) * building.CountFloor;
            var k            = listSquares.Sum();

            //б)
            while (listSquares.Sum() > livingSquare)
            {
                building.FlatsExcess.Add(building.Flats.First());
                building.Flats.Remove(building.Flats.First());
                listSquares.Remove(listSquares.First());
            }
            //а)
            while (building.Flats.Count % building.CountFloor != 0)
            {
                building.FlatsExcess.Add(building.Flats.First());
                building.Flats.Remove(building.Flats.First());
            }
            return(building);
        }
Example #5
0
        internal static string ToIconValue(this object icon)
        {
            if (icon.IsUsed())
            {
                var value = Convert.ToInt32(icon);

                if (icon.GetType() == typeof(FlatIcon))
                {
                    return(Flat.Get((FlatIcon)value));
                }
                else if (icon.GetType() == typeof(Flat2Icon))
                {
                    return(Flat2.Get((Flat2Icon)value));
                }
                else if (icon.GetType() == typeof(FontawesomeIcon))
                {
                    return(Fontawesome.Get((FontawesomeIcon)value));
                }
                else if (icon.GetType() == typeof(LineawesomeIcon))
                {
                    return(Lineawesome.Get((LineawesomeIcon)value));
                }
                else if (icon.GetType() == typeof(SocIcon))
                {
                    return(Soc.Get((SocIcon)value));
                }
                else if (icon.GetType() == typeof(SvgIcon))
                {
                    return(Svg.Get((SvgIcon)value));
                }
            }

            return("");
        }
Example #6
0
        public void DeleteFlat(long id)
        {
            Flat flt = GetFlat(id);

            flatRepository.Remove(flt);
            flatRepository.SaveChanges();
        }
        private void buttonSave_Click(object sender, EventArgs e)
        {
            using (var context = new MyDBContext()) //MyDBContext это названиие главной базы из  главного точка кс
            {
                NumberOfResidents c = new NumberOfResidents()
                {
                    numberOfResidents = Convert.ToInt32(textBox6.Text),

                    Datetime = textBox15.Text,

                    Number = Convert.ToInt32(textBox1.Text)
                };
                context.Peoples.Add(c);
                NameSakeListOfResidents d = new NameSakeListOfResidents()
                {
                    Datetime = textBox15.Text,
                    Number   = Convert.ToInt32(textBox1.Text)
                };
                context.nameSakeListOfResidents.Add(d);
                var flat1 = new Flat()
                {
                    Number            = Convert.ToInt32(textBox1.Text),
                    Entrance          = Convert.ToInt32(textBox3.Text),
                    floor             = Convert.ToInt32(textBox2.Text),
                    TotalArea         = Convert.ToInt32(textBox4.Text),
                    LivingArea        = Convert.ToInt32(textBox5.Text),
                    numberOfResidents = c ?? null,
                };
                context.Flats.Add(flat1);
                context.SaveChanges();
            }
        }
Example #8
0
        public static IDwelling GenerateDwelling(HouseType type, string postCode, string identifier, string householderName, int residents, bool singleFloored = true)
        {
            IDwelling result = null;

            switch (type)
            {
            case HouseType.Bungalow:
                Bungalow bungalow = new Bungalow(postCode, identifier);
                bungalow.HouseholderName = householderName;
                bungalow.Residents       = residents;
                result = bungalow;
                break;

            case HouseType.Flat:
                Flat flat = new Flat(postCode, identifier);
                flat.HouseholderName = householderName;
                flat.Residents       = residents;
                result = flat;
                break;

            default:
                //HouseType.House
                House house = new House(postCode, identifier);
                house.HouseholderName = householderName;
                house.Residents       = residents;
                house.SingleFloored   = singleFloored;
                result = house;
                break;
            }

            return(result);
        }
Example #9
0
        public async Task Update(Flat entity)
        {
            var flatToUpdate = await _rentContext.Flat
                               .Include(x => x.Address)
                               .Include(x => x.Owner)
                               .Include(x => x.Tenant)
                               .Include(x => x.Images)
                               .SingleOrDefaultAsync(x => x.Id == entity.Id);

            if (flatToUpdate != null)
            {
                flatToUpdate.Owner   = entity.Owner;
                flatToUpdate.Images  = entity.Images;
                flatToUpdate.Tenant  = entity.Tenant;
                flatToUpdate.Address = entity.Address;
                flatToUpdate.Floor   = entity.Floor;
                flatToUpdate.Price   = entity.Price;

                flatToUpdate.District      = flatToUpdate.District;
                flatToUpdate.IsElevator    = flatToUpdate.IsElevator;
                flatToUpdate.SquareMeters  = flatToUpdate.SquareMeters;
                flatToUpdate.NumberOfRooms = flatToUpdate.NumberOfRooms;
                flatToUpdate.DateOfUpdate  = DateTime.Now;
                await _rentContext.SaveChangesAsync();
            }
        }
Example #10
0
        public async Task CreateFlat(CreateFlatDTO dto)
        {
            Guid     id       = Guid.NewGuid();
            var      streetId = (await GetStreetEntity(dto.Street)).StreetId;
            Building building = await GetBuildingEntity(dto.Building, streetId);

            if (building == null)
            {
                await CreateBuilding(new BuildingDTO { Number = dto.Building }, streetId);
            }
            building = await GetBuildingEntity(dto.Building, streetId);

            var DontCreate = await Exist(building.BuildingId, dto.Number);

            if (DontCreate != Guid.Empty)
            {
                return;
            }
            using (MUEContext db = new MUEContext())
            {
                Flat flat = new Flat {
                    Square         = dto.Square,
                    Rooms          = dto.Rooms,
                    CountResidents = dto.CountResidents,
                    FlatId         = id,
                    Number         = dto.Number,
                    BuildingId     = building.BuildingId
                };
                db.Flats.Add(flat);
                await db.SaveChangesAsync();
            }
        }
Example #11
0
        public async Task <IActionResult> CreateChoreForFlat([FromBody] ChoreDTO choreDTO)
        {
            ClaimsIdentity identity = HttpContext.User.Identity as ClaimsIdentity;

            int userID = Int16.Parse(identity.FindFirst(ClaimTypes.NameIdentifier).Value);
            var usr    = await _userRepository.Get(userID);

            int?flatId   = usr.FlatId;
            var assignee = await _userRepository.Get(choreDTO.Assignee);

            if (assignee == null)
            {
                return(BadRequest());
            }

            Chore chore = _mapper.Map <ChoreDTO, Chore>(choreDTO);

            chore.AssignedUser = assignee;

            await _choresRepository.Add(chore);

            List <Chore> chores = await GetAllChoresFromFlatId(flatId);

            Flat flat = await _flatRepository.Get(flatId.Value);

            chores.Add(chore);
            flat.Chores = chores;
            await _flatRepository.Update(flat);

            return(Ok());
        }
        public ActionResult <FlatDTO> createFlat()
        {
            var identity = HttpContext.User.Identity as ClaimsIdentity;
            int userID   = Int16.Parse(identity.FindFirst(ClaimTypes.NameIdentifier).Value);
            var user     = _context.User.FirstOrDefault(x => x.Id == userID);

            if (user.FlatId > 0)
            {
                Response.StatusCode = 403;
                return(null);
            }
            var flat = new Flat
            {
                //Temporary flat address. Will need to be added in with the post request later
                Address = "50 Symonds Street",
                Users   = new List <User> {
                    user
                },
                Schedules = new List <Schedule>(),
                Payments  = new List <Payment>()
            };

            user.Flat = flat;
            _context.Add(flat);
            _context.SaveChanges();
            Response.StatusCode = 201;
            return(new FlatDTO(flat));
        }
Example #13
0
        public async Task <ActionResult <Flat> > PostFlat(Flat flat)
        {
            _context.Flats.Add(flat);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("GetFlat", new { id = flat.FlatId }, flat));
        }
        void addFlat(int id, Position3D a, Position3D b, Position3D c, Position3D d = null)
        {
            var flat = new Flat(id);

            flat.Points.Add(new FlatPoint
            {
                VertexId = addVertex(a.X, a.Y, a.Z)
            });
            flat.Points.Add(new FlatPoint
            {
                VertexId = addVertex(b.X, b.Y, b.Z)
            });
            flat.Points.Add(new FlatPoint
            {
                VertexId = addVertex(c.X, c.Y, c.Z)
            });
            if (d != null)
            {
                flat.Points.Add(new FlatPoint
                {
                    VertexId = addVertex(d.X, d.Y, d.Z)
                });
            }

            flats.Add(flat);
        }
Example #15
0
 /// <summary>
 /// Returns all items with a mapper returning an item deriving from <typeparamref name="T" />
 /// </summary>
 /// <typeparam name="T">The base type to look for</typeparam>
 /// <returns>A list of items that derives from <typeparamref name="T" /></returns>
 public IEnumerable <T> InvokeDerivedMappers <T>()
 {
     return(Flat
            .Where(n => n.Matched)
            .Where(n => n != this)
            .Where(
                n =>
                n.Token.GetType().IsConstructedGenericType
                &&
                n.Token.GetType().GetGenericTypeDefinition() == typeof(BNF.Mapper <>)
                &&
                typeof(T).IsAssignableFrom(n.Token.GetType().GetGenericArguments().First())
                )
            .Select(
                n => {
         try
         {
             return (T)n.Token
             .GetType()
             .GetMethod(nameof(BNF.Mapper <T> .InvokeMatcher))
             .Invoke(n.Token, new object[] { n });
         }
         catch (System.Reflection.TargetInvocationException tex)
         {
             // As we use reflection, unwrap the exception here
             throw tex.InnerException;
         }
     }
                ));
 }
Example #16
0
        public async Task Remove(int id)
        {
            Flat flat = await GetFlatIfCurrentUserHasPermissions(id);

            _context.Flats.Remove(flat);
            await _context.SaveChangesAsync();
        }
Example #17
0
        public string Add(Flat flat)
        {
            try
            {
                if (flat.Id != 0)
                {
                    return(Update(flat.Id, flat));
                }
                else
                {
                    var nameValidation = ValidateName(flat);
                    if (nameValidation != null)
                    {
                        return(nameValidation);
                    }

                    _flatRepository.Add(flat);
                    _flatRepository.SaveChanges();
                    return(null);
                }
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }
        }
Example #18
0
        public async Task <IActionResult> PutFlat(int id, Flat flat)
        {
            if (id != flat.FlatId)
            {
                return(BadRequest());
            }

            _context.Entry(flat).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!FlatExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
        void addFlat(int id, Position3D a, Position3D b, Position3D c, Position3D d,
                     Position2D ta, Position2D tb, Position2D tc, Position2D td)
        {
            var flat = new Flat(id);

            flat.Points.Add(new FlatPoint
            {
                VertexId  = addVertex(a.X, a.Y, a.Z),
                TextureId = addTexture(ta)
            });
            flat.Points.Add(new FlatPoint
            {
                VertexId  = addVertex(b.X, b.Y, b.Z),
                TextureId = addTexture(tb)
            });
            flat.Points.Add(new FlatPoint
            {
                VertexId  = addVertex(c.X, c.Y, c.Z),
                TextureId = addTexture(tc)
            });
            flat.Points.Add(new FlatPoint
            {
                VertexId  = addVertex(d.X, d.Y, d.Z),
                TextureId = addTexture(td)
            });

            flats.Add(flat);
        }
Example #20
0
        public async Task <IActionResult> PutFlat(int id, Flat flat)
        {
            if (id != flat.Id)
            {
                return(BadRequest("You can only update a Flat with the same ID"));
            }

            try
            {
                if (IsTheSameFlat(flat))
                {
                    return(BadRequest("Flat with the same properties already exist"));
                }
                _context.Entry(flat).State = EntityState.Modified;
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!FlatExists(id))
                {
                    return(NotFound("Flat with ID {id} does not exist"));
                }
                else
                {
                    throw;
                }
            }

            return(Ok($"Flat with ID {id} is updated"));
        }
        public static Flat GetFlat()
        {
            var flat = new Flat
            {
                Id                 = 1,
                CreatedAt          = new DateTime(2015, 1, 1),
                Deleted            = false,
                Title              = "title",
                Description        = "description",
                Details            = "details",
                City               = "city",
                Price              = 1,
                Visible            = true,
                Pictures           = null,
                Counter            = 1,
                Location           = "location",
                Area               = 10,
                Storey             = 1,
                TechnicalCondition = "technicalCondition",
                Rooms              = 1,
                Heating            = "heating",
                Rent               = "rent",
                Ownership          = "ownership",
                PricePerMeter      = "pricePerMeter",
                ToLet              = true
            };

            return(flat);
        }
Example #22
0
        private void FillFlat(Flat flat)
        {
            var src   = flat.Data;
            var dst   = this.screen.Data;
            var scale = this.screen.Width / 320;
            var xFrac = Fixed.One / scale - Fixed.Epsilon;
            var step  = Fixed.One / scale;

            for (var x = 0; x < this.screen.Width; x++)
            {
                var yFrac = Fixed.One / scale - Fixed.Epsilon;
                var p     = this.screen.Height * x;

                for (var y = 0; y < this.screen.Height; y++)
                {
                    var spotX = xFrac.ToIntFloor() & 0x3F;
                    var spotY = yFrac.ToIntFloor() & 0x3F;
                    dst[p] = src[(spotY << 6) + spotX];
                    yFrac += step;
                    p++;
                }

                xFrac += step;
            }
        }
Example #23
0
        public Flat addRoom()
        {
            Flat flat = new Flat();
            XMLFileOperator dataSource = new XMLFileOperator("file.xml");

            Console.Clear();
            Console.WriteLine("Add your room or apartament");
            Console.Write("1. Enter a region: ");
            flat.FlatAddress.Region = Console.ReadLine();
            Console.Write("Enter a street title: ");
            flat.FlatAddress.Street = Console.ReadLine();
            Console.Write("Enter a house number: ");
            flat.FlatAddress.HouseNumb = Console.ReadLine();
            Console.Write("Enter a flat number: ");
            flat.FlatAddress.FlatNumb = Int16.Parse(Console.ReadLine());
            Console.Write("Enter rooms count: ");
            flat.RoomCount = Int16.Parse(Console.ReadLine());
            Console.Write("Enter a monthly privce ");
            flat.Price = Int16.Parse(Console.ReadLine());

            dataSource.FillFlatIntoXml(flat);
            dataSource.fillCounter();

            return flat;
        }
Example #24
0
        private Flat ProcessResult()
        {
            var infos = WatinBrowser.Tables.Where(t => t.ClassName == "object-view").ToArray();

            var flat       = new Flat(infos);
            var isInregion = Map.IsInRegion(flat.Lng, flat.Lat);

            var dbFlat = SearchContext.Current.Data.Flats.FirstOrDefault(f => f.Id == flat.Id);

            if (dbFlat == null)
            {
                dbFlat         = flat;
                dbFlat.Visible = isInregion;
                SearchContext.Current.Data.Flats.Add(dbFlat);
            }
            else
            {
                dbFlat.GetInfo(flat);
            }
            SearchContext.Current.Data.SetVisibility(flat.Address, isInregion);
            flatBindingSource.DataSource = dbFlat;
            SetStatus(isInregion);

            Parent.Text = dbFlat.Address;

            return(dbFlat);
        }
Example #25
0
        public int CountUsersInFlat(Flat flat, DateTime Day)
        {
            List <Lease> leasesInDay  = dbContext.Leases.Where(x => x.FlatsId == flat.Id).Where(x => x.To < Day).Where(x => x.From > Day).ToList <Lease>();
            var          unique_items = new HashSet <Lease>(leasesInDay);

            return(unique_items.Count());
        }
Example #26
0
        public bool insertFlat(Flat f)
        {
            try
            {
                //Creamos instancia y abrimos la conexión de la BD
                conn = new SqlConnection(bdConnection);
                conn.Open();

                /*Realizamos la sentencia SQL y la ejecutamos. Tiene dos parámetros, un string (con la sentencia SQL)
                 * y una instancia de SqlConnection, para pasarle la conexión.*/
                comm = new SqlCommand("Insert Into [dbo].[Flat] (id,province,city,address,postal_code,capacity,description,owner,profile_img,img1,img2,img3,img4,img5,img6,img7,price) VALUES('" + f.ID + "','" + f.Province + "','" + f.City + "','" + f.Address + "','" + f.PC + "','" + f.Capacity + "','" + f.Description + f.Owner + "','" + f.Profile + "','" + f.IMG1 + "','" + f.IMG2 + "','" + f.IMG3 + "','" + f.IMG4 + "','" + f.IMG5 + "','" + f.IMG6 + "','" + f.IMG7 + "','" + f.Price + "')", conn);
                int result = comm.ExecuteNonQuery();

                if (result == 1)
                {
                    return(true);
                }
                return(false);
            }
            catch (SqlException Ex)
            {
                throw Ex;
            }
            finally
            {
                if (conn != null)
                {
                    conn.Close();
                }
            }
        }
        public async Task <IActionResult> CreatePaymentForFlat(int flatId, [FromBody] PaymentDTO paymentDTO, [FromHeader] List <int> userIds)
        {
            Payment payment = _mapper.Map <PaymentDTO, Payment>(paymentDTO);

            await _paymentsRepository.Add(payment);

            List <Payment> payments = await GetAllPaymentsFromFlatId(flatId);

            Flat flat = await _flatRepository.Get(flatId);

            payments.Add(payment);

            flat.Payments = payments;

            await _flatRepository.Update(flat);

            foreach (int userId in userIds)
            {
                User user = await _userRepository.Get(userId);

                UserPayment userPayment = new UserPayment {
                    Payment = payment, User = user, PaymentId = payment.Id, UserId = user.Id
                };

                user.UserPayments.Add(userPayment);

                await _userRepository.Update(user);
            }

            return(Ok(paymentDTO));
        }
Example #28
0
        public bool deleteFlat(Flat f)
        {
            try
            {
                //Creamos instancia y abrimos la conexión de la BD
                conn = new SqlConnection(bdConnection);
                conn.Open();

                /*Realizamos la sentencia SQL y la ejecutamos. Tiene dos parámetros, un string (con la sentencia SQL)
                 * y una instancia de SqlConnection, para pasarle la conexión.*/
                comm = new SqlCommand("DELETE * FROM [dbo].[Flat] WHERE id ='" + f.ID + "'", conn);
                int result = comm.ExecuteNonQuery();
                if (result == 1)
                {
                    return(true);
                }
                return(false);
            }
            catch (SqlException Ex)
            {
                throw Ex;
            }
            finally
            {
                if (conn != null)
                {
                    conn.Close();
                }
            }
        }
        public IActionResult Detail(int id)
        {
            Flat flat = _dataRepository.GetFlat(id);

            if (flat == null)
            {
                return(NotFound());
            }
            FlatViewModel model = new FlatViewModel
            {
                Balcony = flat.Balcony,
                AdditionalInformation = flat.AdditionalInformation,
                City            = flat.Address.City.Name,
                Street          = flat.Address.Street.Name,
                FlatNumber      = flat.Address.FlatNumber,
                FlatPicturePath = flat.FlatPicture,
                PriceForMonth   = flat.PriceForMonth,
                HouseNumber     = flat.Address.HouseNumber,
                NumberOfRooms   = flat.NumberOfRooms,
                Header          = flat.Header,
                TotalArea       = flat.TotalArea,
                TypeOfHouse     = flat.TypeOfHouse,
                OwnerId         = flat.OwnerId,
                Owner           = flat.Owner
            };

            return(View(model));
        }
Example #30
0
        public string UpdateFlat(FlatModel flat)
        {
            Mapper.CreateMap <FlatModel, Flat>().ForMember(dest => dest.FlatPLCs, sec => sec.Ignore());
            Flat           fl        = Mapper.Map <FlatModel, Flat>(flat);
            int            i         = fservice.EditFlat(fl);
            FlatPLCService fpservice = new FlatPLCService();
            var            model     = fpservice.GetFlatPLCListByFlatID(fl.FlatID);

            foreach (var ft in model)
            {
                FlatPLC md = new FlatPLC();
                md.FlatPLCID = ft.FlatPLCID;
                int ii = fpservice.DeleteFlatPLC(md);
            }
            foreach (string st in flat.FlatPLCs)
            {
                if (st != "0")
                {
                    FlatPLC fpm = new FlatPLC();
                    fpm.FlatID = fl.FlatID;
                    fpm.PLCID  = Convert.ToInt32(st);
                    int ii = fpservice.AddFlatPLC(fpm);
                }
            }
            return(i.ToString());
        }
Example #31
0
        private Flat ParseFlat(string addrStr)
        {
            var flat        = new Flat();
            var flatMarkers = Markers.CreateFlatMarkers();

            foreach (var marker in flatMarkers) //Пробуем поиск по маркеру дома
            {
                var index = addrStr.IndexOf(marker);
                if (index < 0)
                {
                    continue;
                }

                var textNumber = TextParser.GetNextWord(addrStr, index, marker);
                if (int.TryParse(textNumber, out int number))
                {
                    flat.Number = number;
                }
            }

            if (flat.Number == 0)
            {
                return(null);
            }

            return(flat);
        }
Example #32
0
 /// <summary>
 /// When the tessellated solid is sliced at the specified plane, the contact surfaces are
 /// described by the return ContactData object. This is a non-destructive function typically
 /// used to find the shape and size of 2D surface on the prescribed plane..
 /// </summary>
 /// <param name="plane">The plane.</param>
 /// <param name="ts">The ts.</param>
 /// <returns>ContactData.</returns>
 /// <exception cref="System.Exception">Contact Edges found that are not contained in loop.</exception>
 public static ContactData DefineContact(Flat plane, TessellatedSolid ts)
 {
     var vertexDistancesToPlane = new double[ts.NumberOfVertices];
     for (int i = 0; i < ts.NumberOfVertices; i++)
         vertexDistancesToPlane[i] = ts.Vertices[i].Position.dotProduct(plane.Normal) - plane.DistanceToOrigin;
     // the edges serve as the easiest way to identify where the solid is interacting with the plane.
     // Instead of a foreach, the while loop lets us look ahead to known edges that are irrelevant.
     var edgeHashSet = new HashSet<Edge>(ts.Edges);
     // Contact elements are constructed and then later arranged into loops. Loops make up the returned object, ContactData.
     var straddleContactElts = new List<ContactElement>();
     var inPlaneContactElts = new List<CoincidentEdgeContactElement>();
     while (edgeHashSet.Any())
     {
         // instead of the foreach, we have this while statement and these first 2 lines to enumerate over the edges.
         var edge = edgeHashSet.First();
         edgeHashSet.Remove(edge);
         var toDistance = vertexDistancesToPlane[edge.To.IndexInList];
         var fromDistance = vertexDistancesToPlane[edge.From.IndexInList];
         if (StarMath.IsNegligible(toDistance) && StarMath.IsNegligible(fromDistance))
             ContactElement.MakeInPlaneContactElement(plane, edge, edgeHashSet, vertexDistancesToPlane,
                 inPlaneContactElts);
         else if ((toDistance > 0 && fromDistance < 0)
                  || (toDistance < 0 && fromDistance > 0))
             straddleContactElts.Add(new ThroughFaceContactElement(plane, edge, toDistance));
     }
     foreach (var contactElement in inPlaneContactElts)
     {
         // next, we find any additional vertices that just touch the plane but don't have in-plane edges
         // to facilitate this we negate all vertices already captures in the inPlaneContactElts
         vertexDistancesToPlane[contactElement.StartVertex.IndexInList] = double.NaN;
         vertexDistancesToPlane[contactElement.EndVertex.IndexInList] = double.NaN;
     }
     for (int i = 0; i < ts.NumberOfVertices; i++)
     {
         if (!StarMath.IsNegligible(vertexDistancesToPlane[i])) continue;
         var v = ts.Vertices[i];
         PolygonalFace negativeFace, positiveFace;
         if (ThroughVertexContactElement.FindNegativeAndPositiveFaces(plane, v, vertexDistancesToPlane,
             out negativeFace, out positiveFace))
             straddleContactElts.Add(new ThroughVertexContactElement(v, negativeFace, positiveFace));
     }
     straddleContactElts.AddRange(inPlaneContactElts);
     var loops = new List<Loop>();
     var numberOfTries = 0;
     while (straddleContactElts.Any() && numberOfTries < straddleContactElts.Count)
     {
         // now build loops from stringing together contact elements
         var loop = FindLoop(plane, straddleContactElts, vertexDistancesToPlane);
         if (loop != null)
         {
             Debug.WriteLine(loops.Count + ": " + loop.MakeDebugContactString() + "  ");
             loops.Add(loop);
             numberOfTries = 0;
         }
         else numberOfTries++;
     }
     if (straddleContactElts.Any()) Debug.WriteLine("Contact Edges found that are not contained in loop.");
     return new ContactData(loops);
 }
        public void GenericFlatTest()
        {
            var f = new Foo
            {
                Parent = new Foo
                {
                    _a = "aaa",
                    a = 23,
                    b = true,
                    Name = "v"
                }
            };

            var flat = new Flat();

            flat.InjectFrom<FlatBoolToString>(f);
            flat.Parentb.IsEqualTo("True");
            flat.Bool.IsEqualTo(null);
        }
 private static double OnTravel(Point shuttle, Flat flat, int hSpeed, int vSpeed)
 {
     int sign = GetSign(shuttle, new Point(flat.Target, flat.Y));
     double hypotenuse = Math.Sqrt(Math.Pow(4,2)-Math.Pow(GRAVITY,2));
     int resting_dist = Math.Abs(flat.Target - shuttle.X);
     int slow_dist = 0;
     for(int x = Math.Abs(hSpeed); x > 0 ; x--)
     {
         slow_dist += x;
     }
     Console.Error.WriteLine(slow_dist+" "+resting_dist);
     if(map._flat.Y > shuttle.Y)
         return 0;
     if(slow_dist > resting_dist & hSpeed != 0)
         return GetBrakeAngle(hSpeed, vSpeed)/2;
     else if(flat.Y < shuttle.Y)
         return (180 - Math.Abs(RadianToDegree(Math.Acos(GRAVITY/4)))) * sign;
     else
         return 0;
 }
        public void FlatTest()
        {
            var f = new Foo
                        {
                            Parent = new Foo
                                         {
                                             _a = "aaa",
                                             a = 23,
                                             b = true,
                                             Name = "v"
                                         }
                        };

            var flat = new Flat();

            flat.InjectFrom<FlatLoopInjection>(f);
            flat.Parent_a.IsEqualTo(f.Parent._a);
            flat.Parenta.IsEqualTo(f.Parent.a);
            flat.Parentb.IsEqualTo(null);
            flat.ParentName.IsEqualTo(f.Parent.Name);
            flat.ParentParentName.IsEqualTo(null);
            flat.oO.IsEqualTo(null);
            flat.d.IsEqualTo(null);
        }
Example #36
0
        /// <summary>
        /// Finds the loop.
        /// </summary>
        /// <param name="plane">The plane.</param>
        /// <param name="contacts">The contacts.</param>
        /// <param name="vertexDistancesToPlane"></param>
        /// <returns>Loop.</returns>
        private static Loop FindLoop(Flat plane, List<ContactElement> contacts, double[] vertexDistancesToPlane)
        {
            Vertex connectingVertex;
            var contactElements = new List<ContactElement>();
            var firstContactElt = contacts[0]; // start with the first one, and keep a reference to it so that we
            // can tell when we've looped around.
            // contacts.RemoveAt(0);  why is this commented out? I left it here to help you understand that it is important
            // to identify a loop. When the below while-loop re-finds this firstContactElt
            var contactElt = firstContactElt;
            int nextContactEltIndex = FindNextContactElement(contacts, contactElt, out connectingVertex);
            if (nextContactEltIndex == -1)
            {
                //if failed to find the loop, stick it on the end and start over
                contacts.RemoveAt(0);
                contacts.Add(contactElt);
                return null;
            }
            while (nextContactEltIndex != -1)
            {
                var nextContactElt = contacts[nextContactEltIndex];
                if (!(contactElt is CoincidentEdgeContactElement))
                    contactElt.ContactEdge = new Edge(contactElt.StartVertex, connectingVertex, null, null);
                else if (contactElt is CoincidentEdgeContactElement &&
                         !(nextContactElt is CoincidentEdgeContactElement))
                {
                    contactElements.Add(contactElt);
                    contactElt = new ThroughVertexContactElement(connectingVertex, null, null)
                    {
                        ContactEdge = new Edge(((CoincidentEdgeContactElement)contactElt).EndVertex, connectingVertex, null, null)
                    };
                }
                contactElements.Add(contactElt);
                contacts.RemoveAt(nextContactEltIndex);
                contactElt = nextContactElt;

                nextContactEltIndex = FindNextContactElement(contacts, contactElt, out connectingVertex);
            }
            if (contactElt == firstContactElt)
                return new Loop(contactElements, plane.Normal, true, false);
            // else work backwards
            contactElt = firstContactElt;
            contacts.RemoveAt(0);
            // now it is right to remove the first contact, and instead, we will re-add the last one
            firstContactElt = contactElements.Last();
            contacts.Add(firstContactElt);
            int prevContactEltIndex = FindPrevContactElement(contacts, contactElt, out connectingVertex);
            while (prevContactEltIndex != -1)
            {
                var prevContactElt = contacts[prevContactEltIndex];
                if (!(contactElt is CoincidentEdgeContactElement))
                    contactElt.ContactEdge = new Edge(connectingVertex, contactElt.StartVertex, null, null);
                else if (contactElt is CoincidentEdgeContactElement &&
                         !(prevContactElt is CoincidentEdgeContactElement))
                {
                    contactElements.Insert(0, contactElt);
                    contactElt = new ThroughVertexContactElement(connectingVertex, null, null)
                    {
                        ContactEdge = new Edge(connectingVertex, ((CoincidentEdgeContactElement)contactElt).StartVertex, null, null)
                    };
                }
                contactElements.Insert(0, contactElt);
                contacts.RemoveAt(prevContactEltIndex);
                contactElt = prevContactElt;
                prevContactEltIndex = FindPrevContactElement(contacts, contactElt, out connectingVertex);
            }
            if (contactElements[0].ContactEdge.From == contactElements.Last().ContactEdge.To)
                return new Loop(contactElements, plane.Normal, true, false);
            if (StarMath.IsPracticallySame(contactElements[0].ContactEdge.From.Position,
                  contactElements.Last().ContactEdge.To.Position))
            {
                contactElements[0].ContactEdge = new Edge(contactElements.Last().ContactEdge.To,
                    contactElements[0].ContactEdge.To, null, null);
                return new Loop(contactElements, plane.Normal, true, true);
            }
            contacts.Remove(firstContactElt); //it didn't work to connect it up, so you're going to have to leave
            // the loop open. Be sure to remove that one contact that you were hoping to re-find. Otherwise, the
            // outer process will continue to consider it.
            var artificialContactElement = new ArtificialContactElement
            {
                ContactEdge =
                    new Edge(contactElements.Last().ContactEdge.To, contactElements[0].ContactEdge.From, null, null)
            };
            Debug.WriteLine("Adding an artificial edge to close the loop for plane @" + plane.Normal.MakePrintString()
                            + " with a distance of " + plane.DistanceToOrigin);
            contactElements.Add(artificialContactElement);
            return new Loop(contactElements, plane.Normal, true, true);
        }
Example #37
0
        /// <summary>
        /// Divides up contact.
        /// </summary>
        /// <param name="ts">The ts.</param>
        /// <param name="contactData">The contact data.</param>
        /// <param name="plane">The plane.</param>
        /// <exception cref="System.Exception">face is supposed to be split at plane but lives only on one side</exception>
        private static void DivideUpContact(TessellatedSolid ts, ContactData contactData, Flat plane)
        {
            var edgesToAdd = new List<Edge>();
            var facesToAdd = new List<PolygonalFace>();
            var verticesToAdd = new List<Vertex>();
            var edgesToDelete = new List<Edge>();
            var facesToDelete = new List<PolygonalFace>();
            var edgesToModify = new List<Edge>();
            foreach (var loop in contactData.AllLoops)
            {
                for (int i = 0; i < loop.Count; i++)
                {
                    var ce = loop[i];
                    if (ce is CoincidentEdgeContactElement)
                        // If the contact element is at a coincident edge, then there is nothing to do in this stage. When contact element was
                        // created, it properly defined SplitFacePositive and SplitFaceNegative.
                        continue;
                    edgesToAdd.Add(ce.ContactEdge); // the contact edge is a new edge for the solid
                    edgesToModify.Add(ce.ContactEdge); // the contact edge will need to be linked to vertices and faces further down.
                    var faceToSplit = ce.SplitFacePositive; //faceToSplit will be removed, but before we do that, we use
                    facesToDelete.Add(faceToSplit);         // use it to build the new 2 to 3 triangles

                    PolygonalFace positiveFace, negativeFace;
                    if (ce is ThroughVertexContactElement)
                    {
                        var vertPlaneDistances =              //signed distances of faceToSplit's vertices from the plane
                        faceToSplit.Vertices.Select(
                            v => v.Position.dotProduct(plane.Normal) - plane.DistanceToOrigin).ToArray();
                        var maxIndex = vertPlaneDistances.FindIndex(vertPlaneDistances.Max());
                        var maxVert = faceToSplit.Vertices[maxIndex];
                        var minIndex = vertPlaneDistances.FindIndex(vertPlaneDistances.Min());
                        var minVert = faceToSplit.Vertices[minIndex];
                        positiveFace = new PolygonalFace(new[] { ce.ContactEdge.From, ce.ContactEdge.To, maxVert });
                        facesToAdd.Add(positiveFace);
                        negativeFace = new PolygonalFace(new[] { ce.ContactEdge.To, ce.ContactEdge.From, minVert });
                        facesToAdd.Add(negativeFace);
                    } //#+1 add v to f           (both of these are done in the preceding PolygonalFace
                    //#+2 add f to v            constructors as well as the one for thirdFace below)
                    else // then ce is a ThroughFaceContactElement
                    {
                        var tfce = (ThroughFaceContactElement)ce; // ce is renamed and recast as tfce
                        edgesToDelete.Add(tfce.SplitEdge);
                        verticesToAdd.Add(tfce.StartVertex);
                        Vertex positiveVertex, negativeVertex;
                        if (tfce.SplitEdge.To.Position.dotProduct(plane.Normal) > plane.DistanceToOrigin)
                        {
                            positiveVertex = tfce.SplitEdge.To;
                            negativeVertex = tfce.SplitEdge.From;
                        }
                        else
                        {
                            positiveVertex = tfce.SplitEdge.From;
                            negativeVertex = tfce.SplitEdge.To;
                        }
                        positiveFace =
                           new PolygonalFace(new[] { ce.ContactEdge.From, ce.ContactEdge.To, positiveVertex });
                        facesToAdd.Add(positiveFace);
                        negativeFace =
                           new PolygonalFace(new[] { ce.ContactEdge.To, ce.ContactEdge.From, negativeVertex });
                        facesToAdd.Add(negativeFace);
                        var positiveEdge = new Edge(positiveVertex, ce.ContactEdge.From, positiveFace, null, true,
                            true);
                        edgesToAdd.Add(positiveEdge);
                        edgesToModify.Add(positiveEdge);
                        var negativeEdge = new Edge(ce.ContactEdge.From, negativeVertex, negativeFace, null, true,
                            true);
                        edgesToAdd.Add(negativeEdge);
                        edgesToModify.Add(negativeEdge);

                        var otherVertex = faceToSplit.Vertices.First(v => v != positiveVertex && v != negativeVertex);
                        PolygonalFace thirdFace;
                        if (otherVertex.Position.dotProduct(plane.Normal) > plane.DistanceToOrigin)
                        {
                            thirdFace = new PolygonalFace(new[] { ce.ContactEdge.To, otherVertex, positiveVertex });
                            facesToAdd.Add(thirdFace);
                            edgesToAdd.Add(new Edge(ce.ContactEdge.To, positiveVertex, positiveFace, thirdFace, true, true));
                        }
                        else
                        {
                            thirdFace = new PolygonalFace(new[] { ce.ContactEdge.To, negativeVertex, otherVertex });
                            facesToAdd.Add(thirdFace);
                            edgesToAdd.Add(new Edge(negativeVertex, ce.ContactEdge.To, negativeFace, thirdFace, true, true));
                        }
                        // for the new edges in a through face this line accomplishes: +3 add f to e; +4 add e to f; +5 add v to e;
                        //    +6 add e to v
                    }
                    loop[i] = new CoincidentEdgeContactElement
                    {
                        ContactEdge = ce.ContactEdge,
                        EndVertex = ce.ContactEdge.To,
                        StartVertex = ce.ContactEdge.From,
                        SplitFaceNegative = negativeFace,
                        SplitFacePositive = positiveFace
                    };
                }
            }
            // -1 remove v from f - no need to do this as no v's are removed
            foreach (var face in facesToDelete)
            {
                foreach (var vertex in face.Vertices)
                    vertex.Faces.Remove(face); //-2 remove f from v
                foreach (var edge in face.Edges)
                {
                    if (edgesToDelete.Contains(edge)) continue;
                    edgesToModify.Add(edge);
                    if (edge.OwnedFace == face) edge.OwnedFace = null; //-3 remove f from e
                    else edge.OtherFace = null;
                }
            }
            //-4 remove e from f - no need to do as the only edges deleted are the ones between deleted faces
            ts.RemoveFaces(facesToDelete);
            // -5 remove v from e - not needed as no vertices are deleted (like -1 above)
            foreach (var edge in edgesToDelete)
            {
                edge.From.Edges.Remove(edge); //-6 remove e from v
                edge.To.Edges.Remove(edge);
            }
            ts.RemoveEdges(edgesToDelete);
            // now to add new faces to modified edges
            ts.AddVertices(verticesToAdd);
            ts.AddFaces(facesToAdd);

            foreach (var edge in edgesToModify)
            {
                var facesToAttach = facesToAdd.Where(f => f.Vertices.Contains(edge.To) && f.Vertices.Contains(edge.From)
                    && !f.Edges.Contains(edge));
                if (facesToAttach.Count() > 2) throw new Exception();
                foreach (var face in facesToAttach)
                {
                    face.Edges.Add(edge); //+4 add e to f
                    var fromIndex = face.Vertices.IndexOf(edge.From);
                    if ((fromIndex == face.Vertices.Count - 1 && face.Vertices[0] == edge.To)
                        || (fromIndex < face.Vertices.Count - 1 && face.Vertices[fromIndex + 1] == edge.To))
                        edge.OwnedFace = face; //+3 add f to e
                    else edge.OtherFace = face;
                }
            }
            ts.AddEdges(edgesToAdd);
        }
Example #38
0
    /// <summary>
    /// Loads the floor plan xml.
    /// </summary>
    /// <param name="xmlPath">Xml path.</param>
    /// <param name="planName">Plan name.</param>
    void LoadFloorPlanXml(string xmlPath, string planName)
    {
        //******************************************************************************
        //*                                                                            *
        //*     Parse the XML to findout which floor plan detail set would be used     *
        //*     Plan Name is carried from EstateMap to tell this script which flat     *
        //*                                                                            *
        //******************************************************************************

        XmlDocument xmlDoc = new XmlDocument();
        TextAsset xmlText = (TextAsset) Resources.Load(xmlPath);
        xmlDoc.LoadXml(xmlText.text);
        XmlNode xmlNode = xmlDoc.SelectSingleNode("floor_plans");
        xmlNode = xmlNode.SelectSingleNode("floor_plan" + planName);

        int flatCount = xmlNode.ChildNodes.Count;

        string path = "Texture/Map/BG_Floor/" + estateName + "/" + xmlNode.Attributes.GetNamedItem("texture").Value;
        Texture2D texture;

        //********************************************
        //*                                          *
        //*     Prepare the Floor Plan BG Texture    *
        //*                                          *
        //********************************************

        mapTexture = (Texture2D) Resources.Load(path);
        sceneMonitor.GetComponent<SceneManager>().SetMapTextureName(path);

        flats = new Flat[flatCount];

        //******************************************************************************
        //*                                                                            *
        //*     Start parsing the XML file and add FLAT icons on to the floor plan     *
        //*                                                                            *
        //******************************************************************************

        for (int i = 0; i < flatCount; i++) {
            GUIStyle guiStyle = new GUIStyle();

            string texName = xmlNode.ChildNodes[i].Attributes.GetNamedItem("texture").Value;
            string[] pos = xmlNode.ChildNodes[i].Attributes.GetNamedItem("pos").Value.Split(",".ToCharArray());
            string flatName = xmlNode.ChildNodes[i].Attributes.GetNamedItem ("name").Value;
            string subpath = "Texture/Map/Icon_EstateMap/";

            Flat flat = new Flat();
            path = subpath + texName;

            //**************************
            //*                        *
            //*     Normal Texture     *
            //*                        *
            //**************************

            sceneMonitor.GetComponent<SceneManager>().SetXMLPath(path);
            texture = (Texture2D) Resources.Load(path);
            flat.position = new Rect(Convert.ToInt32(pos[0].Trim()), Convert.ToInt32(pos[1].Trim()), texture.width, texture.height);
            flat.flatPlanName = flatName;

            //*************************
            //*                       *
            //*     Hover Texture     *
            //*                       *
            //*************************
            guiStyle.normal.background = texture;
            path = subpath + texName + "_Clicked";
            texture = (Texture2D) Resources.Load(path);

            guiStyle.active.background = texture;
            guiStyle.focused.background = texture;
            flat.guiStyle = guiStyle;
            flats[i] = flat;
        }
    }
Example #39
0
        public void readFromFile(String fileName)
        {
            StreamReader sr = new StreamReader(fileName);
            String line;
            String[] tokens;
            errorCounter = 0;

            List<Transaction> newList = new List<Transaction>();
            try
            {
                while ((line = sr.ReadLine()) != null)
                {
                    tokens = line.Split(new String[] { ";" }, StringSplitOptions.None);

                    if ("Flat".Equals(tokens[0]))
                    {
                        if (tokens.Length != 6)
                        {
                            throw new MyException("Wrong number of arguments!");
                        }
                        Flat flat = new Flat(Convert.ToInt32(tokens[2]), tokens[3], Convert.ToInt32(tokens[1]));
                        Transaction trans = new Transaction(flat, Convert.ToInt32(tokens[4]), Convert.ToInt32(tokens[5]));
                        val.validateTransaction(trans);
                        newList.Add(trans);
                    }
                    else if ("House".Equals(tokens[0]))
                    {
                        if (tokens.Length != 7)
                        {
                            throw new MyException("Wrong number of arguments!");
                        }
                        House house = new House(Convert.ToInt32(tokens[3]), tokens[4], Convert.ToInt32(tokens[2]), Convert.ToInt32(tokens[1]));
                        Transaction trans = new Transaction(house, Convert.ToInt32(tokens[5]), Convert.ToInt32(tokens[6]));
                        val.validateTransaction(trans);
                        newList.Add(trans);
                    }
                    else if ("CommercialSpace".Equals(tokens[0]))
                    {
                        if (tokens.Length != 5)
                        {
                            throw new MyException("Wrong number of arguments!");
                        }
                        CommercialSpace commercialSpace = new CommercialSpace(Convert.ToInt32(tokens[1]), tokens[2]);
                        Transaction trans = new Transaction(commercialSpace, Convert.ToInt32(tokens[3]), Convert.ToInt32(tokens[4]));
                        val.validateTransaction(trans);
                        newList.Add(trans);
                    }
                    else
                    {
                        throw new MyException("Error reading from file!");
                    }
                }

            }
            catch (FormatException ex)
            {
                errorCounter++;
                throw new MyException(ex.Message);
            }
            catch (MyException ex)
            {
                errorCounter++;
                throw new MyException(ex.getMessage());
            }

            this.repo.replaceContent(newList);
            sr.Close();
        }
 private static double GetLandingAngle(int speed_h, int speed_v, Point shuttle, Flat flat)
 {
     int height = shuttle.Y - flat.Y;
     if(height < LANDING_HEIGHT & !decreaseHSpeed)
         return 0;
     double hypotenuse = Math.Sqrt(Math.Pow(speed_h,2)+Math.Pow(speed_v,2));
     return GetBrakeAngle(speed_h, speed_v);
 }
Example #41
0
        /// <summary>
        /// Performs the slicing operation on the prescribed flat plane. This destructively alters
        /// the tessellated solid into one or more solids which are returned in the "out" parameter
        /// lists.
        /// </summary>
        /// <param name="oldSolid">The old solid.</param>
        /// <param name="plane">The plane.</param>
        /// <param name="positiveSideSolids">The solids that are on the positive side of the plane
        /// This means that are on the side that the normal faces.</param>
        /// <param name="negativeSideSolids">The solids on the negative side of the plane.</param>
        public static void OnFlat(TessellatedSolid ts, Flat plane,
            out List<TessellatedSolid> positiveSideSolids, out List<TessellatedSolid> negativeSideSolids)
        {
            var contactData = DefineContact(plane, ts);

            DivideUpContact(ts, contactData, plane);
            var loops =
                contactData.AllLoops.Where(loop => loop.All(
                            ce => !(ce.ContactEdge.Curvature == CurvatureType.Convex && ce is CoincidentEdgeContactElement))).ToList();
            var allNegativeStartingFaces =
               loops.SelectMany(loop => loop.Select(ce => ce.SplitFaceNegative)).ToList();
            var allPositiveStartingFaces =
                loops.SelectMany(loop => loop.Select(ce => ce.SplitFacePositive)).ToList();

            var negativeSideFaceList = FindAllSolidsWithTheseFaces(allNegativeStartingFaces, allPositiveStartingFaces);
            var positiveSideFaceList = FindAllSolidsWithTheseFaces(allPositiveStartingFaces, allNegativeStartingFaces);

            negativeSideSolids = convertFaceListsToSolids(ts, negativeSideFaceList, loops, false, plane);
            positiveSideSolids = convertFaceListsToSolids(ts, positiveSideFaceList, loops, true, plane);
        }
    public Map(List<Point> _lst)
    {
        this.Points = _lst;
        this.Points.Sort();
        
        Point last = null;
        _flat = new Flat();

        foreach(Point item in Points)
        {
            if(last != null)
            {
                if(item.Y == last.Y)
                {
                    if(_flat.Xmin == -1)
                    {
                        _flat.Xmin = last.X;
                        _flat.Y = last.Y;
                    }
                }
                else{
                    if(_flat.Xmin != -1 && _flat.Xmax == -1)
                    {
                        _flat.Xmax = last.X;
                    }
                }
            }
            last = item;
        }
    }
Example #43
0
 private static List<TessellatedSolid> convertFaceListsToSolids(TessellatedSolid ts, List<List<PolygonalFace>> facesLists,
     List<Loop> loops, Boolean onPositiveSide, Flat plane)
 {
     List<TessellatedSolid> solids = new List<TessellatedSolid>();
     foreach (var facesList in facesLists)
     {
         // get a list of the vertex indices from the original solid
         var vertIndices = facesList.SelectMany(f => f.Vertices.Select(v => v.IndexInList))
             .Distinct().OrderBy(index => index).ToArray();
         var numVertices = vertIndices.Count();
         // get the set of connected loops for this list of faces. it could be one or it could be all
         var connectedLoops = loops.Where(loop =>
             (onPositiveSide && loop.Any(ce => facesList.Contains(ce.SplitFacePositive)))
             || (!onPositiveSide && loop.Any(ce => facesList.Contains(ce.SplitFaceNegative))))
             .ToList();
         // put the vertices from vertIndices in subSolidVertices, except those that are on the loop.
         // you'll need to copy those.
         var subSolidVertices = new Vertex[numVertices];
         var indicesToCopy = connectedLoops.SelectMany(loop => loop.Select(ce => ce.StartVertex.IndexInList))
             .OrderBy(index => index).ToArray();
         var numIndicesToCopy = indicesToCopy.GetLength(0);
         var newEdgeVertices = new Vertex[connectedLoops.Count][];
         for (int i = 0; i < connectedLoops.Count; i++)
             newEdgeVertices[i] = new Vertex[connectedLoops[i].Count];
         var copyIndex = 0;
         for (int i = 0; i < numVertices; i++)
         {
             Vertex vertexCopy;
             if (copyIndex < numIndicesToCopy && vertIndices[i] == indicesToCopy[copyIndex])
             {
                 var oldVertex = ts.Vertices[vertIndices[i]];
                 vertexCopy = oldVertex.Copy();
                 for (int j = 0; j < connectedLoops.Count; j++)
                 {
                     var k = connectedLoops[j].FindIndex(ce => ce.StartVertex == oldVertex);
                     newEdgeVertices[j][k] = vertexCopy;
                 }
                 foreach (var face in oldVertex.Faces.Where(face => facesList.Contains(face)))
                 {
                     face.Vertices.Remove(oldVertex);
                     face.Vertices.Add(vertexCopy);
                     vertexCopy.Faces.Add(face);
                 }
                 while (copyIndex < numIndicesToCopy && vertIndices[i] >= indicesToCopy[copyIndex])
                     copyIndex++;
             }
             else vertexCopy = ts.Vertices[vertIndices[i]];
             vertexCopy.IndexInList = i;
             subSolidVertices[i] = vertexCopy;
         }
         solids.Add(new TessellatedSolid(facesList, subSolidVertices, newEdgeVertices, onPositiveSide ? plane.Normal.multiply(-1) : plane.Normal,
             connectedLoops.Select(loop => loop.IsPositive).ToArray()));
     }
     return solids;
 }
Example #44
0
        public void printSelectedFlat(Flat flat)
        {
            Console.Clear();
            Console.WriteLine(flat);
            Console.WriteLine("Views count:" + dataSource.getViewsCountForFlatId(flat.Id));
            dataSource.updateViewsCountForFlatId(flat.Id);
            Console.WriteLine("1. Save to file");
            Console.WriteLine("2. Return to menu\n");
            string selection = Console.ReadLine();

            if (selection == "1")
                FileWriter.saveToFile(flat);
            else if (selection == "2")
                return;
        }