Exemplo n.º 1
0
        private void EventsOnBodiesBeginCollide(RigidBody body1, RigidBody body2)
        {
            if (body1.Tag != null && body2.Tag != null)
            {
                var node1 = _hierarchy.Lookup(body1.Tag);
                var node2 = _hierarchy.Lookup(body2.Tag);

                if (node1 == null)
                {
                    _consoleHandle.LogWarning("Unable to find hierarchy node for physics rigid body: " + body1.Tag);
                }

                if (node2 == null)
                {
                    _consoleHandle.LogWarning("Unable to find hierarchy node for physics rigid body: " + body2.Tag);
                }

                if (node1 != null && node2 != null)
                {
                    // TODO: This is pretty silly.  It should just be the nodes, not their parents.
                    var parent1 = node1.Parent ?? node1;
                    var parent2 = node2.Parent ?? node2;

                    var owner1 = parent1.UntypedValue;
                    var owner2 = parent2.UntypedValue;

                    var @event = new PhysicsCollisionBeginEvent(_gameContext, _serverContext, _updateContext, body1,
                                                                body2, owner1, owner2);

                    _physicsEventEngine.Fire(_physicsEventContext, @event);
                }
            }
        }
Exemplo n.º 2
0
        public IEnumerable <IEntity> Read(Stream stream, object context, Func <IPlan, object, bool> filter)
        {
            var node = _hierarchy.Lookup(context);

            var document = new XmlDocument();

            document.Load(stream);

            if (document.DocumentElement == null)
            {
                throw new InvalidOperationException("The level data doesn't contain a document element.");
            }

            // Find the <gameObjectFolder> node under the root element.  This is
            // the top of our hierarchy.
            var gameObjectFolder =
                document.DocumentElement.ChildNodes.OfType <XmlElement>()
                .FirstOrDefault(x => x.LocalName == "gameObjectFolder");

            if (gameObjectFolder == null)
            {
                throw new InvalidOperationException("No top level game folder found in ATF level.");
            }

            // Construct the plans for the level.
            var plansList = new List <IPlan>();

            foreach (var element in gameObjectFolder.ChildNodes.OfType <XmlElement>())
            {
                ProcessElementToPlan(node, null, element, plansList, 0, filter);
            }

            // Validate the level configuration.
            var plans = plansList.ToArray();
            IEnumerable <IEntity> entities = null;
            bool isOkay = false;

            try
            {
                _kernel.ValidateAll(plans);

                // Resolve all the plans.
                entities = _kernel.ResolveAll(plans).OfType <IEntity>();
                isOkay   = true;
                return(entities);
            }
            finally
            {
                if (!isOkay)
                {
                    _kernel.DiscardAll(plans);

                    foreach (var plan in plans)
                    {
                        // Also detach the child nodes that were appended to the root object.
                        _hierarchy.RemoveChildNode(node, (INode)plan);
                    }
                }
            }
        }
Exemplo n.º 3
0
        public void AttachBatchedPhysics(CompoundShape shape)
        {
            var component = _batchedControlFactory.CreatePhysicalBatchedStaticCompoundComponent(shape);

            _hierarchy.MoveNode(_node, _hierarchy.Lookup(component));

            component.Static                  = true;
            component.StaticAndImmovable      = true;
            component.Target                  = PhysicsTarget.Component;
            component.Transform.LocalPosition = -shape.Shift.ToXNAVector();
        }
        public PROJECT_SAFE_NAMEWorld(
            INode worldNode,
            IHierarchy hierarchy,
            I2DRenderUtilities twoDRenderUtilities,
            IAssetManagerProvider assetManagerProvider,
            IEntityFactory entityFactory)
        {
            this.Entities = new List<IEntity>();

            _renderUtilities = twoDRenderUtilities;
            _assetManager = assetManagerProvider.GetAssetManager();
            _defaultFont = this._assetManager.Get<FontAsset>("font.Default");

            // You can also save the entity factory in a field and use it, e.g. in the Update
            // loop or anywhere else in your game.
            var entityA = entityFactory.CreateExampleEntity("EntityA");
            entityA.Transform.LocalPosition = new Vector3(100, 50, 0);
            var entityB = entityFactory.CreateExampleEntity("EntityB");
            entityB.Transform.LocalPosition = new Vector3(120, 100, 0);

            // Don't forget to add your entities to the world!
            hierarchy.MoveNode(worldNode, hierarchy.Lookup(entityA));
            hierarchy.MoveNode(worldNode, hierarchy.Lookup(entityB));
        }
