Exemplo n.º 1
0
        public override void Execute()
        {
            
            #line 3 "..\..\Views\Shared\Fields\Settings\_OptionsField.cshtml"
  
    var attribute = Model.FieldAttribute as Realtair.Framework.Core.Actions.FieldAttributes.OptionsFieldAttribute;
    var options = attribute.Options(Model.Action, Html.LoggedInUser());
    var hopefullyUniqueId = Math.Abs(Model.GetHashCode());

            
            #line default
            #line hidden
WriteLiteral("\r\n\r\n<div");

WriteLiteral(" class=\"form-group\"");

WriteLiteral(">\r\n    <div");

WriteLiteral(" class=\"col-md-3 col-sm-4\"");

WriteLiteral(">\r\n        <label");

WriteLiteral(" class=\"control-label\"");

WriteLiteral(">");

            
            #line 11 "..\..\Views\Shared\Fields\Settings\_OptionsField.cshtml"
                                Write(Model.Label);

            
            #line default
            #line hidden
WriteLiteral("</label>\r\n    </div>\r\n\r\n    <div");

WriteLiteral(" class=\"col-md-9 col-sm-8\"");

WriteLiteral(">\r\n");

            
            #line 15 "..\..\Views\Shared\Fields\Settings\_OptionsField.cshtml"
        
            
            #line default
            #line hidden
            
            #line 15 "..\..\Views\Shared\Fields\Settings\_OptionsField.cshtml"
         if (options.Count() == 0)
        {

            
            #line default
            #line hidden
WriteLiteral("            <select");

WriteAttribute("id", Tuple.Create(" id=\"", 545), Tuple.Create("\"", 568)
            
            #line 17 "..\..\Views\Shared\Fields\Settings\_OptionsField.cshtml"
, Tuple.Create(Tuple.Create("", 550), Tuple.Create<System.Object, System.Int32>(hopefullyUniqueId
            
            #line default
            #line hidden
, 550), false)
);

WriteLiteral(" class=\"form-control\"");

WriteLiteral(" disabled>\r\n                <option>None to display</option>\r\n            </selec" +
"t>\r\n");

            
            #line 20 "..\..\Views\Shared\Fields\Settings\_OptionsField.cshtml"
        }
        else
        {

            
            #line default
            #line hidden
WriteLiteral("            <select");

WriteAttribute("id", Tuple.Create(" id=\"", 730), Tuple.Create("\"", 753)
            
            #line 23 "..\..\Views\Shared\Fields\Settings\_OptionsField.cshtml"
, Tuple.Create(Tuple.Create("", 735), Tuple.Create<System.Object, System.Int32>(hopefullyUniqueId
            
            #line default
            #line hidden
, 735), false)
);

WriteLiteral(" class=\"form-control\"");

WriteAttribute("name", Tuple.Create(" name=\"", 775), Tuple.Create("\"", 799)
            
            #line 23 "..\..\Views\Shared\Fields\Settings\_OptionsField.cshtml"
, Tuple.Create(Tuple.Create("", 782), Tuple.Create<System.Object, System.Int32>(Model.UniqueName
            
            #line default
            #line hidden
, 782), false)
);

WriteLiteral(">\r\n");

            
            #line 24 "..\..\Views\Shared\Fields\Settings\_OptionsField.cshtml"
                
            
            #line default
            #line hidden
            
            #line 24 "..\..\Views\Shared\Fields\Settings\_OptionsField.cshtml"
                 foreach (var option in options)
                {

            
            #line default
            #line hidden
WriteLiteral("                    <option ");

            
            #line 26 "..\..\Views\Shared\Fields\Settings\_OptionsField.cshtml"
                        Write(option.Id.ToString() == Model.FormValue?.ToString() ? "selected" : "");

            
            #line default
            #line hidden
WriteLiteral(" value=\"");

            
            #line 26 "..\..\Views\Shared\Fields\Settings\_OptionsField.cshtml"
                                                                                                       Write(option.Id.ToString());

            
            #line default
            #line hidden
WriteLiteral("\">");

            
            #line 26 "..\..\Views\Shared\Fields\Settings\_OptionsField.cshtml"
                                                                                                                              Write(option.Description);

            
            #line default
            #line hidden
WriteLiteral("</option>\r\n");

            
            #line 27 "..\..\Views\Shared\Fields\Settings\_OptionsField.cshtml"
                }

            
            #line default
            #line hidden
WriteLiteral("            </select>\r\n");

            
            #line 29 "..\..\Views\Shared\Fields\Settings\_OptionsField.cshtml"
        }

            
            #line default
            #line hidden
WriteLiteral("\r\n        <link");

WriteLiteral(" rel=\"stylesheet\"");

WriteLiteral(" type=\"text/css\"");

WriteLiteral(" href=\"https://static.realtair.com/plugins/select2/css/select2.min.css\"");

WriteLiteral(">\r\n        <script");

WriteLiteral(" src=\"https://static.realtair.com/plugins/select2/js/select2.min.js\"");

WriteLiteral("></script>\r\n        <script>\r\n            $(window).resize(function () {\r\n       " +
"         $(\'.select2\').css(\'width\', \"100%\");\r\n            });\r\n\r\n    \t    $(\'#");

            
            #line 38 "..\..\Views\Shared\Fields\Settings\_OptionsField.cshtml"
            Write(hopefullyUniqueId);

            
            #line default
            #line hidden
WriteLiteral("\').select2();\r\n        </script>\r\n    </div>\r\n</div>\r\n\r\n");

        }
Exemplo n.º 2
0
    public MeshAndColors createMesh(VoxelModelChunk voxelChunk, ShapeNodeChunk shape)
    {
        Vector3 ve = rotateVector(new Vector3(voxelChunk.sizeChunk.sizeX, voxelChunk.sizeChunk.sizeY, voxelChunk.sizeChunk.sizeZ), shape.transform);

        int sizeX = (int)Math.Abs(ve.x);
        int sizeY = (int)Math.Abs(ve.y);
        int sizeZ = (int)Math.Abs(ve.z);

        // WTF? Dont drink and code!!!
        Vector3 correction = new Vector3((ve.x < 0) ? Math.Abs(ve.x) - 1 : 0, (ve.y < 0) ? Math.Abs(ve.y) - 1 : 0, (ve.z < 0) ? Math.Abs(ve.z) - 1 : 0);

        RenderVoxel[,,] voxelArray = new RenderVoxel[sizeX, sizeY, sizeZ];

        float maxX = 0;
        float maxY = 0;
        float maxZ = 0;
        float minX = sizeX;
        float minY = sizeY;
        float minZ = sizeZ;

        foreach (Voxel voxel in voxelChunk.voxels)
        {
            Vector3 rotVec = rotateVector(new Vector3(voxel.x, voxel.y, voxel.z), shape.transform) + correction;
            voxelArray[(int)rotVec.x, (int)rotVec.y, (int)rotVec.z] = new RenderVoxel(voxel.colorIndex);
            if (rotVec.x < minX)
            {
                minX = rotVec.x;
            }
            if (rotVec.y < minY)
            {
                minY = rotVec.y;
            }
            if (rotVec.z < minZ)
            {
                minZ = rotVec.z;
            }
            if (rotVec.x > maxX)
            {
                maxX = rotVec.x;
            }
            if (rotVec.y > maxY)
            {
                maxY = rotVec.y;
            }
            if (rotVec.z > maxZ)
            {
                maxZ = rotVec.z;
            }
        }

        shape.singleCenter = new Vector3((float)Math.Ceiling(minX + (maxX - minX) / 2f), minZ, (float)Math.Ceiling(minY + (maxY - minY) / 2f));
        Vector3 shifts = shape.singleCenter;

        MeshAndColors meshAndColors = createMeshFromVoxelArray(voxelArray, shifts);

        return(meshAndColors);
    }
Exemplo n.º 3
0
        /// <summary>
        /// Updates this instance.
        /// </summary>
        public override void Update()
        {
            var columnSeries = (IColumnSeriesView) View;

            var padding = columnSeries.ColumnPadding;

            var totalSpace = ChartFunctions.GetUnitWidth(AxisOrientation.X, Chart, View.ScalesXAt) - padding;
            var typeSeries = Chart.View.ActualSeries.Where(x =>
            {
                if (x == View) return true;
                var icsv = x as IColumnSeriesView;
                return icsv != null && icsv.SharesPosition;
            }).ToList();

            var singleColWidth = totalSpace / typeSeries.Count;

            double exceed = 0;

            var seriesPosition = typeSeries.IndexOf(columnSeries);

            if (singleColWidth > columnSeries.MaxColumnWidth)
            {
                exceed = (singleColWidth - columnSeries.MaxColumnWidth)*typeSeries.Count/2;
                singleColWidth = columnSeries.MaxColumnWidth;
            }

            var relativeLeft = padding + exceed + singleColWidth*(seriesPosition);

            var startAt = CurrentYAxis.FirstSeparator >= 0 && CurrentYAxis.LastSeparator > 0   //both positive
                ? CurrentYAxis.FirstSeparator                                                  //then use axisYMin
                : (CurrentYAxis.FirstSeparator < 0 && CurrentYAxis.LastSeparator <= 0          //both negative
                    ? CurrentYAxis.LastSeparator                                               //then use axisYMax
                    : 0);                                                                      //if mixed then use 0

            var zero = ChartFunctions.ToDrawMargin(startAt, AxisOrientation.Y, Chart, View.ScalesYAt);

            foreach (var chartPoint in View.ActualValues.GetPoints(View))
            {
                var reference =
                    ChartFunctions.ToDrawMargin(chartPoint, View.ScalesXAt, View.ScalesYAt, Chart);

                chartPoint.View = View.GetPointView(chartPoint,
                    View.DataLabels ? View.GetLabelPointFormatter()(chartPoint) : null);

                chartPoint.SeriesView = View;

                var rectangleView = (IRectanglePointView) chartPoint.View;

                var h = Math.Abs(reference.Y - zero);
                var t = reference.Y < zero
                    ? reference.Y
                    : zero;

                rectangleView.Data.Height = h;
                rectangleView.Data.Top = t;

                rectangleView.Data.Left = reference.X + relativeLeft;
                rectangleView.Data.Width = singleColWidth - padding;

                rectangleView.ZeroReference = zero;

                chartPoint.ChartLocation = new CorePoint(rectangleView.Data.Left + singleColWidth/2 - padding/2,
                    t);

                chartPoint.View.DrawOrMove(null, chartPoint, 0, Chart);
            }
        }
Exemplo n.º 4
0
 public static int AbsoluteDifference(Enumeration firstValue, Enumeration secondValue)
 {
     var absoluteDifference = Math.Abs(firstValue.Value - secondValue.Value);
     return absoluteDifference;
 }
