Beispiel #1
0
        public static Vector GetOffset(
            UIElement element1,
            InterestPoint interestPoint1,
            UIElement element2,
            InterestPoint interestPoint2,
            Rect element2Bounds)
        {
            Point point = element1.TranslatePoint(GetPoint(element1, interestPoint1), element2);

            if (element2Bounds.IsEmpty)
            {
                return(point - GetPoint(element2, interestPoint2));
            }
            else
            {
                return(point - GetPoint(element2Bounds, interestPoint2));
            }
        }
 public OperationResult Delete(InterestPoint interestPoint)
 {
     try
     {
         _dao.Delete(interestPoint);
         return(new OperationResult()
         {
             Success = true
         });
     }
     catch (Exception e)
     {
         return(new OperationResult()
         {
             Success = true, Exception = e
         });
     }
 }
Beispiel #3
0
        // more info: https://www.movable-type.co.uk/scripts/latlong.html
        private int CalculateDistance(InterestPoint point, GeographicPoint currentLocation)
        {
            int earthRadiusMeters = (int)6371e3;

            float firstLatitudeRadians  = (float)(currentLocation.latitude * (Math.PI / 180));
            float secondLatitudeRadians = (float)(point.latitude * (Math.PI / 180));

            float deltaLatitude  = (float)((secondLatitudeRadians - firstLatitudeRadians) * (Math.PI / 180));
            float deltaLongitude = (float)((point.longitude - currentLocation.longitude) * (Math.PI / 180));

            float haversineA = (float)(Math.Sin(deltaLatitude / 2) * Math.Sin(deltaLatitude / 2) +
                                       Math.Cos(firstLatitudeRadians) * Math.Cos(secondLatitudeRadians) *
                                       Math.Sin(deltaLongitude / 2) * Math.Sin(deltaLongitude / 2));

            float haversineC = (float)(2 * Math.Atan2(Math.Sqrt(haversineA), Math.Sqrt(1 - haversineA)));

            return((int)(earthRadiusMeters * haversineC));
        }
Beispiel #4
0
        public void CreateGraph1()
        {
            CityMapGraph graph = new CityMapGraph();

            Assert.IsTrue(graph.NodeCount == 0);
            Assert.IsTrue(graph.EdgeCount == 0);

            InterestPoint p1 = new InterestPoint("P1");

            graph.AddNode(1, p1);
            graph.AddNode(2, new InterestPoint("P2"));
            graph.AddNode(3, new InterestPoint("P3"));
            graph.AddNode(4, new InterestPoint("P4"));
            graph.AddNode(5, new InterestPoint("P5"));
            graph.AddNode(6, new InterestPoint("P6"));
            Assert.IsTrue(graph.NodeCount == 6);

            graph.AddEdge(1, 2, new Route(100.0));
            graph.AddEdge(1, 4, new Route(200.0));
            graph.AddEdge(4, 2, new Route(300.0));
            graph.AddEdge(2, 5, new Route(400.0));
            graph.AddEdge(5, 4, new Route(500.0));
            graph.AddEdge(3, 5, new Route(600.0));
            graph.AddEdge(3, 6, new Route(700.0));
            graph.AddEdge(6, 6, new Route(0.0));
            Assert.ThrowsException <InvalidOperationException>(() => graph.AddEdge(17, 2, new Route(250.0)));
            Assert.ThrowsException <InvalidOperationException>(() => graph.AddEdge(1, 17, new Route(250.0)));
            Assert.ThrowsException <InvalidOperationException>(() => graph.AddEdge(1, 2, new Route(250.0)));
            Assert.IsTrue(graph.EdgeCount == 8);

            Assert.IsTrue(graph.ContainsNode(4));
            Assert.IsFalse(graph.ContainsNode(17));

            List <int> plist = new List <int>(graph.GetPredecessorNodes(5));

            Assert.IsTrue(plist.Count == 2);
            Assert.IsTrue(plist[0] == 2);
            Assert.IsTrue(plist[1] == 3);

            List <int> slist = new List <int>(graph.GetSuccessorNodes(5));

            Assert.IsTrue(slist.Count == 1);
            Assert.IsTrue(slist[0] == 4);
        }
