Exemplo n.º 1
0
        public RenderSystem(LoderGame game, SystemManager systemManager, EntityManager entityManager)
        {
            _game = game;
            _systemManager = systemManager;
            _entityManager = entityManager;
            _animationManager = game.animationManager;
            //_sortedRenderablePrimitives = new SortedDictionary<float, List<IRenderablePrimitive>>();
            _cameraSystem = _systemManager.getSystem(SystemType.Camera) as CameraSystem;
            _graphicsDevice = game.GraphicsDevice;
            _spriteBatch = game.spriteBatch;
            _backgroundRenderer = new BackgroundRenderer(_spriteBatch);
            _fluidRenderTarget = new RenderTarget2D(_graphicsDevice, _graphicsDevice.Viewport.Width, _graphicsDevice.Viewport.Height);
            _renderedFluid = new RenderTarget2D(_graphicsDevice, _graphicsDevice.Viewport.Width, _graphicsDevice.Viewport.Height);
            _debugFluid = new RenderTarget2D(_graphicsDevice, _graphicsDevice.Viewport.Width, _graphicsDevice.Viewport.Height);
            _postSourceUnder = new RenderTarget2D(_graphicsDevice, _graphicsDevice.Viewport.Width, _graphicsDevice.Viewport.Height);
            _postSourceOver = new RenderTarget2D(_graphicsDevice, _graphicsDevice.Viewport.Width, _graphicsDevice.Viewport.Height);

            _contentManager = new ContentManager(game.Services);
            _contentManager.RootDirectory = "Content";
            _fluidEffect = _contentManager.Load<Effect>("fluid_effect");
            _fluidParticleTexture = _contentManager.Load<Texture2D>("fluid_particle");
            _reticle = _contentManager.Load<Texture2D>("reticle");
            _materialRenderer = new MaterialRenderer(game.GraphicsDevice, _contentManager, game.spriteBatch);
            _primitivesEffect = _contentManager.Load<Effect>("effects/primitives");
            _pixel = new Texture2D(_graphicsDevice, 1, 1);
            _pixel.SetData<Color>(new [] { Color.White });
            _circle = _contentManager.Load<Texture2D>("circle");
            _tooltipFont = _contentManager.Load<SpriteFont>("shared_ui/tooltip_font");
        }
 public static int CreateEntity(
     EntityManager entityManager,
     IBlueprintManager blueprintManager,
     string blueprintId)
 {
     return CreateEntity(entityManager, blueprintManager, blueprintId, null);
 }
Exemplo n.º 3
0
    public EntityError Resolve(EntityManager em) {
      IsServerError = true;
      try {
        EntityType entityType = null;
        if (EntityTypeName != null) {
          var stName = TypeNameInfo.FromClrTypeName(EntityTypeName).ToClient(em.MetadataStore).StructuralTypeName;
          entityType = em.MetadataStore.GetEntityType(stName);
          var ek = new EntityKey(entityType, KeyValues);
          Entity = em.GetEntityByKey(ek);
        }

        
        if (entityType != null) {
          if (PropertyName != null) {
            Property = entityType.Properties.FirstOrDefault(p => p.NameOnServer == PropertyName);
            if (Property != null) {
              PropertyName = Property.Name;
            }
          }
          
          var vc = new ValidationContext(this.Entity);
          vc.Property = Property;
          var veKey = (ErrorName ?? ErrorMessage) + (PropertyName ?? "");
          var ve = new ValidationError(null, vc, ErrorMessage, veKey);
          ve.IsServerError = true;
          this.Entity.EntityAspect.ValidationErrors.Add(ve);
        }
      } catch (Exception e) {
        ErrorMessage = ( ErrorMessage ?? "") + ":  Unable to Resolve this error: " + e.Message;
      }
      return this;
    }
 // Useful utility method
 private Customer CreateFakeExistingCustomer(EntityManager entityManager, string companyName = "Existing Customer") {
     var customer = new Customer();
     customer.CompanyName = companyName;
     customer.CustomerID = Guid.NewGuid();
     entityManager.AttachEntity(customer);
     return customer;
 }
        private void ComputeLod(Node root, double k, EntityManager entityManager)
        {
            var mesh = entityManager.GetComponent<StaticMesh>(root.Entity);

            var side = (root.Bounds.Max - root.Bounds.Min).X;
            var radius = Math.Sqrt(side*side + side*side);

            for (int i = 0; i < 6; i++)
            {
                if (PlaneDistance(_frustumPlanes[i], root.Bounds.Center) <= -radius)
                {
                    return;
                }
            }

            var error = root.GeometricError;
            var distance = (root.Bounds.Center - _camera.Position).Length;
            var rho = (error / distance) * k;

            var threshhold = 100;
            if (rho <= threshhold || root.Leafs.Length == 0)
            {
                mesh.IsVisible = true;
            }
            else
            {
                for (int j = 0; j < root.Leafs.Length; j++)
                {
                    ComputeLod(root.Leafs[j], k, entityManager);
                }
            }
        }
        public async Task ExportImportFromIsolatedStorage()
        {
            var manager1 = new EntityManager(_serviceName);
            await PrimeCache(manager1);
            var expectedEntityCount = manager1.GetEntities().Count();

            var exportData = manager1.ExportEntities();

            var isoStore = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Assembly, null, null);
            string importData;
            using (var isoStream = new IsolatedStorageFileStream("ExportEntities.txt", FileMode.Create, isoStore))
            {
                using (var writer = new StreamWriter(isoStream))
                {
                    writer.Write(exportData);
                }
            }

            using (var isoStream = new IsolatedStorageFileStream("ExportEntities.txt", FileMode.Open, isoStore))
            {
                using (var reader = new StreamReader(isoStream))
                {
                    importData = reader.ReadToEnd();
                }
            }
            
            // import into a new EntityManager
            var manager2 = new EntityManager(_serviceName);
            manager2.ImportEntities(importData);

            Assert.AreEqual(expectedEntityCount, manager2.GetEntities().Count());
        }
Exemplo n.º 7
0
 public EntityWorld()
 {
     _systemManager = new SystemManager(this);
     _entityManager = new EntityManager(this);
     _tagManager = new TagManager(this);
     _gameTime = new AmphibianGameTime();
 }
Exemplo n.º 8
0
 public RenderingSystem(Form form, EntityManager manager)
     : base(manager)
 {
     _form = form;
     _halfWidth = form.ClientRectangle.Width / 2;
     _halfHeight = form.ClientRectangle.Height / 2;
 }
Exemplo n.º 9
0
    public static EntityManager Instance()
    {
        if (self == null)
            self = new EntityManager();

        return self;
    }
Exemplo n.º 10
0
 private void EntityManagerInitialisieren()
 {
     if (_daten_ikunde == null)
     {
         _daten_ikunde = new EntityManager<IKunde>();
     }
 }
Exemplo n.º 11
0
 public static SaveException Parse(EntityManager em, String json) {
   var jn = JNode.DeserializeFrom(json);
   var message = jn.Get<String>("ExceptionMessage");
   var entityErrors = jn.GetArray<EntityError>("EntityErrors");
   var saveErrors = entityErrors.Select(ee => ee.Resolve(em));
   return new SaveException(message ?? "see EntityErrors property", saveErrors);
 }
Exemplo n.º 12
0
        static void Main()
        {
            using (var source = new CancellationTokenSource())
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                var form = new Form1();
                var manager = new EntityManager();
                var keyboard = new Keyboard();
                var systems = new SystemBase[] {
                    new EnemySpawnSystem(manager),
                    new FieldOfPlaySystem(manager),
                    new BulletEnemyCollisionSystem(manager),
                    new KeyboardSystem(manager, form, keyboard),
                    new LifetimeSystem(manager),
                    new MovementSystem(manager),
                    new RenderingSystem(form, manager)
                };

                PlayerTemplate.Create(manager);

                form.KeyDown += (s, e) => keyboard.KeyDown(e.KeyCode);
                form.KeyUp += (s, e) => keyboard.KeyUp(e.KeyCode);
                form.FormClosing += (s, e) => source.Cancel();
                form.Load += (s, e) => Run(systems, source.Token);

                Application.Run(form);
            }
        }
Exemplo n.º 13
0
 public TransformSystem(EntityManager em, EntitySystemManager esm)
     : base(em, esm)
 {
     EntityQuery = new EntityQuery();
     EntityQuery.AllSet.Add(typeof(TransformComponent));
     EntityQuery.Exclusionset.Add(typeof(SlaveMoverComponent));
 }