Exemplo n.º 5
0
    public GameObject ImportMagicaVoxelFile(string path)
    {
        Material vertexMaterial = Resources.Load("VertexShading", typeof(Material)) as Material;

        GameObject levelGo = new GameObject(Path.GetFileName(path));

        levelGo.AddComponent <TeardownProperties>();
        MagicaImportedFile magicaImportedFile = levelGo.AddComponent <MagicaImportedFile>();

        magicaImportedFile.voxFile = Path.GetFileName(path);

        List <GameObject> gameObjects = new List <GameObject>();
        Dictionary <string, GameObject> namedGameObjects = new Dictionary <string, GameObject>();

        Chunk           mainChunk      = MagicaVoxelReader.ReadMagicaChunks(path);
        List <Material> colorMaterials = ImportColors(mainChunk);
        List <string>   names          = new List <string>();
        List <string>   doubleNames    = new List <string>();

        for (int i = 0; i < mainChunk.children.Count; i++)
        {
            Chunk chunk = mainChunk.children[i];
            if (chunk is VoxelModelChunk)
            {
                VoxelModelChunk voxelChunk = (VoxelModelChunk)chunk;

                foreach (ShapeNodeChunk shape in voxelChunk.shapes)
                {
                    MeshAndColors meshAndColors = createMesh(voxelChunk, shape);
                    Color[]       colors        = new Color[meshAndColors.colors.Count];
                    for (int c = 0; c < meshAndColors.colors.Count; c++)
                    {
                        colors[c] = colorMaterials[meshAndColors.colors[c] - 1].color;
                    }
                    meshAndColors.mesh.colors = colors;

                    TransformNodeChunk transformNodeChunk = shape.transform;
                    GameObject         go = new GameObject();
                    gameObjects.Add(go);
                    ObjectAttributes script   = go.AddComponent <ObjectAttributes>();
                    MeshRenderer     renderer = go.AddComponent <MeshRenderer>();
                    renderer.material = vertexMaterial;
                    MeshFilter filter = go.AddComponent <MeshFilter>();
                    filter.mesh = meshAndColors.mesh;

                    Vector3 shift = Vector3.zero; //new Vector3(script.singleCenter.x, 0, script.singleCenter.y);
                    while (transformNodeChunk != null)
                    {
                        if (transformNodeChunk.attributes.Count > 0 && transformNodeChunk.attributes.ContainsKey("_name"))
                        {
                            string name = transformNodeChunk.attributes["_name"];
                            script.names.Add(name);

                            if (names.Contains(name))
                            {
                                if (!doubleNames.Contains(name))
                                {
                                    doubleNames.Add(name);
                                }
                            }
                            else
                            {
                                names.Add(name);
                                namedGameObjects.Add(name, go);
                            }
                        }

                        if (transformNodeChunk.frameAttributes[0].ContainsKey("_r"))
                        {
                            script.rotations.Add(transformNodeChunk.frameAttributes[0]["_r"]);
                        }

                        Vector3[] rotationMatrix = getRotationMatrix(transformNodeChunk);
                        script.rotationMatrices.Add(rotationMatrix);

                        if (transformNodeChunk.frameAttributes[0].ContainsKey("_t"))
                        {
                            string[] coords       = transformNodeChunk.frameAttributes[0]["_t"].Split(' ');
                            Vector3  currentShift = new Vector3(float.Parse(coords[0]) / 10f, float.Parse(coords[2]) / 10f, float.Parse(coords[1]) / 10f);;
                            script.magicaTransitions.Add(currentShift);
                            shift += currentShift;
                        }
                        if (transformNodeChunk.group != null && transformNodeChunk.group.transform != null)
                        {
                            transformNodeChunk = transformNodeChunk.group.transform;
                        }
                        else
                        {
                            transformNodeChunk = null;
                        }
                    }

                    Vector3 ve = rotateVector(new Vector3(voxelChunk.sizeChunk.sizeX, voxelChunk.sizeChunk.sizeY, voxelChunk.sizeChunk.sizeZ), shape.transform);

                    script.magicaTotalSize = new Vector3(Math.Abs(ve.x), Math.Abs(ve.z), Math.Abs(ve.y));

                    script.bottomCenterOfVoxelMass = shape.singleCenter / 10f;

                    script.centerOfMagicaMass = new Vector3((float)Math.Floor((double)(Math.Abs(ve.x) / 2f)) / 10f, (float)Math.Floor((double)(Math.Abs(ve.z) / 2f)) / 10f, (float)Math.Floor((double)(Math.Abs(ve.y) / 2f)) / 10f);
                    script.parentVoxFile      = Path.GetFileName(path);
                    //shift -= script.trans;
                    shift += new Vector3(script.bottomCenterOfVoxelMass.x - script.centerOfMagicaMass.x, script.bottomCenterOfVoxelMass.y - script.centerOfMagicaMass.y, script.bottomCenterOfVoxelMass.z - script.centerOfMagicaMass.z);
                    //shift += (script.bottomCenterOfVoxelMass - script.centerOfMagicaMass);

                    go.transform.localScale = new Vector3(0.1f, 0.1f, 0.1f);
                    go.transform.position   = shift;

                    go.transform.parent = levelGo.transform;

                    if (script.names.Count > 0)
                    {
                        go.name = script.names[0];
                    }
                }
            }
        }

        // remove double named objects since we cannot insert them properly
        foreach (string name in doubleNames)
        {
            namedGameObjects.Remove(name);
        }

        foreach (GameObject g in gameObjects)
        {
            if (namedGameObjects.Values.Contains(g))
            {
                TeardownProperties teardownProperties = g.AddComponent <TeardownProperties>();
            }
        }

        return(levelGo);
    }
Exemplo n.º 6
0
		public static VoronoiGraph ComputeVoronoiGraph(IEnumerable Datapoints)
		{
			BinaryPriorityQueue PQ = new BinaryPriorityQueue();
			Hashtable CurrentCircles = new Hashtable();
			VoronoiGraph VG = new VoronoiGraph();
			VNode RootNode = null;
			foreach(Vector V in Datapoints)
			{
				PQ.Push(new VDataEvent(V));
			}
			while(PQ.Count>0)
			{
				VEvent VE = PQ.Pop() as VEvent;
				VDataNode[] CircleCheckList;
				if(VE is VDataEvent)
				{
					RootNode = VNode.ProcessDataEvent(VE as VDataEvent,RootNode,VG,VE.Y,out CircleCheckList);
				}
				else if(VE is VCircleEvent)
				{
					CurrentCircles.Remove(((VCircleEvent)VE).NodeN);
					if(!((VCircleEvent)VE).Valid)
						continue;
					RootNode = VNode.ProcessCircleEvent(VE as VCircleEvent,RootNode,VG,VE.Y,out CircleCheckList);
				}
				else throw new Exception("Got event of type "+VE.GetType().ToString()+"!");
				foreach(VDataNode VD in CircleCheckList)
				{
					if(CurrentCircles.ContainsKey(VD))
					{
						((VCircleEvent)CurrentCircles[VD]).Valid=false;
						CurrentCircles.Remove(VD);
					}
					VCircleEvent VCE = VNode.CircleCheckDataNode(VD,VE.Y);
					if(VCE!=null)
					{
						PQ.Push(VCE);
						CurrentCircles[VD]=VCE;
					}
				}
				if(VE is VDataEvent)
				{
					Vector DP = ((VDataEvent)VE).DataPoint;
					foreach(VCircleEvent VCE in CurrentCircles.Values)
					{
						if(MathTools.Dist(DP[0],DP[1],VCE.Center[0],VCE.Center[1])<VCE.Y-VCE.Center[1] && Math.Abs(MathTools.Dist(DP[0],DP[1],VCE.Center[0],VCE.Center[1])-(VCE.Y-VCE.Center[1]))>1e-10)
							VCE.Valid = false;
					}
				}
			}
			VNode.CleanUpTree(RootNode);
			foreach(VoronoiEdge VE in VG.Edges)
			{
				if(VE.Done)
					continue;
				if(VE.VVertexB == Fortune.VVUnkown)
				{
					VE.AddVertex(Fortune.VVInfinite);
					if(Math.Abs(VE.LeftData[1]-VE.RightData[1])<1e-10 && VE.LeftData[0]<VE.RightData[0])
					{
						Vector T = VE.LeftData;
						VE.LeftData = VE.RightData;
						VE.RightData = T;
					}
				}
			}
			
			ArrayList MinuteEdges = new ArrayList();
			foreach(VoronoiEdge VE in VG.Edges)
			{
				if(!VE.IsPartlyInfinite && VE.VVertexA.Equals(VE.VVertexB))
				{
					MinuteEdges.Add(VE);
					// prevent rounding errors from expanding to holes
					foreach(VoronoiEdge VE2 in VG.Edges)
					{
						if(VE2.VVertexA.Equals(VE.VVertexA))
							VE2.VVertexA = VE.VVertexA;
						if(VE2.VVertexB.Equals(VE.VVertexA))
							VE2.VVertexB = VE.VVertexA;
					}
				}
			}
			foreach(VoronoiEdge VE in MinuteEdges)
				VG.Edges.Remove(VE);

			return VG;
		}