Beispiel #5
0
    public void CreatePoint()
    {
        Ray        ray = new Ray(transform.position, transform.forward);
        RaycastHit hit;

        Physics.Raycast(ray, out hit, 100f, sphereLayer);

        GameObject p = Instantiate(obj, hit.point + hit.normal * scale, Quaternion.identity);

        p.transform.SetParent(list.transform);
        p.transform.LookAt(transform);

        InterestPoint ip = p.GetComponent <InterestPoint>();

        ip.position   = hit.point + hit.normal * scale;
        ip.stringText = text.text;
        current       = list.childCount - 1;
        ip.Setup();
    }
        public async Task <OperationResult> DeleteAsync(InterestPoint interestPoint)
        {
            try
            {
                await _dao.DeleteAsync(interestPoint);

                return(new OperationResult()
                {
                    Success = true
                });
            }
            catch (Exception e)
            {
                return(new OperationResult()
                {
                    Success = true, Exception = e
                });
            }
        }
Beispiel #7
0
 public void PickRandomInterrestPoint()
 {
     // If the submarine currently hacking a point.
     if (hackingTimer > 0)
     {
         nextInterestPoint.currentHackState = HackState.unhacked;
         nextInterestPoint.hackProgression  = 0f;
         soundAlreadyPlay  = false;
         hackingTimer      = 0;
         randomNumber      = Random.Range(0, interestPoints.Count);
         nextInterestPoint = interestPoints[randomNumber];
         movingToNextPoint = true;
     }
     else
     {
         randomNumber      = Random.Range(0, interestPoints.Count);
         nextInterestPoint = interestPoints[randomNumber];
         movingToNextPoint = true;
     }
 }
Beispiel #8
0
    public void OpenHotelViewPopUp(InterestPoint interestPoint)
    {
        if (_currentInterestPoint)
        {
            _currentInterestPoint.GetComponent <SpriteChanger>().ChangeSprite(0);
        }
        _currentInterestPoint = interestPoint;
        interestPoint.GetComponent <SpriteChanger>().ChangeSprite(1);
        _hotelViewPopUp.SetActive(true);
        string path = "";

        switch (interestPoint._type)
        {
        case InterestPoint.Type.UnderOneRoof:
            path = "Images/HotelView/Under One Roof/";
            break;

        case InterestPoint.Type.RoomsAndSuites:
            path = "Images/HotelView/Rooms And Suites/";
            break;

        case InterestPoint.Type.EventSpaces:
            path = "Images/HotelView/Event Spaces/";
            break;

        default:
            path = "Images/HotelView/Other/";
            break;
        }
        Debug.Log(path + interestPoint._imagePath);
        if (!string.IsNullOrEmpty(interestPoint._imagePath))
        {
            _hotelViewImage.sprite = Resources.Load <Sprite>(path + interestPoint._imagePath);
        }

        // Enable the button only if it is linked to an element in the galery/espace view
        _hotelViewImage.GetComponent <Button>().interactable = _nestedListUI._subElementsDictionnary.ContainsKey(_currentInterestPoint._roomId);

        _hotelViewTitle.text       = LanguageManager.Instance.GetText(interestPoint._titleKey);
        _hotelViewDescription.text = LanguageManager.Instance.GetText(interestPoint._descriptionKey);
    }
        public void TestCreateInterestPointAsync()
        {
            BoraNowSeeder.Seed();
            var ipbo = new InterestPointBusinessObject();
            var cbo  = new CompanyBusinessObject();
            var pbo  = new ProfileBusinessObject();

            var profile = new Profile("II", "AA");

            pbo.Create(profile);

            var company = new Company("kfc", "you", "9111222", "11111", profile.Id);

            cbo.Create(company);

            var interestPoint = new InterestPoint("a", "b", "c", "d", "e", "f", "g", true, true, company.Id);

            var resCreate = ipbo.CreateAsync(interestPoint).Result;
            var resGet    = ipbo.ReadAsync(interestPoint.Id).Result;

            Assert.IsTrue(resCreate.Success && resGet.Success && resGet.Result != null);
        }
        public IActionResult DeleteInterestPointById(int idInterestPoint)
        {
            InterestPoint interestPointDelete = Context.InterestPoint
                                                .Where(a => a.IdInterestPoint == idInterestPoint)
                                                .Include(a => a.VoteInterestPoint)
                                                .Include(a => a.Description)
                                                .ThenInclude(a => a.VoteDescription)
                                                .SingleOrDefault();

            if (interestPointDelete == null)
            {
                return(NotFound());
            }
            else
            {
                deleteVoteInterestPoint(interestPointDelete);
                deleteDescriptionInterestPoint(interestPointDelete);
                Context.InterestPoint.Remove(interestPointDelete);
                Context.SaveChanges();

                return(Ok());
            }
        }
        public void TestUpdateInterestpointCategoryAsync()
        {
            BoraNowSeeder.Seed();
            var ipcipbo = new InterestPointCategoryInterestPointBusinessObject();
            var resList = ipcipbo.ListAsync().Result;
            var item    = resList.Result.FirstOrDefault();


            var ipbo  = new InterestPointBusinessObject();
            var cipbo = new CategoryInterestPointBusinessObject();
            var pbo   = new ProfileBusinessObject();

            var profile = new Profile("II", "AA");

            pbo.Create(profile);

            var c       = new CompanyBusinessObject();
            var company = new Company("A", "B", "12345678", "1234567", profile.Id);

            c.Create(company);

            var interestPoint = new InterestPoint("a", "b", "c", "d", "e", "f", "g", true, true, company.Id);
            var category      = new CategoryInterestPoint("vegan");

            ipbo.Create(interestPoint);
            cipbo.Create(category);
            var interestPointCategoryInterestPoint = new InterestPointCategoryInterestPoint(interestPoint.Id, category.Id);

            item.InterestPointId = interestPointCategoryInterestPoint.InterestPointId;
            item.CategoryId      = interestPointCategoryInterestPoint.CategoryId;
            var resUpdate = ipcipbo.UpdateAsync(item).Result;

            resList = ipcipbo.ListAsync().Result;

            Assert.IsTrue(resUpdate.Success && resList.Success && resList.Result.First().InterestPointId == interestPoint.Id &&
                          resList.Result.First().CategoryId == category.Id);
        }
