Example #1
0
        public Junction Filter(ILogger logger, Func<LogEntry, bool> func)
        {
            var junction = new Junction();
            junction.Add(logger, func);

            return junction;
        }
 private Junction(Junction aDescendant, Node aNode)
 {
     // Private constructor used by split. This junction will be a
     // ancestor of an existing junction.
     debugId = debugIdNext++;
     aNode.Ancestors.Remove(aDescendant);
     AddNode(aNode);
 }
Example #3
0
 void AssignVertices(Junction[] points)
 {
     for (int i = 0; i < points.Length; i++) {
         if (points[i].vertexIndex == -1){
             points[i].vertexIndex = vertices.Count;
             vertices.Add(points[i].position);
         }
     }
 }
Example #4
0
            public static Junction Parse(string input)
            {
                var res = new Junction();
                string[] coords = input.Split(' ');

                res.X = Double.Parse(coords[0], CultureInfo.InvariantCulture);
                res.Y = Double.Parse(coords[1], CultureInfo.InvariantCulture);
                res.Id = _idFactory++;
                res.Neighbours = new Dictionary<Junction, Street>();

                return res;
            }
Example #5
0
        private async Task Junction_LocationDefaults()
        {
            using (var odw = new OracleDatabaseWorker(tbOracleConnectionStringText))
            {
                List <string> boundaries = odw.GetDistinctDataColumn(junkTable, "CITY");
                List <string> types      = odw.GetListForDataColumn(@"select distinct FINALTYPE from junctions");

                List <string> statuses = odw.GetDistinctDataColumn(junkTable, "STATUS");
                statuses.Add(UNK);
                List <string> routes = odw.GetDistinctDataColumn(junkTable, "ROUTE");

                //unknjown junction
                using (var uow = new UnitOfWork(Tsdl))
                {
                    var gss  = GlobalSystemSettings.GetInstanceFromDatabase(uow);
                    var junc = new Junction(uow)
                    {
                        LocationName = UNK,
                        Status       = gss.DefaultLocationStatusActive
                    };
                    uow.CommitChanges();
                }
                //routes
                var del = new MyDelegate((lst) =>
                {
                    using (var uow = new UnitOfWork(Tsdl))
                    {
                        foreach (var str in lst
                                 .Where(s => s != ""))
                        {
                            if (!uow.Query <Route>().Any(x => x.Name == str))

                            {
                                Route cs = new Route(uow)
                                {
                                    Name = str
                                };
                                uow.CommitChanges();
                            }
                        }
                    }
                    return(true);
                });
                IAsyncResult routeres = del.BeginInvoke(routes, null, null);

                await Task.FromResult(routes);

                //boundaries
                del = new MyDelegate((lst) =>
                {
                    using (var uow = new UnitOfWork(Tsdl))
                    {
                        foreach (var str in lst
                                 .Where(s => s != ""))
                        {
                            if (!string.IsNullOrWhiteSpace(str) && !uow.Query <Boundary>().Any(x => x.Name == str))

                            {
                                Boundary cs = new Boundary(uow)
                                {
                                    Name = str
                                };
                                uow.CommitChanges();
                            }
                        }
                    }
                    return(true);
                });
                IAsyncResult boundres = del.BeginInvoke(boundaries, null, null);
                await Task.FromResult(boundres);

                //type
                del = new MyDelegate((lst) =>
                {
                    using (var uow = new UnitOfWork(Tsdl))
                    {
                        foreach (var str in lst
                                 .Where(s => s != ""))
                        {
                            if (!uow.Query <JunctionType>().Any(x => x.TypeName == str))

                            {
                                JunctionType cs = new JunctionType(uow)
                                {
                                    TypeName = str, TypeDescription = str
                                };
                                uow.CommitChanges();
                            }
                        }
                    }
                    return(true);
                });
                IAsyncResult typeres = del.BeginInvoke(types, null, null);
                await Task.FromResult(typeres);

                // status
                del = new MyDelegate((lst) =>
                {
                    using (var uow = new UnitOfWork(Tsdl))
                    {
                        foreach (var str in lst
                                 .Where(s => s != ""))
                        {
                            if (!uow.Query <LocationStatus>().Any(x => x.StatusName == str))

                            {
                                LocationStatus cs = new LocationStatus(uow)
                                {
                                    StatusName = str, StatusDescription = str
                                };
                                uow.CommitChanges();
                            }
                        }
                    }
                    return(true);
                });
                IAsyncResult statusres = del.BeginInvoke(statuses, null, null);
                await Task.FromResult(statusres);
            }//using odw
        }
Example #6
0
        /// <summary>
        /// Get the candidates of the i.
        /// get the candidate for the jucntion i.
        /// An Inter-path is a sequence of road intersections that connect the source to the destination, satisfying two key requirements, shorter routing distances, and higher connectivity. To meet these two requirements, we developed a heuristic function with two probability distributions, the connectivity distribution (denoted by ξ ̃_(i,j)) and the shortest distance distribution (denoted by〖 Φ ̃〗_(i,j)).
        /// </summary>
        /// <param name="_i"></param>
        /// <returns></returns>
        public CandidateJunction CandidateJunction(Junction _i, Junction _des)
        {
            string protocol = Settings.Default.RoutingProtocolString;
            List <CandidateJunction>    candidateJunctions = new List <Routing.CandidateJunction>();
            ShortestDistanceSelector    computer           = new ShortestDistanceSelector();
            SegmentConnectivitySelector connect            = new SegmentConnectivitySelector();

            // values:
            foreach (Junction _j in _i.Adjacentjunctions)
            {
                RoadSegment roadSegment = GetRoadSegment(_i, _j);
                if (roadSegment != null)
                {
                    switch (protocol)
                    {
                    case "VEFR":
                    {
                        CandidateJunction can = new CandidateJunction();
                        can.CurrentJunction             = _i;
                        can.NextJunction                = _j;
                        can.NextJunction                = _j; // CAN id.
                        can.DestinationJunction         = _des;
                        can.NextRoadSegment             = roadSegment;
                        can.RSSInput                    = new RSSInput(); // new one.
                        can.RSSInput.DensityCrisp       = Settings.Default.WeightConnectivity * Crisps.Density(roadSegment.SegmentLength, roadSegment.VehiclesCount, Settings.Default.CommunicationRange, roadSegment.LanesCount);
                        can.RSSInput.ValidDistanceCrisp = Settings.Default.WeightShortestDistance * Crisps.ValidDistance(_i.CenterLocation, _j.CenterLocation, _des.CenterLocation);
                        can.Priority                    = RSSRuleBase.Aggregate(can.RSSInput);
                        candidateJunctions.Add(can);
                        if (Settings.Default.SaveJunctionsCrisp)
                        {
                            ///
                        }
                        if (_des.JID == _j.JID)
                        {
                            return(can);
                        }
                    }
                    break;

                    case "HERO":
                    {
                        CandidateJunction can = new Routing.CandidateJunction();
                        can.CurrentJunction     = _i;
                        can.NextJunction        = _j;
                        can.NextJunction        = _j;  // CAN id.
                        can.DestinationJunction = _des;
                        can.NextRoadSegment     = roadSegment;

                        // values:
                        //1- shortes distance:
                        can.Perpendiculardistance = computer.Perpendiculardistance(_j.CenterLocation, _i.CenterLocation, _des.CenterLocation);

                        if (_des.JID == _j.JID)
                        {
                            can.AngleDotProdection = 1;
                        }
                        else
                        {
                            computer.AngleDotProdection(_i.CenterLocation, _j.CenterLocation, _des.CenterLocation);
                        }

                        can.Length = computer.Length(_i.CenterLocation, _j.CenterLocation);
                        //-2 connectivity.
                        can.Connectivity = connect.SegmentConnectivity(roadSegment.SegmentLength, roadSegment.VehiclesCount, roadSegment.VehicleInterArrivalMean, Settings.Default.CommunicationRange, roadSegment.LanesCount);


                        candidateJunctions.Add(can);
                    }
                    break;
                    }
                }
            }
            switch (protocol)
            {
            case "VEFR":
            {
                if (candidateJunctions.Count > 0)
                {
                    CandidateJunction max = candidateJunctions[0];
                    for (int j = 1; j < candidateJunctions.Count; j++)
                    {
                        if (candidateJunctions[j].Priority > max.Priority)
                        {
                            max = candidateJunctions[j];
                        }
                    }
                    return(max);
                }
            }
            break;

            case "HERO":
            {
                // get the max priority.
                if (candidateJunctions.Count > 0)
                {
                    CandidateJunction max = candidateJunctions[0];
                    for (int j = 1; j < candidateJunctions.Count; j++)
                    {
                        if (candidateJunctions[j].HeuristicFunction > max.HeuristicFunction)
                        {
                            max = candidateJunctions[j];
                        }
                    }

                    return(max);
                }
            }
            break;
            }
            return(null);
        }
Example #7
0
 public LaneInfo(int aConnectLane, Junction aJunction)
 {
     connectLane = aConnectLane;
     junctions = new List<Junction>(1) { aJunction };
 }