Exemplo n.º 7
0
        public override void UpdatePointPosition(int index, Mouse3DPosition vertex)
        {
            if (SelectedEntity.TargetShape() == null)
            {
                return;
            }
            var  faceToChangeIndex = 0;
            Node nodeToChange      = null;
            var  faceShape         = new TopoDSShape();

            if (SelectedEntity.Node.Get <FunctionInterpreter>().Name == FunctionNames.Cut)
            {
                var nb             = new NodeBuilder(SelectedEntity.Node);
                var affectedShapes = NodeBuilderUtils.GetCutNodeBaseExtrudeNodes(nb).ToList();//nb.Dependency[3];
                var clickedPlane   = GeomUtils.ExtractPlane(SelectedEntity.TargetShape());
                if (clickedPlane == null)
                {
                    return;
                }
                foreach (var node in affectedShapes)
                {
                    var faces = GeomUtils.ExtractFaces(new NodeBuilder(node).Shape);
                    int count = 1;
                    foreach (var face in faces)
                    {
                        var direction = GeomUtils.ExtractPlane(face);
                        if (direction == null)
                        {
                            count++;
                            continue;
                        }
                        count++;
                        if (direction.Axis.Direction.IsParallel(clickedPlane.Axis.Direction, Precision.Confusion))
                        {
                            var projectedPnt = GeomUtils.ProjectPointOnPlane(direction.Location, clickedPlane, Precision.Confusion);
                            if (projectedPnt.IsEqual(direction.Location, Precision.Confusion))
                            {
                                faceShape = face;
                                break;
                            }
                        }
                    }

                    // if the face matches the clicked plane, count will be > 0 and will hold the face index on the extruded solid
                    if (count > 0)
                    {
                        faceToChangeIndex = count - 1;
                        nodeToChange      = node;
                        break;
                    }
                }
            }
            if (SelectedEntity.Node.Get <FunctionInterpreter>().Name == FunctionNames.Extrude)
            {
                faceToChangeIndex = SelectedEntity.ShapeCount;
                nodeToChange      = SelectedEntity.Node;
                faceShape         = SelectedEntity.TargetShape();
            }

            if (prevFaceCount < 0)
            {
                prevFaceCount = faceToChangeIndex;
            }
            if (faceToChangeIndex != prevFaceCount)
            {
                return;
            }
            if (nodeToChange == null)
            {
                return;
            }
            var distance      = 0.0;
            var numberOfFaces = GeomUtils.ExtractFaces(new NodeBuilder(nodeToChange).Shape).Count;

            if (faceToChangeIndex == numberOfFaces) //top of shape
            {
                distance = GeomUtils.CalculateDistance(vertex.Point.GpPnt,
                                                       new NodeBuilder(nodeToChange).Dependency[0].
                                                       ReferenceBuilder.Shape);

                var extrudeNb = new NodeBuilder(nodeToChange);
                if (Math.Abs(distance) < Precision.Confusion)
                {
                    distance = 0.1;
                }
                extrudeNb.Dependency[2].Real = distance;
                extrudeNb.ExecuteFunction();
            }

            if (faceToChangeIndex == (numberOfFaces - 1))
            {
                // bottom of shape - sketch which was extruded
                var extrudeNb       = new NodeBuilder(nodeToChange);
                var extrudeHeight   = extrudeNb.Dependency[2].Real;
                var baseSketch      = extrudeNb.Dependency[0].ReferenceBuilder;
                var faces           = GeomUtils.ExtractFaces(extrudeNb.Shape);
                var topFace         = faces[numberOfFaces - 1];
                var distanceTopFace = GeomUtils.CalculateDistance(vertex.Point.GpPnt,
                                                                  topFace);
                distance = GeomUtils.CalculateDistance(vertex.Point.GpPnt,
                                                       SelectedEntity.TargetShape());

                var dirBottomFace         = GeomUtils.ExtractDirection(SelectedEntity.TargetShape());
                var orientationBottomFace = SelectedEntity.TargetShape().Orientation();
                if (orientationBottomFace != TopAbsOrientation.TopAbs_REVERSED)
                {
                    dirBottomFace.Reverse();
                }
                var bottomFaceGravityCenter = GeomUtils.ExtractGravityCenter(topFace);
                var vertexOnDir             = TransformationInterpreter.ProjectPointOnLine(bottomFaceGravityCenter,
                                                                                           dirBottomFace, vertex.Point).Value;
                var startPointOnDir = TransformationInterpreter.ProjectPointOnLine(bottomFaceGravityCenter,
                                                                                   dirBottomFace, new Point3D(previousMousePosition)).Value;

                var vertexvector = new gpVec(startPointOnDir.GpPnt, vertexOnDir.GpPnt);
                var normalvector = new gpVec(dirBottomFace);
                var isOpposite   = false;
                try
                {
                    isOpposite = vertexvector.IsOpposite(normalvector, Precision.Angular);
                }
                catch { return; }
                // calculate new height for the solid
                var newHeight = 0.0;
                if (isOpposite)
                {
                    newHeight = Math.Abs(extrudeHeight) - Math.Abs(distance);
                }
                else
                {
                    newHeight = Math.Abs(extrudeHeight) + Math.Abs(distance);
                }
                newHeight *= Math.Sign(extrudeHeight);
                var face = SelectedEntity.TargetShape();
                if (face == null)
                {
                    return;
                }

                // calculate the new position for the solid
                var transformation = baseSketch.Node.Get <TransformationInterpreter>().CurrTransform;
                var locationOld    = new gpPnt(0, 0, 0).Transformed(transformation);
                var shape          = SelectedEntity.TargetShape();

                var dir         = GeomUtils.ExtractDirection(shape);
                var orientation = shape.Orientation();
                if (orientation != TopAbsOrientation.TopAbs_REVERSED)
                {
                    dir.Reverse();
                }
                if (isOpposite)
                {
                    dir.Reverse();
                }

                var locationNew = new gpPnt
                {
                    X = locationOld.X + dir.X * Math.Abs(distance),
                    Y = locationOld.Y + dir.Y * Math.Abs(distance),
                    Z = locationOld.Z + dir.Z * Math.Abs(distance)
                };

                // set the new transformation for the base sketch
                var T             = new gpTrsf();
                var oldSystemAxis = new gpAx3(new gpPnt(0, 0, 0), new gpDir(0, 0, 1));
                var newSystemAxis = new gpAx3(locationNew, dir);
                T.SetTransformation(oldSystemAxis, newSystemAxis);

                var transformationSet = baseSketch.Node.Set <TransformationInterpreter>();
                transformationSet.CurrTransform = T.Inverted;

                extrudeNb.Dependency[2].Real = newHeight;
                baseSketch.ExecuteFunction();
                previousMousePosition = vertex.Point.GpPnt;
            }

            if (faceToChangeIndex < (numberOfFaces - 1))
            {
                var         shape           = faceShape;
                var         gravityCenter   = GeomUtils.ExtractGravityCenter(shape);
                var         extrudeNb       = new NodeBuilder(nodeToChange);
                var         baseSketch      = extrudeNb.Dependency[0].ReferenceBuilder;
                var         transformation  = baseSketch.Node.Get <TransformationInterpreter>().CurrTransform;
                var         locationSketch  = new gpPnt(0, 0, 0).Transformed(transformation);
                var         directionSketch = new gpDir(0, 0, 1).Transformed(transformation);
                var         sketchPlane     = new gpPln(locationSketch, directionSketch);
                var         pointOnPlane    = new Point3D(GeomUtils.ProjectPointOnPlane(gravityCenter.GpPnt, sketchPlane, Precision.Confusion));
                var         sketchNodes     = NodeUtils.GetSketchNodes(baseSketch.Node, baseSketch.Node.Root.Get <DocumentContextInterpreter>().Document, true);
                NodeBuilder draggedLine     = null;
                foreach (var node in sketchNodes)
                {
                    var nb = new NodeBuilder(node);
                    if (nb.FunctionName != FunctionNames.LineTwoPoints)
                    {
                        continue;
                    }
                    var edges = GeomUtils.ExtractEdges(nb.Shape);
                    if (edges.Count != 1)
                    {
                        continue;
                    }
                    if (GeomUtils.PointIsOnEdge(edges[0], pointOnPlane))
                    {
                        draggedLine = nb;
                        break;
                    }
                }

                if (draggedLine != null)
                {
                    var axisLength    = CoreGlobalPreferencesSingleton.Instance.ZoomLevel * 10;
                    var faceDirection = GeomUtils.ExtractDirection(shape);
                    var orientation   = shape.Orientation();
                    if (orientation != TopAbsOrientation.TopAbs_REVERSED)
                    {
                        faceDirection.Reverse();
                    }
                    var vertexOnPlane = new Point3D(GeomUtils.ProjectPointOnPlane(vertex.Point.GpPnt, sketchPlane, Precision.Confusion));

                    vertexOnPlane.X = (vertexOnPlane.X) * Math.Abs(faceDirection.X);
                    vertexOnPlane.Y = (vertexOnPlane.Y) * Math.Abs(faceDirection.Y);
                    vertexOnPlane.Z = (vertexOnPlane.Z) * Math.Abs(faceDirection.Z);
                    var pointOnPlaneAxis = new Point3D
                    {
                        X = pointOnPlane.X * Math.Abs(faceDirection.X),
                        Y = pointOnPlane.Y * Math.Abs(faceDirection.Y),
                        Z = pointOnPlane.Z * Math.Abs(faceDirection.Z)
                    };
                    var translateValue = vertexOnPlane.SubstractCoordinate(pointOnPlaneAxis);
                    NodeUtils.TranslateSketchNode(draggedLine, translateValue, baseSketch.Node);
                    var constraintMapper = new ConstraintDocumentHelper(baseSketch.Node.Root.Get <DocumentContextInterpreter>().Document, baseSketch.Node);
                    constraintMapper.SetMousePosition(draggedLine.Dependency[0].Reference.Index);
                    var error = constraintMapper.ImpactAndSolve(draggedLine.Dependency[1].Node.Get <ReferenceInterpreter>().Node);
                    baseSketch.ExecuteFunction();
                    extrudeNb.Color = solidColor;
                    extrudeNb.ExecuteFunction();
                }
            }
        }