Beispiel #12
0
        private static Point GetPoint(Rect rect, InterestPoint interestPoint)
        {
            switch (interestPoint)
            {
            case InterestPoint.TopLeft:
                return(rect.TopLeft);

            case InterestPoint.TopRight:
                return(rect.TopRight);

            case InterestPoint.BottomLeft:
                return(rect.BottomLeft);

            case InterestPoint.BottomRight:
                return(rect.BottomRight);

            case InterestPoint.Center:
                return(new Point(rect.Left + rect.Width / 2,
                                 rect.Top + rect.Height / 2));

            default:
                throw new ArgumentOutOfRangeException(nameof(interestPoint));
            }
        }
Beispiel #13
0
        public void TestUpdateInterestPointNewsletterAsync()
        {
            BoraNowSeeder.Seed();
            var ipnbo   = new InterestPointNewsletterBusinessObject();
            var resList = ipnbo.List();
            var item    = resList.Result.FirstOrDefault();

            var nbo  = new NewsletterBusinessObject();
            var cbo  = new CompanyBusinessObject();
            var ipbo = new InterestPointBusinessObject();
            var pbo  = new ProfileBusinessObject();

            var profile = new Profile("II", "AA");

            pbo.Create(profile);

            var news          = new Newsletter("New in town, this doughnut place is nuts", "New in town");
            var company       = new Company("a", "b", "c", "123333", profile.Id);
            var interestPoint = new InterestPoint("a", "b", "c", "d", "e", "f", "g", true, true, company.Id);

            nbo.Create(news);
            cbo.Create(company);
            ipbo.Create(interestPoint);

            var newInterestPointNews = new InterestPointNewsletter(interestPoint.Id, news.Id);

            item.InterestPointId = newInterestPointNews.InterestPointId;
            item.NewsLetterId    = newInterestPointNews.NewsLetterId;

            var resUpdate = ipnbo.UpdateAsync(item).Result;

            resList = ipnbo.ListAsync().Result;

            Assert.IsTrue(resUpdate.Success && resList.Success &&
                          resList.Result.First().InterestPointId == newInterestPointNews.InterestPointId && resList.Result.First().NewsLetterId == newInterestPointNews.NewsLetterId);
        }
    protected ProceduralCameraStrategy BuildCameraStrategy(InterestPoint point, EmotionEvent e, float shotDuration)
    {
        List <KeyValuePair <ProceduralCameraStrategy, float> > strategies = new List <KeyValuePair <ProceduralCameraStrategy, float> >();

        float normalizedEnergy = ProceduralEngine.Instance.EmotionEngine.GetSmoothEnergy(e.timestamp) / ProceduralEngine.Instance.EmotionEngine.MaxEnergy;

        float overviewWeight = 0.2f;
        float dollyWeight    = 2f + (1f - normalizedEnergy);
        float orbitWeight    = 1f + normalizedEnergy;

        TrackChunkData structureChunk = ProceduralEngine.Instance.EmotionEngine.GetCurrentStructureData(e.timestamp);
        StructureType  structure      = ProceduralEngine.Instance.EmotionEngine.GetStructureAtTime(e.timestamp);

        switch (structure)
        {
        case StructureType.None:
            break;

        case StructureType.Sustain:
            break;

        case StructureType.Increasing:
            overviewWeight += (1f - structureChunk.GetIntensity(e.timestamp)) * 200f;
            break;

        case StructureType.Decreasing:
            overviewWeight += (1f - structureChunk.GetIntensity(e.timestamp)) * 200f;
            break;
        }

        strategies.Add(new KeyValuePair <ProceduralCameraStrategy, float>(new OverviewCameraStrategy(), overviewWeight));
        strategies.Add(new KeyValuePair <ProceduralCameraStrategy, float>(new DollyCameraStrategy(), dollyWeight));
        strategies.Add(new KeyValuePair <ProceduralCameraStrategy, float>(new OrbitCameraStrategy(), orbitWeight));

        return(ProceduralEngine.SelectRandomWeighted(strategies, x => x.Value).Key);
    }
 public async Task DeleteAsync(InterestPoint interestPoint)
 {
     interestPoint.IsDeleted = true;
     await UpdateAsync(interestPoint);
 }
 public void Delete(InterestPoint interestPoint)
 {
     interestPoint.IsDeleted = true;
     Update(interestPoint);
 }
 public async Task UpdateAsync(InterestPoint interestPoint)
 {
     _context.Entry(interestPoint).State = EntityState.Modified;
     await _context.SaveChangesAsync();
 }
 public void Update(InterestPoint interestPoint)
 {
     _context.Entry(interestPoint).State = EntityState.Modified;
     _context.SaveChanges();
 }
        public async Task CreateAsync(InterestPoint interestPoint)
        {
            await _context.InterestPoint.AddAsync(interestPoint);

            await _context.SaveChangesAsync();
        }
 public void Create(InterestPoint interestPoint)
 {
     _context.InterestPoint.Add(interestPoint);
     _context.SaveChanges();
 }