Exemplo n.º 14
0
    private async void ExecuteQuery() {
      var serviceName = "http://localhost:7150/breeze/NorthwindIBModel/";
      var em = new EntityManager(serviceName);

      
      

      var query = "Employees";
      
      // var metadata = await client.FetchMetadata();

      var q = new EntityQuery<Foo.Customer>("Customers");
      var q2 = q.Where(c => c.CompanyName.StartsWith("C") && c.Orders.Any(o => o.Freight > 10));
      var q3 = q2.OrderBy(c => c.CompanyName).Skip(2);
      // var q3 = q2.Select(c => c.Orders); // fails
      // var q4 = q2.Select(c => new Dummy() { Orders = c.Orders}  );
      // var q4 = q2.Select(c => new { Orders = c.Orders });
      // var q4 = q3.Select(c => new { c.CompanyName, c.Orders });
      var x = await q3.Execute(em);
      //var q3 = q2.Expand(c => c.Orders);
      //var q4 = q3.OrderBy(c => c.CompanyName);
      //var zzz = q4.GetResourcePath();
      //var x = await q4.Execute(em);
      var addresses = x.Select(c => {
        var z = c.CompanyName;
        var cid = c.CustomerID;
        c.CompanyName = "Test123";
        return c.Address;
      }).ToList();
      
    }
Exemplo n.º 15
0
    public EntityError Resolve(EntityManager em) {
      IsServerError = true;
      try {
        EntityType entityType = null;
        if (EntityTypeName != null) {
          var stName = StructuralType.ClrTypeNameToStructuralTypeName(EntityTypeName);
          entityType = MetadataStore.Instance.GetEntityType(stName);
          var ek = new EntityKey(entityType, KeyValues);
          Entity = em.FindEntityByKey(ek);
        }

        if (PropertyName != null) {
          PropertyName = MetadataStore.Instance.NamingConvention.ServerPropertyNameToClient(PropertyName);
        }
        if (Entity != null) {
          Property = entityType.GetProperty(PropertyName);
          var vc = new ValidationContext(this.Entity);
          vc.Property = this.Property;
          var veKey = (ErrorName ?? ErrorMessage) + (PropertyName ?? "");
          var ve = new ValidationError(null, vc, ErrorMessage, veKey);
          ve.IsServerError = true;
          this.Entity.EntityAspect.ValidationErrors.Add(ve);
        }
      } catch (Exception e) {
        ErrorMessage = ( ErrorMessage ?? "") + ":  Unable to Resolve this error: " + e.Message;
      }
      return this;
    }
Exemplo n.º 16
0
 public EquipmentSystem(SystemManager systemManager, EntityManager entityManager)
 {
     _systemManager = systemManager;
     _entityManager = entityManager;
     _defaultRopeMaterial = new RopeMaterial(ResourceManager.getResource("default_rope_material"));
     _rng = new Random();
 }
Exemplo n.º 17
0
 public override CollResult RedirectedCheckAgainst(zCollisionPrimitive other, EntityManager.Transform myRoot, EntityManager.Transform hisRoot)
 {
     CollResult ret = new CollResult();
     ret.collided = false;
     ret.normal = Vector2.Zero;
     return ret;
 }
Exemplo n.º 18
0
 protected virtual void ProcessEntities(EntityManager.EntityEnumerator entities)
 {
     foreach (Entity entity in entities)
     {
         Process(entity);
     }
 }
Exemplo n.º 19
0
        public MeteorFactory(EntityManager entityManager, ContentManager contentManager)
        {
            _entityManager = entityManager;

            _meteorRegions = new Dictionary<int, TextureRegion2D[]>()
            {
                { 4, new [] 
                    {
                        new TextureRegion2D(contentManager.Load<Texture2D>("meteorBrown_big1")),
                        new TextureRegion2D(contentManager.Load<Texture2D>("meteorBrown_big2")),
                        new TextureRegion2D(contentManager.Load<Texture2D>("meteorBrown_big3")),
                        new TextureRegion2D(contentManager.Load<Texture2D>("meteorBrown_big4"))
                    }
                },
                { 3, new []
                    {
                        new TextureRegion2D(contentManager.Load<Texture2D>("meteorBrown_med1")),
                        new TextureRegion2D(contentManager.Load<Texture2D>("meteorBrown_med3"))
                    }
                },
                { 2, new []
                    {
                        new TextureRegion2D(contentManager.Load<Texture2D>("meteorBrown_small1")),
                        new TextureRegion2D(contentManager.Load<Texture2D>("meteorBrown_small2"))
                    }
                },
                { 1, new []
                    {
                        new TextureRegion2D(contentManager.Load<Texture2D>("meteorBrown_tiny1")),
                        new TextureRegion2D(contentManager.Load<Texture2D>("meteorBrown_tiny2"))
                    }
                }

            };
        }
Exemplo n.º 20
0
        protected void btnfinalize_Click(object sender, EventArgs e)
        {
            Dictionary<int, int> cartItems1 = (Dictionary<int, int>)Session["ShoppingCart"];
            int prodid1;
            int prodqty1;

            foreach (KeyValuePair<int, int> productidQty in cartItems1)
            {
                prodid1 = productidQty.Key;
                prodqty1 = productidQty.Value;

                EntityManager<ProductListing> pcat = new EntityManager<ProductListing>();
                ProductListing procat = new ProductListing();
                procat.ProductID = prodid1;
                List<ProductListing> prodcatID = pcat.Search(procat);

            }

               // ShoppingCrt.
            //EntityManager<ShippingAddress> pcat = new EntityManager<ShippingAddress>();
            //ShippingAddress procat = new ShippingAddress();
            //procat.CustomerID = 10;
            //procat.AddressLine1 = "sdfag";

            //List<ShippingAddress> prodcatID = pcat.Insert(procat);
        }
Exemplo n.º 21
0
        protected void btn_Checkout_Click(object sender, EventArgs e)
        {
            string abc = "";
               // Response.Redirect("Checkout.aspx");
            int customerid = Convert.ToInt32(Session["customerid"].ToString());

            EntityManager<ShippingAddress> pcat = new EntityManager<ShippingAddress>();
            ShippingAddress procat = new ShippingAddress();
            procat.CustomerID = customerid;
            List<ShippingAddress> prodcatID = pcat.Search(procat);
            if (prodcatID.Count != 0)
            {
                abc = prodcatID[0].AddressLine1;
            }
            if (abc == "")
            {
                addressedit.Visible = true;
            }
            else
            {

                addressview.Visible = true;
            }
            btnfindis.Visible = true;
            btn_Checkout.Visible = false;
        }
Exemplo n.º 22
0
    public override CollResult CheckAgainst(zCollisionPrimitive other, EntityManager.Transform myRoot, EntityManager.Transform hisRoot)
    {
        //Transform both into correct space
        if(other is zCollisionAABB)
        {
            CollResult ret = new CollResult();
            ret.collided = false;
            ret.normal = Vector2.Zero;
            Rectangle mine = m_rect;
            mine.Offset((int)myRoot.GetPos().X, (int)myRoot.GetPos().Y);

            Rectangle his = (other as zCollisionAABB).m_rect;
            his.Offset((int)hisRoot.GetPos().X, (int)hisRoot.GetPos().Y);

            if(mine.Intersects(his))
            {
                ret.collided = true;
                ret.normal = new Vector2(his.Center.X - mine.Center.X, his.Center.Y - mine.Center.Y);
                ret.normal.Normalize();
            }
            return ret;
        }

        //Oh no we can't handle any others.
        return other.RedirectedCheckAgainst(this, hisRoot, myRoot); //Note the swap of transforms
    }
 public void TestInitialize()
 {
     Game game = new Game();
     EntityManager entityManager = new EntityManager(game);
     // Create compound entities.
     new CompoundEntities<TestCompound>(entityManager);
 }
Exemplo n.º 24
0
        protected override bool ValidateSave()
        {
            base.ValidateSave();

            // Create a sandbox to do the validation in.
            var em = new EntityManager(EntityManager);
            em.CacheStateManager.RestoreCacheState(EntityManager.CacheStateManager.GetCacheState());

            // Find all entities supporting custom validation                
            var entities =
                em.FindEntities(EntityState.AllButDetached).OfType<EntityBase>().ToList();

            foreach (var e in entities)
            {
                var entityAspect = EntityAspect.Wrap(e);
                if (entityAspect.EntityState.IsDeletedOrDetached()) continue;

                var validationErrors = new VerifierResultCollection();
                e.Validate(validationErrors);

                validationErrors =
                    new VerifierResultCollection(entityAspect.ValidationErrors.Concat(validationErrors.Errors));
                validationErrors.Where(vr => !entityAspect.ValidationErrors.Contains(vr))
                    .ForEach(entityAspect.ValidationErrors.Add);

                if (validationErrors.HasErrors)
                    throw new EntityServerException(validationErrors.Select(v => v.Message).ToAggregateString("\n"),
                                                    null,
                                                    PersistenceOperation.Save, PersistenceFailure.Validation);
            }

            return true;
        }