Exemplo n.º 8
0
        private void Client_TimeReceived(object sender, NtpTimeReceivedEventArgs e)
        {
            this.buttonPingNTPServer.Visible = true;

            TimeSpan timeDifference = OtpTime.getTime().Subtract(e.CurrentTime);

            this.Invoke((Action)(() =>
            {
                if (-5000 < timeDifference.TotalMilliseconds && timeDifference.TotalMilliseconds < 5000)
                {
                    MessageBox.Show(String.Format(KeeOtp2Statics.TroubleshootingPingResultOk, Math.Round(Math.Abs(timeDifference.TotalMilliseconds)), Math.Round(Math.Abs((float)timeDifference.TotalMilliseconds / 1000), 1), (timeDifference.TotalMilliseconds < 0 ? "behind" : "before")), "NTP Request", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else if (-30000 < timeDifference.TotalMilliseconds && timeDifference.TotalMilliseconds < 30000)
                {
                    MessageBox.Show(String.Format(KeeOtp2Statics.TroubleshootingPingResultModerate, Math.Round(Math.Abs(timeDifference.TotalMilliseconds)), Math.Round(Math.Abs((float)timeDifference.TotalMilliseconds / 1000), 1), (timeDifference.TotalMilliseconds < 0 ? "behind" : "before")), "NTP Request", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show(String.Format(KeeOtp2Statics.TroubleshootingPingResultBad, Math.Round(Math.Abs(timeDifference.TotalMilliseconds)), Math.Round(Math.Abs((float)timeDifference.TotalMilliseconds / 1000), 1), (timeDifference.TotalMilliseconds < 0 ? "behind" : "before")), "NTP Request", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }));
            this.Enabled = true;
        }
Exemplo n.º 9
0
 public static Vector2 Abs(this Vector2 v)
 {
     return(new Vector2(Math.Abs(v.X), Math.Abs(v.Y)));
 }
Exemplo n.º 10
0
        public WindowManager(Viewer viewer)
        {
            Viewer = viewer;
            WindowManagerMaterial   = new BasicBlendedMaterial(viewer, "WindowManager");
            PopupWindowMaterial     = (PopupWindowMaterial)Viewer.MaterialManager.Load("PopupWindow");
            SpriteBatchMaterial     = (SpriteBatchMaterial)Viewer.MaterialManager.Load("SpriteBatch");
            TextManager             = new WindowTextManager();
            TextFontDefault         = TextManager.GetScaled("Arial", 10, System.Drawing.FontStyle.Regular);
            TextFontDefaultOutlined = TextManager.GetScaled("Arial", 10, System.Drawing.FontStyle.Regular, 1);
            TextFontSmall           = TextManager.GetScaled("Arial", 8, System.Drawing.FontStyle.Regular);
            TextFontSmallOutlined   = TextManager.GetScaled("Arial", 8, System.Drawing.FontStyle.Regular, 1);

            SpriteBatch = new SpriteBatch(Viewer.GraphicsDevice);

            if (WhiteTexture == null)
            {
                WhiteTexture = new Texture2D(Viewer.GraphicsDevice, 1, 1, false, SurfaceFormat.Color);
                WhiteTexture.SetData(new[] { Color.White });
            }
            if (FlushTexture == null)
            {
                FlushTexture = new Texture2D(Viewer.GraphicsDevice, 1, 1, false, SurfaceFormat.Color);
                FlushTexture.SetData(new[] { Color.Transparent });
            }
            if (ScrollbarTexture == null)
            {
                // TODO: This should happen on the loader thread.
                ScrollbarTexture = SharedTextureManager.Get(Viewer.RenderProcess.GraphicsDevice, System.IO.Path.Combine(Viewer.ContentPath, "WindowScrollbar.png"));
            }
            if (LabelShadowTexture == null)
            {
                // TODO: This should happen on the loader thread.
                LabelShadowTexture = SharedTextureManager.Get(Viewer.RenderProcess.GraphicsDevice, System.IO.Path.Combine(Viewer.ContentPath, "WindowLabelShadow.png"));
            }
            if (NoticeTexture == null)
            {
                var size         = 256;
                var background   = new Color(Color.Black, 0.5f);
                var borderRadius = size / 7;
                var data         = new Color[size * size * 2];

                // Rounded corner background.
                for (var y = 0; y < size; y++)
                {
                    for (var x = 0; x < size; x++)
                    {
                        if ((x > borderRadius && x < size - borderRadius) || (y > borderRadius && y < size - borderRadius) ||
                            (Math.Sqrt((x - borderRadius) * (x - borderRadius) + (y - borderRadius) * (y - borderRadius)) < borderRadius) ||
                            (Math.Sqrt((x - size + borderRadius) * (x - size + borderRadius) + (y - borderRadius) * (y - borderRadius)) < borderRadius) ||
                            (Math.Sqrt((x - borderRadius) * (x - borderRadius) + (y - size + borderRadius) * (y - size + borderRadius)) < borderRadius) ||
                            (Math.Sqrt((x - size + borderRadius) * (x - size + borderRadius) + (y - size + borderRadius) * (y - size + borderRadius)) < borderRadius))
                        {
                            data[y * size + x] = background;
                        }
                    }
                }

                // Notice texture is just the rounded corner background.
                NoticeTexture = new Texture2D(Viewer.GraphicsDevice, size, size, false, SurfaceFormat.Color);
                NoticeTexture.SetData(data, 0, size * size);

                // Clone the background for pause texture (it has two states).
                Array.Copy(data, 0, data, size * size, size * size);

                // Play ">" symbol.
                for (var y = size / 7; y < size - size / 7; y++)
                {
                    for (var x = size / 7; x < size - size / 7 - 2 * Math.Abs(y - size / 2); x++)
                    {
                        data[y * size + x] = Color.White;
                    }
                }

                // Pause "||" symbol.
                for (var y = size + size / 7; y < 2 * size - size / 7; y++)
                {
                    for (var x = size * 2 / 7; x < size * 3 / 7; x++)
                    {
                        data[y * size + x] = Color.White;
                    }
                    for (var x = size * 4 / 7; x < size * 5 / 7; x++)
                    {
                        data[y * size + x] = Color.White;
                    }
                }

                PauseTexture = new Texture2D(Viewer.GraphicsDevice, size, size * 2, false, SurfaceFormat.Color);
                PauseTexture.SetData(data);
            }
        }
Exemplo n.º 11
0
        protected override void OnPaint(PaintEventArgs e)
        {
            e.Graphics.CompositingMode = CompositingMode.SourceOver;
            int scaledSwatchSize = UI.ScaleWidth(this.unscaledSwatchSize);
            int swatchColumns = this.ClientSize.Width / scaledSwatchSize;

            Point mousePt = Control.MousePosition;
            mousePt = PointToClient(mousePt);
            int activeIndex = MouseXYToColorIndex(mousePt.X, mousePt.Y);

            for (int i = 0; i < this.colors.Count; ++i)
            {
                ColorBgra c = this.colors[i];

                int swatchX = i % swatchColumns;
                int swatchY = i / swatchColumns;

                Rectangle swatchRect = new Rectangle(
                    swatchX * scaledSwatchSize,
                    swatchY * scaledSwatchSize,
                    scaledSwatchSize,
                    scaledSwatchSize);

                PushButtonState state;

                if (this.mouseDown)
                {
                    if (i == this.mouseDownIndex)
                    {
                        state = PushButtonState.Pressed;
                    }
                    else
                    {
                        state = PushButtonState.Normal;
                    }
                }
                else if (i == activeIndex)
                {
                    state = PushButtonState.Hot;
                }
                else
                {
                    state = PushButtonState.Normal;
                }

                bool drawOutline;

                switch (state)
                {
                    case PushButtonState.Hot:
                        drawOutline = true;
                        break;

                    case PushButtonState.Pressed:
                        drawOutline = false;
                        break;

                    case PushButtonState.Default:
                    case PushButtonState.Disabled:
                    case PushButtonState.Normal:
                        drawOutline = false;
                        break;

                    default:
                        throw new InvalidEnumArgumentException();
                }

                Utility.DrawColorRectangle(e.Graphics, swatchRect, c.ToColor(), drawOutline);
            }

            if (this.blinkHighlight)
            {
                int period = (Math.Abs(Environment.TickCount) / blinkInterval) % 2;
                Color color;

                switch (period)
                {
                    case 0:
                        color = SystemColors.Window;
                        break;

                    case 1:
                        color = SystemColors.Highlight;
                        break;

                    default:
                        throw new InvalidOperationException();
                }

                using (Pen pen = new Pen(color))
                {
                    e.Graphics.DrawRectangle(pen, new Rectangle(0, 0, Width - 1, Height - 1));
                }
            }

            base.OnPaint(e);
        }
Exemplo n.º 12
0
 string directionStr(int f) => f < 0 ? $"Lost {Math.Abs(f)}" : $"Gained {f}";
Exemplo n.º 13
0
 string directionStr(double f) => f < 0d ? $"Lost {Math.Abs(f)}" : $"Gained {f}";
Exemplo n.º 14
0
 string directionStr(float f) => f < 0f ? $"Lost {Math.Abs(f)}" : $"Gained {f}";
Exemplo n.º 15
0
        /// <summary>
        /// Calculates whether a number is approximately equal to another using the threshold
        /// </summary>
        /// <param name="x">The first value</param>
        /// <param name="y">The second value</param>
        /// <returns>Whether the values are equal within the threshold</returns>
        private static bool ApproximatelyEquals(double x, double y)
        {
            double actualDifference = Math.Abs(x - y);

            return(actualDifference <= Threshold);
        }
Exemplo n.º 16
0
 public static Vector3 Abs(this Vector3 v)
 {
     return(new Vector3(Math.Abs(v.X), Math.Abs(v.Y), Math.Abs(v.Z)));
 }
Exemplo n.º 17
0
        public ActionResult<List<string>> Post([FromForm] string matrixString, [FromForm] string sequenceString, [FromForm] int bufferSize)
        {
            _logger.LogInformation($"Performing solve over {matrixString} for {sequenceString} with length {bufferSize}");
            if (string.IsNullOrWhiteSpace(matrixString) || string.IsNullOrWhiteSpace(sequenceString) || bufferSize <= 0)
            {
                _logger.LogError("Matrix, sequence, or memory size missing or invalid");
                return BadRequest(new List<string>() { "Missing matrix, sequence, or memory size" });
            }

            List<string> matrix = matrixString.Split(",").ToList();
            List<string> sequences = sequenceString.Split(",").ToList();

            // Make sure that each row has the right number of cells and matches the count
            List<string> errors = new List<string>();
            matrix.ForEach(x =>
            {
                if (x.Length % 2 != 0)
                {
                    _logger.LogError($"Matrix row '{x}' is not a multiple of 2 characters");
                    errors.Add($"Matrix row '{x}' is not a multiple of 2 characters");
                    return;
                }

                if (Math.Floor((double)x.Length / 2) != matrix.Count)
                {
                    _logger.LogError($"Matrix row '{x}' does permit a square matrix");
                    errors.Add($"Matrix row '{x}' does permit a square matrix");
                    return;
                }
            });

            // Validate each of the sequences
            sequences.ForEach(x =>
            {
                var parts = x.Split("=").ToList();
                var seq = parts.First();
                var value = parts.ElementAtOrDefault(1);

                if (seq.Length % 2 != 0)
                {
                    _logger.LogError($"Sequence '{x}' is not a multiple of two characters");
                    errors.Add($"Sequence '{x}' is not a multiple of two characters");
                    return;
                }

                if (!String.IsNullOrWhiteSpace(value) && !int.TryParse(value, out int iValue))
                {
                    _logger.LogError($"Sequence value for '{x}' is not a valid integer");
                    errors.Add($"Sequence value for '{x}' is not a valid integer");
                    return;
                }
            });

            // Error out on validation if needed
            if (errors.Count > 0)
                return BadRequest(errors);

            // Since we got this far, we know we have a square matrix based on comma splices
            int height = matrix.Count;
            int width = height;

            _logger.LogInformation($"Creating a {width} wide, by {height} tall matrix with buffer size {bufferSize}");

            // Createa the solver and send in all the rows
            Solver s = new Solver(height, width) { BufferSize = bufferSize };
            for (int i = 0; i < matrix.Count; i++)
                s.SetRow(i, matrix[i]);

            // Figure out the sequences to solve and send those in
            for (int i = 0; i < sequences.Count; i++)
            {
                var parts = sequences[i].Split("=").ToList();
                var seq = parts.First();
                var value = parts.ElementAtOrDefault(1);
                int iValue = i + 1;
                if (!String.IsNullOrWhiteSpace(value))
                    iValue = int.Parse(value);

                s.AddSequence(seq, iValue);
            }

            Sequence result = null;
            try
            {
                _logger.LogInformation("Solving matrix");
                // Go ahead and solve it 
                result = s.Solve();
                _logger.LogInformation("Solution found");
            }
            catch (Exception e)
            {
                _logger.LogError("Exception occurred during the solve", e);
                return StatusCode(500, new { message = e.Message });
            }


            // No results means no solution
            if (result == null || result.SolvedValues.Count == 0)
            {
                _logger.LogWarning("No solution found");
                return NotFound(new List<string>() { "No solution found" });
            }

            string letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            List<string> resultStr = new List<string>
            {
                // Pretty print the solution
                $"Best solution:",
                $"  Solved: {String.Join(", ", result.SolvedValues)} for {result.Value} total",
                $"  Start Chain: {result.Used}",
                $"  Solution:"
            };

            Cell prev = null;
            for (int i = 0; i < result.Cells.Count; i++)
            {
                Cell c = result.Cells[i];
                if (i == 0)
                {
                    resultStr.Add($"    Start in column {letters[c.Column]} at {c.Value} ({c.Row + 1},{letters[c.Column]})");
                    prev = c;
                }
                else 
                {
                    string movement = "";
                    int horiz = c.Column - prev.Column;
                    int vert = c.Row - prev.Row;
                    if (horiz != 0)
                        movement = $"{Math.Abs(horiz)} {(horiz > 0 ? "right" : "left ")}";
                    else
                        movement = $"{Math.Abs(vert)} {(vert > 0 ? "down " : "up   ")}";

                    resultStr.Add($"    {movement} to {c.Value} ({c.Row + 1},{letters[c.Column]})");
                    prev = c;
                }
            }
            //resultStr.Add("  Old Solution:");
            //result.Cells.ForEach(c => resultStr.Add($"    {c.Value} ({c.Row + 1},{letters[c.Column]})"));

            return Ok(resultStr);
        }
Exemplo n.º 18
0
 public static Vector4 Abs(this Vector4 v)
 {
     return(new Vector4(Math.Abs(v.X), Math.Abs(v.Y), Math.Abs(v.Z), Math.Abs(v.W)));
 }
        /// <summary>
        /// Translate the number in words (English)
        /// </summary>
        /// <param name="value">Number to translate</param>
        /// <returns>String</returns>
        public static string ToWords(this int value)
        {
            if (value == 0)
            {
                return("Zero");
            }

            if (value < 0)
            {
                return("Minus " + ToWords(Math.Abs(value)));
            }

            var words = string.Empty;

            if ((value / 1000000) > 0)
            {
                words += ToWords(value / 1000000) + " million ";
                value %= 1000000;
            }

            if ((value / 1000) > 0)
            {
                words += ToWords(value / 1000) + " Thousand ";
                value %= 1000;
            }

            if ((value / 100) > 0)
            {
                words += ToWords(value / 100) + " Hundred ";
                value %= 100;
            }

            if (value > 0)
            {
                if (string.IsNullOrEmpty(words) == false)
                {
                    words += "and ";
                }

                var units = new[]
                {
                    "Zero",
                    "One",
                    "Two",
                    "Three",
                    "Four",
                    "Five",
                    "Six",
                    "Seven",
                    "Eight",
                    "Nine",
                    "Ten",
                    "Eleven",
                    "Twelve",
                    "Thirteen",
                    "Fourteen",
                    "Fifteen",
                    "Sixteen",
                    "Seventeen",
                    "Eighteen",
                    "Nineteen"
                };
                var tens = new[]
                { "Zero", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" };

                if (value < 20)
                {
                    words += units[value];
                }
                else
                {
                    words += tens[value / 10];

                    if ((value % 10) > 0)
                    {
                        words += "-" + units[value % 10];
                    }
                }
            }

            return(words);
        }
Exemplo n.º 20
0
        public override void DrawOrMove(ChartPoint previousDrawn, ChartPoint current, int index, ChartCore chart)
        {
            if (IsNew)
            {
                Slice.Width  = chart.DrawMargin.Width;
                Slice.Height = chart.DrawMargin.Height;

                Slice.WedgeAngle    = 0;
                Slice.RotationAngle = 0;
            }

            if (DataLabel != null && double.IsNaN(Canvas.GetLeft(DataLabel)))
            {
                Canvas.SetTop(DataLabel, chart.DrawMargin.Height / 2);
                Canvas.SetLeft(DataLabel, chart.DrawMargin.Width / 2);
            }

            if (HoverShape != null)
            {
                var hs = (PieSlice)HoverShape;

                hs.Width         = chart.DrawMargin.Width;
                hs.Height        = chart.DrawMargin.Height;
                hs.WedgeAngle    = Wedge;
                hs.RotationAngle = Rotation;
                hs.InnerRadius   = InnerRadius;
                hs.Radius        = Radius;
            }

            Slice.Width  = chart.DrawMargin.Width;
            Slice.Height = chart.DrawMargin.Height;

            var lh = 0d;

            if (DataLabel != null)
            {
                DataLabel.UpdateLayout();
                lh = DataLabel.ActualHeight;
            }

            var hypo = ((PieSeries)current.SeriesView).LabelPosition == PieLabelPosition.InsideSlice
                ? (Radius + InnerRadius) * (Math.Abs(InnerRadius) < 0.01 ? .65 : .5)
                : Radius + lh;
            var gamma = current.Participation * 360 / 2 + Rotation;
            var cp    = new Point(hypo * Math.Sin(gamma * (Math.PI / 180)), hypo * Math.Cos(gamma * (Math.PI / 180)));

            if (chart.View.DisableAnimations)
            {
                Slice.InnerRadius   = InnerRadius;
                Slice.Radius        = Radius;
                Slice.WedgeAngle    = Wedge;
                Slice.RotationAngle = Rotation;
                Canvas.SetTop(Slice, chart.DrawMargin.Height / 2);
                Canvas.SetLeft(Slice, chart.DrawMargin.Width / 2);

                if (DataLabel != null)
                {
                    DataLabel.UpdateLayout();

                    var lx = cp.X + chart.DrawMargin.Width / 2 - DataLabel.ActualWidth * .5;
                    var ly = chart.DrawMargin.Height / 2 - cp.Y - DataLabel.ActualHeight * .5;

                    Canvas.SetLeft(DataLabel, lx);
                    Canvas.SetTop(DataLabel, ly);
                }

                return;
            }

            var animSpeed = chart.View.AnimationsSpeed;

            if (DataLabel != null)
            {
                DataLabel.UpdateLayout();

                var lx = cp.X + chart.DrawMargin.Width / 2 - DataLabel.ActualWidth * .5;
                var ly = chart.DrawMargin.Height / 2 - cp.Y - DataLabel.ActualHeight * .5;

                DataLabel.CreateCanvasStoryBoardAndBegin(lx, ly, animSpeed);
            }

            Slice.BeginDoubleAnimation("(Canvas.Left)", chart.DrawMargin.Width / 2, animSpeed);
            Slice.BeginDoubleAnimation("(Canvas.Top)", chart.DrawMargin.Height / 2, animSpeed);
            Slice.BeginDoubleAnimation(nameof(PieSlice.InnerRadius), InnerRadius, animSpeed);
            Slice.BeginDoubleAnimation(nameof(PieSlice.Radius), Radius, animSpeed);
            Slice.BeginDoubleAnimation(nameof(PieSlice.WedgeAngle), Wedge, animSpeed);
            Slice.BeginDoubleAnimation(nameof(PieSlice.RotationAngle), Rotation, animSpeed);
        }
Exemplo n.º 21
0
 /*****************************************************************************
 *  EVENT HANDLER:  btnShowCorrelation_Click
 *  Description:
 *  Parameters:
 *****************************************************************************/
 private void btnShowCorrelation_Click(object sender, EventArgs e)
 {
     BtnShowState = Math.Abs(BtnShowState - 1);
     SendMessage(Application.OpenForms[0].Handle, WM_SHOWBTNCLICK, (IntPtr)BtnShowState, IntPtr.Zero);
 }
Exemplo n.º 22
0
 static bool CheckEQ(float a, float b)
 {
     return(Math.Abs(a - b) < EPS);
 }
Exemplo n.º 23
0
        /// <summary>
        /// MACD of independent MA types
        /// </summary>
        /// <returns></returns>
        public zMaMacd zMaMacd(Data.IDataSeries input, RWT_MA.MAType aType1, RWT_MA.MAType aType2, double len1, double len2)
        {
            if (cachezMaMacd != null)
                for (int idx = 0; idx < cachezMaMacd.Length; idx++)
                    if (cachezMaMacd[idx].AType1 == aType1 && cachezMaMacd[idx].AType2 == aType2 && Math.Abs(cachezMaMacd[idx].Len1 - len1) <= double.Epsilon && Math.Abs(cachezMaMacd[idx].Len2 - len2) <= double.Epsilon && cachezMaMacd[idx].EqualsInput(input))
                        return cachezMaMacd[idx];

            lock (checkzMaMacd)
            {
                checkzMaMacd.AType1 = aType1;
                aType1 = checkzMaMacd.AType1;
                checkzMaMacd.AType2 = aType2;
                aType2 = checkzMaMacd.AType2;
                checkzMaMacd.Len1 = len1;
                len1 = checkzMaMacd.Len1;
                checkzMaMacd.Len2 = len2;
                len2 = checkzMaMacd.Len2;

                if (cachezMaMacd != null)
                    for (int idx = 0; idx < cachezMaMacd.Length; idx++)
                        if (cachezMaMacd[idx].AType1 == aType1 && cachezMaMacd[idx].AType2 == aType2 && Math.Abs(cachezMaMacd[idx].Len1 - len1) <= double.Epsilon && Math.Abs(cachezMaMacd[idx].Len2 - len2) <= double.Epsilon && cachezMaMacd[idx].EqualsInput(input))
                            return cachezMaMacd[idx];

                zMaMacd indicator = new zMaMacd();
                indicator.BarsRequired = BarsRequired;
                indicator.CalculateOnBarClose = CalculateOnBarClose;
#if NT7
                indicator.ForceMaximumBarsLookBack256 = ForceMaximumBarsLookBack256;
                indicator.MaximumBarsLookBack = MaximumBarsLookBack;
#endif
                indicator.Input = input;
                indicator.AType1 = aType1;
                indicator.AType2 = aType2;
                indicator.Len1 = len1;
                indicator.Len2 = len2;
                Indicators.Add(indicator);
                indicator.SetUp();

                zMaMacd[] tmp = new zMaMacd[cachezMaMacd == null ? 1 : cachezMaMacd.Length + 1];
                if (cachezMaMacd != null)
                    cachezMaMacd.CopyTo(tmp, 0);
                tmp[tmp.Length - 1] = indicator;
                cachezMaMacd = tmp;
                return indicator;
            }
        }
Exemplo n.º 24
0
        public double GetSquared()
        {
            if (DistanceSquared >= 0)
            {
                return(DistanceSquared);
            }

            Vector3d diff  = triangle.V0 - point;
            Vector3d edge0 = triangle.V1 - triangle.V0;
            Vector3d edge1 = triangle.V2 - triangle.V0;
            double   a00   = edge0.LengthSquared;
            double   a01   = edge0.Dot(edge1);
            double   a11   = edge1.LengthSquared;
            double   b0    = diff.Dot(edge0);
            double   b1    = diff.Dot(edge1);
            double   c     = diff.LengthSquared;
            double   det   = Math.Abs(a00 * a11 - a01 * a01);
            double   s     = a01 * b1 - a11 * b0;
            double   t     = a01 * b0 - a00 * b1;
            double   sqrDistance;

            if (s + t <= det)
            {
                if (s < 0)
                {
                    if (t < 0)  // region 4
                    {
                        if (b0 < 0)
                        {
                            t = 0;
                            if (-b0 >= a00)
                            {
                                s           = 1;
                                sqrDistance = a00 + (2) * b0 + c;
                            }
                            else
                            {
                                s           = -b0 / a00;
                                sqrDistance = b0 * s + c;
                            }
                        }
                        else
                        {
                            s = 0;
                            if (b1 >= 0)
                            {
                                t           = 0;
                                sqrDistance = c;
                            }
                            else if (-b1 >= a11)
                            {
                                t           = 1;
                                sqrDistance = a11 + (2) * b1 + c;
                            }
                            else
                            {
                                t           = -b1 / a11;
                                sqrDistance = b1 * t + c;
                            }
                        }
                    }
                    else    // region 3
                    {
                        s = 0;
                        if (b1 >= 0)
                        {
                            t           = 0;
                            sqrDistance = c;
                        }
                        else if (-b1 >= a11)
                        {
                            t           = 1;
                            sqrDistance = a11 + (2) * b1 + c;
                        }
                        else
                        {
                            t           = -b1 / a11;
                            sqrDistance = b1 * t + c;
                        }
                    }
                }
                else if (t < 0)    // region 5
                {
                    t = 0;
                    if (b0 >= 0)
                    {
                        s           = 0;
                        sqrDistance = c;
                    }
                    else if (-b0 >= a00)
                    {
                        s           = 1;
                        sqrDistance = a00 + (2) * b0 + c;
                    }
                    else
                    {
                        s           = -b0 / a00;
                        sqrDistance = b0 * s + c;
                    }
                }
                else    // region 0
                {
                    // minimum at interior point
                    double invDet = (1) / det;
                    s          *= invDet;
                    t          *= invDet;
                    sqrDistance = s * (a00 * s + a01 * t + (2) * b0) +
                                  t * (a01 * s + a11 * t + (2) * b1) + c;
                }
            }
            else
            {
                double tmp0, tmp1, numer, denom;

                if (s < 0)  // region 2
                {
                    tmp0 = a01 + b0;
                    tmp1 = a11 + b1;
                    if (tmp1 > tmp0)
                    {
                        numer = tmp1 - tmp0;
                        denom = a00 - (2) * a01 + a11;
                        if (numer >= denom)
                        {
                            s           = 1;
                            t           = 0;
                            sqrDistance = a00 + (2) * b0 + c;
                        }
                        else
                        {
                            s           = numer / denom;
                            t           = 1 - s;
                            sqrDistance = s * (a00 * s + a01 * t + (2) * b0) +
                                          t * (a01 * s + a11 * t + (2) * b1) + c;
                        }
                    }
                    else
                    {
                        s = 0;
                        if (tmp1 <= 0)
                        {
                            t           = 1;
                            sqrDistance = a11 + (2) * b1 + c;
                        }
                        else if (b1 >= 0)
                        {
                            t           = 0;
                            sqrDistance = c;
                        }
                        else
                        {
                            t           = -b1 / a11;
                            sqrDistance = b1 * t + c;
                        }
                    }
                }
                else if (t < 0)    // region 6
                {
                    tmp0 = a01 + b1;
                    tmp1 = a00 + b0;
                    if (tmp1 > tmp0)
                    {
                        numer = tmp1 - tmp0;
                        denom = a00 - (2) * a01 + a11;
                        if (numer >= denom)
                        {
                            t           = 1;
                            s           = 0;
                            sqrDistance = a11 + (2) * b1 + c;
                        }
                        else
                        {
                            t           = numer / denom;
                            s           = 1 - t;
                            sqrDistance = s * (a00 * s + a01 * t + (2) * b0) +
                                          t * (a01 * s + a11 * t + (2) * b1) + c;
                        }
                    }
                    else
                    {
                        t = 0;
                        if (tmp1 <= 0)
                        {
                            s           = 1;
                            sqrDistance = a00 + (2) * b0 + c;
                        }
                        else if (b0 >= 0)
                        {
                            s           = 0;
                            sqrDistance = c;
                        }
                        else
                        {
                            s           = -b0 / a00;
                            sqrDistance = b0 * s + c;
                        }
                    }
                }
                else    // region 1
                {
                    numer = a11 + b1 - a01 - b0;
                    if (numer <= 0)
                    {
                        s           = 0;
                        t           = 1;
                        sqrDistance = a11 + (2) * b1 + c;
                    }
                    else
                    {
                        denom = a00 - (2) * a01 + a11;
                        if (numer >= denom)
                        {
                            s           = 1;
                            t           = 0;
                            sqrDistance = a00 + (2) * b0 + c;
                        }
                        else
                        {
                            s           = numer / denom;
                            t           = 1 - s;
                            sqrDistance = s * (a00 * s + a01 * t + (2) * b0) +
                                          t * (a01 * s + a11 * t + (2) * b1) + c;
                        }
                    }
                }
            }

            // Account for numerical round-off error.
            if (sqrDistance < 0)
            {
                sqrDistance = 0;
            }
            DistanceSquared = sqrDistance;

            TriangleClosest    = triangle.V0 + s * edge0 + t * edge1;
            TriangleBaryCoords = new Vector3d(1 - s - t, s, t);
            return(sqrDistance);
        }
Exemplo n.º 25
0
    public GameObject ImportMagicaVoxelFileAssets(string path)
    {
        GameObject levelGo = new GameObject(Path.GetFileName(path));

        string fileName = Path.GetFileName(path);

        List <GameObject> gameObjects = new List <GameObject>();
        Dictionary <string, GameObject> namedGameObjects = new Dictionary <string, GameObject>();

        Chunk           mainChunk      = MagicaVoxelReader.ReadMagicaChunks(path);
        List <Material> colorMaterials = ImportColors(mainChunk);
        List <string>   names          = new List <string>();
        List <string>   doubleNames    = new List <string>();

        string localPath      = AssetDatabase.GenerateUniqueAssetPath(Path.Combine("Assets", "ImportedPrefabs", fileName));
        string materialFolder = Path.Combine("Assets", "ImportedPrefabs", fileName, "Materials");
        string meshFolder     = Path.Combine("Assets", "ImportedPrefabs", fileName, "Meshes");

        if (!AssetDatabase.IsValidFolder(localPath))
        {
            AssetDatabase.CreateFolder(Path.Combine("Assets", "ImportedPrefabs"), fileName);
        }
        if (!AssetDatabase.IsValidFolder(materialFolder))
        {
            AssetDatabase.CreateFolder(localPath, "Materials");
        }
        if (!AssetDatabase.IsValidFolder(meshFolder))
        {
            AssetDatabase.CreateFolder(localPath, "Meshes");
        }

        for (int m = 0; m < colorMaterials.Count; m++)
        {
            AssetDatabase.CreateAsset(colorMaterials[m], Path.Combine(materialFolder, "Color_" + m + ".mat"));
        }

        for (int i = 0; i < mainChunk.children.Count; i++)
        {
            Chunk chunk = mainChunk.children[i];
            if (chunk is VoxelModelChunk)
            {
                VoxelModelChunk voxelChunk = (VoxelModelChunk)chunk;

                foreach (ShapeNodeChunk shape in voxelChunk.shapes)
                {
                    TransformNodeChunk transformNodeChunk = shape.transform;

                    bool isPotentialAsset = false;
                    while (transformNodeChunk != null)
                    {
                        if (transformNodeChunk.attributes.Count > 0 && transformNodeChunk.attributes.ContainsKey("_name"))
                        {
                            isPotentialAsset = true;
                            break;
                        }
                    }
                    if (!isPotentialAsset)
                    {
                        continue;
                    }

                    MeshAndColors   meshAndColors = createMesh(voxelChunk, shape);
                    List <Material> materials     = new List <Material>();
                    foreach (int color in meshAndColors.colors)
                    {
                        materials.Add(colorMaterials[color - 1]);
                    }

                    GameObject go = new GameObject();
                    gameObjects.Add(go);
                    ObjectAttributes script = go.AddComponent <ObjectAttributes>();

                    MeshRenderer renderer = go.AddComponent <MeshRenderer>();
                    renderer.materials = materials.ToArray();
                    MeshFilter filter = go.AddComponent <MeshFilter>();
                    filter.mesh = meshAndColors.mesh;

                    Vector3 shift = Vector3.zero; //new Vector3(script.singleCenter.x, 0, script.singleCenter.y);
                    while (transformNodeChunk != null)
                    {
                        if (transformNodeChunk.attributes.Count > 0 && transformNodeChunk.attributes.ContainsKey("_name"))
                        {
                            string name = transformNodeChunk.attributes["_name"];
                            script.names.Add(name);

                            if (names.Contains(name))
                            {
                                if (!doubleNames.Contains(name))
                                {
                                    doubleNames.Add(name);
                                }
                            }
                            else
                            {
                                names.Add(name);
                                namedGameObjects.Add(name, go);
                            }
                        }

                        if (transformNodeChunk.frameAttributes[0].ContainsKey("_r"))
                        {
                            script.rotations.Add(transformNodeChunk.frameAttributes[0]["_r"]);
                        }

                        Vector3[] rotationMatrix = getRotationMatrix(transformNodeChunk);
                        script.rotationMatrices.Add(rotationMatrix);

                        if (transformNodeChunk.frameAttributes[0].ContainsKey("_t"))
                        {
                            string[] coords       = transformNodeChunk.frameAttributes[0]["_t"].Split(' ');
                            Vector3  currentShift = new Vector3(float.Parse(coords[0]) / 10f, float.Parse(coords[2]) / 10f, float.Parse(coords[1]) / 10f);;
                            script.magicaTransitions.Add(currentShift);
                            shift += currentShift;
                        }
                        if (transformNodeChunk.group != null && transformNodeChunk.group.transform != null)
                        {
                            transformNodeChunk = transformNodeChunk.group.transform;
                        }
                        else
                        {
                            transformNodeChunk = null;
                        }
                    }

                    Vector3 ve = rotateVector(new Vector3(voxelChunk.sizeChunk.sizeX, voxelChunk.sizeChunk.sizeY, voxelChunk.sizeChunk.sizeZ), shape.transform);

                    script.magicaTotalSize = new Vector3(Math.Abs(ve.x), Math.Abs(ve.z), Math.Abs(ve.y));

                    script.bottomCenterOfVoxelMass = shape.singleCenter / 10f;

                    script.centerOfMagicaMass = new Vector3((float)Math.Floor((double)(Math.Abs(ve.x) / 2f)) / 10f, (float)Math.Floor((double)(Math.Abs(ve.z) / 2f)) / 10f, (float)Math.Floor((double)(Math.Abs(ve.y) / 2f)) / 10f);
                    script.parentVoxFile      = Path.GetFileName(path);
                    //shift -= script.trans;
                    shift += new Vector3(script.bottomCenterOfVoxelMass.x - script.centerOfMagicaMass.x, script.bottomCenterOfVoxelMass.y - script.centerOfMagicaMass.y, script.bottomCenterOfVoxelMass.z - script.centerOfMagicaMass.z);
                    //shift += (script.bottomCenterOfVoxelMass - script.centerOfMagicaMass);

                    go.transform.localScale = new Vector3(0.1f, 0.1f, 0.1f);
                    go.transform.position   = shift;
                    go.name             = script.names[0];
                    go.transform.parent = levelGo.transform;
                }
            }
        }

        // remove double named objects since we cannot insert them properly
        foreach (string name in doubleNames)
        {
            namedGameObjects.Remove(name);
        }

        foreach (GameObject g in namedGameObjects.Values)
        {
            TeardownProperties teardownProperties = g.AddComponent <TeardownProperties>();

            // Create the new Prefab.
            AssetDatabase.CreateAsset(g.GetComponent <MeshFilter>().sharedMesh, Path.Combine(meshFolder, g.name.Replace(" ", "_") + ".mesh"));
            AssetDatabase.SaveAssets();
            PrefabUtility.SaveAsPrefabAssetAndConnect(g, Path.Combine("Assets", "ImportedPrefabs", fileName, g.name.Replace(" ", "_") + ".prefab"), InteractionMode.UserAction);
        }

        PrefabUtility.SaveAsPrefabAssetAndConnect(levelGo, Path.Combine("Assets", "ImportedPrefabs", fileName, fileName + ".prefab"), InteractionMode.UserAction);

        return(levelGo);
    }
        protected void SampleAnyItemPair(int user_id, out int item_id, out int other_item_id)
        {
            var user_items = Feedback.UserMatrix [user_id];

            while (true)
            {
                item_id       = random.Next(MaxItemID + 1);
                other_item_id = random.Next(MaxItemID + 1);

                if ((user_items.Contains(item_id) && user_items.Contains(other_item_id)) ||
                    (!user_items.Contains(item_id) && !user_items.Contains(other_item_id)))
                {
                    if (item_id >= item_attributes.NumberOfRows || other_item_id >= item_attributes.NumberOfRows)
                    {
                        continue;
                    }

                    var attrList = item_attributes.GetEntriesByRow(item_id);
                    if (attrList.Count == 0)
                    {
                        continue;
                    }
                    float sum1 = 0;
                    foreach (int g in attrList)
                    {
                        sum1 += item_attribute_weight_by_user[user_id, g];                        //weights [user_id, g];
                    }
                    sum1 /= attrList.Count;

                    attrList = item_attributes.GetEntriesByRow(other_item_id);
                    if (attrList.Count == 0)
                    {
                        continue;
                    }
                    float sum2 = 0;
                    foreach (int g in attrList)
                    {
                        sum2 += item_attribute_weight_by_user[user_id, g];                        //weights [user_id, g];
                    }
                    sum2 /= attrList.Count;

                    //Console.WriteLine (Math.Abs(sum1-sum2));
                    if (Math.Abs(sum1 - sum2) < 3.5)
                    {
                        continue;
                    }

                    if (sum1 < sum2)
                    {
                        int aux = other_item_id;
                        other_item_id = item_id;
                        item_id       = aux;
                    }
                    return;
                }
                else
                {
                    if (!user_items.Contains(item_id))
                    {
                        int aux = other_item_id;
                        other_item_id = item_id;
                        item_id       = aux;
                    }
                    return;
                }
            }
        }
Exemplo n.º 27
0
    public static List<Planet> MyPlanetsAll = null; // pw.MyPlanet() + Expansions

    public static void DoTurn(PlanetWars pw)
    {
        DateTime StartTime = DateTime.Now; // Startzeit festhalten, um herauszufinden, wie lange der Zug des Bots andauert

        //List<Fleet> ShadowFleets = pw.MyFleets(); // "ShadowFleets" sind alle unsere Flotten + die in dieser Runde von uns losgeschicken Flotten. (Letztere sind nicht teil von pw.MyFleets()!)

        turn++;
        //log("turn: " + turn.ToString());
        if (pw.Winner() != -1) return; // spiel ist vorbei, abbruch.

        // Start-Expanison ------------------------------------------------------------------------------------------------------------------
        // Wir benutzen knapsack01. Achtung: Diese Vorgehensweise beduetet nicht notwendiger Weise eine optimale Expansion!
        if (turn == 1)
        {
            Planet my_start = pw.MyPlanets()[0];
            Planet enemy_start = pw.EnemyPlanets()[0];

            // Schritt 1: Wie viele Schiffe kann ich schicken, ohne dass mein Hauptplanet eingenommen werden kann?
            int ships_available = Math.Min(my_start.NumShips(), my_start.GrowthRate() * ((int)distance(my_start, enemy_start)+1));

            // Schritt 2: Planet heraus suchen, die fuer eine Expansion grundsaetzlich geeignet sind
            List<Planet> candidates = new List<Planet>();
            foreach (Planet p in pw.NeutralPlanets())
            {
                if (Math.Ceiling(distance(p, my_start)) <= Math.Ceiling(distance(p, enemy_start)))
                    candidates.Add(p);
            }

            // Schritt 3: Suche die besten Planeten zur Expansion heraus
            Expansions = knapsack01(candidates, ships_available, my_start);

            // Schritt 4: Expansion starten
            foreach (Planet p in Expansions)
            {
                SendShips(pw, my_start, p, p.NumShips() + 1);
            }

            return;
        }

        int MyGain = 0; // Gesamtproduktionsrate aller (meiner) Planeten
        int OpGain = 0;
        int MyShipCount = pw.NumShips(1); // Gesamtzahl aller meiner Schfife (auf Planeten und unterwegs)
        int OpShipCount = pw.NumShips(2);
        int MyScore = 0; // Meine Bewertung
        bool AttackIsEnabled = true; // duerfen wir in dieser Runde angreifen?

        // Statistiken fuer beide Spieler erheben ------------------------------------------------------------------------------------------------------------------
        MyPlanetCount = 0; OpPlanetCount = 0;
        foreach (Planet p in pw.Planets())
        {
            if (p.Owner() == 1)
            {
                MyGain += p.GrowthRate();
                MyPlanetCount++;
            }
            if (p.Owner() == 2)
            {
                OpGain += p.GrowthRate();
                OpPlanetCount++;
            }
        }

        MyScore = (MyShipCount + MyGain) - (OpShipCount + OpGain);

        MyPlanetsAll = pw.MyPlanets(); // MyPlanetsAll := pw.MyPlanet() + Expansions
        foreach (Planet p in MyPlanetsAll) { // Planeten, auf die wi expandieren wollten, und die nun uns gehoeren, aus der Liste der Expansionsplaneten entfernen
            foreach (Planet ep in Expansions) {
                if (p.PlanetID() == ep.PlanetID())
                {
                    Expansions.Remove(ep);
                    break;
                }
            }
        }
        MyPlanetsAll.AddRange(Expansions);

        // Front-Planeten finden ------------------------------------------------------------------------------------------------------------------
        if (OpPlanetCount > 0 && MyPlanetCount > 0)
        {
            // Haupt-Planeten finden
            foreach (Planet p in MyPlanetsAll)
            {
                double minDist = Double.MaxValue;
                double dist = 0;
                double opDist = 0;
                Planet e = null;
                Planet q = null;

                // naehesten Planeten des Gegners finden: e
                foreach (Planet opp in pw.EnemyPlanets())
                {
                    dist = distance(p, opp);
                    if (dist < minDist)
                    {
                        minDist = dist;
                        e = opp;
                    }
                }
                opDist = minDist;

                // den eigenen Planeten finden, der e am naehsten ist: q
                if (MyPlanetsAll.Count > 1)
                {
                    minDist = Double.MaxValue;
                    foreach (Planet myp in MyPlanetsAll)
                    {
                        dist = distance(e, myp);
                        if ((dist < minDist) && (distance(p, myp) <= opDist))
                        {
                            minDist = dist;
                            q = myp;
                        }
                    }
                }
                else q = p;

                if (p == q)
                {
                    p.IsHead(true);
                    p.TargetPlanetID(e.PlanetID());
                }
                else
                {
                    p.IsHead(false);
                    p.TargetPlanetID(q.PlanetID());
                }
            }
        }

        // Verteidigung ------------------------------------------------------------------------------------------------------------------
        int maxturns = 0;
        foreach (Fleet f in pw.Fleets())
        {
            if (f.TurnsRemaining() > maxturns) maxturns = f.TurnsRemaining();
        }

        foreach (Planet p in MyPlanetsAll)
        {
            p.SimOwner(p.Owner()); p.SimShips(p.NumShips()); p.AvailShips(p.NumShips()); p.TimeOfFall(-1);
        }

        // Berechne, wie viele Schiffe jeder Planet schicken kann, ohne vom Gegner uebernommen zu werden.
        // Dabei wird auch erkannt, welche Planeten vom Gegner erobert werden, sofern sie keine Verstaerkung erhalten.
        for (int i = 1; i <= maxturns; i++)
        {
            foreach (Planet p in MyPlanetsAll)
            {
                if (p.SimOwner() != 0) p.SimShips(p.SimShips() + p.GrowthRate()); // Schiffproduktion berechnen

                foreach (Fleet f in pw.Fleets())
                {
                    if (f.DestinationPlanet() == p.PlanetID() && f.TurnsRemaining() == i)
                    {
                        // achtung: reihenfolge der folgenden if-abfragen ist relevant!
                        if (p.SimOwner() == f.Owner())
                        {
                            p.SimShips(p.SimShips() + f.NumShips()); // eigener Planet (aus Sicht der Flotte)
                            //if (p.SimOwner() == 2) p.SimOpShips(p.SimOpShips() + f.NumShips());
                        }
                        if (p.SimOwner() != f.Owner()) // neutraler/gegnerischer Planet (aus Sicht der Flotte)
                        {
                            p.SimShips(p.SimShips() - f.NumShips());
                            if (p.SimShips() < 0) p.SimOwner(f.Owner());
                            p.SimShips(Math.Abs(p.SimShips()));
                            if (p.SimOwner() == 2)
                            {
                                p.TimeOfFall(i); // speichern, wann der Planet vom Gegner erobert wurde (eigene Rueckeroberungen interessieren hier nicht)
                                p.SimOpShips(p.SimShips());
                                p.AvailShips(0); // Der Planet wurde zwischenzeitlich erobert. Moeglicherweise wird er spaeter zurueck erobert, aber trotzdem soll er in dieser Runde erst einmal keine Schfife schicken. Tendenziell kann dadurch die Zeit, bis der Planet zurueckerobert wird, sinken, was mehr Produktion fuer uns bedeutet.
                            }
                            else p.TimeOfFall(-1);
                        }
                    }
                }

                if (p.Owner() == 1) p.AvailShips(Math.Min(p.AvailShips(), p.SimShips()));
            }
        }

        // Listen erstellen der Planeten, die erobert werden bzw. Verstaerkung schicken koennen
        List<Planet> defplanets = new List<Planet>();
        List<Planet> fallenplanets = new List<Planet>();
        foreach (Planet p in MyPlanetsAll)
        {
            if (p.TimeOfFall() != -1) // Planeten, die ohne zusaetzliche Verstaerkung dauerhaft erobert wuerden
            {
                fallenplanets.Add(p);
                fallenplanets[fallenplanets.Count - 1].Score(p.GrowthRate());
                p.AvailShips(0); // der Planet hat keine Schiffe, die er als Verstaerkung schicken kann, ohne erobert zu werden, da er (voraussichtlich) so oder so erobert wird.
            }
            if (p.TimeOfFall() == -1 && p.AvailShips() > 0 && p.Owner() == 1) defplanets.Add(p); // Planeten, die ohne zusaetliche Verstaerkung nicht erobert werden (oder aber wieder zurueck erobert werden) und evtl. Schiffe schicken koennen
        }
        fallenplanets.Sort(comparePlanetListDesc); // nach Prioritaet sortieren

        // Zu den bedrohten Planeten Verstaerkung schicken
        foreach (Planet fallenplanet in fallenplanets)
        {
            foreach (Planet p in defplanets) // Fuer alle Planeten, die Verstaerkung schicken koennen/sollen...
            {
                p.Score((int)Math.Ceiling(distance(fallenplanet, p))); // ...Entfernung zum Zielplaneten ermitteln
            }
            defplanets.Sort(comparePlanetListAsc); // Wir wollen zuerst von nahe gelegenen Planeten Unterstuetzung senden.

            int sended = 0; // Gibt an, wie viele Schiffe andere Planeten, die naeher am Zielplaneten sind, schon gesendet haben
            int iMustSend = 0; // Anzahl Schiffe, die der Planet senden muss (ob er so viele Schiffe hat, wird hier nicht beruecksichtigt)

            foreach (Planet p in defplanets)
            {
                if (p.AvailShips() == 0) continue; // Planeten, die keine Schiffe schicken koennen, ignorieren
                if (p.Score() <= fallenplanet.TimeOfFall()) // p.score()=Entfernung=Zeit, bis Flotten den bedrohten Planet erreichen koennen
                {
                    iMustSend = fallenplanet.SimOpShips() + 1 - sended; // Ich befinde mich nah genug beim Zielplaneten, um eingreifen zu koennen, bevor er erobert wird. SimOpShips() gibt an, wie viele Schiffe der Planet direkt nach der Eroberung hat. Wenn der Planet so viele Schiffe mehr schickt, wird die Eroberung verhindert. [Es kann sein, dass der Planet zu viele Schiffe schickt, wenn z.B. der Planet vor der endgueltigen Eroberung schon mal  kurz erobert wurde und wir das verhinderen, denn dann werden ja mehr Schfife fuer uns produziert.] 
                }
                else
                {
                    iMustSend = fallenplanet.SimOpShips() + 1 + (int)(p.Score() - fallenplanet.TimeOfFall()) * fallenplanet.GrowthRate() - sended; // wie oben, aber jetzt beruecksichtigt der Planet zusaetlich, dass seine Flotte er erst nach der Eroberung eintrifft und der Gegner dann schon zusaetzliche Schiffe produziert hat. Es wird aber nicht beruecksichtigt, dass der Gegner ggf. Verstaerkung zu dem Planeten schickt.
                }

                if (p.AvailShips() >= iMustSend)
                {
                    p.AvailShips(p.AvailShips() - iMustSend);
                    SendShips(pw, p, fallenplanet, iMustSend);
                    break; // Es wurden (voraussichtlich) genug Schiffe gesendet, um den Planeten zurueck zu erobern. Bearbeitung dies Planeten abbrechen.
                }
                else
                {
                    sended += p.AvailShips();
                    SendShips(pw, p, fallenplanet, p.AvailShips());
                    p.AvailShips(0);
                }
            }
        }

        

        //// Expansion ------------------------------------------------------------------------------------------------------------------
        if (MyPlanetCount > 0 && OpPlanetCount > 0 && (MyScore < 150 && (MyGain - 5 < OpGain)))
        //if (MyPlanetCount > 0 && OpPlanetCount > 0 && (MyScore < 250 && (MyGain - 20 < OpGain)))
        {
            // Suche einen geeigneten Planeten zur Expansion:
            Planet ExpansionPlanet = null;
            Planet MyNearestPlanet = null;
            double maxScore = Double.MaxValue;
            foreach (Planet p in pw.NeutralPlanets())
            {
                if (p.GrowthRate() == 0) continue; // planeten ohne produktion interessieren uns nicht

                // pruefen, ob wir noch nicht zu diesem Planeten expandieren
                bool gofornext = false;
                foreach (Planet ExP in Expansions)
                {
                    if (p.PlanetID() == ExP.PlanetID())
                    {
                        p.Score(-1);
                        gofornext = true;
                        break;
                    }
                }
                if (gofornext == true) continue;

                p.Score(p.NumShips() / p.GrowthRate()); // p.GrowthRate() == 0 kann hier nicht auftreten

                // Der Planet sollte/muss in unserem Gebiet liegen oder zumindest fuer uns guenstiger als fuer den Gegner
                int MyEmpireDistance = int.MaxValue;
                int OpEmpireDistance = int.MaxValue;
                Planet SaveMyNearestPlanet = null;
                foreach (Planet MyP in pw.MyPlanets())
                {
                    int mindDist = (int)Math.Ceiling(distance(p, MyP));
                    if (mindDist < MyEmpireDistance)
                    {
                        MyEmpireDistance = mindDist;
                        SaveMyNearestPlanet = MyP;
                    }
                }
                foreach (Planet OpP in pw.EnemyPlanets())
                {
                    int mindDist = (int)Math.Ceiling(distance(p, OpP));
                    if (mindDist < OpEmpireDistance) OpEmpireDistance = mindDist;
                }

                // Entfernungen mit in die Bewertung einbeziehen
                //if (OpEmpireDistance < MyEmpireDistance) p.Score(p.Score() + 100 + (MyEmpireDistance - OpEmpireDistance)); // Wir wollen Planeten, die naeher zum Gegner sind also zu uns, nur im Notfall. Daher erhalten sie eine dratsich schlechtere Wertung.
                if (OpEmpireDistance < MyEmpireDistance) continue; // Wir wollen Planeten, die naeher zum Gegner sind also zu uns, nicht einnehmen.
                p.Score(p.Score() + MyEmpireDistance);

                if (p.Score() < maxScore)
                {
                    maxScore = p.Score();
                    ExpansionPlanet = p;
                    MyNearestPlanet = SaveMyNearestPlanet;
                }
            }

            log(" "); log("turn: " + turn);
            log("MyGain: " + MyGain + ", OpGain: " + OpGain + ", Score: " + MyScore);
            //if (ExpansionPlanet == null) log("Kein Expansionplanet gefunden."); else log("Expansionplanet gefunden!!!  ID: " + ExpansionPlanet.PlanetID() + " - Score: " + ExpansionPlanet.Score());

            if (ExpansionPlanet != null) // kein fuer Expansion geeigneter Planet gefunden: Abbruch
            {
                // Berechne via AvailShips, ob wir genuegend Schfife haben, um die Eroberung des Planeten in dieser Runde einzuleiten.
                int haveShips = 0;
                foreach (Planet p in pw.MyPlanets())
                {
                    haveShips += p.AvailShips();
                    if (haveShips >= ExpansionPlanet.NumShips() + 1) break;
                }

                bool Expand = true;
                if (haveShips>0) { // Wenn wir genug Schiffe fuer die Expansion haben:
                    int amortizeTime = ExpansionPlanet.NumShips() / ExpansionPlanet.GrowthRate() + (int)Math.Ceiling(distance(MyNearestPlanet, ExpansionPlanet));
                    int needed = ExpansionPlanet.NumShips() + 1;
                    log("amortizeTime: " + amortizeTime + ", MyNearestPlanet: " + MyNearestPlanet.PlanetID() + ", haveShips: " + haveShips + ", neededShips: " + needed);

                    foreach (Planet HeadPlanet in MyPlanetsAll) // Angriff auf jeden HeadPlaneten simulieren; auch Expansionsplaneten beruecksichtigen
                    {
                        if (HeadPlanet.IsHead() == true)
                        {
                            int SimShips = 0;
                            int IsTarget = 0;
                            List<Fleet> ESimFleets = new List<Fleet>(); // Simulierte Flotten hier speichern
                            foreach (Planet p in pw.Planets()) // Alle nicht-neutralen Planeten greifen an (bzw. verstaerken)
                            {
                                if (p.Owner() != 0)
                                {
                                    for (int i = 0; i <= amortizeTime; i++)
                                    {
                                        SimShips = p.GrowthRate(); // Die Schiff-Produktion beruecksichtigen
                                        if (i == 0 && p.PlanetID() != HeadPlanet.PlanetID()) SimShips = p.NumShips(); // Alle Schiffe losschicken
                                        if (p.PlanetID() == HeadPlanet.PlanetID()) IsTarget = 1; else IsTarget=0; // Flotte markieren: Diese Flotte wurde vom Zielplaneten losgeschickt (sie fliegt also eigentlich gar nicht. Sie wird nur losgeschickt, damit die Produktion des Ziel-Planeten beruecksichtigt wird)
                                        if (SimShips > 0) // wir wollen keine 0-Schiff-Flotten losschicken
                                        {
                                            Fleet ThisFleet = new Fleet(p.Owner(), SimShips, IsTarget, 0, -1, (int)Math.Ceiling(distance(p, HeadPlanet)));
                                            ESimFleets.Add(ThisFleet); // Flotte der Liste hinzufuegen
                                        }
                                    }
                                }
                            }

                            ESimFleets.Sort(compareFleetListAsc); // Flotten nach Ankunftszeit sortieren

                            SimShips = HeadPlanet.NumShips() - needed; // Der Zielplanet verfuegt ueber die auf ihm stationierten Schiffe. Die Schiffe fuer die Expansion werden abgezogen.
                            int SimOwner = 1; // Besitzer des Zielplaneten
                            foreach (Fleet ESimFleet in ESimFleets) // Eintreffen der Flotten simulieren. Da diese nach Entfernung sortiert sind, muss die exakte Akunftszeit hier nicht mehr beruecksichtigt werden.
                            {
                                if (ESimFleet.Owner() == SimOwner || ESimFleet.SourcePlanet() == 1) // Wenn der Zielplnaet zum Besitzer der Flotte gehoert (oder die Flotte als zum Zielplanet gehoerend markiert wurde):
                                {
                                    SimShips += ESimFleet.NumShips(); // Schiffe addieren
                                }
                                else
                                {
                                    SimShips -= ESimFleet.NumShips(); // Schiffe abziehen
                                    if (SimShips < 0) // Wenn wir < 0 Schiffe haben...
                                    {
                                        SimOwner = ESimFleet.Owner(); // wechselt der Besitzer des Planeten.
                                        SimShips = Math.Abs(SimShips); 
                                    }
                                }
                            }

                            log("Ergebnis der Simulation: " + SimShips + " (" + SimOwner + ")");
                            if (SimOwner != 1) // Wenn wir nicht der Besitzer des Planeten sind...
                            {
                                Expand = false; // Expansion abbrechen, da keine sichere Expansion moeglich ist. 
                                break; // Schleife ueber die Head-Planeten verlassen
                            }
                        }
                    }

                    if ((haveShips >= needed) && (Expand == true))
                    {
                        List<Planet> SourcePlanets = EvalSendPlanets(pw, ExpansionPlanet); // Liste aller infrage kommender eigener Planeten, die Flotten schicken koennen, erstellen. Fuer jeden Planeten eine Bewertung mitliefern.
                        SourcePlanets.Sort(comparePlanetListDesc); // Liste sortieren (nach Bewertung)

                        foreach (Planet SourcePlanet in SourcePlanets) // Alle moeglichen eigenen Planeten durchlaufen, die zum aktuellen Zielplaneten Flotten schicken koennen
                        {
                            int ships = SourcePlanet.AvailShips();
                            if (ships == 0) continue; // wir wollen ja keine 0-Schiff-Flotten losschicken
                            if (ships >= needed) // Wenn der Planet mehr Schiffe hat als fuer die Expansion benoetigt werden:
                            {
                                SourcePlanet.AvailShips(SourcePlanet.AvailShips() - needed);
                                SendShips(pw, SourcePlanet, ExpansionPlanet, needed);
                                break; // Abbruch, es wurden genug Schiffe losgeschickt
                            }
                            else
                            {
                                SourcePlanet.AvailShips(0);
                                SendShips(pw, SourcePlanet, ExpansionPlanet, ships);
                                needed -= ships;
                            }
                        }

                        Expansions.Add(ExpansionPlanet); // Planet zu der Liste der Expansionsplaneten hinzufuegen
                    }
                    else
                    {
                        if (haveShips < needed && Expand == true) AttackIsEnabled = false; // keine Angriffe durchfuehren, sondern warten, dass genug Schiffe produziert worden
                    }
                }
            }
        }
        
        // Nachschublinien ------------------------------------------------------------------------------------------------------------------
        if (OpPlanetCount > 0 && MyPlanetsAll.Count > 1) // Nachschub schicken, wenn der Gegner Planeten besitzt und wir mehr als 1 Planeten besitzen:
        {
            foreach (Planet p in pw.MyPlanets())
            {
                //if (p.AvailShips() > 0 && p.IsHead() == false && p.Owner() == 1)
                if (p.AvailShips() > 0 && p.IsHead() == false) // Nachschub schicken, wenn dafuer Schiffe verfuegbar sind und wir kein HEad-Planet sind.
                {
                    SendShips(pw, p, pw.GetPlanet(p.TargetPlanetID()), p.AvailShips());
                }
            }
        }

        // Angriff ------------------------------------------------------------------------------------------------------------------
        //log("Attack? : " + AttackIsEnabled + ", AvaiLShips(2): " + pw.GetPlanet(2).AvailShips() + ", OpPCount: " + OpPlanetCount + ", MyPCount: " + MyPlanetCount);
        if (OpPlanetCount > 0 && MyPlanetCount > 0 && AttackIsEnabled == true)
        {
            foreach (Planet p in pw.MyPlanets())
            {
                if (p.AvailShips() > 0 && p.IsHead() == true) // Angreifen, wenn wir Schiffe dazu haben und wir ein Head-Planet sind:
                {
                    int ships_available = p.AvailShips() + p.GrowthRate() * ((int)distance(p, pw.GetPlanet(p.TargetPlanetID())));
                    if (pw.GetPlanet(p.TargetPlanetID()).NumShips() <= ships_available || MyScore > 200)
                    {
                        if (MyScore > 250) // Wenn wir ueber x Schiffe mehr haben als der Gegner, greifen wir aggressiv an. 
                        {
                            ships_available = p.AvailShips();
                        }
                        else
                        {
                            ships_available = Math.Min(ships_available - pw.GetPlanet(p.TargetPlanetID()).NumShips(), p.AvailShips());
                        }
                        if (ships_available > 0) SendShips(pw, p, pw.GetPlanet(p.TargetPlanetID()), ships_available);
                    }
                }
            }
        }

        log("ExecutionTime: " + (DateTime.Now - StartTime).TotalMilliseconds + " Milliseconds (" + (DateTime.Now - StartTime).TotalSeconds + " Seconds)"); // Ausfuehrungszeit loggen.
    }
        /// <summary>
        /// Sample a pair of items, given a user
        /// </summary>
        /// <param name='user_id'>
        /// the user ID
        /// </param>
        /// <param name='item_id'>
        /// the ID of the first item
        /// </param>
        /// <param name='other_item_id'>
        /// the ID of the second item
        /// </param>
        protected override void SampleItemPair(int user_id, out int item_id, out int other_item_id)
        {
            //SampleAnyItemPair(user_id, out item_id, out other_item_id);
            //return;
            var user_items = Feedback.UserMatrix [user_id];

            item_id = user_items.ElementAt(random.Next(user_items.Count));

            if (item_id >= item_attributes.NumberOfRows)
            {
                do
                {
                    other_item_id = random.Next(MaxItemID + 1);
                }while (user_items.Contains(other_item_id));
                return;
            }

            var   attrList = item_attributes.GetEntriesByRow(item_id);
            float sum1     = 0;

            foreach (int g in attrList)
            {
                sum1 += item_attribute_weight_by_user[user_id, g];                //weights [user_id, g];
            }
            if (attrList.Count > 0)
            {
                sum1 /= attrList.Count;
            }
            else
            {
                sum1 = 0;
            }

            while (true)
            {
                other_item_id = random.Next(MaxItemID + 1);
                if (!user_items.Contains(other_item_id))
                {
                    return;
                }

                if (other_item_id >= item_attributes.NumberOfRows)
                {
                    continue;
                }

                attrList = item_attributes.GetEntriesByRow(other_item_id);
                float sum2 = 0;
                foreach (int g in attrList)
                {
                    sum2 += item_attribute_weight_by_user[user_id, g];                    //weights[user_id, g];
                }
                if (attrList.Count > 0)
                {
                    sum2 /= attrList.Count;
                }
                else
                {
                    sum2 = 0;
                }

                if (Math.Abs(sum1 - sum2) < 2.5)
                {
                    continue;
                }

                if (sum1 < sum2)
                {
                    int aux = item_id;
                    item_id       = other_item_id;
                    other_item_id = aux;
                }
                return;
            }
        }
Exemplo n.º 29
0
        //assumes that the caller has responsibility to handle data stream disposal ("stream" parameter)
        private async Task ImportFullData(CounterConnectionStringOptions connectionString, Stream stream)
        {
            CountingStream sizeStream;
            JsonTextReader jsonReader;

            if (SmugglerHelper.TryGetJsonReaderForStream(stream, out jsonReader, out sizeStream) == false)
            {
                throw new InvalidOperationException("Failed to get reader for the data stream.");
            }

            if (jsonReader.TokenType != JsonToken.StartObject)
            {
                throw new InvalidDataException("StartObject was expected");
            }

            ICounterStore store = null;

            try
            {
                if (jsonReader.Read() == false && jsonReader.TokenType != JsonToken.StartArray)
                {
                    throw new InvalidDataException("StartArray was expected");
                }

                store = new CounterStore
                {
                    Url         = connectionString.Url,
                    Name        = connectionString.CounterStoreId,
                    Credentials = new OperationCredentials(connectionString.ApiKey, connectionString.Credentials)
                };
                store.Initialize(true);

                ShowProgress($"Initialized connection to counter store (name = {store.Name})");
                var existingCounterGroupsAndNames = await store.Admin.GetCounterStorageNameAndGroups(token : CancellationToken)
                                                    .WithCancellation(CancellationToken)
                                                    .ConfigureAwait(false);

                while (jsonReader.Read() && jsonReader.TokenType != JsonToken.EndArray)
                {
                    if (jsonReader.TokenType != JsonToken.StartObject)
                    {
                        continue;
                    }

                    var counterInfo = (RavenJObject)RavenJToken.ReadFrom(jsonReader);

                    var delta       = Math.Abs(counterInfo.Value <long>("Positive")) - Math.Abs(counterInfo.Value <long>("Negative"));
                    var groupName   = counterInfo.Value <string>("Group");
                    var counterName = counterInfo.Value <string>("Name");

                    if (existingCounterGroupsAndNames.Any(x => x.Group == groupName && x.Name == counterName))
                    {
                        ShowProgress($"Counter {groupName} - {counterName} is already there. Reset is performed");
                        await store.ResetAsync(groupName, counterName, CancellationToken).ConfigureAwait(false); //since it is a full import, the values are overwritten
                    }

                    ShowProgress($"Importing counter {groupName} - {counterName}");
                    store.Batch.ScheduleChange(groupName, counterName, delta);
                }

                ShowProgress("Finished import...");
                await store.Batch.FlushAsync().WithCancellation(CancellationToken).ConfigureAwait(false);
            }
            finally
            {
                store?.Dispose();
            }
        }
Exemplo n.º 30
0
 private int GetBucketNumber(object key)
 {
     return(Math.Abs(key.GetHashCode()) % list.Count);
 }