Beispiel #21
0
        public static void  Seed()
        {
            using var _ctx = new BoraNowContext();
            _ctx.Database.EnsureDeleted();
            _ctx.Database.EnsureCreated();
            var categoryOne     = new CategoryInterestPoint("VeganFood");
            var categoryTwo     = new CategoryInterestPoint("SeaFood");
            var categoryThree   = new CategoryInterestPoint("AsianFood");
            var quiz            = new Quiz("BoraNow quiz");
            var quizQuestion    = new QuizQuestion("What type of food are you looking for?", quiz.Id);
            var quizAnswerOne   = new QuizAnswer("Vegan", quizQuestion.Id);
            var quizAnswerTwo   = new QuizAnswer("Sea food", quizQuestion.Id);
            var quizAnswerThree = new QuizAnswer("Asian style", quizQuestion.Id);


            var countryOne = new Country("Angola");
            var countryTwo = new Country("Portugal");
            var profileOne = new Profile("blogueira vegana que adora viajar e conhecer novos locais", "mefamousstar.jpg");
            var profileTwo = new Profile("Business Man with a chain of restauarants across Lisbon", "merichstar.jpg");
            var company    = new Company("PearTree Company", "Marco Pereria", "919200000", "23453554", profileTwo.Id);
            var visitor    = new Visitor("Bruna", "Costa", DateTime.Now.AddYears(-24), "Female", profileOne.Id, countryOne.Id);


            var interestPoint         = new InterestPoint("PearTree Abc", "very chill place that offers lots off tradicional food", "abc street", "uhuhuu.jpg", "3 am", "5 pm", "fridays", true, true, company.Id);
            var interestPointCategory = new InterestPointCategoryInterestPoint(interestPoint.Id, categoryOne.Id);
            var result = new Result("questionário nº 1", DateTime.Now, quiz.Id, visitor.Id);
            var resultInterestPoint = new ResultInterestPoint(result.Id, interestPoint.Id);

            var newsletter = new Newsletter("New place in town that has many vegan options", "Brand New");
            var interestPointNewsletter = new InterestPointNewsletter(interestPoint.Id, newsletter.Id);

            var meteorology = new Meteorology(19, 27, 0, 1, 0, DateTime.Now.AddDays(1));
            var feedback    = new Feedback("very nice place, cousy vibes, really good food", 5, DateTime.Now.AddDays(-1), interestPoint.Id, visitor.Id);



            _ctx.Country.AddRange(countryOne);
            _ctx.Country.AddRange(countryTwo);
            _ctx.Profile.AddRange(profileOne);
            _ctx.Profile.AddRange(profileTwo);
            _ctx.Company.AddRange(company);
            _ctx.Visitor.AddRange(visitor);

            _ctx.Category.AddRange(categoryOne);
            _ctx.Category.AddRange(categoryTwo);
            _ctx.Category.AddRange(categoryThree);
            _ctx.Quiz.AddRange(quiz);
            _ctx.QuizQuestion.AddRange(quizQuestion);
            _ctx.QuizAnswer.AddRange(quizAnswerOne);
            _ctx.QuizAnswer.AddRange(quizAnswerTwo);
            _ctx.QuizAnswer.AddRange(quizAnswerThree);
            _ctx.InterestPoint.AddRange(interestPoint);
            _ctx.InterestPointCategory.AddRange(interestPointCategory);
            _ctx.Result.AddRange(result);
            _ctx.ResultInterestPoint.AddRange(resultInterestPoint);

            _ctx.Newsletter.AddRange(newsletter);
            _ctx.InterestPointNewsletter.AddRange(interestPointNewsletter);

            _ctx.Feedback.AddRange(feedback);
            _ctx.Meteorology.AddRange(meteorology);

            _ctx.SaveChanges();
        }
