Inheritance: MonoBehaviour
        public override void Apply( Renderers.Renderer renderer, Primitives.VisualItem item )
        {
            Primitives.DelegateVisitor visitor = new Primitives.DelegateVisitor();

            visitor.VisitBoundsMarkerDelegate = delegate( Primitives.BoundsMarker marker )
            {
                Primitives.VisualItem to = CreateItem( marker );

                if( to != null )
                {
                    to.Style.MergeWith( marker.Style );
                }

                marker.Parent.Replace( marker, to );
            };
            visitor.VisitPointMarkerDelegate = delegate( Primitives.PointMarker marker )
            {
                Primitives.VisualItem to = CreateItem( marker );

                if( to != null )
                {
                    to.Style.MergeWith( marker.Style );
                }

                marker.Parent.Replace( marker, to );
            };

            item.Visit( visitor );
        }
Esempio n. 2
0
        protected override void Apply( Renderers.Renderer renderer, Primitives.Path path )
        {
            Factories.SoftShadow softShadow = new Factories.SoftShadow( renderer, _offset, _extent, _color );

            Primitives.VisualItem shadow = softShadow.Create( path );

            path.Parent.AddFront( shadow );
        }
Esempio n. 3
0
            protected override void Apply( Renderers.Renderer renderer, Primitives.Path path )
            {
                double index = int.Parse( path.Style.GetExtra( "RowIndex" ) );
                double count = int.Parse( path.Style.GetExtra( "RowCount" ) );

                Paint.Color color = Paint.Color.Combine( _baseColor, Paint.Color.White, 1 - index / (count * 1.5) );

                path.Pen = new Paint.Pens.SolidPen( Paint.Color.White, 2 );
                path.Brush = new Paint.Brushes.SolidBrush( color );
            }
Esempio n. 4
0
        public Lookup( Primitives.Container container )
        {
            if( container == null )
            {
                throw new ArgumentNullException( "container" );
            }

            Visitor visitor = new Visitor( _mapStyleToItems );

            container.Visit( visitor );
        }
        public void TestMuesliVsBinaryFormatter( )
        {
            Primitives objToStore = new Primitives( );

            //	Slight cheat...
            SerializationIdMap map = SerializationIdMap.Instance;
            map.ToString( );

            ProfileSerialization( new BinaryFormatter( ), new MemoryStream( ), objToStore, 10000 ).Dump( "Muesli" );
            ProfileSerialization( new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter( ), new MemoryStream( ), objToStore, 10000 ).Dump( "BF" );
        }
Esempio n. 6
0
        public override void Apply( Renderers.Renderer renderer, Primitives.VisualItem item )
        {
            Primitives.DelegateVisitor visitor = new Primitives.DelegateVisitor();

            visitor.VisitPathDelegate = delegate( Primitives.Path path )
            {
                Apply( renderer, path );
            };

            item.Visit( visitor );
        }
Esempio n. 7
0
        public override void Apply( Renderers.Renderer renderer, Primitives.VisualItem item )
        {
            Primitives.DelegateVisitor visitor = new Primitives.DelegateVisitor();

            visitor.VisitTextDelegate = delegate( Primitives.Text text )
            {
                Apply( renderer, text );
            };

            item.Visit( visitor );
        }
Esempio n. 8
0
        public void setPrimitives(Primitives p)
        {
            if (primitives == p)
                return;

            if (primitives)
                primitives.setContext(NULL);

            primitives = p;
            if (primitives)
                primitives.setContext(this);
        }
        protected override Primitives.VisualItem CreateItem( Primitives.BoundsMarker marker )
        {
            Primitives.Path rect = new Primitives.Path();

            rect.Add( new Primitives.Path.Move( marker.Rectangle.TopLeft ) );
            rect.Add( new Primitives.Path.Line( marker.Rectangle.TopRight ) );
            rect.Add( new Primitives.Path.Line( marker.Rectangle.BottomRight ) );
            rect.Add( new Primitives.Path.Line( marker.Rectangle.BottomLeft ) );
            rect.Add( new Primitives.Path.Line( marker.Rectangle.TopLeft ) );
            rect.Add( new Primitives.Path.Close() );

            return rect;
        }
Esempio n. 10
0
        public override Primitives.VisualItem Create( Primitives.Path source )
        {
            Primitives.Container container = new Primitives.Container( _offset );

            Primitives.Path shadow = (Primitives.Path) source.Copy();

            shadow.Pen = null;
            shadow.Brush = new Paint.Brushes.SolidBrush( _color );

            container.AddBack( shadow );

            return container;
        }
Esempio n. 11
0
        /// <summary>
        /// create GeoSphere game object
        /// </summary>
        /// <param name="radius">radius of sphere</param>
        /// <param name="subdivision">number of subdivision</param>
        /// <param name="baseType">type of generation primitive</param>
        /// <param name="normals">type of normals to be generated</param>
        /// <param name="pivotPosition">position of the model pivot</param>
        /// <returns>GeoSphere class with GeoSphere game object</returns>
        public static GeoSphere Create(float radius, int subdivision, Primitives.GeoSpherePrimitive.BaseType baseType, NormalsType normals, PivotPosition pivotPosition)
        {
            var sphereObject = new GameObject("GeoSpherePro");

            sphereObject.AddComponent<MeshFilter>();
            var renderer = sphereObject.AddComponent<MeshRenderer>();

            renderer.sharedMaterial = new Material(Shader.Find("Diffuse"));

            var sphere = sphereObject.AddComponent<GeoSphere>();
            sphere.GenerateGeometry(radius, subdivision, baseType, normals, pivotPosition);

            return sphere;
        }
Esempio n. 12
0
 private static void HandleNullModel(ref Primitives.Playlist model, PlaylistPlaceholder placeholder)
 {
     if (model == null)
     {
         if (placeholder.Key == Primitives.Playlist.MusicLibraryPlaylistKey)
             model = Primitives.Playlist.CreateMusicLibrary();
         else
             model = new Primitives.Playlist
             {
                 Key = placeholder.Key,
                 Version = PlaylistVersions.Current
             };
     }
 }
Esempio n. 13
0
            public override void PreVisitVisualItem( Primitives.VisualItem visualItem )
            {
                foreach( string c in visualItem.Style.Classes )
                {
                    List<Primitives.VisualItem> items;

                    if( !_mapStyleToItems.TryGetValue( c, out items ) )
                    {
                        items = new List<Primitives.VisualItem>();
                        _mapStyleToItems.Add( c, items );
                    }

                    items.Add( visualItem );
                }
            }
Esempio n. 14
0
        public void Apply( Primitives.Container container )
        {
            List<Primitives.Path> sources = new List<Primitives.Path>();
            Primitives.DelegateVisitor visitor = new Primitives.DelegateVisitor();

            visitor.VisitPathDelegate = delegate( Primitives.Path path )
            {
                sources.Add( path );
            };

            container.Visit( visitor );

            foreach( Primitives.Path source in sources )
            {
                container.AddFront( Create( source ) );
            }
        }
Esempio n. 15
0
        public void Apply( Renderers.Renderer renderer, Primitives.Container container )
        {
            foreach( KeyValuePair<string, Modifier> kvp in _modifiers )
            {
                Lookup lookup = new Lookup( container );

                string style = kvp.Key;
                Modifier modifier = kvp.Value;

                Primitives.VisualItem[] items = lookup.GetVisualItems( style );

                foreach( Primitives.VisualItem item in items )
                {
                    modifier.Apply( renderer, item );
                }
            }
        }
Esempio n. 16
0
        protected override void Apply( Renderers.Renderer renderer, Primitives.Text text )
        {
            if( _fontFamily != null )
            {
                text.FontFamily = _fontFamily;
            }

            if( _fontSizeInPoints != null )
            {
                text.FontSizePoints = _fontSizeInPoints.Value;
            }

            if( _fontStyleFlags != null )
            {
                text.FontStyle = _fontStyleFlags.Value;
            }
        }
Esempio n. 17
0
        public override Primitives.VisualItem Create( Primitives.Path source )
        {
            Primitives.Container container = new Primitives.Container( _offset );
            PathCommandVisitor visitor = new PathCommandVisitor( this );

            source = _renderer.FlattenPath( source );

            foreach( Primitives.Path.Command command in source.Commands )
            {
                command.Visit( visitor );
            }

            foreach( Primitives.Path path in visitor.Paths )
            {
                container.AddFront( path );
            }

            return container;
        }
Esempio n. 18
0
        /// <summary>
        /// create GeoSphere game object
        /// </summary>
        /// <param name="radius">radius of sphere</param>
        /// <param name="subdivision">number of subdivision</param>
        /// <param name="baseType">type of generation primitive</param>
        /// <param name="normalsType">type of normals to be generated</param>
        /// <param name="pivotPosition">position of the model pivot</param>
        public void GenerateGeometry(float radius, int subdivision, Primitives.GeoSpherePrimitive.BaseType baseType, NormalsType normalsType, PivotPosition pivotPosition)
        {
            // generate new mesh and clear old one
            var meshFilter = GetComponent<MeshFilter>();

            if (meshFilter.sharedMesh == null)
            {
                meshFilter.sharedMesh = new Mesh();
            }

            var mesh = meshFilter.sharedMesh;

            // geneate geometry
            GenerationTimeMS = Primitives.GeoSpherePrimitive.GenerateGeometry(mesh, radius, subdivision, baseType, normalsType, pivotPosition);

            this.radius = radius;
            this.subdivision = subdivision;
            this.baseType = baseType;
            this.normalsType = normalsType;
            this.flipNormals = false;
            this.pivotPosition = pivotPosition;
        }
        public Vector3 CalculateRezLocation(
            RezObjectParams rezparams,
            Vector3 scale)
        {
            Vector3 pos = rezparams.RayEnd + new Vector3(0, 0, scale.Z / 2f);

            if (rezparams.RayEndIsIntersection)
            {
                return(rezparams.RayEnd);
            }

            Vector3 projectedWaterLocation = Vector3.Zero;
            double  waterHeight            = RegionSettings.WaterHeight;

            if (rezparams.RayStart.Z > waterHeight && rezparams.RayEnd.Z < waterHeight)
            {
                Vector3 dir   = rezparams.RayEnd - rezparams.RayStart;
                double  ratio = (waterHeight - rezparams.RayStart.Z) / dir.Z;

                projectedWaterLocation    = rezparams.RayStart;
                projectedWaterLocation.X += ratio * dir.X;
                projectedWaterLocation.Y += ratio * dir.Y;
                projectedWaterLocation.Z  = waterHeight;
            }
            else
            {
                projectedWaterLocation.Z = waterHeight;
            }

            ObjectPart target;

            if (Primitives.TryGetValue(rezparams.RayTargetID, out target))
            {
                pos = target.GlobalPosition;
            }
            RayResult[] results = PhysicsScene.RayTest(rezparams.RayStart, pos);

            if (rezparams.RayTargetID != UUID.Zero)
            {
                foreach (RayResult ray in results)
                {
                    if (ray.PartId == rezparams.RayTargetID)
                    {
                        return(CalculateTargetedRezLocation(ray, scale, projectedWaterLocation));
                    }
                }
            }
            else
            {
                foreach (RayResult ray in results)
                {
                    if (ray.IsTerrain)
                    {
                        return(CalculateTargetedRezLocation(ray, scale, projectedWaterLocation));
                    }
                }
            }

            if (results.Length > 0)
            {
                return(CalculateTargetedRezLocation(results[0], scale, projectedWaterLocation));
            }
            else
            {
                pos = rezparams.RayEnd;
                LocationInfo info = GetLocationInfoProvider().At(pos);
                pos.Z = info.GroundHeight;
                if (pos.Z < info.WaterHeight && rezparams.RayStart.Z >= info.WaterHeight)
                {
                    pos.Z = info.WaterHeight;
                }
                pos.Z += scale.Z * 0.5;
            }
            return(pos);
        }
