Example #1
0
        public void transform()
        {
            CCApplication application = CCApplication.sharedApplication();

            if (this.m_bIsTransformGLDirty)
            {
                TransformUtils.CGAffineToGL(this.nodeToParentTransform(), ref this.m_pTransformGL);
                this.m_bIsTransformGLDirty = false;
            }
            this.m_tCCNodeTransform = TransformUtils.CGAffineToMatrix(this.m_pTransformGL);
            if (this.m_fVertexZ > 0f)
            {
                this.m_tCCNodeTransform *= Matrix.CreateRotationZ(this.m_fVertexZ);
            }
            if ((this.m_pCamera != null) && ((this.m_pGrid == null) || !this.m_pGrid.Active))
            {
                if (this.m_tAnchorPointInPixels.x == 0f)
                {
                    float y = this.m_tAnchorPointInPixels.y;
                }
                Matrix?nullable = this.m_pCamera.locate();
                if (nullable.HasValue)
                {
                    this.m_tCCNodeTransform = ((Matrix.CreateTranslation(-this.m_tAnchorPointInPixels.x, -this.m_tAnchorPointInPixels.y, 0f) * nullable.Value) * Matrix.CreateTranslation(this.m_tAnchorPointInPixels.x, this.m_tAnchorPointInPixels.y, 0f)) * this.m_tCCNodeTransform;
                }
            }
            application.basicEffect.World = this.m_tCCNodeTransform * application.basicEffect.World;
        }
Example #2
0
            internal void UpdateRenderEntitiesData(ref MatrixD worldMatrixD, bool useTransparency, float transparency)
            {
                int  model = this.Model;
                bool flag  = this.RenderObjectId != uint.MaxValue;

                if (this.InstanceCount <= 0)
                {
                    if (flag)
                    {
                        this.UnloadRenderObjects();
                    }
                }
                else
                {
                    RenderFlags flags = RenderFlags.Visible | RenderFlags.CastShadows;
                    if (!flag)
                    {
                        string byId = MyModel.GetById(model);
                        this.RenderObjectId = MyRenderProxy.CreateRenderEntity("Instance parts, part: " + model, byId, this.Parent.SectorMatrix, MyMeshDrawTechnique.MESH, flags, CullingOptions.Default, Vector3.One, Vector3.Zero, useTransparency ? transparency : 0f, this.MaxViewDistance, 0, 1f, true);
                    }
                    MyRenderProxy.SetInstanceBuffer(this.RenderObjectId, this.InstanceBuffer, 0, this.InstanceData.Count, this.Parent.SectorBox, null);
                    MyRenderProxy.UpdateRenderEntity(this.RenderObjectId, new Color?(Vector3.One), new Vector3?(Vector3.Zero), new float?(useTransparency ? transparency : 0f), true);
                    MatrixD     sectorMatrix = this.Parent.SectorMatrix;
                    BoundingBox?aabb         = null;
                    Matrix?     localMatrix  = null;
                    MyRenderProxy.UpdateRenderObject(this.RenderObjectId, new MatrixD?(sectorMatrix), aabb, -1, localMatrix);
                }
            }
Example #3
0
        public ScreenEngine(GameEngine game, string fileName)
        {
            this.game     = game;
            this.Content  = new ContentManager(game.Services, GameEngine.ContentRootDirectory);
            this.FileName = fileName;

            this.CurrentEvents = new Dictionary <string, bool>();
            this.tapAreas      = new List <XTapArea>();
            this.obstacles     = new List <XElement>();

            this.spriteBatch = new SpriteBatchWithFloats(this.game.GraphicsDevice);

            if (this.game.Scale != Vector3.One)
            {
                scaleMatrix = Matrix.CreateScale(this.game.Scale);
            }

            this.initializeParameters = new InitializeParameters()
            {
                Game = game, ScreenEngine = this
            };
            this.updateParameters = new UpdateParameters()
            {
                Game = game, ScreenEngine = this
            };
            this.drawParameters = new DrawParameters()
            {
                Game = game, ScreenEngine = this, SpriteBatch = spriteBatch
            };
        }
Example #4
0
        //public static Dictionary<VertexElementUsage, int> vertexChannelSize = new Dictionary<VertexElementUsage, int>()
        //{
        //    { VertexElementUsage.Position, 3 }
        //    { VertexElementUsage., 3 }
        //};

        /// <summary>
        /// transform = null: apply ParentBone.Transform and set it to identity
        /// </summary>
        public static void ApplyTransform(Model model, Matrix?transform = null)
        {
            foreach (ModelMesh mesh in model.Meshes)
            {
                ApplyTransform(mesh, transform);
            }
        }
Example #5
0
        /// <summary>
        /// Begins a new sprite and text batch with the specified render state.
        /// </summary>
        /// <param name="sortMode">The drawing order for sprite and text drawing. <see cref="SpriteSortMode.Deferred"/> by default.</param>
        /// <param name="blendState">State of the blending. Uses <see cref="BlendState.AlphaBlend"/> if null.</param>
        /// <param name="samplerState">State of the sampler. Uses <see cref="SamplerState.LinearClamp"/> if null.</param>
        /// <param name="depthStencilState">State of the depth-stencil buffer. Uses <see cref="DepthStencilState.None"/> if null.</param>
        /// <param name="rasterizerState">State of the rasterization. Uses <see cref="RasterizerState.CullCounterClockwise"/> if null.</param>
        /// <param name="effect">A custom <see cref="Effect"/> to override the default sprite effect. Uses default sprite effect if null.</param>
        /// <param name="transformMatrix">An optional matrix used to transform the sprite geometry. Uses <see cref="Matrix.Identity"/> if null.</param>
        /// <exception cref="InvalidOperationException">Thrown if <see cref="Begin"/> is called next time without previous <see cref="End"/>.</exception>
        /// <remarks>This method uses optional parameters.</remarks>
        /// <remarks>The <see cref="Begin"/> Begin should be called before drawing commands, and you cannot call it again before subsequent <see cref="End"/>.</remarks>
        public void Begin
        (
            SpriteSortMode sortMode             = SpriteSortMode.Deferred,
            BlendState blendState               = null,
            SamplerState samplerState           = null,
            DepthStencilState depthStencilState = null,
            RasterizerState rasterizerState     = null,
            Effect effect          = null,
            Matrix?transformMatrix = null
        )
        {
            if (_beginCalled)
            {
                throw new InvalidOperationException("Begin cannot be called again until End has been successfully called.");
            }

            // defaults
            _sortMode          = sortMode;
            _blendState        = blendState ?? BlendState.AlphaBlend;
            _samplerState      = samplerState ?? SamplerState.LinearClamp;
            _depthStencilState = depthStencilState ?? DepthStencilState.None;
            _rasterizerState   = rasterizerState ?? RasterizerState.CullCounterClockwise;
            _effect            = effect;
            _matrix            = transformMatrix ?? Matrix.Identity;

            // Setup things now so a user can change them.
            if (sortMode == SpriteSortMode.Immediate)
            {
                Setup();
            }

            _beginCalled = true;
        }
Example #6
0
        public IEnumerable <SceneObject> BuildDoodads(IEnumerable <IModelDefinition> definitions, IList <StringReference> references,
                                                      RectangleF bounds, Matrix?rootTransform = null)
        {
            foreach (var definition in definitions)
            {
                if (definition.Id != null && !_builtIds.Add(definition.Id.Value))
                {
                    continue;
                }
                var doodad = Files.GetDoodad(definition.GetModelReference(references));
                if (doodad.Triangles.Length == 0)
                {
                    continue;
                }

                var transform = definition.GetTranform();
                if (rootTransform.HasValue)
                {
                    transform = transform * rootTransform.Value;
                }

                var sceneObject = BuildModelFromTransform(doodad.Vertices, doodad.Triangles, transform, definition.GetModelReference(references));
                if (bounds.Intersects(sceneObject.Bounds))
                {
                    yield return(sceneObject);
                }
            }
        }
Example #7
0
        public void Begin(
            BlendState blendState               = null,
            SamplerState samplerState           = null,
            DepthStencilState depthStencilState = null,
            RasterizerState rasterizerState     = null,
            Effect effect     = null,
            Matrix?viewMatrix = null)
        {
            CheckAfterDraw();

            var projectionMatrix = Matrix
                                   .CreateOrthographicOffCenter(
                new Rectangle(Point.Zero, Runner.Application.ActualSize),
                -1000f, 1000f);

            _graphicsDevice.BlendState        = blendState ?? BlendState.AlphaBlend;
            _graphicsDevice.SamplerStates[0]  = samplerState ?? SamplerState.PointClamp;
            _graphicsDevice.RasterizerState   = rasterizerState ?? RasterizerState.CullNone;
            _graphicsDevice.DepthStencilState = depthStencilState ?? DepthStencilState.None;
            _effect = effect ?? _basicEffect;

            if (_effect is IEffectMatrices)
            {
                var effectMatrices = _effect as IEffectMatrices;
                effectMatrices.Projection = projectionMatrix;
                effectMatrices.View       = viewMatrix ?? Matrix.Identity;
            }

            _hasBegun = true;
        }