Example #8
0
            public void AddJunction(Junction junction, int handicap)
            {
                lock (Lock)
                {
                    Street street = CurrentJunction.Neighbours[junction];

                    CurrentDistance += street.AlreadyUsed ? 0 : street.Length;
                    CurrentTimer += street.Cost;
                    ReusedDistance += street.AlreadyUsed ? street.OriginalLength : 0;
                    street.AlreadyUsed = true;
                    street.Length = 0;
                    street.Bonus = 0;
                    street.Handicap += handicap;
                    TakenStreets.Add(street);
                    TakenJunctions.Add(junction);
                }
            }
        private void BuildExpressionsInternal(JObject where, Junction expressions, string tableAlias, ResolveFieldContext fieldContext, IDictionary <string, string> indexAliases)
        {
            foreach (var entry in where.Properties())
            {
                IPredicate expression = null;

                var values = entry.Name.Split('_', 2);

                // Gets the full path name without the comparison e.g. aliasPart.alias, not aliasPart.alias_contains.
                var property = values[0];

                // figure out table aliases for collapsed parts and ones with the part suffix removed by the dsl
                if (tableAlias == null || !tableAlias.EndsWith("Part", StringComparison.OrdinalIgnoreCase))
                {
                    var whereArgument = fieldContext?.FieldDefinition?.Arguments.FirstOrDefault(x => x.Name == "where");

                    if (whereArgument != null)
                    {
                        var whereInput = (WhereInputObjectGraphType)whereArgument.ResolvedType;

                        foreach (var field in whereInput.Fields.Where(x => x.GetMetadata <string>("PartName") != null))
                        {
                            var partName = field.GetMetadata <string>("PartName");
                            if ((tableAlias == null && field.GetMetadata <bool>("PartCollapsed") && field.Name.Equals(property, StringComparison.OrdinalIgnoreCase)) ||
                                (tableAlias != null && partName.ToFieldName().Equals(tableAlias, StringComparison.OrdinalIgnoreCase)))
                            {
                                tableAlias = indexAliases.TryGetValue(partName, out var indexTableAlias) ? indexTableAlias : tableAlias;
                                break;
                            }
                        }
                    }
                }

                if (tableAlias != null)
                {
                    property = $"{tableAlias}.{property}";
                }

                if (values.Length == 1)
                {
                    if (string.Equals(values[0], "or", StringComparison.OrdinalIgnoreCase))
                    {
                        expression = Expression.Disjunction();
                        BuildWhereExpressions(entry.Value, (Junction)expression, tableAlias, fieldContext, indexAliases);
                    }
                    else if (string.Equals(values[0], "and", StringComparison.OrdinalIgnoreCase))
                    {
                        expression = Expression.Conjunction();
                        BuildWhereExpressions(entry.Value, (Junction)expression, tableAlias, fieldContext, indexAliases);
                    }
                    else if (string.Equals(values[0], "not", StringComparison.OrdinalIgnoreCase))
                    {
                        expression = Expression.Conjunction();
                        BuildWhereExpressions(entry.Value, (Junction)expression, tableAlias, fieldContext, indexAliases);
                        expression = Expression.Not(expression);
                    }
                    else if (entry.HasValues && entry.Value.Type == JTokenType.Object)
                    {
                        // Loop through the part's properties, passing the name of the part as the table tableAlias.
                        // This tableAlias can then be used with the table alias to index mappings to join with the correct table.
                        BuildWhereExpressions(entry.Value, expressions, values[0], fieldContext, indexAliases);
                    }
                    else
                    {
                        var propertyValue = entry.Value.ToObject <object>();
                        expression = Expression.Equal(property, propertyValue);
                    }
                }
                else
                {
                    var value = entry.Value.ToObject <object>();

                    switch (values[1])
                    {
                    case "not": expression = Expression.Not(Expression.Equal(property, value)); break;

                    case "gt": expression = Expression.GreaterThan(property, value); break;

                    case "gte": expression = Expression.GreaterThanOrEqual(property, value); break;

                    case "lt": expression = Expression.LessThan(property, value); break;

                    case "lte": expression = Expression.LessThanOrEqual(property, value); break;

                    case "contains": expression = Expression.Like(property, (string)value, MatchOptions.Contains); break;

                    case "not_contains": expression = Expression.Not(Expression.Like(property, (string)value, MatchOptions.Contains)); break;

                    case "starts_with": expression = Expression.Like(property, (string)value, MatchOptions.StartsWith); break;

                    case "not_starts_with": expression = Expression.Not(Expression.Like(property, (string)value, MatchOptions.StartsWith)); break;

                    case "ends_with": expression = Expression.Like(property, (string)value, MatchOptions.EndsWith); break;

                    case "not_ends_with": expression = Expression.Not(Expression.Like(property, (string)value, MatchOptions.EndsWith)); break;

                    case "in": expression = Expression.In(property, entry.Value.ToObject <object[]>()); break;

                    case "not_in": expression = Expression.Not(Expression.In(property, entry.Value.ToObject <object[]>())); break;

                    default: expression = Expression.Equal(property, value); break;
                    }
                }

                if (expression != null)
                {
                    expressions.Add(expression);
                }
            }
        }
        static Junction Algorithm(Junction junc_traffic)
        {
            /* Setup your example here, code that should run once
             */
            int junc_north, junc_east, junc_south, junc_west;

            int[] volume = new int[4];
            var   ratio  = new Ratio(4);

            int[] effective = new int[4];
            int[] green = new int[4];
            int[] res = new int[3];
            int   cycle = 20;                      // One Complete Cycle = 20 Seconds
            int   max_flow_rate = 700;
            int   i = 0;
            int   x1, x2, y1, y2, temp1, temp2, temp3, temp4, temp5, temp6;

            // Initialize Variables
            //ratio.priority1[0] = 1;
            //ratio.priority1[1] = 2;
            //ratio.priority1[2] = 3;
            //ratio.priority1[3] = 4;
            //ratio.flow_value[0] = 0;
            //ratio.flow_value[1] = 0;
            //ratio.flow_value[2] = 0;
            //ratio.flow_value[3] = 0;
            //ratio.percentage_value[0] = 0;
            //ratio.percentage_value[1] = 0;
            //ratio.percentage_value[2] = 0;
            //ratio.percentage_value[4] = 0;

            junc_north = Convert.ToInt32(junc_traffic.north_traffic);
            junc_east  = Convert.ToInt32(junc_traffic.east_traffic);
            junc_south = Convert.ToInt32(junc_traffic.south_traffic);
            junc_west  = Convert.ToInt32(junc_traffic.west_traffic);

            /* Code in this loop will run repeatedly
             */
            volume[0] = current_traffic_volume(junc_north, cycle);
            volume[1] = current_traffic_volume(junc_east, cycle);
            volume[2] = current_traffic_volume(junc_south, cycle);
            volume[3] = current_traffic_volume(junc_west, cycle);

            ratio.flow_value[0] = flow_ratio(volume[0], max_flow_rate);
            ratio.flow_value[1] = flow_ratio(volume[1], max_flow_rate);
            ratio.flow_value[2] = flow_ratio(volume[2], max_flow_rate);
            ratio.flow_value[3] = flow_ratio(volume[3], max_flow_rate);

            ratio.percentage_value[0] = (ratio.flow_value[0] / (ratio.flow_value[0] + ratio.flow_value[1] + ratio.flow_value[2] + ratio.flow_value[3]));
            ratio.percentage_value[1] = (ratio.flow_value[1] / (ratio.flow_value[0] + ratio.flow_value[1] + ratio.flow_value[2] + ratio.flow_value[3]));
            ratio.percentage_value[2] = (ratio.flow_value[2] / (ratio.flow_value[0] + ratio.flow_value[1] + ratio.flow_value[2] + ratio.flow_value[3]));
            ratio.percentage_value[3] = (ratio.flow_value[3] / (ratio.flow_value[0] + ratio.flow_value[1] + ratio.flow_value[2] + ratio.flow_value[3]));

            ratio = compare(ratio);     // Find Max Ratio

            effective[0] = effective_green_time(ratio.percentage_value[0], cycle);

            green[0] = phase_green_time(effective[0]);

            res[0] = remaining_green_time(cycle, green[0]);

            effective[1] = remaining_effective_green_time(res[0], ratio.percentage_value[1], ratio.percentage_value[0], 0, ratio.percentage_value);

            green[1] = phase_green_time(effective[1]);

            res[1] = remaining_green_time(res[0], green[1]);

            effective[2] = remaining_effective_green_time(res[1], ratio.percentage_value[2], ratio.percentage_value[1], 1, ratio.percentage_value);

            green[2] = phase_green_time(effective[2]);

            res[2] = remaining_green_time(res[1], green[2]);

            effective[3] = remaining_effective_green_time(res[2], ratio.percentage_value[3], ratio.percentage_value[2], 2, ratio.percentage_value);

            green[3] = phase_green_time(effective[3]);

            for (x1 = 0; x1 < 3; x1++)
            {
                for (y1 = 0; y1 < 3; y1++)
                {
                    if (green[y1] < green[y1 + 1])
                    {
                        temp1     = green[y1];
                        green[y1] = green[y1 + 1];
                        green[y1] = temp1;

                        temp2 = ratio.priority1[y1];
                        ratio.priority1[y1]     = ratio.priority1[y1 + 1];
                        ratio.priority1[y1 + 1] = temp2;

                        temp3 = ratio.priority2[y1];
                        ratio.priority2[y1]     = ratio.priority2[y1 + 1];
                        ratio.priority2[y1 + 1] = temp3;
                    }
                }
            }

            for (x2 = 0; x2 < 3; x2++)
            {
                for (y2 = 0; y2 < 3; y2++)
                {
                    if (ratio.priority1[y2] > ratio.priority1[y2 + 1])
                    {
                        temp4         = green[y2];
                        green[y2]     = green[y2 + 1];
                        green[y2 + 1] = temp4;

                        temp5 = ratio.priority1[y2];
                        ratio.priority1[y2]     = ratio.priority1[y2 + 1];
                        ratio.priority1[y2 + 1] = temp5;

                        temp6 = ratio.priority2[y2];
                        ratio.priority2[y2]     = ratio.priority2[y2 + 1];
                        ratio.priority2[y2 + 1] = temp6;
                    }
                }
            }

            junc_traffic.north_priority = ratio.priority2[0];
            junc_traffic.east_priority  = ratio.priority2[1];
            junc_traffic.south_priority = ratio.priority2[2];
            junc_traffic.west_priority  = ratio.priority2[3];

            for (i = 0; i < 4; i++)
            {
                if (ratio.priority1[i] == 1)
                {
                    junc_traffic.north_green_time = green[0];
                }

                else if (ratio.priority1[i] == 2)
                {
                    junc_traffic.east_green_time = green[1];
                }

                else if (ratio.priority1[i] == 3)
                {
                    junc_traffic.south_green_time = green[2];
                }

                else if (ratio.priority1[i] == 4)
                {
                    junc_traffic.west_green_time = green[3];
                }
            }

            return(junc_traffic);
        }
                private static Chain ConvertStandaloneJunctionToChain(Junction junction)
                {
                    #region asserts

#if DEBUG
                    if (junction.Chains.Count != 2)
                    {
                        throw new ArgumentException("This function expects a junction containing exactly two chains");
                    }
#endif

                    #endregion

                    return new Chain(GetPolyFromTouchingChains(junction.Chains[0], junction.Chains[1]).ToArray(), true);
                }