Exemplo n.º 5
0
        private BatchedControlEntity BatchPhysics(IGameContext gameContext, INode node, BatchedControlEntity entity)
        {
            var physicsComponentsToProcess = new List <Tuple <INode, PhysicalBaseRigidBodyComponent> >();

            FindPhysicsComponentsUnderNode(node, physicsComponentsToProcess);

            var transformedShapes = new List <CompoundShape.TransformedShape>();

            foreach (var pair in physicsComponentsToProcess)
            {
                foreach (var body in pair.Item2.RigidBodies)
                {
                    transformedShapes.Add(new CompoundShape.TransformedShape(
                                              body.Shape,
                                              JMatrix.CreateFromQuaternion(pair.Item2.FinalTransform.AbsoluteRotation.ToJitterQuaternion()),
                                              pair.Item2.FinalTransform.AbsolutePosition.ToJitterVector()));
                }
            }

            if (transformedShapes.Count == 0)
            {
                return(entity);
            }

            var compoundShape = new CompoundShape(transformedShapes);

            if (entity == null)
            {
                entity = CreateBatchedControlEntity();
            }

            foreach (var pair in physicsComponentsToProcess)
            {
                pair.Item2.SetBatchedEntity(entity);
            }

            entity.AttachBatchedPhysics(compoundShape);

            _hierarchy.MoveNode(node, _hierarchy.Lookup(entity));

            _consoleHandle.LogInfo("Batching physics objected combined " + transformedShapes.Count + " shapes.");

            return(entity);
        }
Exemplo n.º 6
0
        protected void RegisterComponent(object component)
        {
            if (_node == null || _hierarchy == null)
            {
                // No hierarchy, always use private list.
                _nonHierarchyComponents.Add(component);

                UpdateCache();
                UpdateEnabledInterfacesCache();
            }
            else
            {
                // Check if the component is underneath this hierarchy, if node, add it.
                if (_node.Children.All(x => x.UntypedValue != component))
                {
                    // It is not underneath the hierarchy; add it.
                    var childNode = _hierarchy.Lookup(component) ?? _hierarchy.CreateNodeForObject(component);

                    _hierarchy.AddChildNode(_node, childNode);
                }
            }
        }
Exemplo n.º 7
0
        private void LoadUserInterface(IGameContext gameContext)
        {
            var document = new XmlDocument();

            document.LoadXml(_userInterfaceAsset.UserInterfaceData);

            var childNodes = document.DocumentElement?.ChildNodes;

            if (childNodes == null)
            {
                return;
            }

            foreach (var element in childNodes.OfType <XmlElement>())
            {
                if (element.Name == "canvas")
                {
                    if (_canvasEntity == null)
                    {
                        var root = ProcessElement(element);
                        if (root is Canvas)
                        {
                            _canvasEntity                 = _kernel.Get <CanvasEntity>(_hierarchy.Lookup(gameContext.World));
                            _canvasEntity.Canvas          = (Canvas)root;
                            _canvasEntity.CanvasesEnabled = Enabled;
                        }
                    }
                    else
                    {
                        throw new InvalidOperationException("User interface file declares more than one canvas.");
                    }
                }
                else if (element.Name == "fragment")
                {
                    _availableFragments[element.GetAttribute("name")] = element;
                }
            }
        }
Exemplo n.º 8
0
 public static IEnumerable <IEntity> GetEntitiesForWorld(this IWorld world, IHierarchy hierarchy)
 {
     return(hierarchy.Lookup(world).Children.Select(x => x.UntypedValue).OfType <IEntity>());
 }