Exemplo n.º 25
0
        public async Task SimpleConcurrencyFault() {

            Configuration.Instance.ProbeAssemblies(typeof(Customer).Assembly);

            // Query Alfred
            var entityManager1 = new EntityManager(_northwindServiceName);
            var query = new EntityQuery<Customer>().Where(c => c.CustomerID == _alfredsID);
            var alfred1 = (await entityManager1.ExecuteQuery(query)).FirstOrDefault();

            // Query a second copy of Alfred in a second entity manager
            var entityManager2 = new EntityManager(_northwindServiceName);
            var alfred2 = (await entityManager2.ExecuteQuery(query)).FirstOrDefault();

            // Modify and save the first Alfred
            alfred1.ContactTitle += "X";

            // Currently, this throws due to "changes to an original record may not be saved"
            // ...whatever that means
            var saveResult1 = await entityManager1.SaveChanges();

            // Attempt to modify and save the second Alfred
            alfred2.ContactName += "Y";
            try {
                var saveResult2 = await entityManager2.SaveChanges();
            }
            catch (SaveException e) {
                var message = e.Message;
            }
        }
Exemplo n.º 26
0
 public JsonEntityConverter(EntityManager entityManager, MergeStrategy mergeStrategy, Func<String, String> normalizeTypeNameFn = null) {
   _entityManager = entityManager;
   _metadataStore = entityManager.MetadataStore;
   _mergeStrategy = mergeStrategy;
   _normalizeTypeNameFn = normalizeTypeNameFn;
   _allEntities = new List<IEntity>();
 }
Exemplo n.º 27
0
        static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                Console.WriteLine("Syntax: ImportBatchCreator filepath");
                return;
            }
            var filePath = args[0];
            var em = new EntityManager("RichardK", "RichardK");
            var objects = new List<Object>();
            foreach (var line in File.ReadLines(filePath))
            {
                var pieces = new String[0];
                if (line != null)
                    pieces = line.Split(',');
                if (pieces.Length < 3)
                {
                    Console.WriteLine("Line not valid: " + line);
                    return;
                }
                var comboOrder = BuildComboOrder(pieces[0], Decimal.Parse(pieces[1]), pieces[2]);
                objects.Add(comboOrder);
            }

            var batchName = String.Format(CultureInfo.CurrentCulture, "Import batch {0}.xml", DateTime.Now.ToString("s", CultureInfo.CurrentCulture).Replace(':', '-'));
            var batch = new ImportBatchData { Batch = objects, Name = batchName };
            var addResults = em.Add(batch);
            if (!addResults.IsValid)
                Console.WriteLine("Results not valid: " + addResults.ValidationResults.Summary);
            else
                Console.WriteLine("Import batch created.");
        }
Exemplo n.º 28
0
        public override void Update(GameTime time, EntityManager manager)
        {
            DijkstraMap map = manager.world.civilianMaps[mapToUse];
            int x = this.getEntityX();//(int) entity.location.Center.X / Tile.SIDE_LENGTH;
            int y = this.getEntityY();//(int) entity.location.Center.Y / Tile.SIDE_LENGTH;
            if (x < 0 || x >= map.Map.Length || y < 0 || y >= map.Map[0].Length)
                return;
            if (map.Map[x][y] < 2 || !entity.currentWorld.tiles[x][y].IsWalkable)
                entity.markForDelete = true;

            if (entity.collidingEntites.Count > 0 && flee == null) {
                Entity.Entity e = entity.collidingEntites[0];
                int modX = (int) e.location.X / Tile.SIDE_LENGTH - x + 3;
                int modY = (int) e.location.Y / Tile.SIDE_LENGTH - y + 3;
                flee = new DijkstraMap(entity.currentWorld, 6, 6, x - 3, y - 3, 1, new int[] { modX, modY });
                flee = flee.GenerateFleeMap(entity.currentWorld);
                fleeCount = 30;
            }
            if (flee != null) {
                entity.direction = this.findPos(flee, 1);
                fleeCount--;
                if (fleeCount <= 0)
                    flee = null;
            } else
                entity.direction = this.findPos(map, 1);
            entity.Move();
        }
        public async Task QueryRoles()
        {
            //Assert.Inconclusive("See comments in the QueryRoles test");

            // Issues:
            //
            // 1.  When the RoleType column was not present in the Role entity in the database (NorthwindIB.sdf), 
            //     the query failed with "Internal Server Error".  A more explanatory message would be nice.  
            //     The RoleType column has been added (nullable int), so this error no longer occurs.
            //
            // 2.  Comment out the RoleType property in the client model (Model.cs in Client\Model_Northwind.Sharp project lines 514-517).
            //     In this case, the client throws a null reference exception in CsdlMetadataProcessor.cs.
            //     This is the FIRST problem reported by the user.  A more informative message would be helpful.
            //
            // Note that this condition causes many other tests to fail as well.
            //
            // 3.  Uncomment the RoleType property in the client model.  Then the client throws in JsonEntityConverter.cs.
            //     This is the SECOND problem reported by the user.  This looks like a genuine bug that should be fixed.
            //

            var manager = new EntityManager(_serviceName);
                // Metadata must be fetched before CreateEntity() can be called
                await manager.FetchMetadata();

                var query = new EntityQuery<Role>();
                var allRoles = await manager.ExecuteQuery(query);

                Assert.IsTrue(allRoles.Any(), "There should be some roles defined");
        }
Exemplo n.º 30
0
 public EventSystem(SystemManager systemManager, EntityManager entityManager)
 {
     _systemManager = systemManager;
     _entityManager = entityManager;
     _levelSystem = (LevelSystem)_systemManager.getSystem(SystemType.Level);
     _handlers = new Dictionary<GameEventType,Dictionary<int,List<IEventHandler>>>();
 }
Exemplo n.º 31
0
 public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
 {
     dstManager.AddSharedComponentData(entity, new PlayerNameComponent {
         Value = PlayerName
     });
 }
Exemplo n.º 32
0
        protected override void OnUpdate()
        {

            var rnd = Parameters.roadNetworkDescription == null ? staticRnd : Parameters.roadNetworkDescription;
            if (rnd == null)
                return;

            var id = rnd.entityRoadId == 0 ? nextId++ : rnd.entityRoadId;
            rnd.entityRoadId = id;
            var ecsRoadNetwork = new EcsRoadNetwork() { id = id };

            //check for an existing road network
            var query = EntityManager.CreateEntityQuery(typeof(EcsRoadNetwork), typeof(EcsRoad));
            query.AddSharedComponentFilter(ecsRoadNetwork);
            if (query.CalculateChunkCount() > 0)
                return;

            var roadEntities = new NativeArray<Entity>(rnd.AllRoads.Length, Allocator.Temp);
            EntityManager.CreateEntity(m_RoadArchetype, roadEntities);

            var junctionEntities = new NativeArray<Entity>(rnd.AllJunctions.Length, Allocator.Temp);
            EntityManager.CreateEntity(m_JunctionArchetype, junctionEntities);

            for (var roadIndex = 0; roadIndex < rnd.AllRoads.Length; roadIndex++)
            {
                var road = rnd.AllRoads[roadIndex];
                var entity = roadEntities[roadIndex];
                EntityManager.SetSharedComponentData(entity, ecsRoadNetwork);
                EntityManager.SetComponentData(entity, new EcsRoad
                {
                    length = road.length,
                    junction = string.IsNullOrEmpty(road.junction) || string.Equals("-1", road.junction) ? Entity.Null : junctionEntities[rnd.GetJunctionIndexById(road.junction)],
                    name = road.name,
                    predecessor = CreateEcsRoadLink(road.predecessor, rnd, roadEntities, junctionEntities),
                    successor = CreateEcsRoadLink(road.successor, rnd, roadEntities, junctionEntities)
                });

                //multiple copies - there is almost certainly a better way
                FillBuffer(road.elevationProfiles, entity);
                FillBuffer(road.geometry, entity);
                FillBuffer(road.laneOffsets, entity);

                var laneSections = EntityManager.GetBuffer<EcsLaneSection>(entity);
                var lanes = EntityManager.GetBuffer<EcsLane>(entity);
                var laneWidthRecords = EntityManager.GetBuffer<LaneWidthRecord>(entity);
                laneSections.ResizeUninitialized(road.laneSections.Count);
                for (var i = 0; i < road.laneSections.Count; i++)
                {
                    var section = road.laneSections[i];

                    laneSections[i] = new EcsLaneSection
                    {
                        centerLaneIndex = lanes.Length + section._centerIdx,
                        firstLaneIndex = lanes.Length,
                        laneCount = section._allLanes.Length,
                        sRoad = section.sRoad
                    };

                    foreach (var lane in section._allLanes)
                    {
                        var ecsLane = new EcsLane
                        {
                            firstLaneWidthRecordIndex = laneWidthRecords.Length,
                            laneWidthRecordCount = lane.widthRecords.Length,
                            firstPredecessorId = FirstOrZero(lane.link.predecessors),
                            predecessorIdCount = lane.link.predecessors?.Length ?? 0,
                            firstSuccessorId = FirstOrZero(lane.link.successors),
                            successorIdCount = lane.link.successors?.Length ?? 0,
                            id = lane.id
                        };

                        var nativeData = new NativeArray<LaneWidthRecord>(lane.widthRecords, Allocator.Temp);
                        laneWidthRecords.AddRange(nativeData);
                        nativeData.Dispose();

                        lanes.Add(ecsLane);
                    }
                }
            }

            for (var junctionIndex = 0; junctionIndex < rnd.AllJunctions.Length; junctionIndex++)
            {
                var junction = rnd.AllJunctions[junctionIndex];
                var entity = junctionEntities[junctionIndex];

                EntityManager.SetSharedComponentData(entity, ecsRoadNetwork);
                EntityManager.SetComponentData(entity, new EcsJunction
                {
                    name = junction.name,
                    junctionId = junction.junctionId
                });
                var connectionBuffer = EntityManager.GetBuffer<EcsJunctionConnection>(entity);
                connectionBuffer.ResizeUninitialized(junction.connections.Count);
                for (int connectionIndex = 0; connectionIndex < junction.connections.Count; connectionIndex++)
                {
                    var connection = junction.connections[connectionIndex];
                    connectionBuffer[connectionIndex] = new EcsJunctionConnection
                    {
                        connectingRoad = roadEntities[rnd.GetRoadIndexById(connection.connectingRoadId)],
                        incomingRoad = roadEntities[rnd.GetRoadIndexById(connection.incomingRoadId)],
                        linkContactPoint = connection.contactPoint
                    };
                }
            }
        }
 public ComponentReplicator(EntityManager entityManager, Unity.Entities.World world) : base(entityManager)
 {
     var bookkeepingSystem = world.GetOrCreateManager <CommandRequestTrackerSystem>();
 }
 public DispatcherHandler(WorkerSystem worker, World world) : base(worker, world)
 {
     entityManager = world.GetOrCreateManager <EntityManager>();
     var bookkeepingSystem = world.GetOrCreateManager <CommandRequestTrackerSystem>();
 }