Example #12
0
    void CreateTriangles(Junction a, Junction b, Junction c)
    {
        triangles.Add (a.vertexIndex);
        triangles.Add (b.vertexIndex);
        triangles.Add (c.vertexIndex);

        Triangle triangle = new Triangle (a.vertexIndex, b.vertexIndex, c.vertexIndex);
        AddTriangleToDictionary (triangle.vertexIndexA, triangle);
        AddTriangleToDictionary (triangle.vertexIndexB, triangle);
        AddTriangleToDictionary (triangle.vertexIndexC, triangle);
    }
                private static Point[] ReduceJunctions_Multiple_ReduceSprtOthersChain(Junction[] chainOfJuncs, int index, Point[] points)
                {
                    List<Point> retVal = new List<Point>();

                    for (int outer = index + 1; outer < chainOfJuncs.Length; outer++)
                    {
                        int[] chain = chainOfJuncs[outer].Chains[0].Points;     // it doesn't matter which chain is used
                        for (int inner = 0; inner < chain.Length - 1; inner++)      // not using the last point in each chain, because the individual chains duplicate the endpoints
                        {
                            retVal.Add(points[chain[inner]]);
                        }
                    }

                    for (int outer = 0; outer < index; outer++)
                    {
                        int[] chain = chainOfJuncs[outer].Chains[0].Points;
                        for (int inner = 0; inner < chain.Length - 1; inner++)
                        {
                            retVal.Add(points[chain[inner]]);
                        }
                    }

                    return retVal.ToArray();
                }
                private static Chain ReduceJunctions_Multiple_FinalChain(Junction[] loopOfJunctions)
                {
                    List<int> points = new List<int>();

                    foreach (Junction junc in loopOfJunctions)
                    {
                        #region asserts
#if DEBUG
                        if (junc.Chains.Count != 1)
                        {
                            throw new ArgumentException("This method expects the junctions passed in to have exactly one chain each");
                        }
#endif
                        #endregion

                        for (int cntr = 0; cntr < junc.Chains[0].Points.Length - 1; cntr++)     // not using the last point in each chain, because it is the same as the first point in the next chain
                        {
                            points.Add(junc.Chains[0].Points[cntr]);
                        }
                    }

                    return new Chain(points.ToArray(), true);
                }
                private static void ReduceJunctions_Multiple_Reduce(Junction[] chainOfJuncs, int index, Point[] points)
                {
                    // Create a point chain with all junctions except index
                    Point[] chainOthers = ReduceJunctions_Multiple_ReduceSprtOthersChain(chainOfJuncs, index, points);

                    int winningChain = -1;

                    // Try each chain to find the one that isn't inside the others
                    for (int outer = 0; outer < chainOfJuncs[index].Chains.Count; outer++)
                    {
                        Point[] chainComplete = ReduceJunctions_Multiple_ReduceSprtCompleteChain(chainOthers, chainOfJuncs[index].Chains[outer].Points, points);

                        // See if any of the other chains in this junction are inside the loop
                        bool hasOutside = false;
                        for (int inner = 0; inner < chainOfJuncs[index].Chains.Count; inner++)
                        {
                            if (inner == outer)
                            {
                                continue;
                            }

                            Point testPoint = GetPointInsideChain(chainOfJuncs[index].Chains[inner], points);
                            if (!Math2D.IsInsidePolygon(chainComplete, testPoint, null))
                            {
                                hasOutside = true;
                                break;
                            }
                        }

                        if (!hasOutside)
                        {
                            // Probably the winner (I think the junction only has two chains anyway by the time this method is called)
                            winningChain = outer;
                            break;
                        }
                    }

                    // Only keep the winning chain
                    if (winningChain < 0)
                    {
                        // If this becomes a problem, they are probably sitting on top of each other
                        throw new ApplicationException("Didn't find outer chain");
                    }

                    Chain winner = chainOfJuncs[index].Chains[winningChain];
                    chainOfJuncs[index].Chains.Clear();
                    chainOfJuncs[index].Chains.Add(winner);
                }
                private static Junction[] ReduceJunctions_Multiple_GetChain(int[] points, List<Junction> junctions)
                {
                    Junction[] retVal = new Junction[points.Length];

                    for (int cntr = 0; cntr < points.Length - 1; cntr++)
                    {
                        retVal[cntr] = ReduceJunctions_Multiple_GetChainSprtFind(points[cntr], points[cntr + 1], junctions);
                    }

                    retVal[points.Length - 1] = ReduceJunctions_Multiple_GetChainSprtFind(points[points.Length - 1], points[0], junctions);

                    return retVal;
                }
                private static void ReduceJunction_Single(Junction junction, Point[] points)
                {
                    if (junction.Chains.Count <= 2)
                    {
                        // This method is only meant for 3 or more chains (reducing down to two)
                        return;
                    }

                    int indexLeft = 0;
                    int indexRight = 1;
                    Point[] currentPoly = GetPolyFromTouchingChains(junction.Chains[indexLeft], junction.Chains[indexRight]).
                        Select(o => points[o]).
                        ToArray();

                    for (int cntr = 2; cntr < junction.Chains.Count; cntr++)
                    {
                        // Compare a point in this chain with the existing polygon
                        if (Math2D.IsInsidePolygon(currentPoly, GetPointInsideChain(junction.Chains[cntr], points), false))
                        {
                            continue;
                        }

                        // Try keeping left (swap right)
                        if (ReduceJunction_Single_Try(ref currentPoly, indexLeft, ref indexRight, cntr, junction.Chains, points))
                        {
                            continue;
                        }

                        // Try keeping right (swap left)
                        if (ReduceJunction_Single_Try(ref currentPoly, indexRight, ref indexLeft, cntr, junction.Chains, points))
                        {
                            continue;
                        }

                        throw new ApplicationException("Couldn't find a chain to remove");
                    }

                    #region Remove inside chains

                    Chain leftChain = junction.Chains[indexLeft];
                    Chain rightChain = junction.Chains[indexRight];

                    junction.Chains.Clear();

                    junction.Chains.Add(leftChain);
                    junction.Chains.Add(rightChain);

                    #endregion
                }
            /// <summary>
            /// Advance the lane to the next element
            /// </summary>
            /// <param name="curLane">Index of the lane to advance</param>
            /// <returns>True if there will still be nodes in this lane</returns>
            private int AdvanceLane(int curLane)
            {
                LaneJunctionDetail lane = _laneNodes[curLane];
                int minLane             = curLane;

                // Advance the lane
                lane.Next();

                // See if we can pull up ancestors
                if (lane.Count == 0 && lane.Junction == null)
                {
                    // Handle a single node branch.
                    _currentRow.Collapse(curLane);
                    _laneNodes.RemoveAt(curLane);
                }
                else if (lane.Count == 0)
                {
                    Node node = lane.Junction.Oldest;
                    foreach (Junction parent in node.Ancestors)
                    {
                        if (parent.CurrentState != Junction.State.Unprocessed)
                        {
                            // This item is already in the lane list, no action needed
                            continue;
                        }

                        var addedLane = new LaneJunctionDetail(parent);
                        addedLane.Next();
                        int addedLaneLane = int.MaxValue;

                        // Check to see if this junction already points to one of the
                        // existing lanes. If so, we'll just add the lane line and not
                        // add it to the laneNodes.
                        if (addedLane.Count == 1)
                        {
                            for (int i = 0; i < _laneNodes.Count; i++)
                            {
                                if (_laneNodes[i].Current == addedLane.Current)
                                {
                                    // We still advance the lane so it gets
                                    // marked as processed.
                                    addedLane.Next();

                                    addedLaneLane = i;
                                    break;
                                }
                            }
                        }

                        // Add to the lane nodes
                        if (addedLaneLane == int.MaxValue)
                        {
                            if (lane.Count == 0)
                            {
                                lane = addedLane;
                                _laneNodes[curLane] = lane;
                                addedLaneLane       = curLane;
                            }
                            else
                            {
                                addedLaneLane = curLane + 1;
                                _laneNodes.Insert(addedLaneLane, addedLane);
                                _currentRow.Expand(addedLaneLane);
                            }
                        }

                        _currentRow.Add(curLane, new Graph.LaneInfo(addedLaneLane, parent));
                    }

                    // If the lane count after processing is still 0
                    // this is a root node of the graph
                    if (lane.Count == 0)
                    {
                        _currentRow.Collapse(curLane);
                        _laneNodes.RemoveAt(curLane);
                    }
                }
                else if (lane.Count == 1)
                {
                    // If any other lanes have this node on top, merge them together
                    for (int i = 0; i < _laneNodes.Count; i++)
                    {
                        if (i == curLane || curLane >= _laneNodes.Count)
                        {
                            continue;
                        }

                        if (_laneNodes[i].Current == _laneNodes[curLane].Current)
                        {
                            int      left;
                            int      right;
                            Junction junction = _laneNodes[curLane].Junction;
                            if (i > curLane)
                            {
                                left  = curLane;
                                right = i;
                            }
                            else
                            {
                                left    = i;
                                right   = curLane;
                                curLane = i;
                            }

                            _currentRow.Replace(right, left);
                            _currentRow.Collapse(right);
                            _laneNodes[right].Clear();
                            _laneNodes.RemoveAt(right);

                            _currentRow.Add(_currentRow.NodeLane, new Graph.LaneInfo(left, junction));
                            minLane = Math.Min(minLane, left);
                        }
                    }

                    // If the current lane is still active, add it. It might not be active
                    // if it got merged above.
                    if (!lane.IsClear)
                    {
                        _currentRow.Add(_currentRow.NodeLane, new Graph.LaneInfo(curLane, lane.Junction));
                    }
                }
                else
                {
                    // lane.Count > 1
                    _currentRow.Add(_currentRow.NodeLane, new Graph.LaneInfo(curLane, lane.Junction));
                }

                return(curLane);
            }
Example #19
0
 public ControlJunction(Vector3 _pos, bool _active, float squareSize)
     : base(_pos)
 {
     active = _active;
     above = new Junction(position + Vector3.forward * squareSize/2f);
     right = new Junction(position + Vector3.right * squareSize/2f);
 }
 public void Clear()
 {
     _node    = null;
     Junction = null;
     _index   = 0;
 }
Example #21
0
        public Square(ControlJunction _topLeft, ControlJunction _topRight, ControlJunction _bottomRight, ControlJunction _bottomLeft)
        {
            topLeft = _topLeft;
            topRight = _topRight;
            bottomRight = _bottomRight;
            bottomLeft = _bottomLeft;

            centreTop = topLeft.right;
            centreRight = bottomRight.above;
            centreBottom = bottomLeft.right;
            centreLeft = bottomLeft.above;

            if (topLeft.active)
                configuration += 8;
            if (topRight.active)
                configuration += 4;
            if (bottomRight.active)
                configuration += 2;
            if (bottomLeft.active)
                configuration += 1;
        }