Exemplo n.º 9
0
        /// <summary>
        /// Creates the entities from the stream.
        /// </summary>
        /// <param name="stream">The stream which contains an Ogmo Editor level.</param>
        /// <param name="context">
        /// The context in which entities are being spawned in the hierarchy.  This is
        /// usually the current world, but it doesn't have to be (e.g. if you wanted to
        /// load a level under an entity group, you would pass the entity group here).
        /// </param>
        /// <returns>A list of entities to spawn within the world.</returns>
        public IEnumerable <IEntity> Read(Stream stream, object context)
        {
            var node = _hierarchy.Lookup(context);

            // FIXME: Store the entities in a tileset so that we
            // can have pre-rendered tilesets.
            // var tilesetEntity = new DefaultTileset();

            // Load the document.
            var doc = XDocument.Load(stream);

            // Load the solids.
            var solidsRoot = doc.Root.Element(XName.Get("Solids"));
            var solids     = solidsRoot == null
                             ? new XElement[0]
                             : solidsRoot.Elements().Where(x => x.Name.LocalName == "rect");

            // Load the tiles.
            var tilesets = from e in doc.Root.Elements()
                           where e.Name.LocalName == "Tiles"
                           select
                           new
            {
                Tileset = e.Attribute(XName.Get("tileset")).Value,
                Tiles   = from x in e.Elements()
                          where x.Name.LocalName == "tile"
                          select
                          new
                {
                    X  = Convert.ToSingle(x.Attribute(XName.Get("x")).Value),
                    Y  = Convert.ToSingle(x.Attribute(XName.Get("y")).Value),
                    TX = Convert.ToInt32(x.Attribute(XName.Get("tx")).Value),
                    TY = Convert.ToInt32(x.Attribute(XName.Get("ty")).Value)
                }
            };

            // Load the entities.
            var entitydefs = from w in doc.Root.Elements()
                             where w.Name.LocalName == "Entities"
                             from e in w.Descendants()
                             select
                             new
            {
                Type       = e.Name.LocalName,
                ID         = Convert.ToInt32(e.Attribute(XName.Get("id")).Value),
                X          = Convert.ToInt32(e.Attribute(XName.Get("x")).Value),
                Y          = Convert.ToInt32(e.Attribute(XName.Get("y")).Value),
                Attributes =
                    e.Attributes().ToDictionary(key => key.Name.LocalName, value => value.Value)
            };

            // Query the kernel to get the classes that
            // implement the required tiles and entities.
            foreach (var solid in solids)
            {
                // TODO: Use Protoinject.Extensions.Factory for the solid entity.
                var entity =
                    this._kernel.Get <ISolidEntity>(
                        node,
                        new NamedConstructorArgument("x", Convert.ToSingle(solid.Attribute(XName.Get("x")).Value)),
                        new NamedConstructorArgument("y", Convert.ToSingle(solid.Attribute(XName.Get("y")).Value)),
                        new NamedConstructorArgument("width", Convert.ToSingle(solid.Attribute(XName.Get("w")).Value)),
                        new NamedConstructorArgument("height", Convert.ToSingle(solid.Attribute(XName.Get("h")).Value)));
                yield return(entity);
            }

            foreach (var tileset in tilesets)
            {
                foreach (var tile in tileset.Tiles)
                {
                    var entity = this._kernel.Get <ITileEntity>(
                        node,
                        tileset.Tileset,
                        new NamedConstructorArgument("x", tile.X),
                        new NamedConstructorArgument("y", tile.Y),
                        new NamedConstructorArgument("tx", tile.TX),
                        new NamedConstructorArgument("ty", tile.TY));
                    yield return(entity);
                }
            }

            foreach (var entitydef in entitydefs)
            {
                var entity = this._kernel.Get <IEntity>(
                    node,
                    entitydef.Type,
                    new NamedConstructorArgument("name", entitydef.Type),
                    new NamedConstructorArgument("id", entitydef.ID),
                    new NamedConstructorArgument("x", entitydef.X),
                    new NamedConstructorArgument("y", entitydef.Y),
                    new NamedConstructorArgument("attributes", entitydef.Attributes));
                yield return(entity);
            }
        }