Exemplo n.º 35
0
 public void Convert(Entity entity, EntityManager entityManager, GameObjectConversionSystem conversionSystem)
 {
     entityManager.AddComponent <FollowEntity>(entity);
 }
        public void SendUpdate(PlayerHeartbeatClient.Update update)
        {
            var component = EntityManager.GetComponentData <PlayerHeartbeatClient.Component>(Entity);

            EntityManager.SetComponentData(Entity, component);
        }
Exemplo n.º 37
0
 private void Start()
 {
     //_particleSystem.Stop();
     _manager = World.DefaultGameObjectInjectionWorld.EntityManager;
 }
 public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
 {
     dstManager.AddComponentData(entity, new SelfDestruct {
         TimeToLive = TimeToLive
     });
 }
Exemplo n.º 39
0
 void Start()
 {
     em = World.Active.EntityManager;
     EventManager.instance.RegisterListener <CollisionEvent>(this);
 }
Exemplo n.º 40
0
        public dynamic InitPcFieldBaseModel(PageComponentContext context, PcFieldBaseOptions options, out string label, string targetModel = "PcFieldBaseModel")
        {
            label = "";
            var model = new PcFieldBaseModel();

            if (context.Items.ContainsKey(typeof(ValidationException)))
            {
                model.ValidationErrors = ((ValidationException)context.Items[typeof(ValidationException)]).Errors;
            }

            model.LabelRenderModeOptions = ModelExtensions.GetEnumAsSelectOptions <LabelRenderMode>();

            model.FieldRenderModeOptions = ModelExtensions.GetEnumAsSelectOptions <FieldRenderMode>();

            if (context.Mode == ComponentMode.Options)
            {
                model.EntitySelectOptions = new MetaService().GetEntitiesAsSelectOptions();
            }

            var recordId = context.DataModel.GetProperty("RecordId");

            if (recordId != null && recordId is Guid)
            {
                model.RecordId = (Guid)recordId;
            }

            var entity = context.DataModel.GetProperty("Entity");

            if (entity != null && entity is Entity)
            {
                model.EntityName = ((Entity)entity).Name;
                if (!String.IsNullOrWhiteSpace(model.EntityName) && model.RecordId != null)
                {
                    model.ApiUrl = $"/api/v3/en_US/record/{model.EntityName}/{model.RecordId}/";
                }
            }

            Entity mappedEntity = null;

            if (options.ConnectedEntityId != null)
            {
                mappedEntity = new EntityManager().ReadEntity(options.ConnectedEntityId.Value).Object;
            }
            else if (options.ConnectedEntityId == null && entity is Entity)
            {
                mappedEntity = (Entity)entity;
            }

            if (mappedEntity != null)
            {
                var fieldName = options.Name;

                if (fieldName.StartsWith("$"))
                {
                    //Field with relation is set. Mapped entity should be changed
                    var fieldNameArray = fieldName.Replace("$", "").Split(".", StringSplitOptions.RemoveEmptyEntries);
                    if (fieldNameArray.Length == 2)
                    {
                        var relationName = fieldNameArray[0];
                        fieldName = fieldNameArray[1];
                        var relation = new EntityRelationManager().Read(relationName).Object;
                        if (relation != null)
                        {
                            if (relation.OriginEntityId == mappedEntity.Id)
                            {
                                mappedEntity = new EntityManager().ReadEntity(relation.TargetEntityId).Object;
                            }
                            else if (relation.TargetEntityId == mappedEntity.Id)
                            {
                                mappedEntity = new EntityManager().ReadEntity(relation.OriginEntityId).Object;
                            }
                        }
                    }
                }

                var entityField = mappedEntity.Fields.FirstOrDefault(x => x.Name == fieldName);
                if (entityField != null)
                {
                    //Connection success set local options if needed
                    if (String.IsNullOrWhiteSpace(model.Placeholder))
                    {
                        model.Placeholder = entityField.PlaceholderText;
                    }

                    if (String.IsNullOrWhiteSpace(model.Description))
                    {
                        model.Description = entityField.Description;
                    }

                    if (String.IsNullOrWhiteSpace(model.LabelHelpText))
                    {
                        model.LabelHelpText = entityField.HelpText;
                    }

                    if (String.IsNullOrWhiteSpace(label))
                    {
                        label = entityField.Label;
                    }

                    model.Required = entityField.Required;

                    if (entityField.EnableSecurity)
                    {
                        var currentUser = context.DataModel.GetProperty("CurrentUser");
                        if (currentUser != null && currentUser is ErpUser)
                        {
                            var canRead   = false;
                            var canUpdate = false;
                            var user      = (ErpUser)currentUser;
                            foreach (var role in user.Roles)
                            {
                                if (entityField.Permissions.CanRead.Any(x => x == role.Id))
                                {
                                    canRead = true;
                                }
                                if (entityField.Permissions.CanUpdate.Any(x => x == role.Id))
                                {
                                    canUpdate = true;
                                }
                            }
                            if (canUpdate)
                            {
                                model.Access = FieldAccess.Full;
                            }
                            else if (canRead)
                            {
                                model.Access = FieldAccess.ReadOnly;
                            }
                            else
                            {
                                model.Access = FieldAccess.Forbidden;
                            }
                        }
                    }

                    //Specific model properties
                    var fieldOptions = new List <SelectOption>();
                    switch (entityField.GetFieldType())
                    {
                    case FieldType.SelectField:
                        var selectField = ((SelectField)entityField);
                        model.DefaultValue = selectField.DefaultValue;
                        fieldOptions       = selectField.Options;
                        break;

                    case FieldType.MultiSelectField:
                        var multiselectField = ((MultiSelectField)entityField);
                        model.DefaultValue = multiselectField.DefaultValue;
                        fieldOptions       = multiselectField.Options;
                        break;

                    default:
                        break;
                    }
                    switch (targetModel)
                    {
                    case "PcFieldSelectModel":
                        return(PcFieldSelectModel.CopyFromBaseModel(model, fieldOptions));

                    case "PcFieldRadioListModel":
                        return(PcFieldRadioListModel.CopyFromBaseModel(model, fieldOptions));

                    case "PcFieldCheckboxListModel":
                        return(PcFieldCheckboxListModel.CopyFromBaseModel(model, fieldOptions));

                    case "PcFieldMultiSelectModel":
                        return(PcFieldMultiSelectModel.CopyFromBaseModel(model, fieldOptions));

                    case "PcFieldCheckboxGridModel":
                        return(PcFieldCheckboxGridModel.CopyFromBaseModel(model, new List <SelectOption>(), new List <SelectOption>()));

                    default:
                        return(model);
                    }
                }
            }

            switch (targetModel)
            {
            case "PcFieldSelectModel":
                return(PcFieldSelectModel.CopyFromBaseModel(model, new List <SelectOption>()));

            case "PcFieldRadioListModel":
                return(PcFieldRadioListModel.CopyFromBaseModel(model, new List <SelectOption>()));

            case "PcFieldCheckboxListModel":
                return(PcFieldCheckboxListModel.CopyFromBaseModel(model, new List <SelectOption>()));

            case "PcFieldMultiSelectModel":
                return(PcFieldMultiSelectModel.CopyFromBaseModel(model, new List <SelectOption>()));

            case "PcFieldCheckboxGridModel":
                return(PcFieldCheckboxGridModel.CopyFromBaseModel(model, new List <SelectOption>(), new List <SelectOption>()));

            default:
                return(model);
            }
        }