Example #22
0
        Junction Algorithm(Junction junc_traffic)
        {
            /* Setup your example here, code that should run once
             */
            int   junc_north, junc_east, junc_south, junc_west;
            int   volume1, volume2, volume3, volume4;
            float ratio1, ratio2, ratio3, ratio4;
            int   effective1, effective2, effective3, effective4;
            int   green1, green2, green3, green4;
            int   res1, res2, res3;
            int   cycle         = 300;              // One Complete Cycle = 300 Seconds
            int   max_flow_rate = 50;
            int   i             = 0;

            Program j3 = new Program();

            junc_north = Convert.ToInt32(junc_traffic.north_traffic);
            junc_east  = Convert.ToInt32(junc_traffic.east_traffic);
            junc_south = Convert.ToInt32(junc_traffic.south_traffic);
            junc_west  = Convert.ToInt32(junc_traffic.west_traffic);

            /* Code in this loop will run repeatedly
             */
            volume1 = current_traffic_volume(junc_north, cycle);
            volume2 = current_traffic_volume(junc_east, cycle);
            volume3 = current_traffic_volume(junc_south, cycle);
            volume4 = current_traffic_volume(junc_west, cycle);

            ratio1 = flow_ratio(volume1, max_flow_rate);
            ratio2 = flow_ratio(volume2, max_flow_rate);
            ratio3 = flow_ratio(volume3, max_flow_rate);
            ratio4 = flow_ratio(volume4, max_flow_rate);

            ratio[0] = compare(ratio1, ratio2, ratio3, ratio4);     // Max Ratio

            effective1 = effective_green_time(ratio[0], cycle);

            green1 = phase_green_time(effective1);

            res1 = remaining_green_time(effective1, green1);

            effective2 = remaining_effective_green_time(res1, ratio[1], ratio[0], 1);

            green2 = phase_green_time(effective2);

            res2 = remaining_green_time(effective2, green2);

            effective3 = remaining_effective_green_time(res2, ratio[2], ratio[1], 2);

            green3 = phase_green_time(effective3);

            res3 = remaining_green_time(effective3, green3);

            effective4 = remaining_effective_green_time(res3, ratio[3], ratio[2], 3);

            green4 = phase_green_time(effective4);

            for (i = 0; i < 3; i++)
            {
                if (j3.ratio_priority[i] == 1)
                {
                    junc_traffic.north_green_time = green1;
                }

                else if (j3.ratio_priority[i] == 2)
                {
                    junc_traffic.east_green_time = green2;
                }

                else if (j3.ratio_priority[i] == 3)
                {
                    junc_traffic.south_green_time = green3;
                }

                else if (j3.ratio_priority[i] == 4)
                {
                    junc_traffic.west_green_time = green4;
                }
            }

            return(junc_traffic);
        }
Example #23
0
        /// <summary>
        /// Filters the query.
        /// </summary>
        /// <param name="query">The query.</param>
        /// <param name="request">The request.</param>
        /// <param name="hasnotSeoDisjunction">The has seo disjunction.</param>
        /// <returns>
        /// Query, filtered with specified filter parameters
        /// </returns>
        protected override NHibernate.IQueryOver <PagesView, PagesView> FilterQuery(NHibernate.IQueryOver <PagesView, PagesView> query,
                                                                                    PagesFilter request, Junction hasnotSeoDisjunction)
        {
            query = base.FilterQuery(query, request, hasnotSeoDisjunction);

            var filter = request as UntranslatedPagesFilter;

            if (filter != null)
            {
                PageProperties alias = null;

                // Exclude from results
                if (filter.ExistingItemsArray.Any())
                {
                    query = query.Where(Restrictions.Not(Restrictions.In(Projections.Property(() => alias.Id), filter.ExistingItemsArray)));
                }

                // Excluded language id
                if (filter.ExcludedLanguageId.HasValue)
                {
                    var languageProxy = repository.AsProxy <Language>(filter.ExcludedLanguageId.Value);
                    query = query.Where(() => (alias.Language != languageProxy || alias.Language == null));
                }

                if (filter.ExcplicitlyIncludedPagesArray.Any())
                {
                    // Include to results explicitly included or untranslated
                    query = query.Where(Restrictions.Disjunction()
                                        .Add(Restrictions.In(Projections.Property(() => alias.Id), filter.ExcplicitlyIncludedPagesArray))
                                        .Add(Restrictions.IsNull(Projections.Property(() => alias.LanguageGroupIdentifier))));
                }
                else
                {
                    // Only untranslated
                    query = query.Where(Restrictions.IsNull(Projections.Property(() => alias.LanguageGroupIdentifier)));
                }
            }

            return(query);
        }