Example #8
0
        static public IEnumerable <Vector2> GetEllipseOutlinePoints(Vector2 center, float width, float height, float rotation, float angleStart, float angleSize, int sampling)
        {
            rotation   = MathHelper.WrapAngle(rotation);
            angleStart = MathHelper.WrapAngle(angleStart);

            bool completed = angleSize >= MathHelper.TwoPi;

            Matrix?rotationMatrix = null;

            if (!rotation.EqualsZero())
            {
                rotationMatrix = Matrix.CreateFromAxisAngle(Vector3.Backward, rotation);
            }

            int   stepCount = GetEllipseOutlinePointsCount(angleSize, sampling);
            float stepSize  = angleSize / (!completed ? stepCount - 1 : stepCount);

            for (int i = 0; i < stepCount; i++)
            {
                float step   = angleStart + i * stepSize;
                var   vertex = new Vector2((float)System.Math.Cos(step) * width, (float)System.Math.Sin(step) * height);

                if (rotationMatrix.HasValue)
                {
                    vertex = Vector2.Transform(vertex, rotationMatrix.Value);
                }

                yield return(center + vertex);
            }
        }
Example #9
0
        /// <summary>
        /// Initializes a new instance of the <see cref="TriangleMeshObject"/> class.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <param name="pos">The pos.</param>
        /// <param name="rotation">The rotation.</param>
        /// <param name="scale">The scale.</param>
        /// <param name="materialDescription">The material description.</param>
        public TriangleMeshObject(IModelo model, Vector3 pos, Matrix?rotation = null, Vector3?scale = null, MaterialDescription materialDescription = null)
        {
            if (materialDescription == null)
            {
                materialDescription = MaterialDescription.DefaultBepuMaterial();
            }

            if (!rotation.HasValue)
            {
                rotation = Matrix.Identity;
            }

            if (!scale.HasValue)
            {
                scale = Vector3.One;
            }

            System.Diagnostics.Debug.Assert(model != null);
            System.Diagnostics.Debug.Assert(scale != Vector3.Zero);

            this.rotation = rotation.Value;
            this.scale    = scale.Value;
            this.position = pos;
            Vector3[] vertices = null;
            int[]     indices  = null;
            ExtractData(ref vertices, ref indices, model);
            triangleGroup          = new StaticMesh(vertices, indices, new AffineTransform(scale.Value, Quaternion.CreateFromRotationMatrix(rotation.Value), position));
            faceVector             = Vector3.Transform(Vector3.Forward, triangleGroup.WorldTransform.Matrix);
            triangleGroup.Material = new BEPUphysics.Materials.Material(materialDescription.StaticFriction, materialDescription.DynamicFriction, materialDescription.Bounciness);
        }
Example #10
0
        public static Matrix GetBaseEnemyFleetTrans(
            App app,
            List <ShipInfo> shipIDs,
            int systemID)
        {
            bool   flag   = false;
            Matrix matrix = Matrix.Identity;

            if (shipIDs.Count > 0)
            {
                int    index = Math.Abs(App.GetSafeRandom().Next()) % shipIDs.Count;
                Matrix?shipSystemPosition = app.GameDatabase.GetShipSystemPosition(shipIDs[index].ID);
                if (shipSystemPosition.HasValue)
                {
                    matrix = shipSystemPosition.Value;
                    flag   = true;
                }
            }
            if (!flag)
            {
                int   encounterOrbitalId = app.GameDatabase.GetEncounterOrbitalId(EasterEgg.EE_ASTEROID_MONITOR, systemID);
                float length             = app.GameDatabase.GetOrbitalTransform(encounterOrbitalId).Position.Length;
                matrix          = Matrix.CreateRotationYPR(MathHelper.DegreesToRadians(0.0f), 0.0f, 0.0f);
                matrix.Position = -matrix.Forward * length;
            }
            return(matrix);
        }
Example #11
0
        /// <summary>
        /// Starts the specified batch.
        /// </summary>
        /// <param name="batch">The batch.</param>
        /// <param name="useCamera">if set to <c>true</c> camera matrix will be applied.</param>
        /// <param name="sortMode">The sort mode.</param>
        /// <param name="blendState">State of the blend.</param>
        /// <param name="samplerState">State of the sampler.</param>
        /// <param name="depthStencilState">State of the depth stencil.</param>
        /// <param name="rasterizerState">State of the rasterizer.</param>
        /// <param name="effect">The effect.</param>
        /// <param name="transform">The transformation matrix.</param>
        public static void Start(this SpriteBatch batch,
                                 bool useCamera                      = false,
                                 SpriteSortMode sortMode             = SpriteSortMode.Deferred,
                                 BlendState blendState               = null,
                                 SamplerState samplerState           = null,
                                 DepthStencilState depthStencilState = null,
                                 RasterizerState rasterizerState     = null,
                                 Effect effect    = null,
                                 Matrix?transform = null)
        {
            Matrix matrix = AlmiranteEngine.IsWinForms ? Matrix.Identity : AlmiranteEngine.Settings.Resolution.Matrix;

            if (useCamera)
            {
                matrix = AlmiranteEngine.Camera.Matrix * matrix;
            }

            if (transform.HasValue)
            {
                matrix = transform.Value * matrix;
            }

            BatchExtensions._sortMode          = sortMode;
            BatchExtensions._blendState        = blendState;
            BatchExtensions._samplerState      = samplerState;
            BatchExtensions._depthStencilState = depthStencilState;
            BatchExtensions._rasterizerState   = rasterizerState;
            BatchExtensions._effect            = effect;
            BatchExtensions._matrix            = matrix;

            batch.Begin(sortMode, blendState, samplerState, depthStencilState, rasterizerState, effect, matrix);
        }
        public void CalcMatrix()
        {
            if (IsWeighted)
            {
                _matrix = new Matrix();
                foreach (BoneWeight w in _weights)
                {
                    if (w.Bone != null)
                    {
                        _matrix += (w.Bone.Matrix * w.Bone.InverseBindMatrix) * w.Weight;
                    }
                }

                //The inverse matrix is only used for unweighting vertices so we don't need to set it now
                _invMatrix = null;
            }
            else if (_weights.Count == 1)
            {
                if (Bone != null)
                {
                    _matrix    = Bone.Matrix;
                    _invMatrix = Bone.InverseMatrix;
                }
            }
            else
            {
                _invMatrix = _matrix = Matrix.Identity;
            }
        }
Example #13
0
        public void Begin(ICanvas canvas, Matrix?transformMatrix = default(Matrix?))
        {
            var batch     = canvas.GetCanvasGraphics <SpriteBatch>();
            var transform = transformMatrix ?? Matrix.Identity;

            batch.Begin(SpriteSortMode.Deferred, blendState: BlendState.Opaque, samplerState: SamplerState.LinearWrap, transformMatrix: transform);
        }