Exemplo n.º 10
0
        public void EndRenderPass(
            IGameContext gameContext,
            IRenderContext renderContext,
            IRenderPass nextPass)
        {
            _renderBatcher.FlushRequests(gameContext, renderContext);

            renderContext.PopRenderTarget();

            renderContext.GraphicsDevice.DepthStencilState = _previousDepthStencilState;
            renderContext.GraphicsDevice.RasterizerState   = _previousRasterizerState;
            renderContext.GraphicsDevice.BlendState        = _previousBlendState;

            renderContext.PushRenderTarget(_diffuseLightRenderTarget);
            renderContext.GraphicsDevice.Clear(Color.Transparent);
            renderContext.PopRenderTarget();

            renderContext.PushRenderTarget(_specularLightRenderTarget);
            renderContext.GraphicsDevice.Clear(Color.Transparent);
            renderContext.PopRenderTarget();

            var lightContext = new DefaultLightContext(
                _colorRenderTarget,
                _normalRenderTarget,
                _depthRenderTarget,
                _specularRenderTarget,
                _diffuseLightRenderTarget,
                _specularLightRenderTarget,
                _lightBlendState,
                _rasterizerStateCullNone,
                _rasterizerStateCullClockwiseFace,
                _rasterizerStateCullCounterClockwiseFace,
                new Vector2(
                    0.5f / renderContext.GraphicsDevice.PresentationParameters.BackBufferWidth,
                    0.5f / renderContext.GraphicsDevice.PresentationParameters.BackBufferHeight));

            var lights = new List <ILight>();

            if (gameContext.World != null)
            {
                foreach (var l in _hierarchy.Lookup(gameContext.World).Children.Select(x => x.UntypedValue).OfType <IHasLights>())
                {
                    lights.AddRange(l.GetLights());
                }
            }

            renderContext.GraphicsDevice.BlendState        = _lightBlendState;
            renderContext.GraphicsDevice.DepthStencilState = _lightDepthStencilState;

            foreach (var light in lights)
            {
                light.Render(gameContext, renderContext, lightContext);
            }

            renderContext.GraphicsDevice.BlendState        = _previousBlendState;
            renderContext.GraphicsDevice.DepthStencilState = _previousDepthStencilState;

            if (DebugGBuffer)
            {
                // Render the G buffer into 4 quadrants on the current render target.
                renderContext.GraphicsDevice.Clear(Color.Purple);
                _graphicsBlit.Blit(
                    renderContext,
                    _colorRenderTarget,
                    null,
                    null,
                    null,
                    null,
                    new Vector2(0, 0),
                    new Vector2(0.33f, 0.5f));
                _graphicsBlit.Blit(
                    renderContext,
                    _normalRenderTarget,
                    null,
                    null,
                    null,
                    null,
                    new Vector2(0.33f, 0),
                    new Vector2(0.34f, 0.5f));
                _graphicsBlit.Blit(
                    renderContext,
                    _depthRenderTarget,
                    null,
                    null,
                    null,
                    null,
                    new Vector2(0.67f, 0f),
                    new Vector2(0.33f, 0.5f));
                _graphicsBlit.Blit(
                    renderContext,
                    _specularRenderTarget,
                    null,
                    null,
                    null,
                    null,
                    new Vector2(0.0f, 0.5f),
                    new Vector2(0.33f, 0.5f));
                _graphicsBlit.Blit(
                    renderContext,
                    _diffuseLightRenderTarget,
                    null,
                    null,
                    null,
                    null,
                    new Vector2(0.33f, 0.5f),
                    new Vector2(0.34f, 0.5f));
                _graphicsBlit.Blit(
                    renderContext,
                    _specularLightRenderTarget,
                    null,
                    null,
                    null,
                    null,
                    new Vector2(0.67f, 0.5f),
                    new Vector2(0.33f, 0.5f));
            }
            else
            {
                var parameterSet = _gbufferCombineEffect.Effect.CreateParameterSet();
                parameterSet["Color"]?.SetValue(_colorRenderTarget);
                parameterSet["DiffuseLight"]?.SetValue(_diffuseLightRenderTarget);
                parameterSet["SpecularLight"]?.SetValue(_specularLightRenderTarget);
                parameterSet["AmbientLight"]?.SetValue(new Vector3(0.2f, 0.2f, 0.2f));

                _graphicsBlit.Blit(
                    renderContext,
                    null,
                    null,
                    _gbufferCombineEffect.Effect,
                    parameterSet,
                    GBufferBlendState);
            }
        }
        public void Update(IGameContext gameContext, IUpdateContext updateContext)
        {
            var toRemove = new List <WeakReference <IPerPixelCollisionComponent> >();

            _waitForChanges = true;

            foreach (var aWR in _components)
            {
                IPerPixelCollisionComponent a;
                if (!aWR.TryGetTarget(out a))
                {
                    toRemove.Add(aWR);
                    continue;
                }

                if (!(a.Texture?.IsReady ?? false))
                {
                    continue;
                }

                var aParent = _hierarchy.Lookup(a)?.Parent?.UntypedValue as IHasTransform;

                var aRectangle = CalculateBoundingBox(aParent, a);

                foreach (var bWR in _components)
                {
                    IPerPixelCollisionComponent b;
                    if (!bWR.TryGetTarget(out b))
                    {
                        toRemove.Add(bWR);
                        continue;
                    }

                    if (ReferenceEquals(a, b))
                    {
                        continue;
                    }

                    if (!(b.Texture?.IsReady ?? false))
                    {
                        continue;
                    }

                    var bParent = _hierarchy.Lookup(b)?.Parent?.UntypedValue as IHasTransform;

                    var bRectangle = CalculateBoundingBox(bParent, b);

                    if (aRectangle.Intersects(bRectangle))
                    {
                        if (aParent != null && bParent != null)
                        {
                            if (IntersectPixels(aParent, a, bParent, b))
                            {
                                _perPixelCollisionEventEngine.Fire(
                                    new DefaultPerPixelCollisionEventContext(),
                                    new PerPixelCollisionEvent(
                                        gameContext,
                                        null,
                                        updateContext,
                                        aParent,
                                        bParent));
                            }
                        }
                    }
                }
            }

            foreach (var tr in toRemove.Distinct())
            {
                _components.Remove(tr);
            }

            if (_pendingChanges.Count > 0)
            {
                foreach (var v in _pendingChanges)
                {
                    v();
                }
                _pendingChanges.Clear();
            }

            _waitForChanges = false;
        }