Example #24
0
        public static FormExtractionResult FindBoxes(int[] imgData, int row, int col, FormExtractionOptions options)
        {
            // Debug image.
            int[,] debugImg = null;
            if (options.GenerateDebugImage)
            {
                debugImg = new int[row, col];
                for (int y = 0; y < row; y++)
                {
                    for (int x = 0; x < col; x++)
                    {
                        debugImg[y, x] = 0;
                    }
                }
            }

            // We are seaching for pattern!
            // We look for junctions.
            // This will help us make a decision.
            // Junction types: T, L, +.
            // Junctions allow us to find boxes contours.

            int width  = options.JunctionWidth;
            int height = options.JunctionHeight;

            // Cache per line speed up the creation of various cache.
            Dictionary <int, List <Junction> > cacheListJunctionPerLine = new Dictionary <int, List <Junction> >();
            List <Junction> listJunction = new List <Junction>();

            // If there is too much junction near each other, maybe it's just a black spot.
            // We must ignore it to prevent wasting CPU and spend too much time.
            int maxProximity = 10;

            for (int y = 1; y < row - 1; y++)
            {
                List <Junction> listJunctionX    = null;
                int             proximityCounter = 0;

                for (int x = 1; x < col - 1; x++)
                {
                    Junction?junction = GetJunction(imgData, row, col, height, width, y, x);
                    if (junction != null)
                    {
                        if (listJunctionX == null)
                        {
                            listJunctionX = new List <Junction>();
                        }
                        listJunctionX.Add(junction.Value);
                        proximityCounter++;
                    }
                    else
                    {
                        if (listJunctionX != null)
                        {
                            if (proximityCounter < maxProximity)
                            {
                                if (!cacheListJunctionPerLine.ContainsKey(y))
                                {
                                    cacheListJunctionPerLine.Add(y, new List <Junction>());
                                }
                                cacheListJunctionPerLine[y].AddRange(listJunctionX);
                                listJunction.AddRange(listJunctionX);
                                listJunctionX.Clear();
                            }
                            else
                            {
                                listJunctionX.Clear();
                            }
                        }
                        proximityCounter = 0;
                    }
                }

                if (proximityCounter < maxProximity && listJunctionX != null)
                {
                    if (!cacheListJunctionPerLine.ContainsKey(y))
                    {
                        cacheListJunctionPerLine.Add(y, new List <Junction>());
                    }
                    cacheListJunctionPerLine[y].AddRange(listJunctionX);
                    listJunction.AddRange(listJunctionX);
                }
            }

            // Console.WriteLine("Junction.count: " + listJunction.Count);

            if (listJunction.Count >= options.MaxJunctions)
            {
                // Something wrong happen. Too much junction for now.
                // If we continue, we would spend too much time processing the image.
                // Let's suppose we don't know.
                return(new FormExtractionResult
                {
                    // Too many junctions. The image seem too complex. You may want to increase MaxJunctions
                    ReturnCode = 10
                });
            }

            // Let's check the list of points.

            // Search near same line.

            // Prepare cache to speedup searching algo.
            int minX = 10;
            int maxX = 70;
            Dictionary <int, Junction[]> cacheNearJunction = new Dictionary <int, Junction[]>();
            Dictionary <int, Junction[]> cachePossibleNextJunctionRight = new Dictionary <int, Junction[]>();
            Dictionary <int, Junction[]> cachePossibleNextJunctionLeft  = new Dictionary <int, Junction[]>();

            foreach (var junction in listJunction)
            {
                var listJunctionNearJunction = new List <Junction>();

                for (int deltaY = -3; deltaY <= 3; deltaY++)
                {
                    if (cacheListJunctionPerLine.ContainsKey(junction.Y - deltaY))
                    {
                        listJunctionNearJunction.AddRange(cacheListJunctionPerLine[junction.Y - deltaY]);
                    }
                }

                var list = listJunctionNearJunction
                           .Where(m =>
                                  Math.Abs(m.X - junction.X) <= maxX
                                  )
                           .ToArray();

                var id = junction.X | junction.Y << 16;

                cacheNearJunction.Add(id, list);

                var possibleNextJunction = list
                                           .Where(m =>
                                                  Math.Abs(m.X - junction.X) >= minX
                                                  )
                                           .ToList();

                cachePossibleNextJunctionLeft.Add(id, possibleNextJunction.Where(m => m.X < junction.X).ToArray());
                cachePossibleNextJunctionRight.Add(id, possibleNextJunction.Where(m => m.X > junction.X).ToArray());
            }

            int numSol = 0;

            List <Line> possibleSol = new List <Line>();


            // We use a dictionary here because we need a fast way to remove entry.
            // We reduce computation and we also merge solutions.
            var elements = listJunction.OrderBy(m => m.Y).ToDictionary(m => m.X | m.Y << 16, m => m);

            int skipSol = 0;

            while (elements.Any())
            {
                var start = elements.First().Value;
                elements.Remove(start.X | start.Y << 16);

                Dictionary <int, List <int> > usedJunctionsForGapX = new Dictionary <int, List <int> >();
                List <Line> listSolutions   = new List <Line>();
                var         junctionsForGap = cacheNearJunction[start.X | start.Y << 16];

                for (int iGap = 0; iGap < junctionsForGap.Length; iGap++)
                {
                    var gap = junctionsForGap[iGap];

                    // Useless because it's already done with: cacheNearJunction.

                    /*
                     * var gapY = Math.Abs(gap.Y - start.Y);
                     * if (gapY > 2)
                     * {
                     *      continue;
                     * }*/

                    var gapX = Math.Abs(gap.X - start.X);
                    if (gapX <= 15 || gapX > 50)
                    {
                        continue;
                    }

                    // We will reduce list of solution by checking if the solution is already found.
                    //if (listSolutions.Any(m => Math.Abs(m.GapX - gapX) < 2 && m.Junctions.Contains(start)))
                    if (usedJunctionsForGapX.ContainsKey(gap.X | gap.Y << 16) &&
                        usedJunctionsForGapX[gap.X | gap.Y << 16].Any(m => Math.Abs(m - gapX) < 10))
                    {
                        skipSol++;
                        continue;
                    }

                    List <Junction> curSolution = new List <Junction>();
                    curSolution.Add(start);

                    int numElementsRight = FindElementsOnDirection(cachePossibleNextJunctionRight, start, gap, gapX, curSolution);
                    int numElementsLeft  = FindElementsOnDirection(cachePossibleNextJunctionLeft, start, gap, -gapX, curSolution);

                    int numElements = numElementsLeft + numElementsRight;

                    if (numElements >= options.MinNumElements)
                    {
                        if (numSol == options.MaxSolutions)
                        {
                            // Something wrong happen. Too much solution for now.
                            // If we continue, we would spend too much time processing the image.
                            // Let's suppose we don't know.
                            return(new FormExtractionResult
                            {
                                // Too much solution. You may want to increase MaxSolutions.
                                ReturnCode = 30
                            });
                        }

                        numSol++;
                        listSolutions.Add(new Line
                        {
                            GapX      = gapX,
                            Junctions = curSolution.ToArray()
                        });
                        foreach (var item in curSolution)
                        {
                            List <int> listGapX;
                            if (!usedJunctionsForGapX.ContainsKey(item.X | item.Y << 16))
                            {
                                listGapX = new List <int>();
                                usedJunctionsForGapX.Add(item.X | item.Y << 16, listGapX);
                            }
                            else
                            {
                                listGapX = usedJunctionsForGapX[item.X | item.Y << 16];
                            }
                            listGapX.Add(gapX);
                        }
                    }
                }

                Line bestSol = listSolutions.OrderByDescending(m => m.Junctions.Count()).FirstOrDefault();

                if (bestSol != null)
                {
                    // Too slow. (faster if we skip removal)
                    // But, we have more solutions.
                    foreach (var item in bestSol.Junctions)
                    {
                        elements.Remove(item.X | item.Y << 16);
                    }

                    possibleSol.Add(bestSol);
                }
            }

            //Console.WriteLine("Skip: " + skipSol);
            //Console.WriteLine(numSol + " : Solution found");
            //Console.WriteLine(possibleSol.Count + " Best solution found");

            // Let's merge near junctions. (vertical line)
            // We assign a group id for each clusters.

            Dictionary <int, int> junctionToGroupId = new Dictionary <int, int>();

            int nextGroupId = 1;

            foreach (var curSolution in possibleSol)
            {
                if (curSolution.Junctions.First().GroupId == 0)
                {
                    for (int i = 0; i < curSolution.Junctions.Length; i++)
                    {
                        ref var j = ref curSolution.Junctions[i];
                        j.GapX = curSolution.GapX;
                    }

                    // Not assigned yet.

                    // Find near junction.
                    int groupId = 0;

                    foreach (var item in curSolution.Junctions)
                    {
                        var alreadyClassified = cacheNearJunction[item.X | item.Y << 16]
                                                .Where(m =>
                                                       // Doesn't work with struct.
                                                       //m.GroupId != 0 &&
                                                       Math.Abs(m.X - item.X) <= 5 &&
                                                       Math.Abs(m.Y - item.Y) <= 3
                                                       // Doesn't work with struct.
                                                       //Math.Abs(m.GapX - item.GapX) <= 2
                                                       ).Where(m => junctionToGroupId.ContainsKey(m.X | m.Y << 16));
                        if (alreadyClassified.Any())
                        {
                            Junction junction = alreadyClassified.First();
                            groupId = junctionToGroupId[junction.X | junction.Y << 16];
                            //groupId = alreadyClassified.First().GroupId;
                            break;
                        }
                    }

                    if (groupId == 0)
                    {
                        // Not found.

                        // Create a new group.
                        nextGroupId++;

                        groupId = nextGroupId;
                    }

                    for (int i = 0; i < curSolution.Junctions.Length; i++)
                    {
                        ref var j = ref curSolution.Junctions[i];
                        j.GroupId = groupId;
                        int id = j.X | j.Y << 16;
                        if (!junctionToGroupId.ContainsKey(id))
                        {
                            junctionToGroupId.Add(id, groupId);
                        }
                    }
                }
Example #25
0
        private Color GetJunctionColor(Junction junction)
        {
            ThreadHelper.AssertOnUIThread();

            // Draw non-relative branches gray
            if (!junction.IsRelative && _revisionGraphDrawStyleCache == RevisionGraphDrawStyleEnum.DrawNonRelativesGray)
            {
                return(_nonRelativeColor);
            }

            // Draw non-highlighted branches gray
            if (!junction.HighLight && _revisionGraphDrawStyleCache == RevisionGraphDrawStyleEnum.HighlightSelected)
            {
                return(_nonRelativeColor);
            }

            if (!AppSettings.MulticolorBranches)
            {
                return(AppSettings.GraphColor);
            }

            // See if this junciton's colour has already been calculated
            if (_colorByJunction.TryGetValue(junction, out var colorIndex))
            {
                return(_possibleColors[colorIndex]);
            }

            // NOTE we reuse _adjacentColors to avoid allocating lists during UI painting.
            // This is safe as we are always on the UI thread here.
            _adjacentColors.Clear();
            _adjacentColors.AddRange(
                from peer in GetPeers().SelectMany()
                where _colorByJunction.TryGetValue(peer, out colorIndex)
                select colorIndex);

            if (_adjacentColors.Count == 0)
            {
                // This is an end-point. We need to 'pick' a new color
                colorIndex = 0;
            }
            else
            {
                // This is a parent branch, calculate new color based on parent branch
                int start = _adjacentColors[0];
                int i;
                for (i = 0; i < preferedColors.Length; i++)
                {
                    colorIndex = (start + preferedColors[i]) % _possibleColors.Length;
                    if (!_adjacentColors.Contains(colorIndex))
                    {
                        break;
                    }
                }

                if (i == preferedColors.Length)
                {
                    colorIndex = _random.Next(preferedColors.Length);
                }
            }

            _colorByJunction[junction] = colorIndex;
            return(_possibleColors[colorIndex]);

            // Get adjacent (peer) junctions
            IEnumerable <IEnumerable <Junction> > GetPeers()
            {
                yield return(junction.Youngest.Ancestors);

                yield return(junction.Youngest.Descendants);

                yield return(junction.Oldest.Ancestors);

                yield return(junction.Oldest.Descendants);
            }
        }
Example #26
0
 public Car(Junction first)
 {
     TakenJunctions = new List<Junction> { first };
     TakenStreets = new List<Street>();
     CurrentDistance = 0;
     CurrentTimer = 0;
 }
    /// <summary>
    /// Only call this function when the thingie is created. Otherwise, you maybe want UpdateLife()?
    /// </summary>
    public void updateSprite()
    {
        if (weirdJunction)
        {
            transform.GetChild(0).gameObject.GetComponent <Junction>().updateSprite();
            transform.GetChild(1).gameObject.GetComponent <Junction>().updateSprite(); //This one is the favorite child
            return;
        }
        string spriteString = "";

        spriteString += WallOrPool ? "w" : "p";
        spriteString += "Corner_";
        spriteString += type.ToString() + "_";
        float angle = 0;

        switch (shape)
        {
        case Shape.Fat:
            Debug.LogError("No no no no no, don't put it there!");
            return;

        case Shape.OOXX:     //down
            angle += 180;
            goto case Shape.XXOO;

        case Shape.OXOX:     //right
            angle += 270;
            goto case Shape.XXOO;

        case Shape.XOXO:     //left
            angle += 90;
            goto case Shape.XXOO;

        case Shape.XXOO:     //up
            spriteString += "up";
            break;

        case Shape.OXXO:     //top-right to bottom-left
            angle += 90;
            goto case Shape.XOOX;

        case Shape.XOOX:     //top-left to bottom-right
            spriteString += "bridge";
            break;

        case Shape.OXXX:     //top left hole
            angle += 180;
            goto case Shape.XXXO;

        case Shape.XXOX:     //bottom left hole
            angle += 270;
            goto case Shape.XXXO;

        case Shape.XOXX:     //top right hole
            angle += 90;
            goto case Shape.XXXO;

        case Shape.XXXO:     //bottom right hole
            spriteString += "bite";
            break;

        case Shape.XXXX:
            spriteString += "full";
            break;
        }
        spriteRenderer.sortingOrder = 2;

        spriteRenderer.sprite = Resources.Load <Sprite>("Blocks/" + spriteString);//e.g. "Blocks/wCorner_Cement_bridge"
        transform.Rotate(Vector3.forward, angle);

        gameObject.layer = LayerMask.NameToLayer("Corners"); //TODO make everything efficient, but especially this
        if (WallOrPool)                                      //If Wall
        {
            spriteRenderer.sortingLayerName = "Walls";

            //Add child object for cracks:
            GameObject buttCrack = new GameObject();
            buttCrack.transform.SetParent(transform);
            Junction junk = buttCrack.AddComponent <Junction>();
            junk.name  = "Cracks";
            junk.type  = Type.Cracks;
            junk.shape = shape;
            junk.life  = life;
            junk.updateCracks();
        }
        else //if pool
        {
            spriteRenderer.sortingLayerName = "Floor";
            spriteRenderer.color            = new Color(1f, 1f, 1f, ((float)life) / ((float)maxLife));
        }
    }
Example #28
0
 public DapperJunctionExpression(Junction junction)
 {
     Assert.NotNull(junction, "Junction must not be null");
     this.junction = junction;
 }
Example #29
0
            private Street GetNextStreetRec(int n, ref List<Street> path, Junction taken, Street street, ref int origTimer, ref int origDistance, ref int origHandicap)
            {
                Street bestStreet = null;

                lock (Lock)
                {
                    if (street != null)
                    {
                        origTimer += street.Cost;
                        origHandicap += street.Handicap;
                        origDistance += street.AlreadyUsed || (path != null && path.Contains(street)) ? 0 : street.Length;
                    }

                    if (n == 0)
                    {
                        path = new List<Street>();
                        return street;
                    }

                    int localTimer = origTimer;
                    int bestTimer = int.MaxValue;
                    int bestDistance = int.MinValue;
                    //double bestRatio = -1;
                    var possibleMoves = taken.Neighbours.Where(p => CurrentTimer + localTimer + p.Value.Cost <= _timeAlloted).ToList();

                    foreach (KeyValuePair<Junction, Street> possibleMove in possibleMoves)
                    {
                        int currentTimer = origTimer;
                        int currentDistance = origDistance;
                        int currentHandicap = origHandicap;
                        Street test = GetNextStreetRec(n - 1, ref path, possibleMove.Key, possibleMove.Value, ref currentTimer, ref currentDistance, ref currentHandicap);

                        if (test == null)
                        {
                            continue;
                        }

                        //double ratio = currentDistance / (double)(currentTimer + currentHandicap);

                        //if (ratio > bestRatio)
                        if (currentDistance >= bestDistance)
                        {
                            if (currentTimer < bestTimer)
                            {
                                bestDistance = currentDistance;
                                bestTimer = currentTimer;
                                bestStreet = test;
                            }
                            //bestRatio = ratio;
                        }
                    }

                    if (path != null)
                    {
                        path.Add(bestStreet);
                    }

                    origTimer = bestTimer;
                    origDistance = bestDistance;
                }

                return bestStreet;
            }
Example #30
0
 public JunctionEvent(double span, bool direction, Junction junction)
     : base(span)
 {
     this.direction = direction;
     this.junction  = junction;
 }
Example #31
0
 public Article()
 {
     Tags = new Junction();
 }
Example #32
0
        private void ComponentMenuItem_Click(object sender, RoutedEventArgs e)
        {
            Point po = Mouse.GetPosition(canvas_vanet);

            MenuItem item       = sender as MenuItem;
            string   itemString = item.Header.ToString();

            switch (itemString)
            {
            case "_Network Generator":
            {
                OpenTopGen();
            }
            break;

            case "_Two Lanes":
            {
                RoadSegment rs = new RoadSegment(this, 2, RoadOrientation.Horizontal);
                rs.Height = rs.LanesCount * PublicParamerters.LaneWidth + 1.5;
                rs.Margin = new Thickness(po.X + 50, po.Y + 50, 0, 0);
                canvas_vanet.Children.Add(rs);
            }
            break;

            case "_Four Lanes":
            {
                RoadSegment rs = new RoadSegment(this, 4, RoadOrientation.Horizontal);
                rs.Height = rs.LanesCount * PublicParamerters.LaneWidth + 1.5;
                rs.Margin = new Thickness(po.X + 50, po.Y + 50, 0, 0);
                canvas_vanet.Children.Add(rs);
            }
            break;

            case "_Six Lanes":
            {
                RoadSegment rs = new RoadSegment(this, 6, RoadOrientation.Horizontal);
                rs.Height = rs.LanesCount * PublicParamerters.LaneWidth + 1.5;
                rs.Margin = new Thickness(po.X + 50, po.Y + 50, 0, 0);
                canvas_vanet.Children.Add(rs);
            }
            break;

            case "_Add Junction":
                Junction jun = new Junction(this);
                jun.Margin = new Thickness(po.X + 50, po.Y + 50, 0, 0);
                canvas_vanet.Children.Add(jun);
                break;

            case "_Import Vanet":
                UiImportTopology uim = new db.UiImportTopology(this);
                uim.Show();
                break;

            case "_Export Vanet":
                UiExportTopology win = new UiExportTopology(this);
                win.Show();
                break;

            case "_Clear":
            {
                Clear();
            }
            break;
            }
        }
        protected virtual IQueryOver <PagesView, PagesView> FilterQuery(IQueryOver <PagesView, PagesView> query,
                                                                        PagesFilter request, Junction hasnotSeoDisjunction)
        {
            PageProperties alias = null;

            if (!request.IncludeArchived)
            {
                query = query.Where(() => !alias.IsArchived);
            }

            if (request.OnlyMasterPages)
            {
                query = query.Where(() => alias.IsMasterPage);
            }
            else if (!request.IncludeMasterPages)
            {
                query = query.Where(() => !alias.IsMasterPage);
            }

            if (!string.IsNullOrWhiteSpace(request.SearchQuery))
            {
                var searchQuery = string.Format("%{0}%", request.SearchQuery);
                query = query.Where(Restrictions.Disjunction()
                                    .Add(Restrictions.InsensitiveLike(Projections.Property(() => alias.Title), searchQuery))
                                    .Add(Restrictions.InsensitiveLike(Projections.Property(() => alias.PageUrl), searchQuery))
                                    .Add(Restrictions.InsensitiveLike(Projections.Property(() => alias.MetaTitle), searchQuery))
                                    .Add(Restrictions.InsensitiveLike(Projections.Property(() => alias.MetaDescription), searchQuery))
                                    .Add(Restrictions.InsensitiveLike(Projections.Property(() => alias.MetaKeywords), searchQuery)));
            }

            if (request.LanguageId.HasValue)
            {
                if (request.LanguageId.Value.HasDefaultValue())
                {
                    query = query.Where(Restrictions.IsNull(Projections.Property(() => alias.Language.Id)));
                }
                else
                {
                    query = query.Where(Restrictions.Eq(Projections.Property(() => alias.Language.Id), request.LanguageId.Value));
                }
            }

            if (request.Tags != null)
            {
                foreach (var tagKeyValue in request.Tags)
                {
                    var id = tagKeyValue.Key.ToGuidOrDefault();
                    query = query.WithSubquery.WhereExists(QueryOver.Of <PageTag>().Where(tag => tag.Tag.Id == id && tag.Page.Id == alias.Id).Select(tag => 1));
                }
            }

            if (request.Categories != null)
            {
                var categories = request.Categories.Select(c => new Guid(c.Key)).Distinct().ToList();

                foreach (var category in categories)
                {
                    var childCategories = categoryService.GetChildCategoriesIds(category).ToArray();
                    query = query.WithSubquery.WhereExists(QueryOver.Of <PageCategory>().Where(cat => !cat.IsDeleted && cat.Page.Id == alias.Id).WhereRestrictionOn(cat => cat.Category.Id).IsIn(childCategories).Select(cat => 1));
                }
            }

            if (request.Status.HasValue)
            {
                if (request.Status.Value == PageStatusFilterType.OnlyPublished)
                {
                    query = query.Where(() => alias.Status == PageStatus.Published);
                }
                else if (request.Status.Value == PageStatusFilterType.OnlyUnpublished)
                {
                    query = query.Where(() => alias.Status != PageStatus.Published);
                }
                else if (request.Status.Value == PageStatusFilterType.ContainingUnpublishedContents)
                {
                    PageContent         pageContentAlias    = null;
                    Root.Models.Content contentAlias        = null;
                    Root.Models.Content contentHistoryAlias = null;
                    var subQuery = QueryOver.Of(() => pageContentAlias)
                                   .Inner.JoinAlias(() => pageContentAlias.Content, () => contentAlias, () => !contentAlias.IsDeleted)
                                   .Left.JoinAlias(() => contentAlias.History, () => contentHistoryAlias, () => !contentHistoryAlias.IsDeleted)
                                   .Where(() => pageContentAlias.Page.Id == alias.Id && !pageContentAlias.IsDeleted)
                                   .Where(() => contentHistoryAlias.Status == ContentStatus.Draft || contentAlias.Status == ContentStatus.Draft)
                                   .Select(p => 1);

                    query = query.WithSubquery.WhereExists(subQuery);
                }
            }

            if (request.SeoStatus.HasValue)
            {
                if (request.SeoStatus.Value == SeoStatusFilterType.HasNotSeo)
                {
                    query = query.Where(hasnotSeoDisjunction);
                }
                else
                {
                    query = query.Where(Restrictions.Not(hasnotSeoDisjunction));
                }
            }

            if (!string.IsNullOrWhiteSpace(request.Layout))
            {
                Guid id;
                var  length = request.Layout.Length - 2;
                if (request.Layout.StartsWith("m-", StringComparison.Ordinal) && Guid.TryParse(request.Layout.Substring(2, length), out id))
                {
                    query = query.Where(() => alias.MasterPage.Id == id);
                }

                if (request.Layout.StartsWith("l-", StringComparison.Ordinal) && Guid.TryParse(request.Layout.Substring(2, length), out id))
                {
                    query = query.Where(() => alias.Layout.Id == id);
                }
            }

            if (request.ContentId.HasValue)
            {
                Root.Models.Content contentAlias      = null;
                ChildContent        childContentAlias = null;
                HtmlContent         htmlContentAlias  = null;
                PageContent         pageContentAlias  = null;

                var htmlChildContentSubQuery =
                    QueryOver.Of(() => htmlContentAlias)
                    .JoinAlias(h => h.ChildContents, () => childContentAlias)
                    .Where(() => htmlContentAlias.Id == contentAlias.Id)
                    .And(() => childContentAlias.Child.Id == request.ContentId.Value)
                    .Select(pageContent => 1);

                var pageContentSubQuery = QueryOver.Of(() => pageContentAlias)
                                          .JoinAlias(() => pageContentAlias.Content, () => contentAlias)
                                          .And(() => pageContentAlias.Page.Id == alias.Id)
                                          .And(() => !contentAlias.IsDeleted)
                                          .And(() => !pageContentAlias.IsDeleted)
                                          .And(Restrictions.Or(
                                                   Restrictions.Where(() => contentAlias.Id == request.ContentId.Value),
                                                   Subqueries.WhereExists(htmlChildContentSubQuery)
                                                   ))
                                          .Select(pageContent => 1);

                query = query.WithSubquery.WhereExists(pageContentSubQuery);
            }

            return(query);
        }
Example #34
0
            public override void ITEMShow(Menu_Base i, int pos = 0)
            {
                if (Junction != null)
                {
                    pos = cnv(pos);
                    switch (Junction.GetMode())
                    {
                    default:
                        if (pos < 1)
                        {
                            base.ITEMShow(i, pos);
                        }
                        else
                        {
                            base.ITEMHide(i, pos);
                        }
                        break;

                    case Mode.Mag_Pool_Stat:
                    case Mode.Mag_Stat:
                        if (pos < 3)
                        {
                            base.ITEMShow(i, pos);
                        }
                        else
                        {
                            base.ITEMHide(i, pos);
                        }
                        break;

                    case Mode.Mag_EL_A:
                    case Mode.Mag_Pool_EL_A:
                        if (pos > 0 && pos < 5)
                        {
                            base.ITEMShow(i, pos);
                        }
                        else
                        {
                            base.ITEMHide(i, pos);
                        }
                        break;

                    case Mode.Mag_EL_D:
                    case Mode.Mag_Pool_EL_D:
                        if (pos > 0 && pos < 4 || pos == 5)
                        {
                            base.ITEMShow(i, pos);
                        }
                        else
                        {
                            base.ITEMHide(i, pos);
                        }
                        break;

                    case Mode.Mag_ST_A:
                    case Mode.Mag_Pool_ST_A:
                        if (pos > 0 && pos < 3 || pos == 6 || pos == 7)
                        {
                            base.ITEMShow(i, pos);
                        }
                        else
                        {
                            base.ITEMHide(i, pos);
                        }
                        break;

                    case Mode.Mag_ST_D:
                    case Mode.Mag_Pool_ST_D:
                        if (pos > 0 && pos < 3 || pos == 6 || pos == 8)
                        {
                            base.ITEMShow(i, pos);
                        }
                        else
                        {
                            base.ITEMHide(i, pos);
                        }
                        break;
                    }
                }
            }
Example #35
0
 /// <summary>
 /// applies the cycle on the trafficlights
 /// </summary>
 /// <param name="res">the resulting junction from running the algo</param>
 /// <param name="totalTime">the total time the cycle runs</param>
 public void schedule(Junction res, float totalTime)
 {
     StartCoroutine(lights(res, totalTime));
 }
Example #36
0
 void Awake()
 {
     _junction     = GetComponent <Junction>();
     _junctionId   = GetComponent <ObjectId>().Id;
     _lastSelected = _junction.selectedBranch;
 }
Example #37
0
 // Start is called before the first frame update
 void Start()
 {
     selector = GameObject.FindObjectOfType <Selector>();
     currentSelectedJunction = selector.overJunction;
     audioManager            = GameObject.Find("AudioManager").GetComponent <AudioManager>();
 }
Example #38
0
 public static bool Prefix(Junction __instance, Junction.SwitchMode mode)
 {
     return(mode == Junction.SwitchMode.NO_SOUND || !JunctionIsBroken(__instance));
 }
Example #39
0
 public override void AddItemRouting(PlatformItem item, int outputPortIndex)
 {
     base.AddItemRouting(item, outputPortIndex);
     Junction.RouteItem(item, outputPortIndex);
 }
 public LaneJunctionDetail(Junction j)
 {
     Junction = j;
     Junction.CurrentState = Junction.State.Processing;
     _index = 0;
 }
Example #41
0
 public LaneInfo(int aConnectLane, Junction aJunction)
 {
     connectLane = aConnectLane;
     junctions = new List<Junction>(1);
     junctions.Add(aJunction);
 }
Example #42
0
        public static void DesrlizeNetwork(MainWindow _MainWindow, string NetName)
        {
            // clear:
            _MainWindow.Clear();

            // now add them to feild.
            PublicParamerters.NetworkName = NetName;
            List <VanetComonent> ImportedComponents = NetworkTopolgy.ImportNetwok(NetName); // get comp

            _MainWindow.tab_vanet.Text = PublicParamerters.NetworkName;



            foreach (VanetComonent vanCom in ImportedComponents)
            {
                if (vanCom.ComponentType == ComponentType.Junction)
                {
                    // junction:
                    Junction jun = new Junction(_MainWindow);
                    jun.Margin = new Thickness(vanCom.Pox, vanCom.Poy, 0, 0);
                    jun.Height = vanCom.Height;
                    jun.Width  = vanCom.Width;
                    _MainWindow.canvas_vanet.Children.Add(jun);
                }
                else if (vanCom.ComponentType == ComponentType.RoadSegment)
                {
                    if (vanCom.RoadOrientation == RoadOrientation.Horizontal)
                    {
                        RoadSegment hrs = new RoadSegment(_MainWindow, vanCom.LanesCount, RoadOrientation.Horizontal);
                        hrs.Margin = new Thickness(vanCom.Pox, vanCom.Poy, 0, 0);
                        hrs.Height = vanCom.Height;
                        hrs.Width  = vanCom.Width;
                        _MainWindow.canvas_vanet.Children.Add(hrs);
                    }
                    else if ((vanCom.RoadOrientation == RoadOrientation.Vertical))
                    {
                        RoadSegment vrs = new RoadSegment(_MainWindow, vanCom.LanesCount, RoadOrientation.Vertical);
                        vrs.Margin = new Thickness(vanCom.Pox, vanCom.Poy, 0, 0);
                        vrs.Height = vanCom.Height;
                        vrs.Width  = vanCom.Width;
                        _MainWindow.canvas_vanet.Children.Add(vrs);
                    }
                }

                // get max X
            }



            BuildRoadNetwork builder = new BuildRoadNetwork(_MainWindow);

            builder.Build();

            double maxX = 0;
            double MaxY = 0;

            for (int j = 0; j < _MainWindow.MyJunctions.Count; j++)
            {
                Junction jun = _MainWindow.MyJunctions[j];
                if (jun.CenterLocation.X > maxX)
                {
                    maxX = jun.CenterLocation.X;
                }
                if (jun.CenterLocation.Y > MaxY)
                {
                    MaxY = jun.CenterLocation.Y;
                }
            }

            _MainWindow.canvas_vanet.Height = 200 + MaxY;
            _MainWindow.canvas_vanet.Width  = 200 + maxX;
        }
Example #43
0
            public Junction Split(Node aNode)
            {
                // The 'top' (Child->node) of the junction is retained by
                // The 'bottom' (node->Parent) of the junction is returned.
                int index = Bunch.IndexOf(aNode);
                if (index == -1)
                {
                    return null;
                }
                var bottom = new Junction(this, aNode);
                // Add 1, since aNode was at the index
                index += 1;
                while (Bunch.Count > index)
                {
                    Node node = Bunch[index];
                    Bunch.RemoveAt(index);
                    node.Ancestors.Remove(this);
                    node.Descendants.Remove(this);
                    bottom.Add(node);
                }

                return bottom;
            }
Example #44
0
        // http://en.wikipedia.org/wiki/File:RBG_color_wheel.svg

        private Color GetJunctionColor(Junction aJunction)
        {
            //Draw non-relative branches gray
            if (!aJunction.IsRelative && revisionGraphDrawStyleCache == RevisionGraphDrawStyleEnum.DrawNonRelativesGray)
            {
                return(_nonRelativeColor);
            }

            //Draw non-highlighted branches gray
            if (!aJunction.HighLight && revisionGraphDrawStyleCache == RevisionGraphDrawStyleEnum.HighlightSelected)
            {
                return(_nonRelativeColor);
            }

            if (!AppSettings.MulticolorBranches)
            {
                return(AppSettings.GraphColor);
            }

            // This is the order to grab the colors in.
            int[] preferedColors = { 4, 8, 6, 10, 2, 5, 7, 3, 9, 1, 11 };

            int colorIndex;

            if (_junctionColors.TryGetValue(aJunction, out colorIndex))
            {
                return(_possibleColors[colorIndex]);
            }

            // Get adjacent junctions
            var adjacentJunctions = new List <Junction>();
            var adjacentColors    = new List <int>();

            adjacentJunctions.AddRange(aJunction.Youngest.Ancestors);
            adjacentJunctions.AddRange(aJunction.Youngest.Descendants);
            adjacentJunctions.AddRange(aJunction.Oldest.Ancestors);
            adjacentJunctions.AddRange(aJunction.Oldest.Descendants);
            foreach (Junction peer in adjacentJunctions)
            {
                if (_junctionColors.TryGetValue(peer, out colorIndex))
                {
                    adjacentColors.Add(colorIndex);
                }
                else
                {
                    colorIndex = -1;
                }
            }

            if (adjacentColors.Count == 0) //This is an end-point. We need to 'pick' a new color
            {
                colorIndex = 0;
            }
            else //This is a parent branch, calculate new color based on parent branch
            {
                int start = adjacentColors[0];
                int i;
                for (i = 0; i < preferedColors.Length; i++)
                {
                    colorIndex = (start + preferedColors[i]) % _possibleColors.Length;
                    if (!adjacentColors.Contains(colorIndex))
                    {
                        break;
                    }
                }
                if (i == preferedColors.Length)
                {
                    var r = new Random();
                    colorIndex = r.Next(preferedColors.Length);
                }
            }

            _junctionColors[aJunction] = colorIndex;
            return(_possibleColors[colorIndex]);
        }
Example #45
0
        private static IEnumerable <IEvaluatable> MergeAndReturnImplicationsThatShareAnAntecedent(IEnumerable <IEvaluatable> implications, Junction usingJunction)
        {
            var commonAntecedentMultipleConsequent_Tuples = implications
                                                            .Select((imp1, x) => new Tuple <IEvaluatable, IEnumerable <IEvaluatable> >(
                                                                        (imp1 as Implication).Antecedent,
                                                                        implications
                                                                        .Where((imp2, y) => ImplicationsShareAntecedent(imp1 as Implication, imp2 as Implication))
                                                                        .Select(imp2 => (imp2 as Implication).Consequent)))
                                                            .Where(tuple => tuple.Item2.Count() > 1);

            return(commonAntecedentMultipleConsequent_Tuples.Where(commonAMultiC_Tuple => commonAMultiC_Tuple.Item2.Any())
                   .Select(commonAMultiC_Tuple =>
                           If.When(commonAMultiC_Tuple.Item1)
                           .Then(ConvertArgumentsToJunction(commonAMultiC_Tuple.Item2, usingJunction)))
                   .Distinct());
        }
Example #46
0
 /// <summary>
 /// Clone initiator
 /// </summary>
 /// <param name="original"> Original Junction </param>
 public Junction(Junction original)
 {
     this._order   = (bool[, ])original._order.Clone();
     this._density = (int[])original._density.Clone();
 }
Example #47
0
        private static IEnumerable <IEvaluatable> MergeAndReturnImplicationsThatShareAConsequent(IEnumerable <IEvaluatable> implications, Junction usingJunction)
        {
            var multipleAntecedentCommonConsequent_Tuples = implications
                                                            .Select((imp1, x) => new Tuple <IEnumerable <IEvaluatable>, IEvaluatable>(
                                                                        implications
                                                                        .Where((imp2, y) => ImplicationsShareConsequent(imp1 as Implication, imp2 as Implication))
                                                                        .Select(imp2 => (imp2 as Implication).Antecedent),
                                                                        (imp1 as Implication).Consequent))
                                                            .Where(tuple => tuple.Item1.Count() > 1);

            return(multipleAntecedentCommonConsequent_Tuples.Where(MultiACommonC_Tuple => MultiACommonC_Tuple.Item1.Any())
                   .Select(MultiACommonC_Tuple =>
                           If.When(ConvertArgumentsToJunction(MultiACommonC_Tuple.Item1, usingJunction))
                           .Then(MultiACommonC_Tuple.Item2)).ToList()
                   .Distinct());
        }
Example #48
0
            public void Add(IComparable aId, IComparable[] aParentIds, DataType aType, GitRevision aData)
            {
                // If we haven't seen this node yet, create a new junction.
                Node node;

                if (!GetNode(aId, out node) && (aParentIds == null || aParentIds.Length == 0))
                {
                    var newJunction = new Junction(node, node);
                    junctions.Add(newJunction);
                }
                nodeCount++;
                node.Data     = aData;
                node.DataType = aType;
                node.Index    = AddedNodes.Count;
                AddedNodes.Add(node);

                foreach (IComparable parentId in aParentIds)
                {
                    Node parent;
                    GetNode(parentId, out parent);
                    if (parent.Index < node.Index)
                    {
                        // TODO: We might be able to recover from this with some work, but
                        // since we build the graph async it might be tough to figure out.
                        //throw new ArgumentException("The nodes must be added such that all children are added before their parents", "aParentIds");
                        continue;
                    }

                    if (node.Descendants.Count == 1 && node.Ancestors.Count <= 1 &&
                        node.Descendants[0].Parent == node &&
                        parent.Ancestors.Count == 0
                        //If this is true, the current revision is in the middle of a branch
                        //and is about to start a new branch. This will also mean that the last
                        //revisions are non-relative. Make sure a new junction is added and this
                        //is the start of a new branch (and color!)
                        && (aType & DataType.Active) != DataType.Active
                        )
                    {
                        // The node isn't a junction point. Just the parent to the node's
                        // (only) ancestor junction.
                        node.Descendants[0].Add(parent);
                    }
                    else if (node.Ancestors.Count == 1 && node.Ancestors[0].Child != node)
                    {
                        // The node is in the middle of a junction. We need to split it.
                        Junction splitNode = node.Ancestors[0].Split(node);
                        junctions.Add(splitNode);

                        // The node is a junction point. We are a new junction
                        var junction = new Junction(node, parent);
                        junctions.Add(junction);
                    }
                    else if (parent.Descendants.Count == 1 && parent.Descendants[0].Parent != parent)
                    {
                        // The parent is in the middle of a junction. We need to split it.
                        Junction splitNode = parent.Descendants[0].Split(parent);
                        junctions.Add(splitNode);

                        // The node is a junction point. We are a new junction
                        var junction = new Junction(node, parent);
                        junctions.Add(junction);
                    }
                    else
                    {
                        // The node is a junction point. We are a new junction
                        var junction = new Junction(node, parent);
                        junctions.Add(junction);
                    }
                }

                bool isRelative = (aType & DataType.Active) == DataType.Active;

                if (!isRelative && node.Descendants.Any(d => d.IsRelative))
                {
                    isRelative = true;
                }

                bool isRebuild = false;

                foreach (Junction d in node.Ancestors)
                {
                    d.IsRelative = isRelative || d.IsRelative;

                    // Uh, oh, we've already processed this lane. We'll have to update some rows.
                    var parent = d.TryGetParent(node);
                    if (parent != null && parent.InLane != int.MaxValue)
                    {
                        int resetTo = d.Parent.Descendants.Aggregate(d.Parent.InLane, (current, dd) => Math.Min(current, dd.Child.InLane));

                        Console.WriteLine("We have to start over at lane {0} because of {1}", resetTo, node);
                        isRebuild = true;
                        break;
                    }
                }

                if (isRebuild)
                {
                    // TODO: It would be nice if we didn't have to start completely over...but it wouldn't
                    // be easy since we don't keep around all of the necessary lane state for each step.
                    int lastLane = lanes.Count - 1;
                    lanes.Clear();
                    lanes.CacheTo(lastLane);

                    // We need to signal the DvcsGraph object that it needs to redraw everything.
                    if (Updated != null)
                    {
                        Updated(this);
                    }
                }
                else
                {
                    lanes.Update(node);
                }
            }
Example #49
0
 public static IEvaluatable ConvertArgumentsToJunction(IEnumerable <IEvaluatable> arguments, Junction asJunction)
 {
     return(asJunction == Junction.AND ? ArgumentsToConjunction(arguments) : ArgumentsToDisjunction(arguments));
 }
Example #50
0
            public void Add(string aId, string[] aParentIds, DataType aType, GitRevision aData)
            {
                // If we haven't seen this node yet, create a new junction.
                Node node;
                if (!GetNode(aId, out node) && (aParentIds == null || aParentIds.Length == 0))
                {
                    var newJunction = new Junction(node, node);
                    junctions.Add(newJunction);
                }
                nodeCount++;
                node.Data = aData;
                node.DataType = aType;
                node.Index = AddedNodes.Count;
                AddedNodes.Add(node);

                foreach (string parentId in aParentIds)
                {
                    Node parent;
                    GetNode(parentId, out parent);
                    if (parent.Index < node.Index)
                    {
                        // TODO: We might be able to recover from this with some work, but
                        // since we build the graph async it might be tough to figure out.
                        Debug.WriteLine("The nodes must be added such that all children are added before their parents");
                        continue;
                    }

                    if (node.Descendants.Count == 1 && node.Ancestors.Count <= 1
                        && node.Descendants[0].Parent == node
                        && parent.Ancestors.Count == 0
                        //If this is true, the current revision is in the middle of a branch
                        //and is about to start a new branch. This will also mean that the last
                        //revisions are non-relative. Make sure a new junction is added and this
                        //is the start of a new branch (and color!)
                        && (aType & DataType.Active) != DataType.Active
                        )
                    {
                        // The node isn't a junction point. Just the parent to the node's
                        // (only) ancestor junction.
                        node.Descendants[0].Add(parent);
                    }
                    else if (node.Ancestors.Count == 1 && node.Ancestors[0].Child != node)
                    {
                        // The node is in the middle of a junction. We need to split it.
                        Junction splitNode = node.Ancestors[0].Split(node);
                        junctions.Add(splitNode);

                        // The node is a junction point. We are a new junction
                        var junction = new Junction(node, parent);
                        junctions.Add(junction);
                    }
                    else if (parent.Descendants.Count == 1 && parent.Descendants[0].Parent != parent)
                    {
                        // The parent is in the middle of a junction. We need to split it.
                        Junction splitNode = parent.Descendants[0].Split(parent);
                        junctions.Add(splitNode);

                        // The node is a junction point. We are a new junction
                        var junction = new Junction(node, parent);
                        junctions.Add(junction);
                    }
                    else
                    {
                        // The node is a junction point. We are a new junction
                        var junction = new Junction(node, parent);
                        junctions.Add(junction);
                    }
                }

                bool isRelative = (aType & DataType.Active) == DataType.Active;
                if (!isRelative && node.Descendants.Any(d => d.IsRelative))
                {
                    isRelative = true;
                }

                bool isRebuild = false;
                foreach (Junction d in node.Ancestors)
                {
                    d.IsRelative = isRelative || d.IsRelative;

                    // Uh, oh, we've already processed this lane. We'll have to update some rows.
                    var parent = d.TryGetParent(node);
                    if (parent != null && parent.InLane != int.MaxValue)
                    {
                        int resetTo = d.Parent.Descendants.Aggregate(d.Parent.InLane, (current, dd) => Math.Min(current, dd.Child.InLane));
                        Debug.WriteLine("We have to start over at lane {0} because of {1}", resetTo, node);
                        isRebuild = true;
                        break;
                    }
                }

                if (isRebuild)
                {
                    // TODO: It would be nice if we didn't have to start completely over...but it wouldn't
                    // be easy since we don't keep around all of the necessary lane state for each step.
                    int lastLane = lanes.Count - 1;
                    lanes.Clear();
                    lanes.CacheTo(lastLane);

                    // We need to signal the DvcsGraph object that it needs to redraw everything.
                    if (Updated != null)
                    {
                        Updated(this);
                    }
                }
                else
                {
                    lanes.Update(node);
                }
            }
Example #51
0
        /// <summary>
        /// check if the segment and the junction are overlapped. and check the oreintation of overlapping.
        /// </summary>
        /// <param name="jun"></param>
        /// <param name="rs"></param>
        public static void AreIntersected(Junction jun, RoadSegment rs)
        {
            double offset = -1;

            if (rs.Roadorientation == RoadOrientation.Vertical)
            {
                if (jun.Margin.Top >= rs.Margin.Top)
                {
                    double distance = offset + Computations.Distance(jun.BottomRightCorner, rs.BottomRightCorner);
                    if (distance < jun.Height)
                    {
                        jun.ToNorthRoadSegment         = rs;
                        jun.IncicdentRoadSegmentCount += 1;
                        jun.VerticalGreenValue        += 1;
                        rs.MyJunctions.Add(jun);
                        // return true;
                    }
                }
                else if (jun.Margin.Top < rs.Margin.Top)
                {
                    double distance = offset + Computations.Distance(jun.TopLeftCorner, rs.TopLeftCorner);
                    if (distance <= jun.Height)
                    {
                        jun.ToSouthRoadSegment         = rs;
                        jun.IncicdentRoadSegmentCount += 1;
                        jun.VerticalGreenValue        += 1;
                        rs.MyJunctions.Add(jun);
                        //  return true;
                    }
                }
            }
            else if (rs.Roadorientation == RoadOrientation.Horizontal)
            {
                if (jun.Margin.Left < rs.Margin.Left)
                {
                    double distance = offset + Computations.Distance(jun.TopLeftCorner, rs.TopLeftCorner);
                    if (distance <= jun.Width)
                    {
                        jun.ToEastRoadSegment          = rs;
                        jun.IncicdentRoadSegmentCount += 1;
                        jun.HorizontalGreenValue      += 1;
                        rs.MyJunctions.Add(jun);
                        // return true;
                    }
                }
                else if (jun.Margin.Left > rs.Margin.Left)
                {
                    double distance = offset + Computations.Distance(jun.TopRightCorner, rs.TopRightCorner);
                    if (distance <= jun.Width)
                    {
                        jun.ToWestRoadSegment          = rs;
                        jun.IncicdentRoadSegmentCount += 1;
                        jun.HorizontalGreenValue      += 1;
                        rs.MyJunctions.Add(jun);
                        // return true;
                    }
                }
            }

            //  return false;
        }
Example #52
0
        // http://en.wikipedia.org/wiki/File:RBG_color_wheel.svg
        private Color GetJunctionColor(Junction aJunction)
        {
            //Draw non-relative branches gray
            if (!aJunction.IsRelative && RevisionGraphDrawNonRelativesGray)
                return _nonRelativeColor;

            if (!MulticolorBranches)
                return GraphColor;

            // This is the order to grab the colors in.
            int[] preferedColors = { 4, 8, 6, 10, 2, 5, 7, 3, 9, 1, 11 };

            int colorIndex;
            if (_junctionColors.TryGetValue(aJunction, out colorIndex))
            {
                return _possibleColors[colorIndex];
            }

            // Get adjacent junctions
            var adjacentJunctions = new List<Junction>();
            var adjacentColors = new List<int>();
            adjacentJunctions.AddRange(aJunction.Child.Ancestors);
            adjacentJunctions.AddRange(aJunction.Child.Descendants);
            adjacentJunctions.AddRange(aJunction.Parent.Ancestors);
            adjacentJunctions.AddRange(aJunction.Parent.Descendants);
            foreach (Junction peer in adjacentJunctions)
            {
                if (_junctionColors.TryGetValue(peer, out colorIndex))
                {
                    adjacentColors.Add(colorIndex);
                }
                else
                {
                    colorIndex = -1;
                }
            }

            if (adjacentColors.Count == 0) //This is an end-point. We need to 'pick' a new color
            {
                colorIndex = 0;
            }
            else //This is a parent branch, calculate new color based on parent branch
            {
                int start = adjacentColors[0];
                int i;
                for (i = 0; i < preferedColors.Length; i++)
                {
                    colorIndex = (start + preferedColors[i]) % _possibleColors.Length;
                    if (!adjacentColors.Contains(colorIndex))
                    {
                        break;
                    }
                }
                if (i == preferedColors.Length)
                {
                    var r = new Random();
                    colorIndex = r.Next(preferedColors.Length);
                }
            }

            _junctionColors[aJunction] = colorIndex;
            return _possibleColors[colorIndex];
        }
Example #53
0
            public Junction Split(Node aNode)
            {
                // The 'top' (Child->node) of the junction is retained by this.
                // The 'bottom' (node->Parent) of the junction is returned.
                int index;
                if (!nodeIndices.TryGetValue(aNode, out index))
                    return null;

                var bottom = new Junction(this, aNode);
                // Add 1, since aNode was at the index
                index += 1;
                while (index < NodesCount)
                {
                    Node node = this[index];
                    RemoveNode(node);
                    node.Ancestors.Remove(this);
                    node.Descendants.Remove(this);
                    bottom.Add(node);
                }

                return bottom;
            }