Esempio n. 20
0
        // Process Port commands.
        // Returns zero on success.
        public override byte CommandHandler(MessageTransaction mtx)
        {
            PacketBuffer g       = mtx.MsgBuffer;
            Boolean      isReply = ((g.flagsRS() & ProtocolConstants.MESSAGE_FLAGS_IS_REPLY) != 0);

            if (((!isReply) && (g.command() < ProtocolConstants.MEDIATOR_CONTROL_CMD_BASE)) ||
                (isReply && (g.senderId() == ProtocolConstants.IDENT_MEDIATOR)))
            {
                byte   dataIndex = ProtocolConstants.GENERAL_DATA_ARRAY_OFFSET;
                byte[] tmp;
                switch (g.command())
                {
                // Standard device commands.
                case ProtocolConstants.MEDIATOR_DEVICE_RESET:     // Reset the module.
                    Manager.AppBabelDeviceReset();
                    break;

                case ProtocolConstants.MEDIATOR_DEVICE_STATUS:     // Get device status.
                    if (isReply)
                    {
                        return(1);
                    }
                    g.dataLength(Diagnostics.GetDeviceStatus(Manager, g.buffer));
                    mtx.ChangeDir = true;
                    mtx.Finish    = MessageTransaction.FinishAction.Normal;
                    break;

                case ProtocolConstants.MEDIATOR_DEVICE_TICKER:     // Get device ticker count.
                    if (isReply)
                    {
                        return(1);             // We've been sent a ticker count.
                    }
                    // Sender wants to know ticker count.
                    tmp = Primitives.UIntToByteArray(Primitives.GetBabelMilliTicker());
                    return(mtx.StoreMessageValue(tmp, (byte)(tmp.Length)));

                case ProtocolConstants.MEDIATOR_DEVICE_ERASE:     // TODO: erase eeprom and restart.
                    return(2);

                case ProtocolConstants.MEDIATOR_DEVICE_READVAR:
                    return((MediatorReadCommand(mtx) == 0) ? (byte)1 : (byte)0);

                case ProtocolConstants.MEDIATOR_DEVICE_WRITEVAR:
                    return((MediatorWriteCommand(mtx) == 0) ? (byte)1 : (byte)0);

                case ProtocolConstants.MEDIATOR_DEVICE_ISOVAR:
                    return((MediatorIsoCommand(mtx) == 0) ? (byte)1 : (byte)0);

                case ProtocolConstants.MEDIATOR_DEVICE_ISOMONVAR:
                    return((MediatorIsoCommand(mtx) == 0) ? (byte)1 : (byte)0);

                case ProtocolConstants.MEDIATOR_DEVICE_ISOMSG:
                    return((MediatorIsoCommand(mtx) == 0) ? (byte)1 : (byte)0);

                case ProtocolConstants.MEDIATOR_DEVICE_LOG:
                    if (!isReply)
                    {
                        if (Settings.LogOn)
                        {
                            uint   ticks = (uint)Primitives.GetArrayValueU(g.buffer, dataIndex, 4);
                            string s;
                            byte   logType = g.buffer[dataIndex + 4];
                            if (Settings.LogBinary || logType == 'B')
                            {
                                int start = dataIndex + 5;
                                int last  = dataIndex + g.dataLength();
                                s = "(";
                                for (int k = start; k < last; k++)
                                {
                                    s = s + g.buffer[k].ToString("X2") + " ";
                                }
                                s += ")";
                            }
                            else
                            {
                                s = Primitives.GetArrayStringValue(g.buffer, dataIndex + 5, g.dataLength() - 5);
                            }
                            Log.d("MediatorNetIf:" + Exchange.Id, ":" + ticks + ":" + s);
                        }
                    }
                    return(1);

                // Connection specific commands.
                case ProtocolConstants.MEDIATOR_DEVICE_GETSN: // Get SN of receiver device at end of link.
                    if (isReply)                              // We've been sent an SN for SPort.
                    {
                        g.buffer[dataIndex + g.dataLength()] = 0;
                        Manager.SerialNumberManager.UpdateSerialNumbers(g.buffer, dataIndex, g.dataLength(), g.iNetIf, g.sender());
                        if (mtx.MsgBuffer.iNetIf != ProtocolConstants.NETIF_USER_BASE)       // Notify master of SN via connection attach command.
                        {
                            SendLinkMediatorCommand(this, true, ProtocolConstants.MEDIATOR_CONNECT_ATTACH, g.dataLength(), g.buffer, dataIndex);
                        }
                        break;
                    }
                    // Sender wants to know SN of master.
                    g.dataLength(Manager.SerialNumberManager.CopyMasterSerialNumber(g.buffer, dataIndex, g.iNetIf));
                    mtx.ChangeDir = true;
                    mtx.Finish    = MessageTransaction.FinishAction.Normal;
                    break;

                case ProtocolConstants.MEDIATOR_CONNECT_ATTACH:     // TODO: Report attach and SN of device.
                case ProtocolConstants.MEDIATOR_CONNECT_DETACH:     // TODO: Report detach of device.
                case ProtocolConstants.MEDIATOR_CONNECT_GATEWAY:    // TODO: Register as a gateway.
                    return(10);

                default:
                    // TODO: try handling via NETIF_MEDIATOR_PORT.
                    return(11);
                }
                return(0);
            }
            return(BabelMessage.ProcessIncomingRawMesssage(Exchange, mtx));
        }
Esempio n. 21
0
        /// <summary>
        /// Write the Voronoi diagram to a .voro file.
        /// </summary>
        /// <param name="mesh"></param>
        /// <param name="filename"></param>
        /// <returns></returns>
        /// <remarks>
        /// The Voronoi diagram is the geometric dual of the Delaunay triangulation.
        /// Hence, the Voronoi vertices are listed by traversing the Delaunay
        /// triangles, and the Voronoi edges are listed by traversing the Delaunay
        /// edges.
        ///
        /// WARNING:  In order to assign numbers to the Voronoi vertices, this
        /// procedure messes up the subsegments or the extra nodes of every
        /// element.  Hence, you should call this procedure last.</remarks>
        public static void WriteVoronoi(Mesh mesh, string filename)
        {
            Otri   tri = default(Otri), trisym = default(Otri);
            Vertex torg, tdest, tapex;
            Point  circumcenter;
            double xi = 0, eta = 0;

            int p1, p2, index = 0;

            tri.orient = 0;

            using (StreamWriter writer = new StreamWriter(filename))
            {
                // Number of triangles, two dimensions, number of vertex attributes, no markers.
                writer.WriteLine("{0} 2 {1} 0", mesh.triangles.Count, mesh.nextras);

                foreach (var item in mesh.triangles.Values)
                {
                    tri.triangle = item;
                    torg         = tri.Org();
                    tdest        = tri.Dest();
                    tapex        = tri.Apex();
                    circumcenter = Primitives.FindCircumcenter(torg, tdest, tapex, ref xi, ref eta);

                    // X and y coordinates.
                    writer.Write("{0} {1} {2}", index, circumcenter.X.ToString(nfi),
                                 circumcenter.Y.ToString(nfi));

                    for (int i = 0; i < mesh.nextras; i++)
                    {
                        writer.Write(" 0");
                        // TODO
                        // Interpolate the vertex attributes at the circumcenter.
                        //writer.Write(" {0}", torg.attribs[i] + xi * (tdes.attribst[i] - torg.attribs[i]) +
                        //    eta * (tapex.attribs[i] - torg.attribs[i]));
                    }
                    writer.WriteLine();

                    tri.triangle.id = index++;
                }


                // Number of edges, zero boundary markers.
                writer.WriteLine("{0} 0", mesh.edges);

                index = 0;
                // To loop over the set of edges, loop over all triangles, and look at
                // the three edges of each triangle.  If there isn't another triangle
                // adjacent to the edge, operate on the edge.  If there is another
                // adjacent triangle, operate on the edge only if the current triangle
                // has a smaller pointer than its neighbor.  This way, each edge is
                // considered only once.
                foreach (var item in mesh.triangles.Values)
                {
                    tri.triangle = item;

                    for (tri.orient = 0; tri.orient < 3; tri.orient++)
                    {
                        tri.Sym(ref trisym);
                        if ((tri.triangle.id < trisym.triangle.id) || (trisym.triangle == Mesh.dummytri))
                        {
                            // Find the number of this triangle (and Voronoi vertex).
                            p1 = tri.triangle.id;

                            if (trisym.triangle == Mesh.dummytri)
                            {
                                torg  = tri.Org();
                                tdest = tri.Dest();

                                // Write an infinite ray. Edge number, index of one endpoint,
                                // -1, and x and y coordinates of a vector representing the
                                // direction of the ray.
                                writer.WriteLine("{0} {1} -1 {2} {3}", index, p1,
                                                 (tdest[1] - torg[1]).ToString(nfi),
                                                 (torg[0] - tdest[0]).ToString(nfi));
                            }
                            else
                            {
                                // Find the number of the adjacent triangle (and Voronoi vertex).
                                p2 = trisym.triangle.id;
                                // Finite edge.  Write indices of two endpoints.
                                writer.WriteLine("{0} {1} {2}", index, p1, p2);
                            }

                            index++;
                        }
                    }
                }
            }
        }
Esempio n. 22
0
 // Token: 0x06000120 RID: 288 RVA: 0x00002962 File Offset: 0x00000B62
 public void GetStaticMethods(Type type, out MethodInfo writer, out MethodInfo reader)
 {
     writer = Primitives.GetWritePrimitive(type);
     reader = Primitives.GetReaderPrimitive(type);
 }
        public int Triangulate(Mesh mesh)
        {
            this.mesh = mesh;

            // Nonexistent x value used as a flag to mark circle events in sweepline
            // Delaunay algorithm.
            xminextreme = 10 * mesh.bounds.Xmin - 9 * mesh.bounds.Xmax;

            SweepEvent[] eventheap;

            SweepEvent nextevent;
            SweepEvent newevent;
            SplayNode  splayroot;
            Otri       bottommost = default(Otri);
            Otri       searchtri  = default(Otri);
            Otri       fliptri;
            Otri       lefttri = default(Otri);
            Otri       righttri = default(Otri);
            Otri       farlefttri = default(Otri);
            Otri       farrighttri = default(Otri);
            Otri       inserttri = default(Otri);
            Vertex     firstvertex, secondvertex;
            Vertex     nextvertex, lastvertex;
            Vertex     connectvertex;
            Vertex     leftvertex, midvertex, rightvertex;
            double     lefttest, righttest;
            int        heapsize;
            bool       check4events, farrightflag = false;

            splaynodes = new List <SplayNode>();
            splayroot  = null;

            CreateHeap(out eventheap);//, out events, out freeevents);
            heapsize = mesh.invertices;

            mesh.MakeTriangle(ref lefttri);
            mesh.MakeTriangle(ref righttri);
            lefttri.Bond(ref righttri);
            lefttri.LnextSelf();
            righttri.LprevSelf();
            lefttri.Bond(ref righttri);
            lefttri.LnextSelf();
            righttri.LprevSelf();
            lefttri.Bond(ref righttri);
            firstvertex = eventheap[0].vertexEvent;

            HeapDelete(eventheap, heapsize, 0);
            heapsize--;
            do
            {
                if (heapsize == 0)
                {
                    SimpleLog.Instance.Error("Input vertices are all identical.", "SweepLine.SweepLineDelaunay()");
                    throw new Exception("Input vertices are all identical.");
                }
                secondvertex = eventheap[0].vertexEvent;
                HeapDelete(eventheap, heapsize, 0);
                heapsize--;
                if ((firstvertex.x == secondvertex.x) &&
                    (firstvertex.y == secondvertex.y))
                {
                    if (Behavior.Verbose)
                    {
                        SimpleLog.Instance.Warning("A duplicate vertex appeared and was ignored.",
                                                   "SweepLine.SweepLineDelaunay().1");
                    }
                    secondvertex.type = VertexType.UndeadVertex;
                    mesh.undeads++;
                }
            } while ((firstvertex.x == secondvertex.x) &&
                     (firstvertex.y == secondvertex.y));
            lefttri.SetOrg(firstvertex);
            lefttri.SetDest(secondvertex);
            righttri.SetOrg(secondvertex);
            righttri.SetDest(firstvertex);
            lefttri.Lprev(ref bottommost);
            lastvertex = secondvertex;

            while (heapsize > 0)
            {
                nextevent = eventheap[0];
                HeapDelete(eventheap, heapsize, 0);
                heapsize--;
                check4events = true;
                if (nextevent.xkey < mesh.bounds.Xmin)
                {
                    fliptri = nextevent.otriEvent;
                    fliptri.Oprev(ref farlefttri);
                    Check4DeadEvent(ref farlefttri, eventheap, ref heapsize);
                    fliptri.Onext(ref farrighttri);
                    Check4DeadEvent(ref farrighttri, eventheap, ref heapsize);

                    if (farlefttri.Equal(bottommost))
                    {
                        fliptri.Lprev(ref bottommost);
                    }
                    mesh.Flip(ref fliptri);
                    fliptri.SetApex(null);
                    fliptri.Lprev(ref lefttri);
                    fliptri.Lnext(ref righttri);
                    lefttri.Sym(ref farlefttri);

                    if (randomnation(SAMPLERATE) == 0)
                    {
                        fliptri.SymSelf();
                        leftvertex  = fliptri.Dest();
                        midvertex   = fliptri.Apex();
                        rightvertex = fliptri.Org();
                        splayroot   = CircleTopInsert(splayroot, lefttri, leftvertex, midvertex, rightvertex, nextevent.ykey);
                    }
                }
                else
                {
                    nextvertex = nextevent.vertexEvent;
                    if ((nextvertex.x == lastvertex.x) &&
                        (nextvertex.y == lastvertex.y))
                    {
                        if (Behavior.Verbose)
                        {
                            SimpleLog.Instance.Warning("A duplicate vertex appeared and was ignored.",
                                                       "SweepLine.SweepLineDelaunay().2");
                        }
                        nextvertex.type = VertexType.UndeadVertex;
                        mesh.undeads++;
                        check4events = false;
                    }
                    else
                    {
                        lastvertex = nextvertex;

                        splayroot = FrontLocate(splayroot, bottommost, nextvertex,
                                                ref searchtri, ref farrightflag);
                        //
                        bottommost.Copy(ref searchtri);
                        farrightflag = false;
                        while (!farrightflag && RightOfHyperbola(ref searchtri, nextvertex))
                        {
                            searchtri.OnextSelf();
                            farrightflag = searchtri.Equal(bottommost);
                        }


                        Check4DeadEvent(ref searchtri, eventheap, ref heapsize);

                        searchtri.Copy(ref farrighttri);
                        searchtri.Sym(ref farlefttri);
                        mesh.MakeTriangle(ref lefttri);
                        mesh.MakeTriangle(ref righttri);
                        connectvertex = farrighttri.Dest();
                        lefttri.SetOrg(connectvertex);
                        lefttri.SetDest(nextvertex);
                        righttri.SetOrg(nextvertex);
                        righttri.SetDest(connectvertex);
                        lefttri.Bond(ref righttri);
                        lefttri.LnextSelf();
                        righttri.LprevSelf();
                        lefttri.Bond(ref righttri);
                        lefttri.LnextSelf();
                        righttri.LprevSelf();
                        lefttri.Bond(ref farlefttri);
                        righttri.Bond(ref farrighttri);
                        if (!farrightflag && farrighttri.Equal(bottommost))
                        {
                            lefttri.Copy(ref bottommost);
                        }

                        if (randomnation(SAMPLERATE) == 0)
                        {
                            splayroot = SplayInsert(splayroot, lefttri, nextvertex);
                        }
                        else if (randomnation(SAMPLERATE) == 0)
                        {
                            righttri.Lnext(ref inserttri);
                            splayroot = SplayInsert(splayroot, inserttri, nextvertex);
                        }
                    }
                }

                if (check4events)
                {
                    leftvertex  = farlefttri.Apex();
                    midvertex   = lefttri.Dest();
                    rightvertex = lefttri.Apex();
                    lefttest    = Primitives.CounterClockwise(leftvertex, midvertex, rightvertex);
                    if (lefttest > 0.0)
                    {
                        newevent = new SweepEvent();

                        newevent.xkey      = xminextreme;
                        newevent.ykey      = CircleTop(leftvertex, midvertex, rightvertex, lefttest);
                        newevent.otriEvent = lefttri;
                        HeapInsert(eventheap, heapsize, newevent);
                        heapsize++;
                        lefttri.SetOrg(new SweepEventVertex(newevent));
                    }
                    leftvertex  = righttri.Apex();
                    midvertex   = righttri.Org();
                    rightvertex = farrighttri.Apex();
                    righttest   = Primitives.CounterClockwise(leftvertex, midvertex, rightvertex);
                    if (righttest > 0.0)
                    {
                        newevent = new SweepEvent();

                        newevent.xkey      = xminextreme;
                        newevent.ykey      = CircleTop(leftvertex, midvertex, rightvertex, righttest);
                        newevent.otriEvent = farrighttri;
                        HeapInsert(eventheap, heapsize, newevent);
                        heapsize++;
                        farrighttri.SetOrg(new SweepEventVertex(newevent));
                    }
                }
            }

            splaynodes.Clear();
            bottommost.LprevSelf();
            return(RemoveGhosts(ref bottommost));
        }