Exemplo n.º 12
0
 public static IEnumerable<IEntity> GetEntitiesForWorld(this IWorld world, IHierarchy hierarchy)
 {
     return hierarchy.Lookup(world).Children.Select(x => x.UntypedValue).OfType<IEntity>();
 }
Exemplo n.º 13
0
        public bool Handle(INetworkEventContext context, IEventEngine <INetworkEventContext> eventEngine, Event @event)
        {
            var networkReceiveEvent = @event as NetworkMessageReceivedEvent;

            if (networkReceiveEvent == null)
            {
                return(false);
            }

            var @object = _networkMessageSerialization.Deserialize(networkReceiveEvent.Payload);

            if (networkReceiveEvent.GameContext != null)
            {
                // Messages which are only allowed to be handled by the client.

                var createEntityMessage = @object as EntityCreateMessage;
                if (createEntityMessage != null)
                {
                    if (_networkEngine.FindObjectByNetworkId(createEntityMessage.EntityID) != null)
                    {
                        // This entity was already created on the client, so we ignore it.
                        return(true);
                    }

                    // Spawn an entity in the world...
                    var world         = networkReceiveEvent.GameContext.World;
                    var spawnedEntity = _kernel.Get(
                        Type.GetType(createEntityMessage.EntityType),
                        _hierarchy.Lookup(world)) as IEntity;

                    _networkEngine.RegisterObjectAsNetworkId(
                        createEntityMessage.EntityID,
                        spawnedEntity);

                    if (spawnedEntity != null)
                    {
                        spawnedEntity.Transform.Assign(createEntityMessage.InitialTransform.DeserializeFromNetwork());
                    }

                    var networkIdentifiableEntity = spawnedEntity as INetworkIdentifiable;
                    if (networkIdentifiableEntity != null)
                    {
                        networkIdentifiableEntity.ReceiveNetworkIDFromServer(
                            networkReceiveEvent.GameContext,
                            networkReceiveEvent.UpdateContext,
                            createEntityMessage.EntityID,
                            createEntityMessage.FrameTick);
                    }

                    // Send any pending property messages?
                    var networkEventListener = spawnedEntity as IEventListener <INetworkEventContext>;
                    if (networkEventListener != null)
                    {
                        if (_pendingEntityPropertyMessages.ContainsKey(createEntityMessage.EntityID))
                        {
                            foreach (var propertyMessage in _pendingEntityPropertyMessages[createEntityMessage.EntityID]
                                     .Where(x => x.Item1 > createEntityMessage.MessageOrder).OrderBy(x => x.Item1))
                            {
                                networkEventListener.Handle(context, eventEngine, propertyMessage.Item2);
                            }

                            _pendingEntityPropertyMessages.Remove(createEntityMessage.EntityID);
                        }
                    }

                    return(true);
                }

                var entityPropertiesMessage = @object as EntityPropertiesMessage;
                if (entityPropertiesMessage != null)
                {
                    var targetObject = _networkEngine.FindObjectByNetworkId(entityPropertiesMessage.EntityID);
                    if (targetObject != null)
                    {
                        // The object willingly didn't accept the message.
                    }
                    else
                    {
                        if (!_pendingEntityPropertyMessages.ContainsKey(entityPropertiesMessage.EntityID))
                        {
                            _pendingEntityPropertyMessages[entityPropertiesMessage.EntityID] = new List <Tuple <int, Event> >();
                        }

                        _pendingEntityPropertyMessages[entityPropertiesMessage.EntityID].Add(new Tuple <int, Event>(entityPropertiesMessage.MessageOrder, networkReceiveEvent));
                    }
                }
            }

            return(false);
        }