Beispiel #22
0
 private static Point GetPoint(UIElement element, InterestPoint interestPoint)
 {
     return(GetPoint(new Rect(element.RenderSize), interestPoint));
 }
    protected void SampleStrategies(List <KeyValuePair <ProceduralCameraStrategy, float> > strategies, InterestPoint point, EmotionEvent e, float shotDuration)
    {
        //Debug.Log("Sampling strategies on frame " + frames);

        int samples = 4;

        for (int i = 0; i < samples; ++i)
        {
            ProceduralCameraStrategy s = BuildCameraStrategy(point, e, shotDuration);

            // If the strategy failed finding a proposal, ignore it
            if (!s.Propose(e, point, shotDuration))
            {
                continue;
            }

            Matrix4x4 viewProj = s.GetViewProjection();

            float frustumWeightAccum           = 0f;
            List <InterestPoint> frustumPoints = GetInterestPointsOnFrustum(viewProj, out frustumWeightAccum);

            float weight = s.Evaluate(e, frustumPoints, frustumWeightAccum);
            strategies.Add(new KeyValuePair <ProceduralCameraStrategy, float>(s, weight));
        }

        //if (strategies.Count == 0)
        //    Debug.Log("Failed... ");
    }
Beispiel #24
0
        internal void CalculateTimes()
        {
            int      startPoiId              = Solver.Instance.WorkingConfiguration.StartingPointId;
            DateTime currNodeTotalTime       = Solver.Instance.WorkingConfiguration.ArrivalTime;
            DateTime currNodeArrivalTime     = currNodeTotalTime;
            TimeSpan currNodeWaitOpeningTime = default;

            BreadthFirstSearch(startPoiId,
                               (node, isVisited) => node.IsVisited = isVisited,
                               node => node.IsVisited,
                               node =>
            {
                node.ArrivalTime     = currNodeArrivalTime;
                node.TotalTime       = currNodeTotalTime;
                node.WaitOpeningTime = currNodeWaitOpeningTime;
            },
                               edge =>
            {
                double averageSpeedWalk = Solver.Instance.WorkingConfiguration.WalkingSpeed;
                TimeSpan timeWalk       = TimeSpan.FromSeconds(edge.Weight.Invoke() / averageSpeedWalk);

                InterestPoint edgeDestNode = edge.Entity.PointTo;
                TimeSpan visitTime         = default;
                if (edgeDestNode.TimeVisit.HasValue)
                {
                    visitTime = edgeDestNode.TimeVisit.Value;
                }

                currNodeArrivalTime = currNodeTotalTime.Add(timeWalk);
                currNodeTotalTime   = currNodeArrivalTime.Add(visitTime);

                if (Solver.Instance.ConstraintsToRelax.Contains(Utils.TimeWindowsConstraint))
                {
                    return;
                }

                Collection <TimeSpan> deltaOpeningTimes = new Collection <TimeSpan>();
                foreach (var time in edgeDestNode.OpeningTimes)
                {
                    if (!time.OpeningTime.HasValue || !time.ClosingTime.HasValue)
                    {
                        continue;
                    }

                    DateTime openingTime = time.OpeningTime.Value;
                    DateTime closingTime = time.ClosingTime.Value;
                    if (currNodeArrivalTime < openingTime)
                    {
                        TimeSpan currDeltaOpeningTime = openingTime.Subtract(currNodeArrivalTime);
                        deltaOpeningTimes.Add(currDeltaOpeningTime);
                    }
                    else if (currNodeArrivalTime > openingTime && currNodeArrivalTime < (closingTime - visitTime))
                    {
                        deltaOpeningTimes.Clear();
                        break;
                    }
                }
                if (deltaOpeningTimes.Count > 0)
                {
                    currNodeWaitOpeningTime = deltaOpeningTimes.Min();
                    currNodeTotalTime       = currNodeTotalTime.Add(currNodeWaitOpeningTime);
                }
                else
                {
                    currNodeWaitOpeningTime = default;
                }
            });
        }
 public void DeregisterInterestPoint(InterestPoint p)
 {
     this.interestPoints.Remove(p);
     this.grid.RemoveInterestPoint(p);
 }