Esempio n. 24
0
    void InitTilesAndEntities()
    {
        //init tiles array
        int tilesAcross = levelData.width;
        int tilesDown   = levelData.height - 1;

        tiles      = new S_Tile[tilesAcross, tilesDown];
        gridWidth  = (int)(tilesAcross * (S_Tile.BASE_TILE_SIZE + 1) * S_Camera.scale + S_Camera.scale);
        gridHeight = (int)(tilesDown * (S_Tile.BASE_TILE_SIZE + 1) * S_Camera.scale + S_Camera.scale);

        //use colours in leveldata to setup entities
        for (int x = 0; x < tilesAcross; x++)
        {
            for (int y = 0; y < tilesDown; y++)
            {
                S_Tile tile;
                switch (FromColour(levelData.GetPixel(x, y)))
                {
                case LevelContent.wall:
                    break;

                case LevelContent.blank:
                    tile = MakeTile(x, y);
                    break;

                case LevelContent.food:
                    tile = MakeTile(x, y);
                    tile.AddPickup();
                    pickupsRemaining++;
                    totalPickups++;
                    break;

                case LevelContent.player:
                    tile = MakeTile(x, y);
                    GameObject playerObject = (GameObject)(GameObject.Instantiate(Resources.Load("prefabs/player")));
                    player = playerObject.GetComponent <S_Player>();
                    player.Init();
                    entities.Add(player);
                    player.MoveToTile(tile, true);
                    break;

                case LevelContent.charger:
                    tile = MakeTile(x, y);
                    GameObject chargerObject = (GameObject)(GameObject.Instantiate(Resources.Load("prefabs/charger")));
                    S_Entity   charger       = chargerObject.GetComponent <S_Charger>();
                    charger.Init();
                    entities.Add(charger);
                    charger.MoveToTile(tile, true);
                    break;

                case LevelContent.enemy:
                    tile = MakeTile(x, y);
                    GameObject pincerObject = (GameObject)(GameObject.Instantiate(Resources.Load("prefabs/pincer")));
                    S_Entity   enemy        = pincerObject.GetComponent <S_Pincer>();
                    enemy.Init();
                    entities.Add(enemy);
                    enemy.MoveToTile(tile, true);
                    break;
                }
            }
        }

        //hierarchy object for entities
        GameObject entityParent = new GameObject("entities");

        entityParent.transform.SetParent(mapObject.transform, false);
        foreach (S_Entity e in entities)
        {
            e.positionSetter.transform.SetParent(entityParent.transform, false);
        }

        //setup map border
        GameObject rect = Primitives.CreateRectangle(tilesAcross * S_Tile.width + S_Camera.scale, tilesDown * S_Tile.height + S_Camera.scale, Colours.RED);

        rect.transform.SetParent(mapObject.transform, false);
        rect.GetComponent <SpriteRenderer>().sortingLayerName = "Tiles";
        rect.GetComponent <SpriteRenderer>().sortingOrder     = 0;
        rect.name = "level_background";

        //add level number (rethink into something symbolic maybe?)

        /*levelNumberObject = Primitives.CreateText(("level " + (Game.Get().levelNumber)));
         * S_Follower follow = levelNumberObject.AddComponent<S_Follower>();
         * follow.Follow(slider.gameObject, 2 * S_Camera.scale, Screen.height - 28 * S_Camera.scale);*/
    }
Esempio n. 25
0
 public static string ToString(Primitives primitive)
 {
     return(PrimitiveDict.GetValue(primitive));
 }
Esempio n. 26
0
 /// <summary>
 /// Adds a brush primitive
 /// </summary>
 /// <param name="type">Type of the brush</param>
 /// <param name="operation">CSG operation of the brush</param>
 /// <param name="blend">Smooth blend distance in voxel units</param>
 /// <param name="transform">Transform to be applied to the brush primitive</param>
 public void AddPrimitive(TBrushType type, BrushOperation operation, float blend, float4x4 transform)
 {
     Primitives.Add(new CustomBrushPrimitive <TBrushType>(type, operation, blend, transform));
 }
Esempio n. 27
0
 void DrawPlaneColliderBounds()
 {
     Primitives.CreatePlaneMesh(3, 3, 2, 2, mesh);
     mesh.RecalculateBounds();
 }
Esempio n. 28
0
        public void HandleObjectSaleInfo(Message m)
        {
            var req = (ObjectSaleInfo)m;

            if (req.CircuitSessionID != req.SessionID ||
                req.CircuitAgentID != req.AgentID)
            {
                return;
            }

            IAgent agent;

            if (!Agents.TryGetValue(req.AgentID, out agent))
            {
                return;
            }

            using (var propHandler = new ObjectPropertiesSendHandler(agent, ID))
            {
                foreach (ObjectSaleInfo.Data d in req.ObjectData)
                {
#if DEBUG
                    m_Log.DebugFormat("ObjectSaleInfo localid={0}", d.ObjectLocalID);
#endif

                    ObjectPart         prim;
                    Object.ObjectGroup grp;
                    if (!Primitives.TryGetValue(d.ObjectLocalID, out prim))
                    {
                        continue;
                    }

                    grp = prim.ObjectGroup;
                    if (grp == null)
                    {
                        continue;
                    }

                    if (!CanEdit(agent, grp, grp.GlobalPosition))
                    {
                        continue;
                    }

                    if (d.SaleType == InventoryItem.SaleInfoData.SaleType.Original &&
                        prim.CheckPermissions(agent.Owner, agent.Group, InventoryPermissionsMask.Copy))
                    {
                        agent.SendAlertMessage(this.GetLanguageString(agent.CurrentCulture, "UnableToSellNoCopyItemAsACopy", "Unable to sell no copy item as a copy."), ID);
                        continue;
                    }

                    if (d.SaleType == InventoryItem.SaleInfoData.SaleType.Copy || d.SaleType == InventoryItem.SaleInfoData.SaleType.Original)
                    {
                        bool foundNoTransfer = false;
                        foreach (ObjectPart part in grp.Values)
                        {
                            if (!part.CheckPermissions(agent.Owner, agent.Group, InventoryPermissionsMask.Transfer))
                            {
                                agent.SendAlertMessage(this.GetLanguageString(agent.CurrentCulture, "UnableToSellNoTransferItem", "Unable to sell no transfer item."), ID);
                                foundNoTransfer = true;
                                break;
                            }
                            foreach (ObjectPartInventoryItem item in part.Inventory.Values)
                            {
                                if (item.CheckPermissions(agent.Owner, agent.Group, InventoryPermissionsMask.Transfer))
                                {
                                    agent.SendAlertMessage(this.GetLanguageString(agent.CurrentCulture, "UnableToSellNoTransferItem", "Unable to sell no transfer item."), ID);
                                    foundNoTransfer = true;
                                    break;
                                }
                            }
                        }
                        if (foundNoTransfer)
                        {
                            continue;
                        }
                    }

                    if (d.SaleType != InventoryItem.SaleInfoData.SaleType.NoSale)
                    {
                        bool foundNoCopyInventory = false;
                        bool foundNoTransfer      = false;
                        foreach (ObjectPartInventoryItem item in prim.Inventory.Values)
                        {
                            if (item.CheckPermissions(agent.Owner, agent.Group, InventoryPermissionsMask.Transfer))
                            {
                                agent.SendAlertMessage(this.GetLanguageString(agent.CurrentCulture, "UnableToSellNoTransferItem", "Unable to sell no transfer item."), ID);
                                foundNoTransfer = true;
                                break;
                            }
                            if (!item.CheckPermissions(agent.Owner, agent.Group, InventoryPermissionsMask.Copy))
                            {
                                foundNoCopyInventory = true;
                            }
                        }
                        if (foundNoTransfer)
                        {
                            continue;
                        }

                        if (foundNoCopyInventory)
                        {
                            agent.SendAlertMessage(this.GetLanguageString(agent.CurrentCulture, "WarningInventoryWillBeSoldAsOriginalAndNotAsCopy", "Warning! Object inventory will be sold as original and not as copy."), ID);
                            continue;
                        }
                    }

                    prim.ObjectGroup.SalePrice = d.SalePrice;
                    prim.ObjectGroup.SaleType  = d.SaleType;
                    propHandler.Send(prim);
                }
            }
        }