Exemplo n.º 41
0
        // Update is called once per frame
        protected override void OnUpdate( )
        {
            if (Time.ElapsedTime <= i_startTime)
            {
                return;                                     // Delay startup.
            }
            EntityCommandBuffer ecb = becb.CreateCommandBuffer();

            ComponentDataFromEntity <NNManagerComponent> a_manager;


            if (group_MMMamager.CalculateChunkCount() == 0)
            {
                // Debug.LogWarning ( "There is no active managers yet." ) ;
                return;
            }


            a_manager = GetComponentDataFromEntity <NNManagerComponent> (false);
            // NNManagerComponent manager ;
            ComponentDataFromEntity <NNTimerComponent> a_managerTimer = GetComponentDataFromEntity <NNTimerComponent> (false);
            ComponentDataFromEntity <IsTimeUpTag>      a_isTimeUpTag  = GetComponentDataFromEntity <IsTimeUpTag> (true);


            int i_activeManager = 0;


            l_managerSharedData.Clear();
            EntityManager.GetAllUniqueSharedComponentData(l_managerSharedData);


            // Ignore default manager entity ( index = 0, version = 0 ), taken from prefab entity.
            for (int i = 0; i < l_managerSharedData.Count; i++)
            {
                NNManagerSharedComponent mangerSharedComponent = l_managerSharedData [i];
                Entity managerEntity = new Entity()
                {
                    Index = mangerSharedComponent.i_entityIndex, Version = mangerSharedComponent.i_entityVersion
                };

                ComponentDataFromEntity <IsAliveTag> a_isAliveTag = GetComponentDataFromEntity <IsAliveTag> (false);
// Debug.Log ( "nnManagerEntity: " + nnManagerEntity ) ;


                // Entity manager must be valid and active.
                if (ManagerMethods._SkipInvalidManager(managerEntity, ref a_isAliveTag))
                {
                    continue;
                }

                if (!a_isTimeUpTag.HasComponent(managerEntity))
                {
                    NNTimerComponent managerTimer = a_managerTimer [managerEntity];

                    NNManagerComponent manager = a_manager [managerEntity];

// Debug.Log ( "Timer" ) ;
                    group_finishedPopulation.SetSharedComponentFilter(mangerSharedComponent);

                    if (Time.ElapsedTime >= managerTimer.f || group_finishedPopulation.CalculateEntityCount() >= manager.i_populationSize)
                    {
                        managerTimer.f = (float)Time.ElapsedTime + manager.i_startLifeTime;

                        a_managerTimer [managerEntity] = managerTimer;   // Set back.

                        ecb.AddComponent <IsTimeUpTag> (managerEntity);

// Debug.LogError ( "Set" ) ;
                    }
                }
                else // if ( a_isTimeUpTag.Exists ( managerEntity ) )
                {
// Debug.LogError ( "Reset" ) ;
                    ecb.RemoveComponent <IsTimeUpTag> (managerEntity);
                }

                i_activeManager++;
            } // for

            becb.AddJobHandleForProducer(Dependency);
        }
Exemplo n.º 42
0
        public override void OnInitialize(EntityManager manager)
        {
            PhysicsBody = BodyFactory.CreateBody(this.GDManager().PhysicsWorld, ConvertUnits2.ToSimUnits(Position), 0, BodyType.Static);

            PhysicsFixture = FixtureFactory.AttachCircle(ConvertUnits.ToSimUnits(_diameter / 2f), 1, PhysicsBody, this);
        }
Exemplo n.º 43
0
    public void Initialize()
    {
        EntityManager = World.DefaultGameObjectInjectionWorld.EntityManager;

        Players = new List <Player>(1);
    }
Exemplo n.º 44
0
 private void OnProximityInit(EntityUid uid, TriggerOnProximityComponent component, ComponentInit args)
 {
     EntityManager.EnsureComponent <AnimationPlayerComponent>(uid);
 }
Exemplo n.º 45
0
 protected static void SetComponentData<TComponentData>(EntityManager entityManager, EntityGuid entityGuid, TComponentData data) 
     where TComponentData : struct, IComponentData
 {
     var entity = GetEntity(entityManager, entityGuid);
     entityManager.SetComponentData(entity, data);
 }
Exemplo n.º 46
0
 public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
 {
     dstManager.AddComponentData(entity, default(DateTimeTicksToProcess));
 }
Exemplo n.º 47
0
 protected static bool HasManagedComponent<TComponentData>(EntityManager entityManager, EntityGuid entityGuid)
     where TComponentData : class, IComponentData
 {
     return entityManager.HasComponent<TComponentData>(GetEntity(entityManager, entityGuid));
 }
Exemplo n.º 48
0
 protected static TComponentData GetComponentData<TComponentData>(EntityManager entityManager, EntityGuid entityGuid) 
     where TComponentData : struct, IComponentData
 {
     return entityManager.GetComponentData<TComponentData>(GetEntity(entityManager, entityGuid));
 }
Exemplo n.º 49
0
 public static ItemSize Retrieve(ISession session, string sizeCode, int catId)
 {
     return(EntityManager.Retrieve <ItemSize>(session, new string[] { "SizeCode", "CategoryID" }, new object[] { sizeCode, catId }));
 }
Exemplo n.º 50
0
 public static bool Delete(ISession session, string sizeCode, int catId)
 {
     return(EntityManager.Delete <ItemSize>(session, new string[] { "SizeCode", "CategoryID" }, new object[] { sizeCode, catId }) > 0);
 }
Exemplo n.º 51
0
 public bool Update(ISession session, params string[] propertyNames2Update)
 {
     return(EntityManager.Update(session, this, propertyNames2Update));
 }
Exemplo n.º 52
0
 public bool Delete(ISession session)
 {
     return(EntityManager.Delete(session, this));
 }
Exemplo n.º 53
0
 public bool Create(ISession session)
 {
     return(EntityManager.Create(session, this));
 }