Example #14
0
        private TrackableResult UpdateWorldCenterResult(out Matrix?cameraTransform)
        {
            TrackableResult result = null;
            Matrix?         additionalTransform = null;

            cameraTransform = null;

            if (this.WorldCenterMode == WorldCenterMode.FirstTarget)
            {
                result = this.TrackableResults.FirstOrDefault();
            }
            else if (this.WorldCenterMode == WorldCenterMode.SpecificTarget &&
                     this.WorldCenterTrackable != null)
            {
                result = this.WorldCenterTrackable.FindMatchedTrackable(this.platformSpecificARService.TrackableResults);

                var resultTransform = this.WorldCenterTrackable.Owner.FindComponent <Transform3D>(false);
                if (resultTransform != null)
                {
                    additionalTransform = Matrix.CreateFromTRS(resultTransform.Position, resultTransform.Orientation, Vector3.One);
                }
            }

            if (result != null)
            {
                cameraTransform = Matrix.Invert(result.Pose);

                if (additionalTransform.HasValue)
                {
                    cameraTransform *= additionalTransform.Value;
                }
            }

            return(result);
        }
        /// <summary>
        ///  Gets the <see cref="Gdi32.HDC"/> from the the given <paramref name="deviceContext"/>.
        /// </summary>
        /// <remarks>
        ///  When a <see cref="Graphics"/> object is created from a <see cref="Gdi32.HDC"/> the clipping region and
        ///  the viewport origin are applied (<see cref="Gdi32.GetViewportExtEx(Gdi32.HDC, out Size)"/>). The clipping
        ///  region isn't reflected in <see cref="Graphics.Clip"/>, which is combined with the HDC HRegion.
        ///
        ///  The Graphics object saves and restores DC state when performing operations that would modify the DC to
        ///  maintain the DC in its original or returned state after <see cref="Graphics.ReleaseHdc()"/>.
        /// </remarks>
        /// <param name="applyGraphicsState">
        ///  Applies the origin transform and clipping region of the <paramref name="deviceContext"/> if it is an
        ///  object of type <see cref="Graphics"/>. Otherwise this is a no-op.
        /// </param>
        /// <param name="saveHdcState">
        ///  When true, saves and restores the <see cref="Gdi32.HDC"/> state.
        /// </param>
        public DeviceContextHdcScope(
            IDeviceContext deviceContext,
            bool applyGraphicsState = true,
            bool saveHdcState       = false)
        {
            DeviceContext = deviceContext ?? throw new ArgumentNullException(nameof(deviceContext));
            ApplyGraphicsProperties apply = applyGraphicsState ? ApplyGraphicsProperties.All : ApplyGraphicsProperties.None;

            _savedHdcState = 0;

            if (apply == ApplyGraphicsProperties.None || !(DeviceContext is Graphics graphics))
            {
                // GetHdc() locks the Graphics object, it cannot be used until ReleaseHdc() is called
                HDC            = (Gdi32.HDC)DeviceContext.GetHdc();
                _savedHdcState = saveHdcState ? Gdi32.SaveDC(HDC) : 0;
                return;
            }

            bool applyTransform = apply.HasFlag(ApplyGraphicsProperties.TranslateTransform);
            bool applyClipping  = apply.HasFlag(ApplyGraphicsProperties.Clipping);

            // This API is very expensive
            object[]? data = applyTransform || applyClipping ? (object[])graphics.GetContextInfo() : null;

            using Region? clipRegion     = (Region?)data?[0];
            using Matrix? worldTransform = (Matrix?)data?[1];

            // elements (XFORM) = [eM11, eM12, eM21, eM22, eDx, eDy], eDx/eDy specify the translation offset.
            float[]? elements = applyTransform ? worldTransform?.Elements : null;
            int dx = elements != null ? (int)elements[4] : 0;
            int dy = elements != null ? (int)elements[5] : 0;

            applyTransform = applyTransform && elements != null && (dx != 0 || dy != 0);

            using var graphicsRegion = applyClipping ? new Gdi32.RegionScope(clipRegion !, graphics) : default;
Example #16
0
        public static Matrix GetBaseEnemyFleetTrans(
            App app,
            List <ShipInfo> shipIDs,
            OrbitalObjectInfo[] objects)
        {
            bool   flag   = false;
            Matrix matrix = Matrix.Identity;

            if (shipIDs.Count > 0)
            {
                int    index = Math.Abs(App.GetSafeRandom().Next()) % shipIDs.Count;
                Matrix?shipSystemPosition = app.GameDatabase.GetShipSystemPosition(shipIDs[index].ID);
                if (shipSystemPosition.HasValue)
                {
                    matrix = shipSystemPosition.Value;
                    flag   = true;
                }
            }
            if (!flag)
            {
                int orbitalId = 0;
                foreach (OrbitalObjectInfo orbitalObjectInfo in objects)
                {
                    if (app.GameDatabase.GetAsteroidBeltInfo(orbitalObjectInfo.ID) != null)
                    {
                        orbitalId = orbitalObjectInfo.ID;
                    }
                }
                float length = app.GameDatabase.GetOrbitalTransform(orbitalId).Position.Length;
                matrix          = Matrix.CreateRotationYPR(0.0f, 0.0f, 0.0f);
                matrix.Position = -matrix.Forward * length;
            }
            return(matrix);
        }
Example #17
0
        private bool IOS_IsPressed(Matrix2D?scale, Matrix?transform3)
        {
            var touches = TouchPanel.GetState();

            for (int i = 0; i < touches.Count; i++)
            {
                if (OnlyTriggerOnRelease)
                {
                    if (touches[i].State != TouchLocationState.Released)
                    {
                        continue;
                    }
                }

                var coor = new Vector2(touches[i].Position.X, touches[i].Position.Y);
                if (scale.HasValue)
                {
                    coor = Vector2.Transform(coor, Matrix2D.Invert(scale.Value));
                }
                if (transform3.HasValue)
                {
                    coor = Vector2.Transform(coor, Matrix.Invert(transform3.Value));
                }
                if (TouchTriggerRect.Contains(coor))
                {
                    this.Press();
                    return(true);
                }
            }

            return(false);
        }
        public void Draw(TiledMapLayer layer, Matrix?viewMatrix = null, Matrix?projectionMatrix = null, Effect effect = null, float depth = 0.0f)
        {
            var viewMatrix1       = viewMatrix ?? Matrix.Identity;
            var projectionMatrix1 = projectionMatrix ?? Matrix.CreateOrthographicOffCenter(0, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height, 0, 0, -1);

            Draw(layer, ref viewMatrix1, ref projectionMatrix1, effect, depth);
        }
        public void Flatten(Matrix?matrix, float flatness)
        {
            IntPtr m      = (matrix == null) ? IntPtr.Zero : matrix.NativeMatrix;
            int    status = Gdip.GdipFlattenPath(_nativePath, m, flatness);

            Gdip.CheckStatus(status);
        }
Example #20
0
 public TextureConverter(uint[] data, int width, byte?alphaTolerance,
                         float?hullTolerance, bool?holeDetection, bool?multipartDetection,
                         bool?pixelOffsetOptimization, Matrix?transform)
 {
     Initialize(data, width, alphaTolerance, hullTolerance, holeDetection,
                multipartDetection, pixelOffsetOptimization, transform);
 }
Example #21
0
 private void SyncFleetShipModels()
 {
     foreach (FleetInfo fleetInfo in this.App.GameDatabase.GetFleetsByPlayerAndSystem(this.App.LocalPlayer.ID, this._targetSystemID, FleetType.FL_ALL))
     {
         if (fleetInfo.PlayerID == this.App.LocalPlayer.ID)
         {
             IEnumerable <ShipInfo> source = this.App.GameDatabase.GetShipInfoByFleetID(fleetInfo.ID, true).Where <ShipInfo>((Func <ShipInfo, bool>)(x => !((IEnumerable <DesignSectionInfo>)x.DesignInfo.DesignSections).Any <DesignSectionInfo>((Func <DesignSectionInfo, bool>)(y => ShipSectionAsset.IsBattleRiderClass(y.ShipSectionAsset.RealClass)))));
             this._manager.PostSetProp("AddFleet", (object)fleetInfo.ID, (object)source.Count <ShipInfo>());
             foreach (ShipInfo shipInfo in source)
             {
                 List <object> objectList = new List <object>();
                 objectList.Add((object)0);
                 ShipDummy state = new ShipDummy(this.App, CreateShipDummyParams.ObtainShipDummyParams(this.App, shipInfo));
                 this.App.AddExistingObject((IGameObject)state, objectList.ToArray());
                 this._manager.PostObjectAddObjects((IGameObject)state);
                 this._pendingObjects.Add((IGameObject)state);
                 Vector3?shipFleetPosition  = this.App.GameDatabase.GetShipFleetPosition(shipInfo.ID);
                 Matrix? shipSystemPosition = this.App.GameDatabase.GetShipSystemPosition(shipInfo.ID);
                 state.PostSetProp("SetShipID", shipInfo.ID);
                 int commandPointCost = this.App.GameDatabase.GetCommandPointCost(shipInfo.DesignID);
                 state.PostSetProp("SetShipCommandCost", commandPointCost);
                 state.PostSetProp("SetFleetID", fleetInfo.ID);
                 state.PostSetProp("SetShipName", shipInfo.ShipName);
                 if (shipFleetPosition.HasValue)
                 {
                     state.PostSetProp("SetFleetPosition", (object)shipFleetPosition.Value.X, (object)shipFleetPosition.Value.Y, (object)shipFleetPosition.Value.Z);
                 }
                 if (shipSystemPosition.HasValue)
                 {
                     state.PostSetProp("SetSystemTransform", shipSystemPosition.Value);
                 }
             }
         }
     }
 }
Example #22
0
        private void RecreateConstraints()
        {
            MyCubeGridRenderCell orAddCell = base.CubeGrid.RenderData.GetOrAddCell((Vector3)(base.Position * base.CubeGrid.GridSize), true);

            using (List <MyEntitySubpart> .Enumerator enumerator = this.m_subparts.GetEnumerator())
            {
                while (true)
                {
                    if (!enumerator.MoveNext())
                    {
                        break;
                    }
                    MyEntitySubpart current = enumerator.Current;
                    if (!current.Closed && !current.MarkedForClose)
                    {
                        Matrix?childToParent = null;
                        current.Render.SetParent(0, orAddCell.ParentCullObject, childToParent);
                        current.NeedsWorldMatrix = false;
                        current.InvalidateOnMove = false;
                        continue;
                    }
                    return;
                }
            }
            this.DisposeConstraints();
            if ((base.InScene && (base.CubeGrid.Physics != null)) && (base.CubeGrid.Physics.IsInWorld || ((MyPhysicsBody)base.CubeGrid.Physics).IsInWorldWelded()))
            {
                this.CreateConstraints();
            }
            if (base.CubeGrid.Physics != null)
            {
                this.UpdateHavokCollisionSystemID(base.CubeGrid.GetPhysicsBody().HavokCollisionSystemID, false);
            }
            this.UpdateDoorPosition();
        }
Example #23
0
 public void Begin(Matrix?matrix = null)
 {
     this.matrix           = matrix;
     this.lastItem         = ItemType.Unknown;
     this.isInBeginEndPair = true;
     this.PrepareCullingParameters();
 }
Example #24
0
        public override unsafe void DebugDraw(Vector2 pos, Vector2 size, List <MyBehaviorTreeNodeMemory> nodesMemory)
        {
            MyRenderProxy.DebugDrawText2D(pos, this.DebugSign, nodesMemory[base.MemoryIndex].NodeStateColor, MyBehaviorTreeNode.DEBUG_TEXT_SCALE, MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_CENTER, false);
            float *singlePtr1 = (float *)ref size.X;

            singlePtr1[0] *= MyBehaviorTreeNode.DEBUG_SCALE;
            Vector2 position   = (this.m_children.Count > 1) ? (pos - (size * 0.5f)) : pos;
            float * singlePtr2 = (float *)ref position.Y;

            singlePtr2[0] += MyBehaviorTreeNode.DEBUG_TEXT_Y_OFFSET;
            float *singlePtr3 = (float *)ref size.X;

            singlePtr3[0] /= (float)Math.Max(this.m_children.Count - 1, 1);
            foreach (MyBehaviorTreeNode node in this.m_children)
            {
                Vector2 vector2 = position - pos;
                vector2.Normalize();
                Vector2 pointTo    = position - (vector2 * MyBehaviorTreeNode.DEBUG_LINE_OFFSET_MULT);
                Matrix? projection = null;
                MyRenderProxy.DebugDrawLine2D(pos + (vector2 * MyBehaviorTreeNode.DEBUG_LINE_OFFSET_MULT), pointTo, nodesMemory[node.MemoryIndex].NodeStateColor, nodesMemory[node.MemoryIndex].NodeStateColor, projection, false);
                node.DebugDraw(position, size, nodesMemory);
                float *singlePtr4 = (float *)ref position.X;
                singlePtr4[0] += size.X;
            }
        }
Example #25
0
        /// <summary>
        /// Begins a new primitive.
        /// </summary>
#if WINDOWS_PHONE
        /// <param name="lineWidth">This value will always be 1 on Windows Phone.</param>
#endif
        public void BeginPrimitive(PrimitiveType primitiveType, Texture2D texture, Matrix?world, float lineWidth)
        {
            if (hasPrimitiveBegin)
            {
                throw new InvalidOperationException("Begin cannot be called until End has been successfully called.");
            }

            hasPrimitiveBegin = true;

            currentPrimitive               = new PrimitiveGroupEntry();
            currentPrimitive.LineWidth     = lineWidth;
            currentPrimitive.World         = world;
            currentPrimitive.PrimitiveType = primitiveType;
            currentPrimitive.Texture       = texture;
            currentPrimitive.StartVertex   = currentVertex;
            currentPrimitive.StartIndex    = currentIndex;

            currentBaseVertex = currentVertex;
            currentBaseIndex  = currentIndex;

            beginSegment = currentSegment;

#if !WINDOWS_PHONE
            lineIndices.Clear();
            currentLineVertex = 0;
            lastLineVertex    = -1;
#endif
        }
Example #26
0
        internal void DerivePhysicsTransform(Vector3?worldPosition, Matrix?worldRotation, Vector3?worldScale, out Matrix outMatrix)
        {
            Vector3 translation = worldPosition ?? Entity.Transform.WorldPosition(), scale;
            Matrix  rotation;

            if (worldScale.HasValue)
            {
                scale = worldScale.Value;
            }
            else
            {
                Entity.Transform.WorldMatrix.GetScale(out scale);
            }

            if (worldRotation.HasValue)
            {
                rotation = worldRotation.Value;
            }
            else
            {
                Entity.Transform.WorldMatrix.GetRotationMatrix(out rotation);
            }

            var translationMatrix = Matrix.Translation(translation);

            Matrix.Multiply(ref rotation, ref translationMatrix, out outMatrix);
        }
        public RenderContext Derive(RectangleF bounds, Matrix?localLayoutTransform,
                                    Matrix?localRenderTransform, Vector2?renderTransformOrigin,
                                    double localOpacity)
        {
            Matrix finalTransform = _transform.Clone();

            if (localLayoutTransform.HasValue && localLayoutTransform != Matrix.Identity)
            {
                // Layout transforms don't support translations, so center the transformation matrix at the start point
                // of the control and apply the layout transform without translation
                Vector2 origin    = new Vector2(bounds.X + 0.5f * bounds.Width, bounds.Y + 0.5f * bounds.Height);
                Matrix  transform = Matrix.Translation(new Vector3(-origin.X, -origin.Y, 0));
                transform     *= localLayoutTransform.Value.RemoveTranslation();
                transform     *= Matrix.Translation(new Vector3(origin.X, origin.Y, 0));
                finalTransform = transform * finalTransform;
            }
            if (localRenderTransform.HasValue && localRenderTransform != Matrix.Identity)
            {
                Vector2 origin = renderTransformOrigin.HasValue ? new Vector2(
                    bounds.X + bounds.Width * renderTransformOrigin.Value.X,
                    bounds.Y + bounds.Height * renderTransformOrigin.Value.Y) : new Vector2(bounds.X, bounds.Y);
                Matrix transform = Matrix.Translation(new Vector3(-origin.X, -origin.Y, 0));
                transform     *= localRenderTransform.Value;
                transform     *= Matrix.Translation(new Vector3(origin.X, origin.Y, 0));
                finalTransform = transform * finalTransform;
            }
            RenderContext result = new RenderContext(finalTransform, _opacity * localOpacity, bounds, _zOrder - 0.001f);

            return(result);
        }
Example #28
0
            public List <MyRenderElement> TransparentRenderElementsToDraw; // if null, MyEntities.Draw() will be used

            public void Clear()
            {
                CallerID = null;

                RenderTargets    = null;
                CameraPosition   = null;
                ViewMatrix       = null;
                ProjectionMatrix = null;
                AspectRatio      = null;
                Fov      = null;
                Viewport = null;

                EnableHDR                = null;
                EnableLights             = null;
                EnableSun                = null;
                ShadowRenderer           = null;
                EnableShadowInterleaving = null;
                EnableSmallLights        = null;
                EnableSmallLightShadows  = null;
                EnableDebugHelpers       = null;
                EnableEnvironmentMapping = null;
                EnableNear               = null;

                BackgroundColor = null;

                EnableOcclusionQueries = true;
                FogMultiplierMult      = 1.0f;
                DepthToAlpha           = false;
                DepthCopy = false;

                EnabledModules       = null;
                EnabledPostprocesses = null;
                EnabledRenderStages  = null;
            }
Example #29
0
        /// <summary>
        /// Create new drawing context.
        /// </summary>
        /// <param name="createInfo">Create info.</param>
        /// <param name="disposables">Array of elements to dispose after drawing has finished.</param>
        public DrawingContextImpl(CreateInfo createInfo, params IDisposable[] disposables)
        {
            _dpi = createInfo.Dpi;
            _visualBrushRenderer    = createInfo.VisualBrushRenderer;
            _disposables            = disposables;
            _canTextUseLcdRendering = !createInfo.DisableTextLcdRendering;
            _grContext = createInfo.GrContext;
            _gpu       = createInfo.Gpu;
            if (_grContext != null)
            {
                Monitor.Enter(_grContext);
            }
            Surface = createInfo.Surface;
            Canvas  = createInfo.Canvas ?? createInfo.Surface?.Canvas;

            _session = createInfo.CurrentSession;

            if (Canvas == null)
            {
                throw new ArgumentException("Invalid create info - no Canvas provided", nameof(createInfo));
            }

            if (!_dpi.NearlyEquals(SkiaPlatform.DefaultDpi))
            {
                _postTransform =
                    Matrix.CreateScale(_dpi.X / SkiaPlatform.DefaultDpi.X, _dpi.Y / SkiaPlatform.DefaultDpi.Y);
            }

            Transform = Matrix.Identity;
        }
Example #30
0
        public static void LoadFromUserFolder(out string nextFreeName, out Matrix?lastShipPos)
        {
            if (m_attachedPhysObjects == null) // When triler was not loaded
            {
                m_attachedPhysObjects = new Dictionary <MyEntity, Dictionary <int, MyPhysObjectTrackedTickData> >();
            }

            foreach (var obj in m_attachedPhysObjects)
            {
                var entity = obj.Key;
                if (MyEntities.GetEntities().Contains(entity))
                {
                    obj.Key.MarkForClose();
                }
            }
            m_attachedPhysObjects.Clear();

            lastShipPos = null;

            var path = Path.Combine(MyFileSystemUtils.GetApplicationUserDataFolder(), "Trailer");

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            int maxFileName = 0;

            var files = Directory.GetFiles(path, "*.tracked");

            for (int i = 0; i < files.Length; i++)
            {
                string fileWithoutExt = Path.GetFileNameWithoutExtension(files[i]);
                int    num;
                if (int.TryParse(fileWithoutExt, out num) && num > maxFileName)
                {
                    maxFileName = num;
                }

                var smallShip = MyGuiScreenGamePlay.Static.CreateFakeMinerShip(null, MinerWars.CommonLIB.AppCode.ObjectBuilders.Object3D.MyMwcObjectBuilder_SmallShip_TypesEnum.GETTYSBURG, new Vector3((i * 100) + 10000, (i * 100) + 10000, (i * 100) + 10000), false, 1.0f);
                AttachPhysObjectFullPath(smallShip, files[i]);
            }

            if (m_attachedPhysObjects.Count > 0)
            {
                var firstTick = m_attachedPhysObjects.Values.Last().First().Value;
                var m         = firstTick.Orientation;
                m.Translation = firstTick.Position;
                lastShipPos   = m;
            }

            m_isEnabled = true;

            m_fromTick   = MillisecondsToTick(0);           // start now
            m_toTick     = MillisecondsToTick(1000 * 1000); // max length 20min
            m_activeTick = m_fromTick;

            nextFreeName = (maxFileName + 1).ToString("D3");
        }
Example #31
0
 public SquareMeshBuilder(float[,] heightMap, Vector3 offset, float tileSize, Matrix? rootTransform = null)
 {
     _tileSize = tileSize;
     _rootTransform = rootTransform;
     _offset = offset;
     _heightMap = heightMap;
     var rows = heightMap.GetLength(0);
     var cols = heightMap.GetLength(1);
     _jumpIndices = ArrayUtil.MakeTwoDimensionalArray(-1, rows, cols);
     _vertices = new List<Vector3>(rows * cols);
 }
Example #32
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ARPanel">Augmented Reality Panel</see> control.
        /// </summary>
        public ARPanel()
        {
            SizeChanged += panel_SizeChanged;
            Loaded += panel_Loaded;
            Unloaded += panel_Unloaded;
            view = Matrix.CreateLookAt(new Vector3(0, 0, 1), Vector3.Zero, Vector3.Up);
            world = Matrix.CreateWorld(Vector3.Zero, new Vector3(0, 0, -1), new Vector3(0, 1, 0));

            if (IsDesignMode)
                _attitude = Matrix.Identity; //This will make control render design time looking horizontal north
        }
Example #33
0
 public void Backup(SpriteSortMode SortMode = SpriteSortMode.Deferred, BlendState BlendState = null,
     SamplerState SamplerState = null, DepthStencilState DepthStencilState = null,
     RasterizerState RasterizerState = null, Effect Effect = null, Matrix? Matrix = null)
 {
     this.SortMode = SortMode;
     this.BlendState = BlendState;
     this.SamplerState = SamplerState;
     this.DepthStencilState = DepthStencilState;
     this.RasterizerState = RasterizerState;
     this.Effect = Effect;
     this.Matrix = Matrix;
 }
Example #34
0
        internal void Construct()
        {
            m_components.Clear();

            m_visible = true;
            m_renderProxyDirty = true;

            m_ID = new MyIDTracker<MyActor>();
            m_localAabb = null;
            m_relativeTransform = null;

            Aabb = BoundingBoxD.CreateInvalid();
        }
        public override void Update(GameTime gameTime)
        {
            if (null == augmentedReality || null == augmentedReality.DetectionResults)
                return;

            var filteredResults = augmentedReality.DetectionResults.Where(r => r.Confidence > confidenceThreshold).ToList();

            if (filteredResults.Count > 0)
                Transform = Utils.ToXnaMatrix(filteredResults.OrderByDescending(r => r.Confidence).First().Transformation);
            else
                Transform = null;

            base.Update(gameTime);
        }
Example #36
0
 internal void Construct()
 {
     CustomViewProjection = null;
     IgnoreDepth = false;
     if(List == null)
     {
         List = new List<MyVertexFormatPositionColor>();
     }
     else
     {
         List.Clear();
     }
     VertexCount = 0;
     StartVertex = 0;
 }
Example #37
0
 public DrawingContext(IDrawingContextImpl impl, Matrix? hiddenPostTransform = null)
 {
     _impl = impl;
     _hiddenPostTransform = hiddenPostTransform;
 }
Example #38
0
        /// <summary>
        /// Updates the transform's cached value.
        /// </summary>
        private void UpdateValue()
        {
            var centerX = (Single)CenterX;
            var centerY = (Single)CenterY;

            var degrees = MathUtil.IsApproximatelyZero(Angle % 360) ? 0f : Angle;
            var radians = Radians.FromDegrees(degrees);

            var hasCenter = (centerX != 0 || centerY != 0);
            if (hasCenter)
            {
                var mtxRotate = Matrix.CreateRotationZ(radians);
                var mtxTransformCenter = Matrix.CreateTranslation(-centerX, -centerY, 0f);
                var mtxTransformCenterInverse = Matrix.CreateTranslation(centerX, centerY, 0f);

                Matrix mtxResult;
                Matrix.Concat(ref mtxTransformCenter, ref mtxRotate, out mtxResult);
                Matrix.Concat(ref mtxResult, ref mtxTransformCenterInverse, out mtxResult);

                this.value = mtxResult;
            }
            else
            {
                this.value = Matrix.CreateRotationZ(radians);
            }

            Matrix invertedValue;
            this.inverse = Matrix.TryInvert(value, out invertedValue) ? invertedValue : (Matrix?)null;
            this.isIdentity = Matrix.Identity.Equals(value);
        }
    public override void Render(RenderContext parentRenderContext)
    {
      if (!IsVisible)
        return;

      RectangleF bounds = ActualBounds;
      if (bounds.Width <= 0 || bounds.Height <= 0)
        return;

      Matrix? layoutTransformMatrix = LayoutTransform == null ? new Matrix?() : LayoutTransform.GetTransform();
      Matrix? renderTransformMatrix = RenderTransform == null ? new Matrix?() : RenderTransform.GetTransform();

      RenderContext localRenderContext = parentRenderContext.Derive(bounds, layoutTransformMatrix,
          renderTransformMatrix, RenderTransformOrigin, Opacity);
       Matrix finalTransform = localRenderContext.Transform;
      if (finalTransform != _finalTransform)
      {
        _finalTransform = finalTransform;
        _inverseFinalTransform = Matrix.Invert(_finalTransform.Value);
        _renderedBoundingBox = CalculateBoundingBox(_innerRect, finalTransform);
      }

      Brushes.Brush opacityMask = OpacityMask;
      if (opacityMask == null && Effect == null)
        // Simply render without opacity mask
        RenderOverride(localRenderContext);
      else
      { 
        // Control has an opacity mask or Effect
        // Get global render surface and render texture or create them if they doesn't exist
        RenderTextureAsset renderTexture = ContentManager.Instance.GetRenderTexture(GLOBAL_RENDER_TEXTURE_ASSET_KEY);

        // Ensure they are allocated
        renderTexture.AllocateRenderTarget(GraphicsDevice.Width, GraphicsDevice.Height);
        if (!renderTexture.IsAllocated)
          return;

        // Morpheus_xx: these are typical performance results comparing direct rendering to texture and rendering 
        // to surfaces (for multisampling support).

        // Results inside GUI-Test OpacityMask screen for default skin (720p windowed / fullscreen 1080p)
        // Surface + full StretchRect -> Texture    : 350 fps / 174 fps 
        // Texture                                  : 485 fps / 265 fps

        // Results inside GUI-Test OpacityMask screen for Reflexion skin (fullscreen 1080p)
        // Surface + full StretchRect -> Texture    : 142 fps
        // Texture                                  : 235 fps

        // Create a temporary render context and render the control to the render texture
        RenderContext tempRenderContext = new RenderContext(localRenderContext.Transform, localRenderContext.Opacity, bounds, localRenderContext.ZOrder);

        // An additional copy step is only required for multisampling surfaces
        bool isMultiSample = GraphicsDevice.Setup.IsMultiSample;
        if (isMultiSample)
        {
          RenderTargetAsset renderSurface = ContentManager.Instance.GetRenderTarget(GLOBAL_RENDER_SURFACE_ASSET_KEY);
          renderSurface.AllocateRenderTarget(GraphicsDevice.Width, GraphicsDevice.Height);
          if (!renderSurface.IsAllocated)
            return;

          // First render to the multisampled surface
          RenderToSurface(renderSurface, tempRenderContext);

          // Unfortunately, brushes/brush effects are based on textures and cannot work with surfaces, so we need this additional copy step
          GraphicsDevice.Device.StretchRectangle(
              renderSurface.Surface,  new Rectangle(Point.Empty, renderSurface.Size),
              renderTexture.Surface0, new Rectangle(Point.Empty, renderTexture.Size),
              TextureFilter.None);
        }
        else
          // Directly render to texture
          RenderToTexture(renderTexture, tempRenderContext);

        // Add bounds to our calculated, occupied area.
        // If we don't do that, lines at the border of this element might be dimmed because of the filter (see OpacityMask test in GUITestPlugin).
        // The value was just found by testing. Any better solution is welcome.
        if (opacityMask != null)
        {
          const float OPACITY_MASK_BOUNDS = 0.9f;
          RectangleF occupiedTransformedBounds = tempRenderContext.OccupiedTransformedBounds;
          occupiedTransformedBounds.X -= OPACITY_MASK_BOUNDS;
          occupiedTransformedBounds.Y -= OPACITY_MASK_BOUNDS;
          occupiedTransformedBounds.Width += OPACITY_MASK_BOUNDS * 2;
          occupiedTransformedBounds.Height += OPACITY_MASK_BOUNDS * 2;

          // If the control bounds have changed we need to update our primitive context to make the 
          // texture coordinates match up
          if (_updateOpacityMask || _opacityMaskContext == null ||
              occupiedTransformedBounds != _lastOccupiedTransformedBounds ||
            renderTexture.Size != _lastOpacityRenderSize)
          {
            UpdateOpacityMask(occupiedTransformedBounds, renderTexture.Width, renderTexture.Height, localRenderContext.ZOrder);
            _lastOccupiedTransformedBounds = occupiedTransformedBounds;
            _updateOpacityMask = false;
            _lastOpacityRenderSize = renderTexture.Size;
          }

          // Now render the opacity texture with the OpacityMask brush)
          if (opacityMask.BeginRenderOpacityBrush(renderTexture.Texture, new RenderContext(Matrix.Identity, bounds)))
          {
            _opacityMaskContext.Render(0);
            opacityMask.EndRender();
          }
        }

        // Render Effect
        Effects.Effect effect = Effect;
        if (effect != null)
        {
          UpdateEffectMask(effect, tempRenderContext.OccupiedTransformedBounds, renderTexture.Width, renderTexture.Height, localRenderContext.ZOrder);
          if (effect.BeginRender(renderTexture.Texture, new RenderContext(Matrix.Identity, 1.0d, bounds, localRenderContext.ZOrder)))
          {
            _effectContext.Render(0);
            effect.EndRender();
          }
        }

      }
      // Calculation of absolute render size (in world coordinate system)
      parentRenderContext.IncludeTransformedContentsBounds(localRenderContext.OccupiedTransformedBounds);
      _lastZIndex = localRenderContext.ZOrder;
    }
        public void CalcMatrix()
        {
            if (IsWeighted)
            {
                _matrix = new Matrix();
                foreach (BoneWeight w in _weights)
                    if (w.Bone != null)
                        _matrix += (w.Bone.Matrix * w.Bone.InverseBindMatrix) * w.Weight;

                //The inverse matrix is only used for unweighting vertices so we don't need to set it now
                _invMatrix = null;
            }
            else if (_weights.Count == 1)
            {
                if (Bone != null)
                {
                    _matrix = Bone.Matrix;
                    _invMatrix = Bone.InverseMatrix;
                }
            }
            else
                _invMatrix = _matrix = Matrix.Identity;
        }
Example #41
0
 private void motion_CurrentValueChanged(object sender, Microsoft.Devices.Sensors.SensorReadingEventArgs<Microsoft.Devices.Sensors.MotionReading> e)
 {
     lock (_attitudeLock)
     {
         //When device changes orientation, the attitude value is invalidated
         _attitude = null;
     }
     //When the device changes orientation, it invalidates the placement of the elements
     Dispatcher.BeginInvoke(() => InvalidateArrange());
 }
Example #42
0
 private void panel_SizeChanged(object sender, SizeChangedEventArgs e)
 {
     _viewport = null; //If the size changes, it invalidates the viewport
     _cameraProjection = null; //camera projection relies on viewport - force reset
     this.Clip = new RectangleGeometry() { Rect = new Rect(0, 0, e.NewSize.Width, e.NewSize.Height) };
     InvalidateArrange();
 }
Example #43
0
        /// <summary>
        /// Updates the transform's cached value.
        /// </summary>
        private void UpdateValue()
        {
            this.value = Matrix.CreateTranslation((Single)X, (Single)Y, 0f);

            Matrix inverse;
            if (Matrix.TryInvert(value, out inverse))
            {
                this.inverse = inverse;
            }
            else
            {
                this.inverse = null;
            }

            this.isIdentity = Matrix.Identity.Equals(value);
        }
 internal void SetCustomViewProjection(ref Matrix m)
 {
     m_customViewProjection = m;
 }
Example #45
0
        public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
        {
            base.Init(objectBuilder, cubeGrid);

            PostBaseInit();

            //MyDebug.AssertDebug(objectBuilder.TypeId == typeof(MyObjectBuilder_Cockpit));
            var def = MyDefinitionManager.Static.GetCubeBlockDefinition(objectBuilder.GetId());
            m_isLargeCockpit = (def.CubeSize == MyCubeSize.Large);
            m_cockpitInteriorModel = BlockDefinition.InteriorModel;
            m_cockpitGlassModel = BlockDefinition.GlassModel;

            NeedsUpdate = MyEntityUpdateEnum.EACH_100TH_FRAME;

            MyObjectBuilder_Cockpit cockpitOb = (MyObjectBuilder_Cockpit)objectBuilder;
            if (cockpitOb.Pilot != null)
            {
                MyEntity pilotEntity;
                MyCharacter pilot = null;
                if (MyEntities.TryGetEntityById(cockpitOb.Pilot.EntityId, out pilotEntity))
                { //Pilot already exists, can be the case after cube grid split
                    pilot = (MyCharacter)pilotEntity;
                    if (pilot.IsUsing is MyShipController && pilot.IsUsing != this)
                    {
                        System.Diagnostics.Debug.Assert(false, "Pilot already sits on another place!");
                        pilot = null;
                    }
                }
                else
                {
                    pilot = (MyCharacter)MyEntities.CreateFromObjectBuilder(cockpitOb.Pilot);
                }

                if (pilot != null)
                {
                    AttachPilot(pilot, storeOriginalPilotWorld: false, calledFromInit: true);
                    if (cockpitOb.PilotRelativeWorld.HasValue)
                        m_pilotRelativeWorld = cockpitOb.PilotRelativeWorld.Value.GetMatrix();
                    else
                        m_pilotRelativeWorld = null;

                    m_singleWeaponMode = cockpitOb.UseSingleWeaponMode;
                }

                IsInFirstPersonView = cockpitOb.IsInFirstPersonView;
            }

            if (cockpitOb.Autopilot != null)
            {
                MyAutopilotBase autopilot = MyAutopilotFactory.CreateAutopilot(cockpitOb.Autopilot);
                autopilot.Init(cockpitOb.Autopilot);
                AttachAutopilot(autopilot, updateSync: false);
            }

            m_pilotGunDefinition = cockpitOb.PilotGunDefinition;

            // backward compatibility check for automatic rifle without subtype
            if (m_pilotGunDefinition.HasValue)
            {
                if (m_pilotGunDefinition.Value.TypeId == typeof(MyObjectBuilder_AutomaticRifle)
                    && string.IsNullOrEmpty(m_pilotGunDefinition.Value.SubtypeName))
                    m_pilotGunDefinition = new MyDefinitionId(typeof(MyObjectBuilder_AutomaticRifle), "RifleGun");
            }

            if (!string.IsNullOrEmpty(m_cockpitInteriorModel))
            {

                if (MyModels.GetModelOnlyDummies(m_cockpitInteriorModel).Dummies.ContainsKey("head"))
                    m_headLocalPosition = MyModels.GetModelOnlyDummies(m_cockpitInteriorModel).Dummies["head"].Matrix.Translation;
            }
            else
            {
                if (MyModels.GetModelOnlyDummies(BlockDefinition.Model).Dummies.ContainsKey("head"))
                    m_headLocalPosition = MyModels.GetModelOnlyDummies(BlockDefinition.Model).Dummies["head"].Matrix.Translation;
            }

            AddDebugRenderComponent(new Components.MyDebugRenderComponentCockpit(this));

            InitializeConveyorEndpoint();

            AddDebugRenderComponent(new Components.MyDebugRenderComponentDrawConveyorEndpoint(m_conveyorEndpoint));

            m_oxygenLevel = cockpitOb.OxygenLevel;
        }
Example #46
0
 public void RemoveOriginalPilotPosition()
 {
     m_pilotRelativeWorld = null;
 }
Example #47
0
 protected override void sync_PilotRelativeEntryUpdated(MyPositionAndOrientation relativeEntry)
 {
     base.sync_PilotRelativeEntryUpdated(relativeEntry);
     m_pilotRelativeWorld = relativeEntry.GetMatrix();
 }
Example #48
0
        public void AttachPilot(MyCharacter pilot, bool storeOriginalPilotWorld = true, bool calledFromInit = false)
        {
            System.Diagnostics.Debug.Assert(pilot != null);
            System.Diagnostics.Debug.Assert(m_pilot == null);

            m_pilot = pilot;
            m_pilot.OnMarkForClose += m_pilotClosedHandler;
            m_pilot.IsUsing = this;

            //m_soundEmitter.OwnedBy = m_pilot;
            if (MyFakes.ENABLE_NEW_SOUNDS)
                StartLoopSound();

            if (storeOriginalPilotWorld)
            {
                m_pilotRelativeWorld = (Matrix)MatrixD.Multiply(pilot.WorldMatrix, this.PositionComp.GetWorldMatrixNormalizedInv());
                if (Sync.IsServer)
                {
                    var relativeEntry = new MyPositionAndOrientation(m_pilotRelativeWorld.Value);
                    SyncObject.SendPilotRelativeEntryUpdate(ref relativeEntry);
                }
            }

            if (pilot.InScene)
                MyEntities.Remove(pilot);

            m_pilot.Physics.Enabled = false;
            m_pilot.PositionComp.SetWorldMatrix(WorldMatrix);
            m_pilot.Physics.Clear();
            //m_pilot.SetPosition(GetPosition() - WorldMatrix.Forward * 0.5f);

            Hierarchy.AddChild(m_pilot, true, true);

            var gunEntity = m_pilot.CurrentWeapon as MyEntity;
            if (gunEntity != null)
            {
                var ob = gunEntity.GetObjectBuilder();
                m_pilotGunDefinition = ob.GetId();
            }
            else
                m_pilotGunDefinition = null;

            MyAnimationDefinition animationDefinition;
            MyDefinitionId id = new MyDefinitionId(typeof(MyObjectBuilder_AnimationDefinition), BlockDefinition.CharacterAnimation);
            if (!MyDefinitionManager.Static.TryGetDefinition(id, out animationDefinition) && !MyFileSystem.FileExists(BlockDefinition.CharacterAnimation))
            {
                BlockDefinition.CharacterAnimation = null;
            }

            PlacePilotInSeat(pilot);
            m_rechargeSocket.PlugIn(m_pilot.SuitBattery);

            // Control should be handled elsewhere if we initialize the grid in the Init(...)
            if (!calledFromInit) GiveControlToPilot();
            m_pilot.SwitchToWeapon(null);
        }
Example #49
0
    /// <summary>
    /// Arranges the UI element and positions it in the given rectangle.
    /// </summary>
    /// <param name="outerRect">The final position and size the parent computed for this child element.</param>
    public void Arrange(RectangleF outerRect)
    {
      if (_isMeasureInvalid)
      {
#if DEBUG_LAYOUT
#if DEBUG_MORE_LAYOUT
        System.Diagnostics.Trace.WriteLine(string.Format("Arrange {0} Name='{1}', exiting because measurement is invalid", GetType().Name, Name));
#endif
#endif
        InvalidateLayout(true, true); // Re-schedule arrangement
        return;
      }
#if DEBUG_LAYOUT
#if DEBUG_MORE_LAYOUT
      System.Diagnostics.Trace.WriteLine(string.Format("Arrange {0} Name='{1}', outerRect={2}", GetType().Name, Name, outerRect));
#endif
#endif
      if (!_isArrangeInvalid && SameRect(_outerRect, outerRect))
      { // Optimization: If our input data is the same and the layout isn't invalid, we don't need to arrange again
#if DEBUG_LAYOUT
#if DEBUG_MORE_LAYOUT
        System.Diagnostics.Trace.WriteLine(string.Format("Arrange {0} Name='{1}', cutting short, outerRect={2} is like before and arrangement is not invalid", GetType().Name, Name, outerRect));
#endif
#endif
        return;
      }
#if DEBUG_LAYOUT
#if !DEBUG_MORE_LAYOUT
      System.Diagnostics.Trace.WriteLine(string.Format("Arrange {0} Name='{1}', outerRect={2}", GetType().Name, Name, outerRect));
#endif
#endif
      _isArrangeInvalid = false;

      // Those two properties have to be set by the render loop again the next time we render. We need to reset the values to null
      // because the BoundingBox property then uses a fallback value. It would be wrong to use the old _boundingBox value if we
      // re-arrange our contents.
      _renderedBoundingBox = null;
      _finalTransform = null;
      _inverseFinalTransform = null;

      _outerRect = SharpDXExtensions.CreateRectangleF(outerRect.Location, outerRect.Size);
      RectangleF rect = SharpDXExtensions.CreateRectangleF(outerRect.Location, outerRect.Size);
      RemoveMargin(ref rect, Margin);

      if (LayoutTransform != null)
      {
        Matrix layoutTransform = LayoutTransform.GetTransform().RemoveTranslation();
        if (!layoutTransform.IsIdentity)
        {
          SizeF resultInnerSize = _innerDesiredSize;
          SizeF resultOuterSize = resultInnerSize;
          layoutTransform.TransformIncludingRectangleSize(ref resultOuterSize);
          if (resultOuterSize.Width > rect.Width + DELTA_DOUBLE || resultOuterSize.Height > rect.Height + DELTA_DOUBLE)
            // Transformation of desired size doesn't fit into the available rect
            resultInnerSize = FindMaxTransformedSize(layoutTransform, rect.Size);
          rect = new RectangleF(
              rect.Location.X + (rect.Width - resultInnerSize.Width) / 2,
              rect.Location.Y + (rect.Height - resultInnerSize.Height) / 2,
              resultInnerSize.Width,
              resultInnerSize.Height);
        }
      }
      _innerRect = rect;

      InitializeTriggers();
      CheckFireLoaded(); // Has to be done after all triggers are initialized to make EventTriggers for UIElement.Loaded work properly

      ArrangeOverride();
      UpdateFocus(); // Has to be done after all children have arranged to make SetFocusPrio work properly
    }
Example #50
0
 public static void ResetClipPlanes(bool applyNow = false)
 {
     Debug.Assert(m_backupMatrix.HasValue, "Nothing to reset, use change clip planes first");
     ProjectionMatrix = m_backupMatrix.Value;
     m_backupMatrix = null;
     if (applyNow)
     {
         UpdateCamera();
     }
     //ChangeClipPlanes(GetSafeNear(), MyCamera.FAR_PLANE_DISTANCE, applyNow);
 }
Example #51
0
    public override void Render(RenderContext parentRenderContext)
    {
      if (!IsVisible)
        return;

      RectangleF bounds = ActualBounds;
      if (bounds.Width <= 0 || bounds.Height <= 0)
        return;

      Matrix? layoutTransformMatrix = LayoutTransform == null ? new Matrix?() : LayoutTransform.GetTransform();
      Matrix? renderTransformMatrix = RenderTransform == null ? new Matrix?() : RenderTransform.GetTransform();

      RenderContext localRenderContext = parentRenderContext.Derive(bounds, layoutTransformMatrix, renderTransformMatrix, RenderTransformOrigin, Opacity);
      Matrix finalTransform = localRenderContext.Transform;
      if (finalTransform != _finalTransform)
      {
        _finalTransform = finalTransform;
        _inverseFinalTransform = Matrix.Invert(_finalTransform.Value);
        _renderedBoundingBox = CalculateBoundingBox(_innerRect, finalTransform);
      }

      Brushes.Brush opacityMask = OpacityMask;
      Effect effect = Effect;
      if (opacityMask == null && effect == null)
        // Simply render without opacity mask
        RenderOverride(localRenderContext);
      else
      {
        // Control has an opacity mask or Effect
        // Get global render surface and render texture or create them if they doesn't exist
        RenderTextureAsset renderTexture = ContentManager.Instance.GetRenderTexture(GLOBAL_RENDER_TEXTURE_ASSET_KEY);

        // Ensure they are allocated
        renderTexture.AllocateRenderTarget(GraphicsDevice.Width, GraphicsDevice.Height);
        if (!renderTexture.IsAllocated)
          return;

        // Morpheus_xx: these are typical performance results comparing direct rendering to texture and rendering 
        // to surfaces (for multisampling support).

        // Results inside GUI-Test OpacityMask screen for default skin (720p windowed / fullscreen 1080p)
        // Surface + full StretchRect -> Texture    : 350 fps / 174 fps 
        // Texture                                  : 485 fps / 265 fps

        // After OpacityMask fix:
        // Surface + full StretchRect -> Texture    : 250 fps / 155 fps 
        // Surface + Occupied Rect -> Texture       : 325 fps / 204 fps 
        // Texture                                  : 330 fps / 213 fps

        // Results inside GUI-Test OpacityMask screen for Reflexion skin (fullscreen 1080p)
        // Surface + full StretchRect -> Texture    : 142 fps
        // Texture                                  : 235 fps

        // Create a temporary render context and render the control to the render texture
        RenderContext tempRenderContext = new RenderContext(localRenderContext.Transform, localRenderContext.Opacity, bounds, localRenderContext.ZOrder);

        // If no effect is applied, clear only the area of the control, not whole render target (performance!)
        tempRenderContext.ClearOccupiedAreaOnly = effect == null;

        // An additional copy step is only required for multisampling surfaces
        bool isMultiSample = GraphicsDevice.Setup.IsMultiSample;
        if (isMultiSample)
        {
          RenderTargetAsset renderSurface = ContentManager.Instance.GetRenderTarget(GLOBAL_RENDER_SURFACE_ASSET_KEY);
          renderSurface.AllocateRenderTarget(GraphicsDevice.Width, GraphicsDevice.Height);
          if (!renderSurface.IsAllocated)
            return;

          // First render to the multisampled surface
          RenderToSurface(renderSurface, tempRenderContext);

          // Unfortunately, brushes/brush effects are based on textures and cannot work with surfaces, so we need this additional copy step
          // Morpheus_xx, 03/2013: changed to copy only the occupied area of Surface, instead of complete area. This improves performance a lot.
          GraphicsDevice.Device.StretchRectangle(
              renderSurface.Surface, ToRect(tempRenderContext.OccupiedTransformedBounds, renderSurface.Size), // new Rectangle(new Point(), renderSurface.Size),
              renderTexture.Surface0, ToRect(tempRenderContext.OccupiedTransformedBounds, renderTexture.Size), // new Rectangle(new Point(), renderTexture.Size),
              TextureFilter.None);
        }
        else
        {
          // Directly render to texture
          RenderToTexture(renderTexture, tempRenderContext);
        }

        // Render Effect
        if (effect == null)
        {
          // Use a default effect to draw the render target if none is set
          if (_defaultEffect == null)
          {
            _defaultEffect = new SimpleShaderEffect { ShaderEffectName = "normal" };
          }

          effect = _defaultEffect;
        }

        UpdateEffectMask(effect, tempRenderContext.OccupiedTransformedBounds, renderTexture.Width, renderTexture.Height, localRenderContext.ZOrder);
        if (effect.BeginRender(renderTexture.Texture, new RenderContext(Matrix.Identity, 1.0d, bounds, localRenderContext.ZOrder)))
        {
          _effectContext.Render(0);
          effect.EndRender();
        }
      }

      // Calculation of absolute render size (in world coordinate system)
      parentRenderContext.IncludeTransformedContentsBounds(localRenderContext.OccupiedTransformedBounds);
      _lastZIndex = localRenderContext.ZOrder;
    }
Example #52
0
 public Matrix GetCachedFinalBrushTransform()
 {
   Matrix? transform = _finalBrushTransform;
   if (transform.HasValue)
     return transform.Value;
   if (Transform != null)
   {
     transform = Matrix.Scaling(new Vector3(_vertsBounds.Width, _vertsBounds.Height, 1));
     transform *= Matrix.Invert(Transform.GetTransform());
     transform *= Matrix.Scaling(new Vector3(1/_vertsBounds.Width, 1/_vertsBounds.Height, 1));
   }
   else
     transform = Matrix.Identity;
   _finalBrushTransform = transform;
   return transform.Value;
 }
Example #53
0
        public virtual void Init(string hudLabelText, MyMwcObjectBuilder_SmallShip_Bot objectBuilder)
        {
            System.Diagnostics.Debug.Assert(objectBuilder.Faction != 0);

            //StringBuilder label = new StringBuilder(hudLabelText);
            TotalAliveBots++;

            string fixedHudLabelText = hudLabelText;
            if (string.IsNullOrEmpty(hudLabelText) || hudLabelText == GetFriendlyName())
            {
                fixedHudLabelText = MyTextsWrapper.GetFormatString(MyTextsWrapperEnum.Ship);
            }

            base.Init(fixedHudLabelText, objectBuilder);

            Faction = objectBuilder.Faction;
            m_aiTemplate = MyBotAITemplates.GetTemplate(objectBuilder.AITemplate);
            Aggressivity = objectBuilder.Aggressivity;
            SeeDistance = objectBuilder.SeeDistance == 0 ? 1000 : objectBuilder.SeeDistance;
            SleepDistance = objectBuilder.SleepDistance == 0 ? 1000 : objectBuilder.SleepDistance;
            PatrolMode = objectBuilder.PatrolMode;
            ActiveAI = true;
            m_leaderId = objectBuilder.Leader;
            AITemplate.SetIdleBehavior(objectBuilder.IdleBehavior);
            LeaderLostEnabled = objectBuilder.LeaderLostEnabled;
            ActiveAI = ActiveAI;

            SetupWeapons(objectBuilder);

            SetupDifficulty();

            //if (hudLabelText == GetFriendlyName())
            //{
            //    label = new StringBuilder("");
            //}

            //if (string.IsNullOrEmpty(hudLabelText) || hudLabelText == GetFriendlyName())
            //{
            //    DisplayName = MyTextsWrapper.GetFormatString(MyTextsWrapperEnum.Ship);
            //}

            //MyHud.ChangeText(this, label, null, 10000, MyHudIndicatorFlagsEnum.SHOW_ALL);


            MyModelDummy dummy;
            if (GetModelLod0().Dummies.TryGetValue("destruction", out dummy))
            {
                m_biochemEffectLocalMatrix = dummy.Matrix;
            }

            m_shock_time = -1;

            MyBotCoordinator.AddBot(this);
            
            InitSpoiledHolograms();

            MyEntities.OnEntityRemove += MyEntities_OnEntityRemove;

            m_dangerZoneId = MyDangerZones.Instance.Register(this);
            
            MySession.Static.LinkEntities += OnLinkEntities;
        }
Example #54
0
 private void UpdateViewMatrix(PageOrientation orientation)
 {
     if (orientation == LandscapeLeft)
     {
         view = Microsoft.Xna.Framework.Matrix.CreateLookAt(
             new Microsoft.Xna.Framework.Vector3(0, 0, 1),
             Microsoft.Xna.Framework.Vector3.Zero,
             Microsoft.Xna.Framework.Vector3.Right);
     }
     else if (orientation == LandscapeRight)
     {
         view = Microsoft.Xna.Framework.Matrix.CreateLookAt(
             new Microsoft.Xna.Framework.Vector3(0, 0, 1),
             Microsoft.Xna.Framework.Vector3.Zero,
             Microsoft.Xna.Framework.Vector3.Left);
     }
     else //if (orientation == PageOrientation.PortraitUp)
     {
         view = Microsoft.Xna.Framework.Matrix.CreateLookAt(
             new Microsoft.Xna.Framework.Vector3(0, 0, 1),
             Microsoft.Xna.Framework.Vector3.Zero,
             Microsoft.Xna.Framework.Vector3.Up);
     }
     //Camera projection relies on the view matrix - invalidate camera projection
     _cameraProjection = null;
     InvalidateArrange();
 }
Example #55
0
 public static void ChangeClipPlanes(float near, float far, bool applyNow = false)
 {
     Debug.Assert(!m_backupMatrix.HasValue, "Reset clip planes before changing clip planes again");
     m_backupMatrix = ProjectionMatrix;
     ProjectionMatrix = Matrix.CreatePerspectiveFieldOfView(FieldOfView, AspectRatio, near, far);
     if (applyNow)
     {
         UpdateCamera();
     }
 }
Example #56
0
 protected void ResetViewMatrix()
 {
     this.viewMatrix = null;
 }
Example #57
0
 protected virtual void OnTransformChanged(IObservable trans)
 {
   _finalBrushTransform = null;
   FireChanged();
 }
Example #58
0
 internal void SetRelativeTransform(Matrix? m)
 {
     m_relativeTransform = m;
 }
Example #59
0
 public override void DeepCopy(IDeepCopyable source, ICopyManager copyManager)
 {
   Detach();
   base.DeepCopy(source, copyManager);
   Brush b = (Brush) source;
   Opacity = b.Opacity;
   RelativeTransform = copyManager.GetCopy(b.RelativeTransform);
   Transform = copyManager.GetCopy(b.Transform);
   Freezable = b.Freezable;
   _finalBrushTransform = null;
   Attach();
 }
Example #60
0
 public void Draw()
 {
   if (!this.FollowCamera)
   {
     this.StarsMesh.Position = this.AdditionalZoom * Vector3.Forward * 125f - 2400f * Vector3.Forward;
     this.StarsMesh.Scale = new Vector3(1f + this.AdditionalScale, 1f + this.AdditionalScale, 1f);
   }
   else if (!this.GameState.InFpsMode)
   {
     FakePointSpritesEffect pointSpritesEffect = this.StarEffect;
     StarField starField1 = this;
     StarField starField2 = this;
     Matrix? nullable1 = new Matrix?();
     Matrix? nullable2 = nullable1;
     starField2.savedViewMatrix = nullable2;
     Matrix? nullable3;
     Matrix? nullable4 = nullable3 = nullable1;
     starField1.savedViewMatrix = nullable3;
     Matrix? nullable5 = nullable4;
     pointSpritesEffect.ForcedViewMatrix = nullable5;
     this.StarsMesh.Position = this.CameraManager.InterpolatedCenter * 0.5f;
     this.StarsMesh.Scale = new Vector3((float) (112.5 / ((double) this.CameraManager.Radius / (double) SettingsManager.GetViewScale(this.GraphicsDevice) + 40.0)));
     if (this.HasHorizontalTrails)
     {
       this.TrailsMesh.Position = this.StarsMesh.Position;
       this.TrailsMesh.Scale = this.StarsMesh.Scale = new Vector3((float) (65.0 / ((double) this.CameraManager.Radius / (double) SettingsManager.GetViewScale(this.GraphicsDevice) + 25.0)));
     }
   }
   else if (this.CameraManager.ProjectionTransition)
   {
     if (this.CameraManager.Viewpoint != Viewpoint.Perspective)
       this.StarEffect.ForcedViewMatrix = new Matrix?(Matrix.Lerp(this.CameraManager.View, this.CameraManager.View, Easing.EaseOut((double) this.CameraManager.ViewTransitionStep, EasingType.Quadratic)));
     else if (!this.savedViewMatrix.HasValue)
       this.savedViewMatrix = new Matrix?(this.CameraManager.View);
   }
   this.StarsMesh.Material.Opacity = this.Opacity;
   this.StarsMesh.Draw();
   if (!this.Enabled || !this.HasHorizontalTrails)
     return;
   this.TrailsMesh.Draw();
 }