Esempio n. 29
0
        public void HandleObjectBuyWorkItem(object o)
        {
            var    req = (ObjectBuy)o;
            IAgent agent;

            if (!Agents.TryGetValue(req.AgentID, out agent))
            {
                return;
            }

            foreach (ObjectBuy.Data data in req.ObjectData)
            {
                ObjectPart part;
                if (!Primitives.TryGetValue(data.ObjectLocalID, out part))
                {
                    agent.SendAlertMessage(this.GetLanguageString(agent.CurrentCulture, "UnableToBuyDueNotFoundObject", "Unable to buy. The object was not found."), ID);
                }
                else
                {
                    Object.ObjectGroup grp = part.ObjectGroup;
                    if (grp.SalePrice != data.SalePrice || grp.SaleType != data.SaleType)
                    {
                        agent.SendAlertMessage(this.GetLanguageString(agent.CurrentCulture, "BuyingCurrentlyNotPossibleDueInvalidRequest", "Buying currently not possible since the viewer request is invalid. You might have to relog."), ID);
                    }
                    else if (grp.SalePrice != 0 && agent.EconomyService == null)
                    {
                        agent.SendAlertMessage(this.GetLanguageString(agent.CurrentCulture, "BuyingForAnyOtherPriceThanZeroIsNotPossible", "Buying for any other price than zero is not possible without economy system."), ID);
                    }
                    else
                    {
                        var       assetids        = new List <UUID>();
                        var       items           = new List <InventoryItem>();
                        bool      foundNoTransfer = false;
                        AssetData newAsset;
                        switch (grp.SaleType)
                        {
                        case InventoryItem.SaleInfoData.SaleType.NoSale:
                        default:
                            continue;

                        case InventoryItem.SaleInfoData.SaleType.Original:
                        case InventoryItem.SaleInfoData.SaleType.Copy:
                            UUID assetID;
                            if (grp.Owner == agent.Owner)
                            {
                                assetID = grp.OriginalAssetID;
                                if (assetID == UUID.Zero)
                                {
                                    newAsset    = grp.Asset(XmlSerializationOptions.WriteXml2 | XmlSerializationOptions.WriteOwnerInfo);
                                    assetID     = UUID.Random;
                                    newAsset.ID = assetID;
                                    AssetService.Store(newAsset);
                                    assetID             = newAsset.ID;
                                    grp.OriginalAssetID = assetID;
                                }
                            }
                            else
                            {
                                assetID = grp.NextOwnerAssetID;
                                if (assetID == UUID.Zero)
                                {
                                    newAsset    = grp.Asset(UGUI.Unknown, XmlSerializationOptions.WriteXml2 | XmlSerializationOptions.AdjustForNextOwner);
                                    assetID     = UUID.Random;
                                    newAsset.ID = assetID;
                                    AssetService.Store(newAsset);
                                    assetID = newAsset.ID;
                                    grp.NextOwnerAssetID = assetID;
                                }
                            }
                            assetids.Add(assetID);

                            if (grp.SaleType == InventoryItem.SaleInfoData.SaleType.Original)
                            {
                                Remove(grp);
                            }

                            bool foundNoCopy = false;
                            foreach (ObjectPart checkpart in grp.Values)
                            {
                                if (!checkpart.CheckPermissions(checkpart.Owner, checkpart.Group, InventoryPermissionsMask.Transfer))
                                {
                                    agent.SendAlertMessage(this.GetLanguageString(agent.CurrentCulture, "UnableToSellNoTransferItem", "Unable to sell no transfer item."), ID);
                                    foundNoTransfer = true;
                                    break;
                                }
                                if (grp.SaleType == InventoryItem.SaleInfoData.SaleType.Copy &&
                                    !checkpart.CheckPermissions(checkpart.Owner, checkpart.Group, InventoryPermissionsMask.Copy))
                                {
                                    agent.SendAlertMessage(this.GetLanguageString(agent.CurrentCulture, "UnableToSellNoCopyItemAsACopy", "Unable to sell no copy item as a copy."), ID);
                                    foundNoCopy = true;
                                    break;
                                }
                                foreach (ObjectPartInventoryItem item in checkpart.Inventory.Values)
                                {
                                    if (item.CheckPermissions(item.Owner, item.Group, InventoryPermissionsMask.Transfer))
                                    {
                                        agent.SendAlertMessage(this.GetLanguageString(agent.CurrentCulture, "UnableToSellNoTransferItem", "Unable to sell no transfer item."), ID);
                                        foundNoTransfer = true;
                                        break;
                                    }
                                }
                            }
                            if (foundNoTransfer || foundNoCopy)
                            {
                                continue;
                            }
                            var objectItem = new InventoryItem
                            {
                                Name          = grp.Name,
                                Description   = grp.Description,
                                LastOwner     = grp.Owner,
                                Owner         = agent.Owner,
                                AssetID       = assetID,
                                AssetType     = AssetType.Object,
                                InventoryType = InventoryType.Object
                            };
                            objectItem.Permissions.Base      = grp.RootPart.BaseMask;
                            objectItem.Permissions.EveryOne  = grp.RootPart.EveryoneMask;
                            objectItem.Permissions.Group     = InventoryPermissionsMask.None;
                            objectItem.Permissions.NextOwner = grp.RootPart.NextOwnerMask;
                            objectItem.Permissions.Current   = objectItem.Permissions.Base;
                            if (!agent.Owner.EqualsGrid(grp.Owner))
                            {
                                objectItem.AdjustToNextOwner();
                            }
                            items.Add(objectItem);
                            break;

                        case InventoryItem.SaleInfoData.SaleType.Content:
                            foreach (ObjectPartInventoryItem item in part.Inventory.Values)
                            {
                                if (!item.CheckPermissions(item.Owner, item.Group, InventoryPermissionsMask.Transfer))
                                {
                                    agent.SendAlertMessage(this.GetLanguageString(agent.CurrentCulture, "UnableToSellNoTransferItem", "Unable to sell no transfer item."), ID);
                                    foundNoTransfer = true;
                                    break;
                                }
                            }

                            if (foundNoTransfer)
                            {
                                continue;
                            }

                            foreach (ObjectPartInventoryItem item in part.Inventory.Values)
                            {
                                assetID = item.NextOwnerAssetID;
                                if (assetID == UUID.Zero && !item.Owner.EqualsGrid(agent.Owner))
                                {
                                    /* create next owner asset id */
                                    item.NextOwnerAssetID = AssetService.GenerateNextOwnerAsset(assetID);
                                }
                                var newItem = new InventoryItem(item);
                                if (!item.Owner.EqualsGrid(agent.Owner))
                                {
                                    newItem.AssetID = item.NextOwnerAssetID;
                                    newItem.AdjustToNextOwner();
                                }
                                assetids.Add(newItem.AssetID);

                                items.Add(newItem);
                                if (!item.CheckPermissions(item.Owner, item.Group, InventoryPermissionsMask.Copy))
                                {
                                    part.Inventory.Remove(item.ID);
                                }
                            }
                            break;
                        }

                        if (grp.SalePrice == 0)
                        {
                            new ObjectBuyTransferItem(
                                agent,
                                this,
                                assetids,
                                items,
                                grp.SaleType == InventoryItem.SaleInfoData.SaleType.Content ? part.Name : string.Empty,
                                part.ID).QueueWorkItem();
                        }
                        else if (agent.EconomyService != null)
                        {
                            IActiveTransaction transaction;
                            try
                            {
                                transaction = agent.EconomyService.BeginTransferTransaction(agent.Owner, part.Owner,
                                                                                            grp.SaleType == InventoryItem.SaleInfoData.SaleType.Content ?
                                                                                            (BaseTransaction) new ObjectInventorySaleTransaction(
                                                                                                GridPosition,
                                                                                                ID,
                                                                                                Name)
                                {
                                    ObjectID   = grp.ID,
                                    ObjectName = grp.Name
                                } :
                                                                                            new ObjectSaleTransaction(
                                                                                                GridPosition,
                                                                                                ID,
                                                                                                Name)
                                {
                                    ObjectID   = grp.ID,
                                    ObjectName = grp.Name
                                },
                                                                                            grp.SalePrice);
                            }
                            catch (InsufficientFundsException)
                            {
                                agent.SendAlertMessage(this.GetLanguageString(agent.CurrentCulture, "UnableToBuyInsufficientFunds", "Unable to buy. Insufficient funds."), ID);
                                continue;
                            }
                            catch (Exception e)
                            {
                                m_Log.Error("Exception at object selling", e);
                                agent.SendAlertMessage(e.Message, ID);
                                continue;
                            }

                            new ObjectBuyTransferItem(
                                agent,
                                this,
                                assetids,
                                items,
                                grp.SaleType == InventoryItem.SaleInfoData.SaleType.Content ? part.Name : string.Empty,
                                part.ID,
                                transaction).QueueWorkItem();
                        }
                        else
                        {
                            agent.SendAlertMessage(this.GetLanguageString(agent.CurrentCulture, "UnableToBuyNoEconomyConfigured", "Unable to buy. No economy configured."), ID);
                        }
                    }
                }
            }
        }
Esempio n. 30
0
        /// <summary>
        /// Creates an <see cref="ISdf"/> that returns the values of the compound SDF of this custom brush.
        /// The SDF must be disposed of when it is no longer needed!
        /// </summary>
        /// <param name="allocator">Allocator with which the SDF data should be allocated</param>
        /// <returns></returns>
        public CustomBrushSdf <TBrushType, TEvaluator> CreateSdf(Allocator allocator)
        {
            var nativePrimitives = new NativeArray <CustomBrushPrimitive <TBrushType> >(Primitives.ToArray(), allocator);

            return(new CustomBrushSdf <TBrushType, TEvaluator>(nativePrimitives, Evaluator));
        }
Esempio n. 31
0
        private SphereTreeNode FindChildToDemote(SphereTreeNode s)
        {
            if (MO.DoLog)
            {
                MO.Log(" Demote this {0} s {1}", this, s);
            }
            Debug.Assert(s.leafNode, "s isn't a leaf node");
            // All children are occupied, and s is not wholly contained in
            // any of them.  Combine s with some child, creating a
            // subordinate.  Choose the child whose center is nearest
            // s.center.  If the child has a larger radius, insert s in
            // the child.  If the child has a smaller radius, s becomes
            // the child, and the child is inserted in s.
            float closest      = float.MaxValue;
            int   closestChild = -1;

            for (int i = 0; i < childCount; i++)
            {
                SphereTreeNode child = children[i];
                Debug.Assert(child != null, "Null child!");
                float d = Primitives.DistanceSquared(s.center, child.center);
                if (d < closest)
                {
                    closest      = d;
                    closestChild = i;
                }
            }
            Debug.Assert(closestChild >= 0, "closestChild not found!");
            SphereTreeNode cs = children[closestChild];

            if (cs.leafNode)
            {
                if (MO.DoLog)
                {
                    MO.Log(" Calling CombineLeafNodes to combine {0} with {1}", cs, this);
                }
                SphereTreeNode n = cs.CombineLeafNodes(s);
                children[closestChild] = n;
                return(n);
            }
            else if (cs.ChildSlotsFree() > 0)
            {
                cs.AddChild(s);
                cs.RecalculateCenterAndRadius();
                return(cs);
            }
            else
            {
                SphereTreeNode n = new SphereTreeNode(sphereTree);
                RemoveChild(cs);
                AddChild(n);
                n.AddChild(cs);
                n.AddChild(s);
                n.RecalculateCenterAndRadius();
                if (MO.DoLog)
                {
                    MO.Log(" In demote, made new node n {0}", n);
                }
                return(n);
            }
        }
Esempio n. 32
0
 internal void Clear()
 {
     Primitives.Clear();
     points_.Clear();
 }