Exemplo n.º 54
0
 public bool Update(ISession session)
 {
     return(EntityManager.Update(session, this));
 }
        /// <summary>
        ///     Try to replace a light bulb in <paramref name="fixtureUid"/>
        ///     using light replacer. Light fixture should have <see cref="PoweredLightComponent"/>.
        /// </summary>
        /// <returns>True if successfully replaced light, false otherwise</returns>
        public bool TryReplaceBulb(EntityUid replacerUid, EntityUid fixtureUid, EntityUid?userUid = null,
                                   LightReplacerComponent?replacer = null, PoweredLightComponent?fixture = null)
        {
            if (!Resolve(replacerUid, ref replacer))
            {
                return(false);
            }
            if (!Resolve(fixtureUid, ref fixture))
            {
                return(false);
            }

            // check if light bulb is broken or missing
            var fixtureBulbUid = _poweredLight.GetBulb(fixture.Owner, fixture);

            if (fixtureBulbUid != null)
            {
                if (!EntityManager.TryGetComponent(fixtureBulbUid.Value, out LightBulbComponent? fixtureBulb))
                {
                    return(false);
                }
                if (fixtureBulb.State == LightBulbState.Normal)
                {
                    return(false);
                }
            }

            // try get first inserted bulb of the same type as targeted light fixtutre
            var bulb = replacer.InsertedBulbs.ContainedEntities.FirstOrDefault(
                (e) => EntityManager.GetComponentOrNull <LightBulbComponent>(e)?.Type == fixture.BulbType);

            // found bulb in inserted storage
            if (bulb.Valid) // FirstOrDefault can return default/invalid uid.
            {
                // try to remove it
                var hasRemoved = replacer.InsertedBulbs.Remove(bulb);
                if (!hasRemoved)
                {
                    return(false);
                }
            }
            // try to create new instance of bulb from LightReplacerEntity
            else
            {
                var bulbEnt = replacer.Contents.FirstOrDefault((e) => e.Type == fixture.BulbType && e.Amount > 0);

                // found right bulb, let's spawn it
                if (bulbEnt != null)
                {
                    bulb = EntityManager.SpawnEntity(bulbEnt.PrototypeName, EntityManager.GetComponent <TransformComponent>(replacer.Owner).Coordinates);
                    bulbEnt.Amount--;
                }
                // not found any light bulbs
                else
                {
                    if (userUid != null)
                    {
                        var msg = Loc.GetString("comp-light-replacer-missing-light",
                                                ("light-replacer", replacer.Owner));
                        _popupSystem.PopupEntity(msg, replacerUid, Filter.Entities(userUid.Value));
                    }
                    return(false);
                }
            }

            // insert it into fixture
            var wasReplaced = _poweredLight.ReplaceBulb(fixtureUid, bulb, fixture);

            if (wasReplaced)
            {
                SoundSystem.Play(Filter.Pvs(replacerUid), replacer.Sound.GetSound(),
                                 replacerUid, AudioParams.Default.WithVolume(-4f));
            }


            return(wasReplaced);
        }
        public ActionResult Save(EditNotificationModel model)
        {
            using (NotificationManager nManager = new NotificationManager())
                using (EntityPermissionManager pManager = new EntityPermissionManager())
                    using (EntityManager entityTypeManager = new EntityManager())
                        using (UserManager userManager = new UserManager())
                        {
                            Dictionary <long, List <string> > dictionary = (Dictionary <long, List <string> >)Session["ResourceFilter"];
                            if (ModelState.IsValid && dictionary != null)
                            {
                                //if edit need comarison between stored dependensies and set in session
                                //get resource filter from the notification
                                //Dictionary<long, List<string>> dictionary = (Dictionary<long, List<string>>)Session["ResourceFilter"];
                                Session["ResourceFilter"] = null;

                                List <Schedule> affectedSchedules = GetAffectedSchedules(dictionary, model.StartDate, model.EndDate);

                                Notification notification = new Rbm.Entities.Booking.Notification();
                                if (model.Id == 0)
                                {
                                    notification = nManager.CreateNotification(model.Subject, model.StartDate, model.EndDate, model.Message);
                                }
                                else
                                {
                                    notification           = nManager.GetNotificationById(model.Id);
                                    notification.Subject   = model.Subject;
                                    notification.StartDate = model.StartDate;
                                    notification.EndDate   = model.EndDate;
                                    notification.Message   = model.Message;
                                    nManager.UpdateNotification(notification);
                                }

                                //save or update dependencies
                                if (model.Id == 0)
                                {
                                    foreach (KeyValuePair <long, List <string> > kp in dictionary)
                                    {
                                        foreach (string value in kp.Value)
                                        {
                                            nManager.CreateNotificationDependency(notification, Convert.ToInt64(kp.Key), value);
                                        }
                                    }
                                }
                                else
                                {
                                    //remove dep.
                                    for (int i = 0; i < notification.NotificationDependency.Count(); i++)
                                    //foreach (NotificationDependency d in notification.NotificationDependency)
                                    {
                                        if (dictionary.ContainsKey(notification.NotificationDependency.ToList()[i].AttributeId))
                                        {
                                            if (dictionary[notification.NotificationDependency.ToList()[i].AttributeId].Contains(notification.NotificationDependency.ToList()[i].DomainItem))
                                            {
                                                //:)
                                            }
                                            else
                                            {
                                                notification.NotificationDependency.Remove(notification.NotificationDependency.ToList()[i]);
                                                nManager.UpdateNotification(notification);
                                                //nManager.DeleteNotificationDependency(d);
                                            }
                                        }
                                        else
                                        {
                                            //delete all dependencies
                                            notification.NotificationDependency.Clear();
                                            nManager.UpdateNotification(notification);
                                        }
                                    }

                                    //add dep
                                    foreach (KeyValuePair <long, List <string> > kvp in dictionary)
                                    {
                                        long id = kvp.Key;
                                        foreach (string value in kvp.Value)
                                        {
                                            if (!notification.NotificationDependency.Any(a => a.AttributeId == id && a.DomainItem == value))
                                            {
                                                nManager.CreateNotificationDependency(notification, Convert.ToInt64(id), value);
                                            }
                                        }
                                    }
                                }


                                if (notification.Id != 0 && model.Id == 0)
                                {
                                    //Start -> add security ----------------------------------------


                                    {
                                        var userTask = userManager.FindByNameAsync(HttpContext.User.Identity.Name);
                                        userTask.Wait();
                                        var user = userTask.Result;

                                        Entity entityType = entityTypeManager.FindByName("Notification");

                                        //31 is the sum from all rights:  Read = 1,  Write = 4, Delete = 8, Grant = 16
                                        int rights = (int)RightType.Read + (int)RightType.Write + (int)RightType.Delete + (int)RightType.Grant;
                                        pManager.Create(user, entityType, notification.Id, rights);
                                    }

                                    //End -> add security ------------------------------------------
                                }

                                //ToDo: Send email with notification to all in a affected schedule involved people
                                if (affectedSchedules.Count > 0)
                                {
                                    SendNotification(notification, affectedSchedules);
                                }

                                //return View("NotificationManager");
                                return(Json(new { success = true }));
                            }
                            else
                            {
                                List <AttributeDomainItemsModel> attributeDomainItems = (List <AttributeDomainItemsModel>)Session["FilterOptions"];
                                //Dictionary<long, List<string>> dictionary = (Dictionary<long, List<string>>)Session["ResourceFilter"];
                                if (dictionary != null)
                                {
                                    foreach (AttributeDomainItemsModel m in attributeDomainItems)
                                    {
                                        for (int i = 0; i < m.DomainItems.Count(); i++)
                                        {
                                            var list = dictionary.SelectMany(x => x.Value);
                                            if (list.Contains(m.DomainItems[i].Key))
                                            {
                                                m.DomainItems[i].Selected = true;
                                            }
                                        }
                                    }
                                }

                                model.AttributeDomainItems = attributeDomainItems;
                                return(PartialView("_editNotification", model));
                            }
                        }
        }