Beispiel #26
0
        // To position the popup, we find the InterestPoints of the placement rectangle/point
        // in the screen coordinate space.  We also find the InterestPoints of the child in
        // the popup's space.  Then we attempt all valid combinations of matching InterestPoints
        // (based on PlacementMode) to find the position that best fits on the screen.
        // NOTE: any reference to the screen implies the monitor for full trust and
        //       the browser area for partial trust
        private void UpdatePosition()
        {
            if (_popupRoot == null)
            {
                return;
            }

            PlacementMode placement = PlacementInternal;

            // Get a list of the corners of the target/child in screen space
            Point[] placementTargetInterestPoints = GetPlacementTargetInterestPoints(placement);
            Point[] childInterestPoints           = GetChildInterestPoints(placement);

            // Find bounds of screen and child in screen space
            Rect targetBounds = GetBounds(placementTargetInterestPoints);
            Rect screenBounds;
            Rect childBounds = GetBounds(childInterestPoints);

            double childArea = childBounds.Width * childBounds.Height;

            Rect windowRect = _secHelper.GetWindowRect();

            _positionInfo ??= new PositionInfo();
            _positionInfo.X         = (int)windowRect.X;
            _positionInfo.Y         = (int)windowRect.Y;
            _positionInfo.ChildSize = windowRect.Size;

            // Rank possible positions
            int              bestIndex       = -1;
            Vector           bestTranslation = new Vector(_positionInfo.X, _positionInfo.Y);
            double           bestScore       = -1;
            PopupPrimaryAxis bestAxis        = PopupPrimaryAxis.None;

            int positions;

            CustomPopupPlacement[] customPlacements = null;

            // Find the number of possible positions
            if (placement == PlacementMode.Custom)
            {
                CustomPopupPlacementCallback customCallback = CustomPopupPlacementCallback;
                if (customCallback != null)
                {
                    customPlacements = customCallback(childBounds.Size, targetBounds.Size, new Point(HorizontalOffset, VerticalOffset));
                }
                positions = customPlacements == null ? 0 : customPlacements.Length;

                // Return if callback closed the popup
                if (!IsOpen)
                {
                    return;
                }
            }
            else
            {
                positions = GetNumberOfCombinations(placement);
            }

            // Try each position until the best one is found
            for (int i = 0; i < positions; i++)
            {
                Vector popupTranslation;

                PopupPrimaryAxis axis;

                // Get the ith Position to rank
                if (placement == PlacementMode.Custom)
                {
                    // The custom callback only calculates relative to 0,0
                    // so the placementTarget's top/left need to be re-applied.
                    popupTranslation = (Vector)placementTargetInterestPoints[(int)InterestPoint.TopLeft]
                                       + (Vector)customPlacements[i].Point; // vector from origin

                    axis = customPlacements[i].PrimaryAxis;
                }
                else
                {
                    PointCombination pointCombination = GetPointCombination(placement, i, out axis);

                    InterestPoint targetInterestPoint = pointCombination.TargetInterestPoint;
                    InterestPoint childInterestPoint  = pointCombination.ChildInterestPoint;

                    // Compute the vector from the screen origin to the top left corner of the popup
                    // that will cause the the two interest points to overlap
                    popupTranslation = placementTargetInterestPoints[(int)targetInterestPoint]
                                       - childInterestPoints[(int)childInterestPoint];
                }

                // Find percent of popup on screen by translating the popup bounds
                // and calculating the percent of the bounds that is on screen
                // Note: this score is based on the percent of the popup that is on screen
                //       not the percent of the child that is on screen.  For certain
                //       scenarios, this may produce in counter-intuitive results.
                //       If this is a problem, more complex scoring is needed
                Rect tranlsatedChildBounds = Rect.Offset(childBounds, popupTranslation);
                screenBounds = GetScreenBounds(targetBounds, placementTargetInterestPoints[(int)InterestPoint.TopLeft]);
                Rect currentIntersection = Rect.Intersect(screenBounds, tranlsatedChildBounds);

                // Calculate area of intersection
                double score = currentIntersection != Rect.Empty ? currentIntersection.Width * currentIntersection.Height : 0;

                // If current score is better than the best score so far, save the position info
                if (score - bestScore > Tolerance)
                {
                    bestIndex       = i;
                    bestTranslation = popupTranslation;
                    bestScore       = score;
                    bestAxis        = axis;

                    // Stop when we find a popup that is completely on screen
                    if (Math.Abs(score - childArea) < Tolerance)
                    {
                        break;
                    }
                }
            }

            // Check to see if the pop needs to be nudged onto the screen.
            // Popups are not nudged if their axes do not align with the screen axes

            // Use the size of the popupRoot in case it is clipping the popup content
            Matrix transformToDevice = _secHelper.GetTransformToDevice();

            childBounds = new Rect((Size)transformToDevice.Transform((Point)GetChildSize()));

            childBounds.Offset(bestTranslation);

            Vector childTranslation = (Vector)transformToDevice.Transform(GetChildTranslation());

            childBounds.Offset(childTranslation);

            screenBounds = GetScreenBounds(targetBounds, placementTargetInterestPoints[(int)InterestPoint.TopLeft]);
            Rect intersection = Rect.Intersect(screenBounds, childBounds);

            // See if width/height of intersection are less than child's
            if (Math.Abs(intersection.Width - childBounds.Width) > Tolerance ||
                Math.Abs(intersection.Height - childBounds.Height) > Tolerance)
            {
                // Nudge Horizontally
                Point topLeft  = placementTargetInterestPoints[(int)InterestPoint.TopLeft];
                Point topRight = placementTargetInterestPoints[(int)InterestPoint.TopRight];

                // Create a vector pointing from the top of the placement target to the bottom
                // to determine which direction the popup should be nudged in.
                // If the vector is zero (NaN's after normalization), nudge horizontally
                Vector horizontalAxis = topRight - topLeft;
                horizontalAxis.Normalize();

                // See if target's horizontal axis is aligned with screen
                // (For opaque windows always translate horizontally)
                if (!IsTransparent || double.IsNaN(horizontalAxis.Y) || Math.Abs(horizontalAxis.Y) < Tolerance)
                {
                    // Nudge horizontally
                    if (childBounds.Right > screenBounds.Right)
                    {
                        bestTranslation.X  = screenBounds.Right - childBounds.Width;
                        bestTranslation.X -= childTranslation.X;
                    }
                    else if (childBounds.Left < screenBounds.Left)
                    {
                        bestTranslation.X  = screenBounds.Left;
                        bestTranslation.X -= childTranslation.X;
                    }
                }
                else if (IsTransparent && Math.Abs(horizontalAxis.X) < Tolerance)
                {
                    // Nudge vertically, limit horizontally
                    if (childBounds.Bottom > screenBounds.Bottom)
                    {
                        bestTranslation.Y  = screenBounds.Bottom - childBounds.Height;
                        bestTranslation.Y -= childTranslation.Y;
                    }
                    else if (childBounds.Top < screenBounds.Top)
                    {
                        bestTranslation.Y  = screenBounds.Top;
                        bestTranslation.Y -= childTranslation.Y;
                    }
                }

                // Nudge Vertically
                Point bottomLeft = placementTargetInterestPoints[(int)InterestPoint.BottomLeft];

                // Create a vector pointing from the top of the placement target to the bottom
                // to determine which direction the popup should be nudged in
                // If the vector is zero (NaN's after normalization), nudge vertically
                Vector verticalAxis = topLeft - bottomLeft;
                verticalAxis.Normalize();

                // Axis is aligned with screen, nudge
                if (!IsTransparent || double.IsNaN(verticalAxis.X) || Math.Abs(verticalAxis.X) < Tolerance)
                {
                    if (childBounds.Bottom > screenBounds.Bottom)
                    {
                        bestTranslation.Y  = screenBounds.Bottom - childBounds.Height;
                        bestTranslation.Y -= childTranslation.Y;
                    }
                    else if (childBounds.Top < screenBounds.Top)
                    {
                        bestTranslation.Y  = screenBounds.Top;
                        bestTranslation.Y -= childTranslation.Y;
                    }
                }
                else if (IsTransparent && Math.Abs(verticalAxis.Y) < Tolerance)
                {
                    if (childBounds.Right > screenBounds.Right)
                    {
                        bestTranslation.X  = screenBounds.Right - childBounds.Width;
                        bestTranslation.X -= childTranslation.X;
                    }
                    else if (childBounds.Left < screenBounds.Left)
                    {
                        bestTranslation.X  = screenBounds.Left;
                        bestTranslation.X -= childTranslation.X;
                    }
                }
            }

            // Finally, take the best position and apply it to the popup
            int bestX = DoubleUtil.DoubleToInt(bestTranslation.X);
            int bestY = DoubleUtil.DoubleToInt(bestTranslation.Y);

            if (bestX != _positionInfo.X || bestY != _positionInfo.Y)
            {
                _positionInfo.X = bestX;
                _positionInfo.Y = bestY;
                _secHelper.SetPopupPos(true, bestX, bestY, false, 0, 0);
            }

            Size GetChildSize()
            {
                if (_popup.Child is { } child)
                {
                    return(child.RenderSize);
                }
                return(_popupRoot.RenderSize);
            }

            Point GetChildTranslation()
            {
                if (_popup.Child is { } child)
                {
                    return(child.TranslatePoint(new Point(), _popupRoot));
                }
                return(new Point());
            }
        }
        private static void InitializeRoutes(XmlDocument document, IEnumerable <InterestPoint> points)
        {
            string filename = _rootDirectory + Path.DirectorySeparatorChar.ToString() +
                              "cityscover-routes-" + points.Count() + ".xml";

            document.Load(filename);

            foreach (XmlNode node in document.GetElementsByTagName("Routes"))
            {
                foreach (XmlNode childNode in node.ChildNodes)
                {
                    if (childNode.NodeType != XmlNodeType.Element || !childNode.Name.Equals("Route"))
                    {
                        continue;
                    }

                    double        distance   = default;
                    InterestPoint pointFrom  = default;
                    InterestPoint pointTo    = default;
                    string        xmlRouteId = childNode.Attributes["id"].Value;
                    int           routeId    = ConvertAttributeId(xmlRouteId);

                    foreach (XmlNode nestedChild in childNode.ChildNodes)
                    {
                        string xmlPointId;
                        int    pointId;
                        switch (nestedChild.Name)
                        {
                        case "PointFrom":
                            xmlPointId = nestedChild.Attributes["id"].Value;
                            pointId    = ConvertAttributeId(xmlPointId);
                            pointFrom  = (from p in points where p.Id == pointId select p).FirstOrDefault();
                            break;

                        case "PointTo":
                            xmlPointId = nestedChild.Attributes["id"].Value;
                            pointId    = ConvertAttributeId(xmlPointId);
                            pointTo    = (from p in points where p.Id == pointId select p).FirstOrDefault();
                            break;

                        case "Distance":
                            var  strDistance = nestedChild.Attributes["value"].Value;
                            bool success     = double.TryParse(strDistance, out double fDistance);
                            if (!success)
                            {
                                throw new FormatException(nameof(distance));
                            }
                            distance = fDistance;
                            break;
                        }
                    }
                    _routes.Add(new Route(routeId, pointFrom, pointTo, distance));
                }
            }

            int ConvertAttributeId(string id)
            {
                bool success = int.TryParse(id, out int result);

                if (!success)
                {
                    throw new FormatException(nameof(id));
                }
                return(result);
            }
        }
Beispiel #28
0
 public PointCombination(InterestPoint targetInterestPoint, InterestPoint childInterestPoint)
 {
     TargetInterestPoint = targetInterestPoint;
     ChildInterestPoint  = childInterestPoint;
 }
Beispiel #29
0
 public PointCombination(InterestPoint targetInterestPoint, InterestPoint childInterestPoint)
 {
     TargetInterestPoint = targetInterestPoint;
     ChildInterestPoint = childInterestPoint;
 }
 internal InterestPointWorker(InterestPoint interestPoint)
 {
     Entity    = interestPoint;
     TotalTime = DateTime.Now.Date;
 }
Beispiel #31
0
 public override bool Propose(EmotionEvent e, InterestPoint p, float shotDuration)
 {
     speed = ProceduralEngine.Instance.EmotionEngine.GetSmoothEnergy(e.timestamp) * 4f / shotDuration;
     return(base.Propose(e, p, shotDuration));
 }