Esempio n. 33
0
        public static Object Call(Cons args, Environment environment)
        {
            string v = //"//(call " + Printer.ConsToString(args) + ")" + NewLine +
                       "{" + NewLine;

            ArrayList argtypes = new ArrayList();
            ArrayList argz     = new ArrayList();

            if (args.Length() > 2)
            {
                foreach (object arg in (args.Cddr() as Cons))
                {
                    if (Primitives.IsAtom(arg))
                    {
                        argz.Add(Printer.WriteToString(arg));
                    }
                    else
                    {
                        string argn = MakeUnique("arg");
                        string sv   = Generate(arg, environment);
                        sv += string.Format(@"{0} {1} = ({0}) retval;
", typeof(object), argn);

                        argz.Add(argn);

                        v += sv;
                    }
                    argtypes.Add(typeof(object));
                }
            }

            string typemethname = args.Car().ToString();

            string methname = typemethname;
            string typename = string.Empty;
            Type   type     = typeof(object);

            int i = methname.LastIndexOf(".");

            if (i >= 0)
            {
                methname = methname.Substring(i + 1);
                typename = typemethname.Substring(0, i);
                type     = TypeCache.FindType(typename);
            }

            MethodInfo mi = null;

            mi = type.GetMethod(methname, BindingFlags.IgnoreCase
                                | BindingFlags.Public | BindingFlags.Instance, binder, argtypes.ToArray(typeof(Type)) as Type[], null);

            string objn = string.Empty;

            if (mi == null)
            {
                type = TypeCache.FindType(args.Second().ToString());
                mi   = type.GetMethod(methname, BindingFlags.IgnoreCase
                                      | BindingFlags.Public | BindingFlags.Static, binder, argtypes.ToArray(typeof(Type)) as Type[], null);

                if (mi == null)
                {
                    // use reflection
                    v += Generate(args.Second(), environment);
                    v += string.Format(@"retval = retval.GetType().InvokeMember(""{0}"", 
BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance, null, retval,
new object[]{{", methname) +
                         string.Join(", ", argz.ToArray(typeof(string)) as string[]) + @"});
}
";
                    return(v);
                }
                else
                {
                    objn = type.ToString();
                }
            }
            else
            {
                objn = MakeUnique("obj");
                v   += Generate(args.Second(), environment);
                v   += string.Format(@"{0} {1} = ({0}) retval;
", type, objn);
            }

            v += "retval = " + (mi.ReturnType == typeof(void) ? @"null;
" : "") + objn + "." + mi.Name + "(" +
                 string.Join(", ", argz.ToArray(typeof(string)) as string[]);

            return(v + @");
}
");
        }
Esempio n. 34
0
        private string getValueFromResultSet(Primitives primitive, QueryResult result)
        {
            bool fetchUsingSeqNumber = ProgGenUtil.coinFlip();

            if (primitive == Primitives.INT)
            {
                if (fetchUsingSeqNumber)
                {
                    return("rs.getInt(" + result.SeqNumber + ");\n");
                }
                return("rs.getInt(\"" + result.Name + "\");\n");
            }
            else if (primitive == Primitives.BYTE)
            {
                if (fetchUsingSeqNumber)
                {
                    return("rs.getByte(" + result.SeqNumber + ");\n");
                }
                return("rs.getByte(\"" + result.Name + "\");\n");
            }
            else if (primitive == Primitives.CHAR)
            {
                if (fetchUsingSeqNumber)
                {
                    return("rs.getString(" + result.SeqNumber + ");\n");
                }
                return("rs.getString(\"" + result.Name + "\");\n");
            }
            else if (primitive == Primitives.DOUBLE)
            {
                if (fetchUsingSeqNumber)
                {
                    return("rs.getDouble(" + result.SeqNumber + ");\n");
                }
                return("rs.getDouble(\"" + result.Name + "\");\n");
            }
            else if (primitive == Primitives.FLOAT)
            {
                if (fetchUsingSeqNumber)
                {
                    return("rs.getFloat(" + result.SeqNumber + ");\n");
                }
                return("rs.getFloat(\"" + result.Name + "\");\n");
            }
            else if (primitive == Primitives.LONG)
            {
                if (fetchUsingSeqNumber)
                {
                    return("rs.getLong(" + result.SeqNumber + ");\n");
                }
                return("rs.getLong(\"" + result.Name + "\");\n");
            }
            else if (primitive == Primitives.SHORT)
            {
                if (fetchUsingSeqNumber)
                {
                    return("rs.getShort(" + result.SeqNumber + ");\n");
                }
                return("rs.getShort(\"" + result.Name + "\");\n");
            }
            else if (primitive == Primitives.STRING)
            {
                if (fetchUsingSeqNumber)
                {
                    return("rs.getString(" + result.SeqNumber + ");\n");
                }
                return("rs.getString(\"" + result.Name + "\");\n");
            }
            return(null);
        }
Esempio n. 35
0
        public float pixelColor; //de pixelkleur in float ipv integer voor de berekeningen

        // initialize
        public void Init()
        {
            //om te proberen definieer ik hier twee lichtpunten
            lights[0] = new Light
            {
                pX    = 300,
                pY    = 100, //x + y * width is de locatie van het licht (x,y) in de pixelarray
                color = MixColor(1, 1, 1)
            };
            lights[1] = new Light
            {
                pX    = 200,
                pY    = 50,
                color = MixColor(1, 1, 0)
            };
            lights[2] = new Light
            {
                pX    = 100,
                pY    = 26,
                color = MixColor(1, 1, 0)
            };

            // hieronder een lege primitive om de code werkend te maken.
            primitives[0] = new Primitives
            {
                centerX        = 5,
                centerY        = 30,
                radius         = 100,
                PrimitivesType = PrimitivesType.Circle
            };

            //hieronder de basiscode uit de opdracht, vertaald naar c# code
            for (int x = 0; x < screen.pixels.Length; x++)
            {
                pixelColor = MixColor(0, 0, 0);

                for (int y = 0; y < lights.Length; y++)
                {
                    ray.O    = ray.pixelPositions(x, screen.width);
                    ray.t    = ray.distanceToLight(lights[y].pX, lights[y].pY);
                    ray.D    = ray.normalizeDirectionToLight(lights[y].pX, lights[y].pY);
                    occluced = false;
                    for (int p = 0; p < primitives.Length; p++)
                    {
                        if (ray.intersects(primitives[p]))
                        {
                            occluced = true;
                        }
                    }
                    if (!occluced)
                    {
                        pixelColor += lights[y].color * ray.lightAttenuation(ray.t);
                    }
                }



                //gaat dit hieronder qua afronding goed?
                screen.pixels[x] = (int)pixelColor;
            }
        }
Esempio n. 36
0
        public AssignmentExpression(Method method)
        {
            Random rand = new Random();

            //should we use field or variable?
            int OptionVarOrField = rand.Next(100) % 2;

            if (OptionVarOrField == 0)
            {
                // Introducing any variable
                lhs = VariableGenerator.getRandomizedVariable(method);
            }
            else
            {
                //Introducing any field
                lhs = FieldGenerator.getRandomField(method.AssociatedClass, method.Static);

                if (lhs == null)
                {
                    //if no field is present, introduce variable
                    lhs = VariableGenerator.getRandomizedVariable(method);
                }
            }

            // if no variable is present, just use print statements
            if (lhs == null)
            {
                output += (new PrintStatement(method)).ToString();
                return;
            }


            Primitives primitive = lhs.type.getType();

            //If the primitive is an object, invoke constructor
            if (primitive == Primitives.OBJECT)
            {
                output += lhs + " = new " + ProgGenUtil.getClassToConstruct(lhs.Type.ToString(), method.ClassList) + "();\n";
                return;
            }

            //Randomly choose to nest operation or not
            int option = rand.Next(100);

            if (option > method.AssociatedClass.Percent)
            {
                leftExpr  = new NormalExpression(method, primitive);
                rightExpr = new NormalExpression(method, primitive);
                Operator binOp = new BinaryOperator(primitive);

                // Removing variable from right expr. if binOp is / or %
                // i6=(i3/2)%(i3-5)  => i6=(i3/2)%constant
                //if (binOp.ToString().Equals("/") || binOp.ToString().Equals("%"))
                //{
                //    do
                //    { //FIXME: only handles int for now.
                //        rightExpr = new Literal(primitive,Int32.MaxValue);
                //    }while (rightExpr.ToString().Contains("(0)")); //avoiding divide by (0)
                //}

                output += lhs + " = (" + lhs.Type + ")(" + leftExpr + binOp.ToString() + rightExpr + ");\n";
            }
            else
            {
                if (ProgGenUtil.useQueries)
                {
                    if (ProgGenUtil.coinFlip())
                    {
                        expr = new NormalExpression(method, primitive);

                        //we don't want assignments statements like this: i8 = i8
                        while (lhs.Equals(expr.ToString()))
                        {
                            expr = new NormalExpression(method, lhs.type.getType());
                        }
                        output += lhs + " = (" + lhs.Type + ")" + expr.ToString() + ";\n";
                    }
                    else
                    {
                        Console.WriteLine("Trying to fetch literal from database for : " + lhs.Type);
                        StringBuilder builder = new StringBuilder();
                        Query         query   = getQueryForType(primitive);
                        if (query == null)
                        {
                            //no query results
                            output += lhs + " = (" + lhs.Type + ")" + new Literal(primitive, Int32.MaxValue) + ";\n";
                            return;
                        }

                        builder.Append("try{");
                        builder.Append("ResultSet rs = DBUtil.getDBUtil().executeQuery(");
                        builder.Append("\"" + query.QueryString + "\"");
                        builder.Append(");\n");

                        builder.Append("rs.last();\n");
                        builder.Append("int rowToSelect = new Random().nextInt(rs.getRow());\n");
                        builder.Append("rs.first();\n");

                        builder.Append("for(int rowToSelectCounter=0; rowToSelectCounter<rowToSelect;rowToSelectCounter++)");
                        builder.Append("{ 	rs.next();	}\n");

                        List <QueryResult> queryResultsForType = getColumnNumbersForType(query, primitive);
                        if (queryResultsForType.Count == 0)
                        {
                            //no query results present for expected type.
                            output += lhs + " = (" + lhs.Type + ")" + new Literal(primitive, Int32.MaxValue) + ";\n";
                            return;
                        }

                        int         resultToSelect = (new Random()).Next(queryResultsForType.Count);
                        QueryResult selectedResult = queryResultsForType[resultToSelect];

                        string result = getValueFromResultSet(primitive, selectedResult);
                        if (result == null)
                        {
                            output += lhs + " = (" + lhs.Type + ")" + new Literal(primitive, Int32.MaxValue) + ";\n";
                            return;
                        }
                        builder.Append(lhs + " = (" + lhs.Type + ")" + result + "\n\n");
                        builder.Append("} catch(Exception e) { e.printStackTrace(); }\n\n");
                        builder.Append("Console.WriteLine(" + lhs + ");\n");
                        output += builder.ToString();
                    }
                }
                else
                {
                    expr = new NormalExpression(method, primitive);

                    //we don't want assignments statements like this: i8 = i8
                    while (lhs.Equals(expr.ToString()))
                    {
                        expr = new NormalExpression(method, lhs.type.getType());
                    }
                    output += lhs + " = (" + lhs.Type + ")" + expr.ToString() + ";\n";
                }
            }
        }
Esempio n. 37
0
            public override void VisitPointMarker( Primitives.PointMarker pointMarker )
            {
                if( !InClip( pointMarker ) )
                {
                    return;
                }

                switch( _renderer.MarkerAction )
                {
                    case MarkerHandling.Display:
                        using( Pen pen = CreateDebugPen() )
                        {
                            _graphics.DrawEllipse( pen, (float) pointMarker.Point.X - 2.0f, (float) pointMarker.Point.Y - 2.0f, 4.0f, 4.0f );
                        }
                        break;
                    case MarkerHandling.Throw:
                        throw new InvalidOperationException( "PointMarker found by renderer." );
                }
            }
Esempio n. 38
0
 public abstract void Apply( Renderers.Renderer renderer, Primitives.VisualItem item );
Esempio n. 39
0
    public static GameObject CreatePauseScreen()
    {
        //all this code is a big pile of rubbish, I need to try unity unity ui next time!

        //background
        GameObject pauseScreen = new GameObject("pause_screen");
        GameObject pauseBG     = Primitives.CreateRectangle(pauseWidth, pauseHeight, Colours.RED);

        pauseBG.transform.SetParent(pauseScreen.transform, false);
        BoxCollider2D pausebgcol = pauseBG.AddComponent <BoxCollider2D>();

        pausebgcol.size   = new Vector2(1, 1);
        pausebgcol.offset = new Vector2(.5f, .5f);
        Util.SetLayer(pauseBG, Util.LayerName.UI, 0);
        Util.SetZ(pauseBG, Util.ZLayer.PauseLayer);
        GameObject pauseBGInner = Primitives.CreateRectangle(pauseWidth - border * 2, pauseHeight - border * 2, Colours.DARK);

        pauseBGInner.transform.position = new Vector2(border, border);
        pauseBGInner.transform.SetParent(pauseScreen.transform, false);
        Util.SetLayer(pauseBGInner, Util.LayerName.UI, 1);
        Util.SetLayer(pauseBG, Util.LayerName.UI, 1);
        pauseScreen.transform.position = new Vector2((int)(Screen.width / 2 - pauseWidth / 2), (int)(Screen.height / 2 - pauseHeight / 2));

        //sliders
        int barWidth = (int)(pauseWidth - border * 2 - gap * 3 - Sprites.GetBounds(Sprites.sound).x *S_Camera.scale);
        int barX     = (int)(border + gap * 2 + Sprites.GetBounds(Sprites.sound).x *S_Camera.scale);
        int currentY = pauseHeight - border;

        currentY            -= gap + S_OptionSlider.TOTAL_HEIGHT;
        S_OptionSlider.music = S_OptionSlider.CreateSlider(barWidth);
        S_OptionSlider.music.transform.position = new Vector2(barX, currentY);
        S_OptionSlider.music.transform.SetParent(pauseScreen.transform, false);
        Util.SetZ(S_OptionSlider.music.gameObject, Util.ZLayer.Sliders);
        GameObject music = Primitives.CreateActor(Sprites.music);

        S_Camera.SetupScale(music.transform);
        music.transform.position = new Vector2(border + gap, currentY + S_OptionSlider.BAR_HEIGHT / 2 - Sprites.GetBounds(Sprites.music).y *S_Camera.scale / 2);
        music.transform.SetParent(pauseScreen.transform, false);
        Util.SetLayer(music, Util.LayerName.UI, 50);
        currentY -= gap + S_OptionSlider.TOTAL_HEIGHT;
        S_OptionSlider.music.SetUpAction(() => { PlayerPrefs.SetFloat("music", S_OptionSlider.music.GetValue()); });
        S_OptionSlider.music.SetRatio(PlayerPrefs.GetFloat("music", .7f));

        S_OptionSlider.sfx = S_OptionSlider.CreateSlider(barWidth);
        S_OptionSlider.sfx.transform.position = new Vector2(barX, currentY);
        S_OptionSlider.sfx.transform.SetParent(pauseScreen.transform, false);
        Util.SetZ(S_OptionSlider.sfx.gameObject, Util.ZLayer.Sliders);
        GameObject sound = Primitives.CreateActor(Sprites.sound);

        S_Camera.SetupScale(sound.transform);
        sound.transform.position = new Vector2(border + gap, currentY + S_OptionSlider.BAR_HEIGHT / 2 - Sprites.GetBounds(Sprites.music).y *S_Camera.scale / 2);
        sound.transform.SetParent(pauseScreen.transform, false);
        Util.SetLayer(sound, Util.LayerName.UI, 50);
        currentY -= gap + S_OptionSlider.TOTAL_HEIGHT;
        S_OptionSlider.sfx.SetUpAction(() => { PlayerPrefs.SetFloat("sfx", S_OptionSlider.sfx.GetValue()); });
        S_OptionSlider.sfx.SetRatio(PlayerPrefs.GetFloat("sfx", .7f));

        //icons
        int codeX  = (pauseWidth - border * 2) / 3 + border;
        int musicX = (pauseWidth - border * 2) / 3 * 2 + border;

        int iconY    = currentY;
        int twitterY = (int)(iconY - gap - Sprites.GetBounds(Sprites.twitter).y *S_Camera.scale / 2f);

        iconY += gap / 2;

        GameObject code = Primitives.CreateActor(Sprites.code);

        S_Camera.SetupScale(code.transform);
        code.transform.position = new Vector2(codeX - Sprites.GetBounds(Sprites.code).x *S_Camera.scale / 2f, iconY - Sprites.GetBounds(Sprites.code).y *S_Camera.scale / 2f);
        code.transform.SetParent(pauseScreen.transform, false);
        Util.SetLayer(code, Util.LayerName.UI, 50);

        music = Primitives.CreateActor(Sprites.music);
        S_Camera.SetupScale(music.transform);
        music.transform.position = new Vector2(musicX - Sprites.GetBounds(Sprites.music).x *S_Camera.scale / 2f, iconY - Sprites.GetBounds(Sprites.music).x *S_Camera.scale / 2f);
        music.transform.SetParent(pauseScreen.transform, false);
        Util.SetLayer(music, Util.LayerName.UI, 50);


        //bottom info
        S_Button myTwitter = S_Button.CreateButton(Sprites.twitter);

        S_Camera.SetupScale(myTwitter.transform);
        myTwitter.transform.position = new Vector2(codeX - Sprites.GetBounds(Sprites.twitter).x *S_Camera.scale / 2f, twitterY - Sprites.GetBounds(Sprites.twitter).y *S_Camera.scale / 2f);
        myTwitter.transform.SetParent(pauseScreen.transform, false);
        Util.SetLayer(myTwitter.gameObject, Util.LayerName.UI, 50);
        myTwitter.SetDownAction(() => Application.OpenURL("https://twitter.com/ColourTann"));

        S_Button website = S_Button.CreateButton(Sprites.website);

        S_Camera.SetupScale(website.transform);
        website.transform.position = new Vector2(musicX - Sprites.GetBounds(Sprites.website).x *S_Camera.scale / 2f, twitterY - Sprites.GetBounds(Sprites.website).x *S_Camera.scale / 2f);
        website.transform.SetParent(pauseScreen.transform, false);
        Util.SetLayer(website.gameObject, Util.LayerName.UI, 50);
        website.SetDownAction(() => Application.OpenURL("http://chriszabriskie.com/"));

        return(pauseScreen);
    }
Esempio n. 40
0
 public abstract void MeasureText( Primitives.Text text, out double width, out double height, out double baselineFromTop );
Esempio n. 41
0
            public override void VisitPath( Primitives.Path path )
            {
                if( !InClip( path ) )
                {
                    return;
                }

                Types.Rectangle bounds = path.GetBounds( _renderer );
                Pen[] pens = _renderer.CreatePens( path.Pen );
                BrushStage[] brushes = _renderer.CreateBrushes( _graphics, bounds, path.Brush );
                GraphicsPath gp = _renderer.CreateGraphicsPath( path );

                foreach( BrushStage brush in brushes )
                {
                    _graphics.FillPath( brush.GetBrush(), gp );

                    brush.Dispose();
                }
                foreach( Pen pen in pens )
                {
                    _graphics.DrawPath( pen, gp );

                    pen.Dispose();
                }
            }
Esempio n. 42
0
        // Read parameter values from RAM or EEPROM.
        // Command syntax: data[]={ readId, cmdFlags, page, <numRead:>numToRead, {parameterIndexes}+ }
        //						<[{[VarKind[,StoreFlgs,ArgsFlgs,value data]}*]>.
        // Or: data[]={ readId, cmdFlags, page, name} when BX_MEDIATOR_DEVICE_RWV_FLAGS_BY_NAME cmdFlag set.
        // In reply to a BY_NAME: strips out request name and sets NAME flag to reply in std form.
        // Returns number of values read / changed depending on readFlags:
        // BX_MEDIATOR_DEVICE_MONITORVAR = Iso compare and return true if parameters have changed.
        // For each parameter, replies with:
        //  {DSK [,DSF, [ ramValue,] [ eepromValue,] [defaultValue]
        //       [dataSize, minValue, maxValue] [name + '\0'] ]}.
        public byte MediatorReadCommand(MessageTransaction mtx)
        {
            DeviceParameterTable pt = Exchange.ParameterTable;
            DeviceParameter      d;
            PacketBuffer         g = mtx.MsgBuffer;

            byte[] pAry;
            int    numReadIndex, dataIndex;
            bool   addMeta, addKindOnly;
            byte   n, j, k, byteCount, numToRead;
            byte   readId, cmdFlags, pageNum, parameterVarKind, parameterFlags, parameterSize, metaSize;
            byte   c = 0, maxData = (byte)(Exchange.Manager.MaxPacketSize - ProtocolConstants.GENERAL_OVERHEADS_SIZE);

            byte[] paramIndexes = new byte[8];
            n = g.dataLength();
            if (n < 5)
            {
                return(0);
            }
            numReadIndex = -1;
            dataIndex    = ProtocolConstants.GENERAL_DATA_ARRAY_OFFSET;
            pAry         = g.buffer;
            readId       = pAry[dataIndex++];
            cmdFlags     = pAry[dataIndex++];
            pageNum      = pAry[dataIndex++];
            n           -= 3;
            // TODO: table page selection.
            addKindOnly = (cmdFlags & ProtocolConstants.MEDIATOR_DEVICE_RWV_FLAGS_PACK_KIND) != 0;
            addMeta     = addKindOnly || (cmdFlags & ProtocolConstants.MEDIATOR_DEVICE_RWV_FLAGS_PACK) == 0;
            if ((cmdFlags & ProtocolConstants.MEDIATOR_DEVICE_RWV_FLAGS_BY_NAME) != 0)
            {
                pAry[dataIndex + n] = 0;
                string name = Primitives.GetArrayStringValue(pAry, dataIndex, n);
                // Search for name in table.
                d = pt.Find(name);
                if (d == null)
                {
                    pAry[dataIndex - 1] = cmdFlags;
                    dataIndex          += n;
                    numToRead           = 0;
                }
                else
                {
                    // If found, fall through and add meta data.
                    cmdFlags       |= ProtocolConstants.MEDIATOR_DEVICE_RWV_FLAGS_NAME;
                    numToRead       = 1;
                    paramIndexes[0] = (byte)d.ParamIndex;
                }
            }
            else
            {
                --n;
                numToRead = (byte)(pAry[dataIndex++] & 0xf);
                if (numToRead > n)
                {
                    numToRead = n;
                }
                j = numToRead;
                if (numToRead > 8)
                {
                    numToRead = 8;
                }
                for (k = 0; k < numToRead; k++)
                {
                    paramIndexes[k] = pAry[dataIndex + k];
                }
            }
            if (numToRead > 0)
            {
                dataIndex         = ProtocolConstants.GENERAL_DATA_ARRAY_OFFSET;
                pAry              = g.buffer;
                pAry[dataIndex++] = readId;
                pAry[dataIndex++] = cmdFlags; // Restore parameters.
                pAry[dataIndex++] = pageNum;
                numReadIndex      = dataIndex;
                pAry[dataIndex++] = 0;
                for (k = 0; k < numToRead; k++)
                {
                    pAry[dataIndex++] = paramIndexes[k];
                }
            }
            byteCount = (byte)dataIndex;
            g.dataLength(byteCount);
            k = 0;
            while (k < numToRead)
            {
                byte paramIndex = paramIndexes[k];
                if (paramIndex > pt.GetLastEntryIndex())
                {
                    break;
                }
                d = pt.Find(paramIndex);
                if (d == null)
                {
                    d = DeviceParameterTable.NullParameter;
                }
                n = 0;
                parameterVarKind = (byte)d.ParamVarKind;
                if (addMeta)
                {
                    // Write out representation kind.
                    metaSize = 1;
                    if ((byteCount + metaSize) >= maxData)
                    {
                        break;
                    }
                    pAry[dataIndex + n++] = parameterVarKind;
                }
                else
                {
                    metaSize = 0;
                }
                if (parameterVarKind != (byte)VariableKind.VK_None)
                {
                    VariableValue p; byte[] b;
                    byte          argsFlags, argsIndex = 0;
                    parameterSize  = (byte)d.ParamSize;
                    parameterFlags = (byte)d.ParamStorageFlags;
                    if (addMeta && !addKindOnly)
                    {
                        // Write out parameter flags & space for argsFlags.
                        metaSize += 2;
                        if ((byteCount + metaSize) >= maxData)
                        {
                            break;
                        }
                        pAry[dataIndex + n++] = parameterFlags;
                        argsIndex             = n++;
                    }
                    argsFlags = 0;
                    // Now write out parameter details depending on cmd flags.
                    if (((cmdFlags & ProtocolConstants.MEDIATOR_DEVICE_RWV_FLAGS_RAM) != 0) &&
                        ((parameterFlags & (byte)StorageFlags.SF_RAM) != 0))
                    {
                        p = d.RamValue;
                        if (p != null)
                        {
                            if (parameterVarKind == (byte)VariableKind.VK_String) // Get size of string.
                            {
                                byte maxSize = (byte)d.MaxValue.ValueLong;
                                int  s       = p.ValueString.Length;
                                if (s > maxSize)
                                {
                                    s = maxSize;
                                }
                                parameterSize = (byte)(1 + s); // Allow one for len byte.
                            }
                            if ((byteCount + metaSize + parameterSize) < maxData)
                            {
                                argsFlags |= ProtocolConstants.MEDIATOR_DEVICE_RWV_FLAGS_RAM;
                                metaSize  += parameterSize;
                                if (parameterVarKind == (byte)VariableKind.VK_String) // Prefix a len byte.
                                {
                                    --parameterSize;
                                    pAry[dataIndex + n++] = parameterSize;
                                    b = Primitives.StringToByteArray(p.ValueString);
                                    for (j = 0; j < parameterSize; j++)
                                    {
                                        pAry[dataIndex + n++] = b[j];
                                    }
                                }
                                else
                                {
                                    if ((mtx.TaskCmd != ProtocolConstants.MEDIATOR_DEVICE_ISOMONVAR) || (c != 0) || (paramIndex == ProtocolConstants.PARAMETER_TABLE_INDEX_TICKER))
                                    {
                                        Array.Copy(p.GetBytes(), 0, pAry, dataIndex + n, parameterSize);
                                    }
                                    else
                                    {
                                        int h = parameterSize;
                                        b = p.GetBytes();
                                        if (h > b.Length)
                                        {
                                            h = b.Length;
                                        }
                                        for (j = 0; j < parameterSize; j++)
                                        {
                                            int i = dataIndex + n + j;
                                            if ((c == 0) && pAry[i] != b[j])
                                            {
                                                c = 1;
                                            }
                                            pAry[i] = b[j];
                                        }
                                    }
                                    n += parameterSize;
                                }
                            }
                        }
                    }
                    if (((cmdFlags & ProtocolConstants.MEDIATOR_DEVICE_RWV_FLAGS_EEPROM) != 0) &&
                        ((parameterFlags & (byte)StorageFlags.SF_EEPROM) != 0))
                    {
                        p = d.EEPromValue;
                        if (p != null)
                        {
                            if (parameterVarKind == (byte)VariableKind.VK_String)   // Get size of string.
                            {
                                byte maxSize = (byte)d.MaxValue.ValueLong;
                                int  s       = p.ValueString.Length;
                                if (s > maxSize)
                                {
                                    s = maxSize;
                                }
                                parameterSize = (byte)(1 + s); // Allow one for len byte.
                            }
                            if ((byteCount + metaSize + parameterSize) < maxData)
                            {
                                argsFlags |= ProtocolConstants.MEDIATOR_DEVICE_RWV_FLAGS_EEPROM;
                                metaSize  += parameterSize;
                                if (parameterVarKind == (byte)VariableKind.VK_String)   // Prefix a len byte.
                                {
                                    --parameterSize;
                                    pAry[dataIndex + n++] = parameterSize;
                                    b = p.GetBytes();
                                    for (j = 0; j < parameterSize; j++)
                                    {
                                        pAry[dataIndex + n++] = b[j];
                                    }
                                }
                                else
                                {
                                    Array.Copy(p.GetBytes(), 0, pAry, dataIndex + n, parameterSize);
                                    n += parameterSize;
                                }
                            }
                        }
                    }
                    if (parameterVarKind == (byte)VariableKind.VK_String)
                    {
                        parameterSize = 1;
                    }
                    else
                    {
                        if ((cmdFlags & ProtocolConstants.MEDIATOR_DEVICE_RWV_FLAGS_DEFAULT) != 0)
                        {
                            if ((byteCount + metaSize + parameterSize) < maxData)
                            {
                                argsFlags |= ProtocolConstants.MEDIATOR_DEVICE_RWV_FLAGS_DEFAULT;
                                metaSize  += parameterSize;
                                Array.Copy(d.DefaultValue.GetBytes(), 0, pAry, dataIndex + n, parameterSize);
                                n += parameterSize;
                            }
                        }
                    }
                    if ((cmdFlags & ProtocolConstants.MEDIATOR_DEVICE_RWV_FLAGS_RANGE) != 0)
                    {
                        byte rangeSize = (byte)(2 + parameterSize * 2);
                        if ((byteCount + metaSize + rangeSize) < maxData)
                        {
                            argsFlags            |= ProtocolConstants.MEDIATOR_DEVICE_RWV_FLAGS_RANGE;
                            metaSize             += rangeSize;
                            pAry[dataIndex + n++] = parameterSize;
                            pAry[dataIndex + n++] = (byte)d.ParamCategory;
                            Array.Copy(d.MinValue.GetBytes(), 0, pAry, dataIndex + n, parameterSize);
                            n += parameterSize;
                            Array.Copy(d.MaxValue.GetBytes(), 0, pAry, dataIndex + n, parameterSize);
                            n += parameterSize;
                        }
                    }
                    if ((cmdFlags & ProtocolConstants.MEDIATOR_DEVICE_RWV_FLAGS_NAME) != 0)
                    {
                        // Get size of string.
                        parameterSize = 0;
                        string s = d.ParamName;
                        if (s != null)
                        {
                            parameterSize = (byte)s.Length;
                        }
                        if (parameterSize > ProtocolConstants.MAX_PARAMETER_NAME_SIZE)
                        {
                            parameterSize = ProtocolConstants.MAX_PARAMETER_NAME_SIZE;
                        }
                        if ((byteCount + metaSize + 1 + parameterSize) < maxData)
                        {
                            argsFlags            |= ProtocolConstants.MEDIATOR_DEVICE_RWV_FLAGS_NAME;
                            metaSize             += (byte)(1 + parameterSize);
                            pAry[dataIndex + n++] = parameterSize;
                            b = Primitives.StringToByteArray(s);
                            for (j = 0; j < parameterSize; j++)
                            {
                                pAry[dataIndex + n++] = b[j];
                            }
                        }
                    }
                    if (addMeta && !addKindOnly)
                    {
                        pAry[dataIndex + argsIndex] = argsFlags;
                    }
                }
                byteCount += metaSize;
                dataIndex += metaSize;
                g.dataLength((byte)(g.dataLength() + metaSize));
                ++k;
            }
            if (numReadIndex >= 0)
            {
                g.buffer[numReadIndex] = (byte)((k << 4) + numToRead);
            }
            mtx.ChangeDir = true;
            mtx.Finish    = MessageTransaction.FinishAction.Normal;
            if (mtx.TaskCmd == ProtocolConstants.MEDIATOR_DEVICE_ISOMONVAR)
            {
                return(c);
            }
            return(k);
        }
Esempio n. 43
0
            public override void VisitText( Primitives.Text text )
            {
                if( !InClip( text ) )
                {
                    return;
                }

                Font font = _renderer.CreateFont( text );
                double width, height, baselineFromTop;

                _renderer.MeasureText( text, out width, out height, out baselineFromTop );

                double x, y;

                switch( text.Alignment )
                {
                    case Primitives.Text.Position.TopLeft:
                    case Primitives.Text.Position.CenterLeft:
                    case Primitives.Text.Position.BaseLeft:
                    case Primitives.Text.Position.BottomLeft:
                        x = text.Point.X;
                        break;
                    case Primitives.Text.Position.TopCenter:
                    case Primitives.Text.Position.Center:
                    case Primitives.Text.Position.BaseCenter:
                    case Primitives.Text.Position.BottomCenter:
                        x = text.Point.X - width / 2 - 1;
                        break;
                    case Primitives.Text.Position.TopRight:
                    case Primitives.Text.Position.CenterRight:
                    case Primitives.Text.Position.BaseRight:
                    case Primitives.Text.Position.BottomRight:
                        x = text.Point.X - width;
                        break;
                    default:
                        throw new InvalidOperationException();
                }

                switch( text.Alignment )
                {
                    case Primitives.Text.Position.TopLeft:
                    case Primitives.Text.Position.TopCenter:
                    case Primitives.Text.Position.TopRight:
                        y = text.Point.Y;
                        break;
                    case Primitives.Text.Position.CenterLeft:
                    case Primitives.Text.Position.Center:
                    case Primitives.Text.Position.CenterRight:
                        y = text.Point.Y - height / 2;
                        break;
                    case Primitives.Text.Position.BaseLeft:
                    case Primitives.Text.Position.BaseCenter:
                    case Primitives.Text.Position.BaseRight:
                        y = text.Point.Y - baselineFromTop;
                        break;
                    case Primitives.Text.Position.BottomLeft:
                    case Primitives.Text.Position.BottomCenter:
                    case Primitives.Text.Position.BottomRight:
                        y = text.Point.Y - height;
                        break;
                    default:
                        throw new InvalidOperationException();
                }

                using( StringFormat sf = new StringFormat( StringFormat.GenericTypographic ) )
                {
                    sf.FormatFlags |= StringFormatFlags.NoClip;
                    sf.FormatFlags |= StringFormatFlags.NoWrap;
                    sf.Trimming = StringTrimming.EllipsisCharacter;

                    using( Brush brush = new SolidBrush( GdiPlusUtility.Convert.Color( text.Color ) ) )
                    {
                        _graphics.DrawString( text.Value, font, brush, (float) x, (float) y );
                    }
                }
            }
 protected override Primitives.VisualItem CreateItem( Primitives.PointMarker marker )
 {
     return null;
 }
Esempio n. 45
0
 public abstract Primitives.Path FlattenPath( Primitives.Path path );
Esempio n. 46
0
 /// Veena : Adding constructor.
 public Type(Primitives primitive, string name)
 {
     this.p    = primitive;
     this.name = name;
 }
Esempio n. 47
0
 public static TypeOf Primitive(Primitives primitive)
 {
     return new TypeOf(primitive);
 }
Esempio n. 48
0
        private void MergeHulls(ref Otri farleft, ref Otri innerleft, ref Otri innerright, ref Otri farright, int axis)
        {
            Vertex vertex;
            Vertex vertex1;
            Vertex vertex2;
            Vertex vertex3;
            Vertex vertex4;
            Vertex i;
            bool   flag;
            bool   flag1;
            Otri   otri    = new Otri();
            Otri   otri1   = new Otri();
            Otri   otri2   = new Otri();
            Otri   otri3   = new Otri();
            Otri   otri4   = new Otri();
            Otri   otri5   = new Otri();
            Otri   otri6   = new Otri();
            Otri   otri7   = new Otri();
            Vertex vertex5 = innerleft.Dest();
            Vertex vertex6 = innerleft.Apex();
            Vertex vertex7 = innerright.Org();
            Vertex vertex8 = innerright.Apex();

            if (this.useDwyer && axis == 1)
            {
                vertex  = farleft.Org();
                vertex2 = farleft.Apex();
                vertex1 = farright.Dest();
                vertex3 = farright.Apex();
                while (vertex2.y < vertex.y)
                {
                    farleft.LnextSelf();
                    farleft.SymSelf();
                    vertex  = vertex2;
                    vertex2 = farleft.Apex();
                }
                innerleft.Sym(ref otri6);
                for (i = otri6.Apex(); i.y > vertex5.y; i = otri6.Apex())
                {
                    otri6.Lnext(ref innerleft);
                    vertex6 = vertex5;
                    vertex5 = i;
                    innerleft.Sym(ref otri6);
                }
                while (vertex8.y < vertex7.y)
                {
                    innerright.LnextSelf();
                    innerright.SymSelf();
                    vertex7 = vertex8;
                    vertex8 = innerright.Apex();
                }
                farright.Sym(ref otri6);
                for (i = otri6.Apex(); i.y > vertex1.y; i = otri6.Apex())
                {
                    otri6.Lnext(ref farright);
                    vertex3 = vertex1;
                    vertex1 = i;
                    farright.Sym(ref otri6);
                }
            }
            do
            {
                flag = false;
                if (Primitives.CounterClockwise(vertex5, vertex6, vertex7) > 0)
                {
                    innerleft.LprevSelf();
                    innerleft.SymSelf();
                    vertex5 = vertex6;
                    vertex6 = innerleft.Apex();
                    flag    = true;
                }
                if (Primitives.CounterClockwise(vertex8, vertex7, vertex5) <= 0)
                {
                    continue;
                }
                innerright.LnextSelf();
                innerright.SymSelf();
                vertex7 = vertex8;
                vertex8 = innerright.Apex();
                flag    = true;
            }while (flag);
            innerleft.Sym(ref otri);
            innerright.Sym(ref otri1);
            this.mesh.MakeTriangle(ref otri7);
            otri7.Bond(ref innerleft);
            otri7.LnextSelf();
            otri7.Bond(ref innerright);
            otri7.LnextSelf();
            otri7.SetOrg(vertex7);
            otri7.SetDest(vertex5);
            vertex = farleft.Org();
            if (vertex5 == vertex)
            {
                otri7.Lnext(ref farleft);
            }
            vertex1 = farright.Dest();
            if (vertex7 == vertex1)
            {
                otri7.Lprev(ref farright);
            }
            Vertex vertex9  = vertex5;
            Vertex vertex10 = vertex7;
            Vertex vertex11 = otri.Apex();
            Vertex vertex12 = otri1.Apex();

            while (true)
            {
                bool flag2 = Primitives.CounterClockwise(vertex11, vertex9, vertex10) <= 0;
                bool flag3 = Primitives.CounterClockwise(vertex12, vertex9, vertex10) <= 0;
                if (flag2 & flag3)
                {
                    break;
                }
                if (!flag2)
                {
                    otri.Lprev(ref otri2);
                    otri2.SymSelf();
                    vertex4 = otri2.Apex();
                    if (vertex4 != null)
                    {
                        flag1 = Primitives.InCircle(vertex9, vertex10, vertex11, vertex4) > 0;
                        while (flag1)
                        {
                            otri2.LnextSelf();
                            otri2.Sym(ref otri4);
                            otri2.LnextSelf();
                            otri2.Sym(ref otri3);
                            otri2.Bond(ref otri4);
                            otri.Bond(ref otri3);
                            otri.LnextSelf();
                            otri.Sym(ref otri5);
                            otri2.LprevSelf();
                            otri2.Bond(ref otri5);
                            otri.SetOrg(vertex9);
                            otri.SetDest(null);
                            otri.SetApex(vertex4);
                            otri2.SetOrg(null);
                            otri2.SetDest(vertex11);
                            otri2.SetApex(vertex4);
                            vertex11 = vertex4;
                            otri3.Copy(ref otri2);
                            vertex4 = otri2.Apex();
                            flag1   = (vertex4 == null ? false : Primitives.InCircle(vertex9, vertex10, vertex11, vertex4) > 0);
                        }
                    }
                }
                if (!flag3)
                {
                    otri1.Lnext(ref otri2);
                    otri2.SymSelf();
                    vertex4 = otri2.Apex();
                    if (vertex4 != null)
                    {
                        flag1 = Primitives.InCircle(vertex9, vertex10, vertex12, vertex4) > 0;
                        while (flag1)
                        {
                            otri2.LprevSelf();
                            otri2.Sym(ref otri4);
                            otri2.LprevSelf();
                            otri2.Sym(ref otri3);
                            otri2.Bond(ref otri4);
                            otri1.Bond(ref otri3);
                            otri1.LprevSelf();
                            otri1.Sym(ref otri5);
                            otri2.LnextSelf();
                            otri2.Bond(ref otri5);
                            otri1.SetOrg(null);
                            otri1.SetDest(vertex10);
                            otri1.SetApex(vertex4);
                            otri2.SetOrg(vertex12);
                            otri2.SetDest(null);
                            otri2.SetApex(vertex4);
                            vertex12 = vertex4;
                            otri3.Copy(ref otri2);
                            vertex4 = otri2.Apex();
                            flag1   = (vertex4 == null ? false : Primitives.InCircle(vertex9, vertex10, vertex12, vertex4) > 0);
                        }
                    }
                }
                if (flag2 || !flag3 && Primitives.InCircle(vertex11, vertex9, vertex10, vertex12) > 0)
                {
                    otri7.Bond(ref otri1);
                    otri1.Lprev(ref otri7);
                    otri7.SetDest(vertex9);
                    vertex10 = vertex12;
                    otri7.Sym(ref otri1);
                    vertex12 = otri1.Apex();
                }
                else
                {
                    otri7.Bond(ref otri);
                    otri.Lnext(ref otri7);
                    otri7.SetOrg(vertex10);
                    vertex9 = vertex11;
                    otri7.Sym(ref otri);
                    vertex11 = otri.Apex();
                }
            }
            this.mesh.MakeTriangle(ref otri2);
            otri2.SetOrg(vertex9);
            otri2.SetDest(vertex10);
            otri2.Bond(ref otri7);
            otri2.LnextSelf();
            otri2.Bond(ref otri1);
            otri2.LnextSelf();
            otri2.Bond(ref otri);
            if (this.useDwyer && axis == 1)
            {
                vertex  = farleft.Org();
                vertex2 = farleft.Apex();
                vertex1 = farright.Dest();
                vertex3 = farright.Apex();
                farleft.Sym(ref otri6);
                for (i = otri6.Apex(); i.x < vertex.x; i = otri6.Apex())
                {
                    otri6.Lprev(ref farleft);
                    vertex2 = vertex;
                    vertex  = i;
                    farleft.Sym(ref otri6);
                }
                while (vertex3.x > vertex1.x)
                {
                    farright.LprevSelf();
                    farright.SymSelf();
                    vertex1 = vertex3;
                    vertex3 = farright.Apex();
                }
            }
        }
Esempio n. 49
0
 /// <summary>
 /// Constructs a field of the specified primitive type </summary>
 /// <param name="name"> : of the field </param>
 /// <param name="primitive"> : type of the field </param>
 protected internal Field(string name, Primitives primitive)
 {
     this.name = name;
     this.type = new Type(primitive, "");
 }
Esempio n. 50
0
        private void DivconqRecurse(int left, int right, int axis, ref Otri farleft, ref Otri farright)
        {
            Otri otri  = new Otri();
            Otri otri1 = new Otri();
            Otri otri2 = new Otri();
            Otri otri3 = new Otri();
            Otri otri4 = new Otri();
            Otri otri5 = new Otri();
            int  num   = right - left + 1;

            if (num == 2)
            {
                this.mesh.MakeTriangle(ref farleft);
                farleft.SetOrg(this.sortarray[left]);
                farleft.SetDest(this.sortarray[left + 1]);
                this.mesh.MakeTriangle(ref farright);
                farright.SetOrg(this.sortarray[left + 1]);
                farright.SetDest(this.sortarray[left]);
                farleft.Bond(ref farright);
                farleft.LprevSelf();
                farright.LnextSelf();
                farleft.Bond(ref farright);
                farleft.LprevSelf();
                farright.LnextSelf();
                farleft.Bond(ref farright);
                farright.Lprev(ref farleft);
                return;
            }
            if (num != 3)
            {
                int num1 = num >> 1;
                this.DivconqRecurse(left, left + num1 - 1, 1 - axis, ref farleft, ref otri4);
                this.DivconqRecurse(left + num1, right, 1 - axis, ref otri5, ref farright);
                this.MergeHulls(ref farleft, ref otri4, ref otri5, ref farright, axis);
                return;
            }
            this.mesh.MakeTriangle(ref otri);
            this.mesh.MakeTriangle(ref otri1);
            this.mesh.MakeTriangle(ref otri2);
            this.mesh.MakeTriangle(ref otri3);
            double num2 = Primitives.CounterClockwise(this.sortarray[left], this.sortarray[left + 1], this.sortarray[left + 2]);

            if (num2 == 0)
            {
                otri.SetOrg(this.sortarray[left]);
                otri.SetDest(this.sortarray[left + 1]);
                otri1.SetOrg(this.sortarray[left + 1]);
                otri1.SetDest(this.sortarray[left]);
                otri2.SetOrg(this.sortarray[left + 2]);
                otri2.SetDest(this.sortarray[left + 1]);
                otri3.SetOrg(this.sortarray[left + 1]);
                otri3.SetDest(this.sortarray[left + 2]);
                otri.Bond(ref otri1);
                otri2.Bond(ref otri3);
                otri.LnextSelf();
                otri1.LprevSelf();
                otri2.LnextSelf();
                otri3.LprevSelf();
                otri.Bond(ref otri3);
                otri1.Bond(ref otri2);
                otri.LnextSelf();
                otri1.LprevSelf();
                otri2.LnextSelf();
                otri3.LprevSelf();
                otri.Bond(ref otri1);
                otri2.Bond(ref otri3);
                otri1.Copy(ref farleft);
                otri2.Copy(ref farright);
                return;
            }
            otri.SetOrg(this.sortarray[left]);
            otri1.SetDest(this.sortarray[left]);
            otri3.SetOrg(this.sortarray[left]);
            if (num2 <= 0)
            {
                otri.SetDest(this.sortarray[left + 2]);
                otri1.SetOrg(this.sortarray[left + 2]);
                otri2.SetDest(this.sortarray[left + 2]);
                otri.SetApex(this.sortarray[left + 1]);
                otri2.SetOrg(this.sortarray[left + 1]);
                otri3.SetDest(this.sortarray[left + 1]);
            }
            else
            {
                otri.SetDest(this.sortarray[left + 1]);
                otri1.SetOrg(this.sortarray[left + 1]);
                otri2.SetDest(this.sortarray[left + 1]);
                otri.SetApex(this.sortarray[left + 2]);
                otri2.SetOrg(this.sortarray[left + 2]);
                otri3.SetDest(this.sortarray[left + 2]);
            }
            otri.Bond(ref otri1);
            otri.LnextSelf();
            otri.Bond(ref otri2);
            otri.LnextSelf();
            otri.Bond(ref otri3);
            otri1.LprevSelf();
            otri2.LnextSelf();
            otri1.Bond(ref otri2);
            otri1.LprevSelf();
            otri3.LprevSelf();
            otri1.Bond(ref otri3);
            otri2.LnextSelf();
            otri3.LprevSelf();
            otri2.Bond(ref otri3);
            otri1.Copy(ref farleft);
            if (num2 > 0)
            {
                otri2.Copy(ref farright);
                return;
            }
            farleft.Lnext(ref farright);
        }
Esempio n. 51
0
        // Called just before message is written to device.
        // Determine if packet needs modification.
        // Updates DUX & BAUD flags.
        // Returns verification action if needed.
        // TODO: set destination.
        public byte PreLinkWriteFilter(PacketBuffer b)
        {
            int  sumDiff      = 0;
            byte verifyAction = ProtocolConstants.VERIFY_ACTION_NONE;
            byte c            = (byte)(b.flagsPid & ProtocolConstants.META_FLAGS_PID);

            if (c == ProtocolConstants.PID_GENERAL_V)
            {
                // Sequence numbers are used to detect bad xfers.
                // Resends must be sent with the same Vno rather than a new Vno.
                if ((b.flagsPid & ProtocolConstants.META_FLAGS_RESEND) != 0)
                {
                    verifyAction = ProtocolConstants.VERIFY_ACTION_RESEND; // This stops vnoLastOutput being incremented below.
                }
                else
                {
                    verifyAction = ProtocolConstants.VERIFY_ACTION_NEW;
                    sumDiff      = (int)b.arg() - (int)IoNetIf.vnoLastOutput;
                    b.arg(IoNetIf.vnoLastOutput);
                }
            }
            else if (c == ProtocolConstants.PID_PING)
            {
                byte arg = b.arg();
                if (arg == 0)   // It's a basic ping, so set arg to vno.
                {
                    sumDiff = -(int)IoNetIf.vnoLastOutput;
                    b.arg(IoNetIf.vnoLastOutput);
                }
                else if (arg >= ProtocolConstants.PID_ARG_BAUD_MIN)
                {
                    switch (arg)
                    {
                    case ProtocolConstants.PID_ARG_RESET:
                        break;

                    case ProtocolConstants.PID_ARG_SLAVE:
                        break;

                    case ProtocolConstants.PID_ARG_MULTI:
                        break;

                    case ProtocolConstants.PID_ARG_MASTER:
                        break;

                    default:     // BAUD: Flag baud ping sent, set UART_*_SetBaudRate = netIfIndex.
                        // This is a broadcast to all on link.
                        IoNetIf.IoNetIfDevice.PerformBaudAction(IoNetIf.DeviceContextIndex,
                                                                (byte)(arg - ProtocolConstants.PID_ARG_BAUD_MIN),
                                                                ProtocolConstants.BAUD_ACTION_SIGNAL);
                        IoNetIf.baudTimeout = Primitives.GetBabelMilliTicker() + LinkMonitor.BAUD_RATE_TIMEOUT;     // Mark Baud broadcast for all.
                        break;
                    }
                }
                // DUX: need to block further writes.
                if ((IoNetIf.duplexKind & (byte)LINK_DUPLEX_KIND.LINK_DUPLEX_KIND_HALF) != 0)
                {
                    IoNetIf.duplexPingReply |= LinkMonitor.DUX_PING_SENT;
                    IoNetIf.duplexNumWaiting = (byte)0xffu;
                    IoNetIf.duplexMode       = (byte)DUX_MODE.DUX_RX;
                }
            }
            else if (c == ProtocolConstants.PID_REPLY)
            {
                IoNetIf.duplexPingReply |= LinkMonitor.DUX_REPLY_SENT;// DUX: flag reply sent.
            }
            // Update checksum: assume valid on entry & work out bit change.
            if (sumDiff != 0)
            {
                // newChkSum = oldChkSum + (oldSumBits - newSumBits).
                byte oldChkSum = b.buffer[b.pktLen - 1];
                b.buffer[b.pktLen - 1] = (byte)(((int)oldChkSum) + sumDiff);
            }
            return(verifyAction);
        }
Esempio n. 52
0
        // Perform a handshake request received from link.
        // Consults original message for r,s details, ports=0, flags=0.
        // TODO: check what happens when a master is pinged etc. Ok?
        public void PerformLinkHandshake(PacketBuffer hp)
        {
            int  idx;
            byte arg = hp.arg();

            // TODO: Check packet is for us first.

            switch (hp.negPidPid() & ProtocolConstants.PID_MASK)
            {
            case ProtocolConstants.PID_PING:     // We received a ping. Now send a reply.
                if (arg >= ProtocolConstants.PID_ARG_BAUD_MIN)
                {
                    switch (arg)
                    {
                    case ProtocolConstants.PID_ARG_RESET:
                        IoNetIf.ResetLinkDriver();
                        break;

                    case ProtocolConstants.PID_ARG_SLAVE:
                        break;

                    case ProtocolConstants.PID_ARG_MULTI:
                        break;

                    case ProtocolConstants.PID_ARG_MASTER:
                        break;

                    default:         // BAUD: Request to change baud rate.
                        IoNetIf.IoNetIfDevice.PerformBaudAction(IoNetIf.DeviceContextIndex,
                                                                (byte)(arg - ProtocolConstants.PID_ARG_BAUD_MIN),
                                                                ProtocolConstants.BAUD_ACTION_SAVE);
                        break;
                    }
                }
                else
                {
                    // Set linkLastInputVno=(VNO_SIZE-1) & linkLastOutputVno=0 ?
                    CheckOrderMissingQ(arg, false);
                    IoNetIf.duplexPingReply |= LinkMonitor.DUX_PING_RECEIVED;
                }
                // Send a reply with Arg = num messages waiting.
                // TODO: unless Q contains Msg destined to sender: use "more" msg code.
                int num = IoNetIf.LinkWriteQueue.Size();         // Arg = num messages waiting.
                SendLinkHandshakePacket(ProtocolConstants.PID_REPLY,
                                        LinkMonitor.Destination, // hp.destination(), // TODO: This should be the linkAdrs.
                                        (byte)((num > 255) ? 255 : num));
                break;

            case ProtocolConstants.PID_REPLY:     //TODO: Now stop pinging.
                // arg=number of waiting messages.
                // If arg>0 read some messages.
                IoNetIf.duplexNumWaiting = arg;
                IoNetIf.duplexPingReply |= LinkMonitor.DUX_REPLY_RECEIVED;
                break;

            case ProtocolConstants.PID_RESEND:     // Resend a message.
                idx = FindVnoInVerifyQueue(IoNetIf.LinkVerifyQueue, arg);
                if (idx == -1)
                {
                    SendLinkHandshakePacket(ProtocolConstants.PID_CANCEL, hp.destination(), arg);
                }
                else if (IoNetIf.LinkWriteQueue.FindFirstOccurrenceIndex(idx) == -1)
                {
                    PacketBuffer b = Manager.IoBuffers[idx];
                    b.flagsPid |= ProtocolConstants.META_FLAGS_RESEND;
                    if (IoNetIf.LinkWriteQueue.PushFirst(idx) == -1)
                    {
                        Manager.IoBuffersFreeHeap.Release(idx);
                    }
                }
                break;

            case ProtocolConstants.PID_CANCEL:     // Remove message from missingQ.
                IoNetIf.LinkMissingQueue.RemoveFirstOccurrence(arg);
                break;

            default: break;
            }
            // TODO: IoNetIf.activityTimeout=Primitives.GetBabelMilliTicker() + LinkMonitor.CONX_ACTIVITY_TIMEOUT;
            IoNetIf.baudTimeout = Primitives.GetBabelMilliTicker() + LinkMonitor.BAUD_RATE_TIMEOUT; // Reset timer after input from specific sender.
        }
Esempio n. 53
0
 protected abstract void Apply( Renderers.Renderer renderer, Primitives.Text text );
Esempio n. 54
0
 public static void DrawNumberInRectangle(string caption, Rectangle rectangle, Color?innerColor = null)
 {
     Primitives.DrawAndFillRectangle(rectangle, innerColor ?? Color.LightBlue, Color.DarkBlue, 2);
     Writer.DrawString(caption.ToString(), rectangle, alignment: TextAlignment.Middle, degrading: true);
 }
Esempio n. 55
0
 public PlaylistFile(Primitives.Playlist value)
 {
     if (value == null)
         throw new ArgumentNullException(nameof(value));
     _playlist = value;
 }
 public override void DrawMiddle(Session session, Rectangle rectMid)
 {
     Primitives.DrawMultiLineText("{b}Objective:{/b} You lead the Existential Risk Prevention Authority (ERPA). Your goal is to see humankind survive until the end of year 2040.\n\n{b}Gameplay:{/b}Each turn (year), you make decision on the agenda items listed in the right bar. Each decision you make has consequences, sometimes next year, sometimes many years later. You must make a decision for each agenda item before ending the turn.\n\n{b}Teams:{/b} ERPA teams are your most important resource. Most decisions will require you to allocate one or more teams to execute them. Use them wisely.\n\n{b}Keyboard shortcuts:{/b} Press Esc to close the active window. Press Enter to select the first option in a window.\n\n{b}Actors:{/b} You are not alone in the world. Major players on the world stage will come to your help, providing extra teams, for example, if you treat them well.\n\n{b}Risks:{/b} If ever a risk becomes reality and destroys humankind, you lose the game and must start over. Make sure that doesn't happen. However, some risks are not really extinction-level risks or may be blown out of proportion. Concentrate on what is necessary right now, but also plan for the future.",
                                  rectMid, Colors.Front);
 }
Esempio n. 57
0
 public TextFontModifier( string fontFamily, double? fontSizeInPoints, Primitives.Text.FontStyleFlags? fontStyleFlags )
 {
     _fontFamily = fontFamily;
     _fontSizeInPoints = fontSizeInPoints;
     _fontStyleFlags = fontStyleFlags;
 }
Esempio n. 58
0
        private static int Main(string[] args)
        {
            string wixpdbsPathsFile = string.Empty;

            string[] wixpdbsPaths = null;
            string   dataFilePath = string.Empty;

            //args = new string[] { "noprocess", @"/wixpdbs:C:\Users\user\Desktop\test\paths.txt" };
            //args = new string[] { "noprocess", @"/binfile:C:\Users\user\Desktop\test\DataFile.bin" };
            //args = new string[] { "noprocess", @"/binfile:C:\Users\user\Desktop\test\DataFile.bin", @"/wixpdbs:\\myshare\Drops\user\wixpdbsPS\sub\Files.txt" };
            if (args != null && args.Count() > 0)
            {
                foreach (var arg in args)
                {
                    switch (arg.ToLowerInvariant())
                    {
                    case "help":
                    case "/help":
                    case "/?":
                        PrintUsage();
                        return(0);

                    case "break":
                        Console.WriteLine("Program stopped, please attach debugger and then hit any key to continue.");
                        Console.ReadKey(true);
                        break;

                    case "debug":
                        _debug = true;
                        break;

                    case "noprocess":
                        _donotprocess = true;
                        break;

                    default:
                        // Path to the file containing a list of paths to the wixpdbs.
                        // e.g. /wixpdbs:c:\myPaths.txt
                        if (arg.StartsWith("/wixpdbs:", StringComparison.OrdinalIgnoreCase))
                        {
                            wixpdbsPathsFile = arg.Substring("/wixpdbs:".Length);
                            wixpdbsPaths     = File.ReadAllLines(wixpdbsPathsFile);
                        }
                        // Path to the file containing the DataFile.bin; if no file is passed in, it will use the embedded one.
                        // e.g. /binfile:C:\DataFile.bin
                        else if (arg.StartsWith("/binfile:", StringComparison.OrdinalIgnoreCase))
                        {
                            dataFilePath = arg.Substring("/binfile:".Length);
                        }
                        break;
                    }
                }
            }

            var ip = new Primitives();

            ConsoleOperations.PrimitiveObject = ip;
            ConsoleOperations.SetUpLogging();

            ip.DoNotExecuteProcess = _donotprocess;
            ip.DebugReporting      = _debug;

            try
            {
                // Check for permissions to run uninstall actions
                var elev = new ElevationDetection();
                if (!elev.Level)
                {
                    ConsoleOperations.SecurityWarning();
                    return(0);
                }
                else
                {
                    Logger.Log("Running elevated or as administrator", Logger.MessageLevel.Information, AppName);
                }
                elev = null;

                // Define base variables for use of primitives object; adding filters, uninstall actions, logging location, and default location of data files
                ConsoleOperations.SetupPrimitivesValues(_debug, _donotprocess);

                // If /wixpdbs is used, .bin data file is generated for the user.
                if (wixpdbsPaths != null && wixpdbsPaths.Length > 0)
                {
                    if (!string.IsNullOrEmpty(dataFilePath) && File.Exists(dataFilePath))
                    {
                        Logger.LogWithOutput(string.Format("Loading from {0}", dataFilePath));
                        ip.LoadFromDataFile(dataFilePath);
                    }

                    Logger.LogWithOutput("Generating data file from wixpdbs ....");
                    foreach (var wixpdbPath in wixpdbsPaths)
                    {
                        ip.LoadFromWixpdb(wixpdbPath);
                    }

                    ip.SaveToDataFile();
                    Logger.Log("Data File generation operation is successful.  Exiting ...", Logger.MessageLevel.Information, AppName);
                    return(0);
                }
                // Else uninstall Visual Studio 2013/2015/vNext
                else
                {
                    if (!string.IsNullOrEmpty(dataFilePath) && File.Exists(dataFilePath))
                    {
                        ip.LoadFromDataFile(dataFilePath);
                    }
                    else
                    {
                        // load from embedded.
                        var assembly = Assembly.GetExecutingAssembly();
                        var dataFile = "Microsoft.VisualStudio.Setup.DataFile.bin";

                        using (Stream stream = assembly.GetManifestResourceStream(dataFile))
                        {
                            ip.LoadFromDataFile(stream);
                        }
                    }

                    ip.InstalledVisualStudioReport();
                    Logger.LogWithOutput("WARNING: This executable is designed to cleanup/scorch all Preview/RC/RTM releases of Visual Studio 2013, Visual Studio 2015 and Visual Studio vNext.");
                    Logger.LogWithOutput("It should be used as the last resort to clean up the user's system before resorting to reimaging the machine. ");
                    Logger.LogWithOutput("Would you like to continue? [Y/N]");
                    var action = Console.ReadLine();
                    if (!string.IsNullOrEmpty(action) && action.StartsWith("y", StringComparison.OrdinalIgnoreCase))
                    {
                        int exitCode = ip.Uninstall();

                        if (exitCode == 3010)
                        {
                            Logger.LogWithOutput("Bundle requested to reboot the system.  Please reboot your computer and run this application again.");
                            return(3010);
                        }
                        ip.CleanupVisualStudioPackageCache();
                        ip.CleanupSecondaryInstallerCache();
                        ip.CleanupVisualStudioRegistryHives();
                    }
                    else
                    {
                        Logger.LogWithOutput("Exiting ...");
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Log(ex, AppName);
            }
            finally
            {
                ip.Dispose();
            }

            return(0);
        }
Esempio n. 59
0
 public static string ToString(Primitives primitive)
 {
     return PrimitiveDict.GetValue(primitive);
 }
Esempio n. 60
0
 void DrawSphereColliderBounds()
 {
     Primitives.CreateSphereMesh(radius, mesh);
     mesh.RecalculateBounds();
 }