Exemplo n.º 57
0
        protected unsafe override void OnUpdate()
        {
            m_GhostReceiveSystem.LastGhostMapWriter.Complete();

            var interpolationTargetTick = m_ClientSimulationSystemGroup.InterpolationTick;

            if (m_ClientSimulationSystemGroup.InterpolationTickFraction < 1)
            {
                --interpolationTargetTick;
            }
            //var predictionTargetTick = m_ClientSimulationSystemGroup.ServerTick;
            var prefabsEntity = GetSingletonEntity <GhostCollection>();
            var prefabs       = EntityManager.GetBuffer <GhostCollectionPrefab>(prefabsEntity).ToNativeArray(Allocator.Temp);

            var ghostSpawnEntity            = GetSingletonEntity <GhostSpawnQueueComponent>();
            var ghostSpawnBufferComponent   = EntityManager.GetBuffer <GhostSpawnBuffer>(ghostSpawnEntity);
            var snapshotDataBufferComponent = EntityManager.GetBuffer <SnapshotDataBuffer>(ghostSpawnEntity);
            var ghostSpawnBuffer            = ghostSpawnBufferComponent.ToNativeArray(Allocator.Temp);
            var snapshotDataBuffer          = snapshotDataBufferComponent.ToNativeArray(Allocator.Temp);

            ghostSpawnBufferComponent.ResizeUninitialized(0);
            snapshotDataBufferComponent.ResizeUninitialized(0);

            var spawnedGhosts            = new NativeList <SpawnedGhostMapping>(16, Allocator.Temp);
            var nonSpawnedGhosts         = new NativeList <NonSpawnedGhostMapping>(16, Allocator.Temp);
            var ghostCollectionSingleton = GetSingletonEntity <GhostCollection>();

            for (int i = 0; i < ghostSpawnBuffer.Length; ++i)
            {
                var    ghost               = ghostSpawnBuffer[i];
                Entity entity              = Entity.Null;
                byte * snapshotData        = null;
                var    ghostTypeCollection = EntityManager.GetBuffer <GhostCollectionPrefabSerializer>(ghostCollectionSingleton);
                var    snapshotSize        = ghostTypeCollection[ghost.GhostType].SnapshotSize;
                bool   hasBuffers          = ghostTypeCollection[ghost.GhostType].NumBuffers > 0;
                if (ghost.SpawnType == GhostSpawnBuffer.Type.Interpolated)
                {
                    // Add to m_DelayedSpawnQueue
                    entity = EntityManager.CreateEntity();
                    EntityManager.AddComponentData(entity, new GhostComponent {
                        ghostId = ghost.GhostID, ghostType = ghost.GhostType, spawnTick = ghost.ServerSpawnTick
                    });
                    var newBuffer = EntityManager.AddBuffer <SnapshotDataBuffer>(entity);
                    newBuffer.ResizeUninitialized(snapshotSize * GhostSystemConstants.SnapshotHistorySize);
                    snapshotData = (byte *)newBuffer.GetUnsafePtr();
                    //Add also the SnapshotDynamicDataBuffer if the entity has buffers to copy the dynamic contents
                    if (hasBuffers)
                    {
                        EntityManager.AddBuffer <SnapshotDynamicDataBuffer>(entity);
                    }
                    EntityManager.AddComponentData(entity, new SnapshotData {
                        SnapshotSize = snapshotSize, LatestIndex = 0
                    });
                    m_DelayedSpawnQueue.Enqueue(new GhostSpawnSystem.DelayedSpawnGhost {
                        ghostId = ghost.GhostID, ghostType = ghost.GhostType, clientSpawnTick = ghost.ClientSpawnTick, serverSpawnTick = ghost.ServerSpawnTick, oldEntity = entity
                    });
                    nonSpawnedGhosts.Add(new NonSpawnedGhostMapping {
                        ghostId = ghost.GhostID, entity = entity
                    });
                }
                else if (ghost.SpawnType == GhostSpawnBuffer.Type.Predicted)
                {
                    // TODO: this could allow some time for the prefab to load before giving an error
                    if (prefabs[ghost.GhostType].GhostPrefab == Entity.Null)
                    {
                        ReportMissingPrefab();
                        continue;
                    }
                    // Spawn directly
                    entity = ghost.PredictedSpawnEntity != Entity.Null ? ghost.PredictedSpawnEntity : EntityManager.Instantiate(prefabs[ghost.GhostType].GhostPrefab);
                    if (EntityManager.HasComponent <GhostPrefabMetaDataComponent>(prefabs[ghost.GhostType].GhostPrefab))
                    {
                        ref var toRemove = ref EntityManager.GetComponentData <GhostPrefabMetaDataComponent>(prefabs[ghost.GhostType].GhostPrefab).Value.Value.DisableOnPredictedClient;
                        //Need copy because removing component will invalidate the buffer pointer, since introduce structural changes
                        var linkedEntityGroup = EntityManager.GetBuffer <LinkedEntityGroup>(entity).ToNativeArray(Allocator.Temp);
                        for (int rm = 0; rm < toRemove.Length; ++rm)
                        {
                            var compType = ComponentType.ReadWrite(TypeManager.GetTypeIndexFromStableTypeHash(toRemove[rm].StableHash));
                            EntityManager.RemoveComponent(linkedEntityGroup[toRemove[rm].EntityIndex].Value, compType);
                        }
                    }
                    EntityManager.SetComponentData(entity, new GhostComponent {
                        ghostId = ghost.GhostID, ghostType = ghost.GhostType, spawnTick = ghost.ServerSpawnTick
                    });
                    var newBuffer = EntityManager.GetBuffer <SnapshotDataBuffer>(entity);
                    newBuffer.ResizeUninitialized(snapshotSize * GhostSystemConstants.SnapshotHistorySize);
                    snapshotData = (byte *)newBuffer.GetUnsafePtr();
                    EntityManager.SetComponentData(entity, new SnapshotData {
                        SnapshotSize = snapshotSize, LatestIndex = 0
                    });
                    spawnedGhosts.Add(new SpawnedGhostMapping {
                        ghost = new SpawnedGhost {
                            ghostId = ghost.GhostID, spawnTick = ghost.ServerSpawnTick
                        }, entity = entity
                    });
                }
                if (entity != Entity.Null)
                {
                    UnsafeUtility.MemClear(snapshotData, snapshotSize * GhostSystemConstants.SnapshotHistorySize);
                    UnsafeUtility.MemCpy(snapshotData, (byte *)snapshotDataBuffer.GetUnsafeReadOnlyPtr() + ghost.DataOffset, snapshotSize);
                    if (hasBuffers)
                    {
                        //Resize and copy the associated dynamic buffer snapshot data
                        var snapshotDynamicBuffer = EntityManager.GetBuffer <SnapshotDynamicDataBuffer>(entity);
                        var dynamicDataCapacity   = SnapshotDynamicBuffersHelper.CalculateBufferCapacity(ghost.DynamicDataSize, out var _);
                        snapshotDynamicBuffer.ResizeUninitialized((int)dynamicDataCapacity);
                        var dynamicSnapshotData = (byte *)snapshotDynamicBuffer.GetUnsafePtr();
                        if (dynamicSnapshotData == null)
                        {
                            throw new InvalidOperationException("snapshot dynamic data buffer not initialized but ghost has dynamic buffer contents");
                        }

                        // Update the dynamic data header (uint[GhostSystemConstants.SnapshotHistorySize)]) by writing the used size for the current slot
                        // (for new spawned entity is 0). Is un-necessary to initialize all the header slots to 0 since that information is only used
                        // for sake of delta compression and, because that depend on the acked tick, only initialized and relevant slots are accessed in general.
                        // For more information about the layout, see SnapshotData.cs.
                        ((uint *)dynamicSnapshotData)[0] = ghost.DynamicDataSize;
                        var headerSize = SnapshotDynamicBuffersHelper.GetHeaderSize();
                        UnsafeUtility.MemCpy(dynamicSnapshotData + headerSize, (byte *)snapshotDataBuffer.GetUnsafeReadOnlyPtr() + ghost.DataOffset + snapshotSize, ghost.DynamicDataSize);
                    }
                }
            }
Exemplo n.º 58
0
        public IActionResult OnGet()
        {
            var initResult = Init();

            if (initResult != null)
            {
                return(initResult);
            }

            #region << InitPage >>
            int           pager     = 0;
            string        sortBy    = "";
            QuerySortType sortOrder = QuerySortType.Ascending;
            PageUtils.GetListQueryParams(PageContext.HttpContext, out pager, out sortBy, out sortOrder);
            Pager     = pager;
            SortBy    = sortBy;
            SortOrder = sortOrder;

            var pageSer = new PageService();
            var entMan  = new EntityManager();
            var appServ = new AppService();

            var pages    = pageSer.GetAll();
            var entities = entMan.ReadEntities().Object;
            var apps     = appServ.GetAllApplications();

            #region << Apply filters >>
            var submittedFilters = PageUtils.GetPageFiltersFromQuery(PageContext.HttpContext);
            foreach (var filter in submittedFilters)
            {
                switch (filter.Name)
                {
                default:
                case "label":
                    if (filter.Type == FilterType.CONTAINS)
                    {
                        pages = pages.FindAll(x => x.Label.ToLowerInvariant().Contains(filter.Value.ToLowerInvariant())).ToList();
                    }
                    break;

                case "name":
                    if (filter.Type == FilterType.CONTAINS)
                    {
                        pages = pages.FindAll(x => x.Name.ToLowerInvariant().Contains(filter.Value.ToLowerInvariant())).ToList();
                    }
                    break;

                case "app":
                    if (filter.Type == FilterType.EQ)
                    {
                        var app = apps.FirstOrDefault(x => x.Name.ToLowerInvariant() == filter.Value.ToLowerInvariant());
                        if (app != null)
                        {
                            pages = pages.FindAll(x => x.AppId == app.Id).ToList();
                        }
                        else
                        {
                            pages = new List <ErpPage>();
                        }
                    }
                    break;

                case "entity":
                    if (filter.Type == FilterType.EQ)
                    {
                        var entity = entities.FirstOrDefault(x => x.Name.ToLowerInvariant() == filter.Value.ToLowerInvariant());
                        if (entity != null)
                        {
                            pages = pages.FindAll(x => x.EntityId == entity.Id).ToList();
                        }
                        else
                        {
                            pages = new List <ErpPage>();
                        }
                    }
                    break;

                case "type":
                    if (filter.Type == FilterType.CONTAINS)
                    {
                        foreach (var typeEnum in Enum.GetValues(typeof(PageType)).Cast <PageType>())
                        {
                            var enumDescription = typeEnum.GetLabel();
                            if (!enumDescription.ToLowerInvariant().Contains(filter.Value.ToLowerInvariant()))
                            {
                                pages = pages.FindAll(x => x.Type != typeEnum).ToList();
                            }
                        }
                        //pages = pages.FindAll(x => x.Type == entity.Id).ToList();
                    }
                    break;

                case "system":
                    if (filter.Type == FilterType.EQ)
                    {
                        if (filter.Value == "true")
                        {
                            pages = pages.FindAll(x => x.System).ToList();
                        }
                        else if (filter.Value == "false")
                        {
                            pages = pages.FindAll(x => !x.System).ToList();
                        }
                    }
                    break;

                case "customized":
                    if (filter.Type == FilterType.EQ)
                    {
                        if (filter.Value == "true")
                        {
                            pages = pages.FindAll(x => x.IsRazorBody).ToList();
                        }
                        else if (filter.Value == "false")
                        {
                            pages = pages.FindAll(x => !x.IsRazorBody).ToList();
                        }
                    }
                    break;
                }
            }
            #endregion

            TotalCount = pages.Count;

            ReturnUrlEncoded = HttpUtility.UrlEncode(PageContext.HttpContext.Request.Path + PageContext.HttpContext.Request.QueryString);

            PageDescription = PageUtils.GenerateListPageDescription(PageContext.HttpContext, "", TotalCount);
            #endregion

            #region << Create Columns >>

            Columns = new List <GridColumn>()
            {
                new GridColumn()
                {
                    Name  = "action",
                    Width = "1%"
                },
                new GridColumn()
                {
                    Label      = "Label",
                    Name       = "label",
                    Sortable   = true,
                    Searchable = true
                },
                new GridColumn()
                {
                    Label      = "Name",
                    Name       = "name",
                    Sortable   = true,
                    Searchable = true
                },
                new GridColumn()
                {
                    Label = "App",
                    Name  = "app",
                    Width = "140px"
                },
                new GridColumn()
                {
                    Label = "Entity",
                    Name  = "entity",
                    Width = "140px"
                },
                new GridColumn()
                {
                    Label    = "Type",
                    Name     = "type",
                    Sortable = true,
                    Width    = "120px"
                },
                new GridColumn()
                {
                    Label    = "system",
                    Name     = "system",
                    Sortable = true,
                    Width    = "80px"
                },
                new GridColumn()
                {
                    Label    = "Customized",
                    Name     = "customized",
                    Sortable = true,
                    Width    = "80px"
                }
            };

            #endregion

            #region << Records >>

            switch (SortBy)
            {
            default:
            case "label":
                if (SortOrder == QuerySortType.Descending)
                {
                    pages = pages.OrderByDescending(x => x.Label).ToList();
                }
                else
                {
                    pages = pages.OrderBy(x => x.Label).ToList();
                }
                break;

            case "name":
                if (SortOrder == QuerySortType.Descending)
                {
                    pages = pages.OrderByDescending(x => x.Name).ToList();
                }
                else
                {
                    pages = pages.OrderBy(x => x.Name).ToList();
                }
                break;

            case "type":
                if (SortOrder == QuerySortType.Descending)
                {
                    pages = pages.OrderByDescending(x => x.Type).ToList();
                }
                else
                {
                    pages = pages.OrderBy(x => x.Type).ToList();
                }
                break;

            case "system":
                if (SortOrder == QuerySortType.Descending)
                {
                    pages = pages.OrderByDescending(x => x.System).ToList();
                }
                else
                {
                    pages = pages.OrderBy(x => x.System).ToList();
                }
                break;

            case "customized":
                if (SortOrder == QuerySortType.Descending)
                {
                    pages = pages.OrderByDescending(x => x.IsRazorBody).ToList();
                }
                else
                {
                    pages = pages.OrderBy(x => x.IsRazorBody).ToList();
                }
                break;
            }

            //Apply pager
            var skipPages = (Pager - 1) * PagerSize;
            pages = pages.Skip(skipPages).Take(PagerSize).ToList();

            foreach (var page in pages)
            {
                //The entity of the page could be deleted. In this case show its id as name
                var pageEntityName = "";
                if (page.EntityId != null)
                {
                    pageEntityName = page.EntityId.Value.ToString();
                }

                var pageEntity = entities.FirstOrDefault(x => x.Id == page.EntityId);
                if (pageEntity != null)
                {
                    pageEntityName = pageEntity.Name;
                }

                var record = new EntityRecord();
                record["id"]    = page.Id;
                record["label"] = page.Label;
                record["name"]  = page.Name;
                record["app"]   = page.AppId != null?apps.First(x => x.Id == page.AppId).Name : "";

                record["entity"]     = pageEntityName;
                record["type"]       = $"{page.Type.GetLabel()}";
                record["system"]     = page.System;
                record["customized"] = page.IsRazorBody;
                Records.Add(record);
            }
            #endregion

            BeforeRender();
            return(Page());
        }
Exemplo n.º 59
0
        public PcFieldBaseOptions InitPcFieldBaseOptions(PageComponentContext context)
        {
            var options = new PcFieldBaseOptions();

            //Check if it is defined in form group
            if (context.Items.ContainsKey(typeof(LabelRenderMode)))
            {
                options.LabelMode = (LabelRenderMode)context.Items[typeof(LabelRenderMode)];
            }
            else
            {
                options.LabelMode = LabelRenderMode.Stacked;
            }


            //Check if it is defined in form group
            if (context.Items.ContainsKey(typeof(FieldRenderMode)))
            {
                options.Mode = (FieldRenderMode)context.Items[typeof(FieldRenderMode)];
            }
            else
            {
                options.Mode = FieldRenderMode.Form;
            }

            var baseOptions = JsonConvert.DeserializeObject <PcFieldBaseOptions>(context.Options.ToString());

            Entity mappedEntity = null;
            var    entity       = context.DataModel.GetProperty("Entity");

            if (options.ConnectedEntityId != null)
            {
                mappedEntity = new EntityManager().ReadEntity(options.ConnectedEntityId.Value).Object;
            }
            else if (options.ConnectedEntityId == null && entity is Entity)
            {
                mappedEntity = (Entity)entity;
            }

            if (mappedEntity != null)
            {
                var fieldName = baseOptions.Name;

                if (fieldName.StartsWith("$"))
                {
                    //Field with relation is set. Mapped entity should be changed
                    var fieldNameArray = fieldName.Replace("$", "").Split(".", StringSplitOptions.RemoveEmptyEntries);
                    if (fieldNameArray.Length == 2)
                    {
                        var relationName = fieldNameArray[0];
                        fieldName = fieldNameArray[1];
                        var relation = new EntityRelationManager().Read(relationName).Object;
                        if (relation != null)
                        {
                            if (relation.OriginEntityId == mappedEntity.Id)
                            {
                                mappedEntity = new EntityManager().ReadEntity(relation.TargetEntityId).Object;
                            }
                            else if (relation.TargetEntityId == mappedEntity.Id)
                            {
                                mappedEntity = new EntityManager().ReadEntity(relation.OriginEntityId).Object;
                            }
                        }
                    }
                }

                var entityField = mappedEntity.Fields.FirstOrDefault(x => x.Name == fieldName);
                if (entityField != null)
                {
                    switch (entityField.GetFieldType())
                    {
                    case FieldType.AutoNumberField:
                    {
                        var fieldMeta = (AutoNumberField)entityField;
                        options.Template = fieldMeta.DisplayFormat;
                    }
                    break;

                    case FieldType.CurrencyField:
                    {
                        var fieldMeta = (CurrencyField)entityField;
                        options.Min          = fieldMeta.MinValue;
                        options.Min          = fieldMeta.MinValue;
                        options.CurrencyCode = fieldMeta.Currency.Code;
                    }
                    break;

                    case FieldType.EmailField:
                    {
                        var fieldMeta = (EmailField)entityField;
                        options.MaxLength = fieldMeta.MaxLength;
                    }
                    break;

                    case FieldType.NumberField:
                    {
                        var fieldMeta = (NumberField)entityField;
                        options.Min = fieldMeta.MinValue;
                        options.Min = fieldMeta.MinValue;
                        if (fieldMeta.DecimalPlaces != null)
                        {
                            if (int.TryParse(fieldMeta.DecimalPlaces.ToString(), out int outInt))
                            {
                                options.DecimalDigits = outInt;
                            }
                        }
                    }
                    break;

                    case FieldType.PasswordField:
                    {
                        var fieldMeta = (PasswordField)entityField;
                        options.Min = (decimal?)fieldMeta.MinLength;
                        options.Max = (decimal?)fieldMeta.MaxLength;
                    }
                    break;

                    case FieldType.PercentField:
                    {
                        var fieldMeta = (PercentField)entityField;
                        options.Min = fieldMeta.MinValue;
                        options.Min = fieldMeta.MinValue;
                        if (fieldMeta.DecimalPlaces != null)
                        {
                            if (int.TryParse(fieldMeta.DecimalPlaces.ToString(), out int outInt))
                            {
                                options.DecimalDigits = outInt;
                            }
                        }
                    }
                    break;

                    case FieldType.PhoneField:
                    {
                        var fieldMeta = (PhoneField)entityField;
                        options.MaxLength = fieldMeta.MaxLength;
                    }
                    break;

                    case FieldType.TextField:
                    {
                        var fieldMeta = (TextField)entityField;
                        options.MaxLength = fieldMeta.MaxLength;
                    }
                    break;

                    default:
                        break;
                    }
                }
            }

            return(options);
        }
Exemplo n.º 60
0
    protected override void OnUpdate()
    {
        Entities.WithNone <SendRpcCommandRequestComponent>().ForEach((Entity reqEnt, ref GoInGameRequest req, ref ReceiveRpcCommandRequestComponent reqSrc) =>
        {
            PostUpdateCommands.AddComponent <NetworkStreamInGame>(reqSrc.SourceConnection);
            UnityEngine.Debug.Log(String.Format("El server establecio la conexion {0} ", EntityManager.GetComponentData <NetworkIdComponent>(reqSrc.SourceConnection).Value));
#if true
            var ghostCollection = GetSingleton <GhostPrefabCollectionComponent>();
            var ghostId         = ProyectoNetcodeGhostSerializerCollection.FindGhostType <SphereSnapshotData>();
            var prefab          = EntityManager.GetBuffer <GhostPrefabBuffer>(ghostCollection.serverPrefabs)[ghostId].Value;
            var player          = EntityManager.Instantiate(prefab);

            EntityManager.SetComponentData(player, new PlayerData
            {
                playerId      = EntityManager.GetComponentData <NetworkIdComponent>(reqSrc.SourceConnection).Value,
                maxHealth     = 100,
                currentHealth = 100,
                death         = false,
                auto          = false,
                autoSpawn     = true,
                dest          = new float3(0f, 1f, 30f),
                dest2         = new float3(0f, 1f, -30f),
                killedBy      = Entity.Null,
                hudEntity     = Entity.Null
            });


            //Posiciones aleatorias
            float x = 0;
            float y = 1;
            float z = 0;
            EntityManager.SetComponentData(player, new Unity.Transforms.Translation {
                Value = new float3(x, y, z)
            });

            PostUpdateCommands.AddBuffer <PlayerInput>(player);
            PostUpdateCommands.SetComponent(reqSrc.SourceConnection, new CommandTargetComponent {
                targetEntity = player
            });
#endif


            PostUpdateCommands.DestroyEntity(reqEnt);
        });
    }