private void SetupDrillSensor(VRageMath.Matrix fromReference, int id, VRageMath.BoundingBox bb)
        {
            // grid size in meters per block
            float gridSize = sensors[id].CubeGrid.GridSize;

            // matrix from grid coordinate system to sensor coordinate system
            VRageMath.Matrix toSensor = new VRageMath.Matrix();
            sensors[id].Orientation.GetMatrix(out toSensor);
            // matrix is orthogonal => transposed matrix = inversed matrix
            VRageMath.Matrix.Transpose(ref toSensor, out toSensor);

            VRageMath.Vector3[] corners = bb.GetCorners();
            VRageMath.Vector3   diffMax = corners[1] - sensors[id].Position;
            VRageMath.Vector3   diffMin = corners[7] - sensors[id].Position;

            List <VRageMath.Vector3> .Enumerator enumerator = XUtils.Directions.GetEnumerator();
            while (enumerator.MoveNext())
            {
                VRageMath.Vector3 dir         = enumerator.Current;
                VRageMath.Vector3 gridDir     = VRageMath.Vector3.Transform(dir, fromReference);
                float             lengthToMax = (diffMax * gridDir).Max();
                float             lengthToMin = (diffMin * gridDir).Max();
                float             offset      = Sensors.getOffset(VRageMath.Vector3.Transform(gridDir, toSensor));
                float             value       = _astroidDetectSize + (Math.Max(lengthToMax, lengthToMin) + offset) * gridSize;
                value = Math.Max(Math.Min(value, sensors.Max), sensors.Min);
                sensors.Extend(dir, id, value);
            }
        }
Example #2
0
        public void Update(float updateStepTime)
        {
            VRageRender.MyRenderProxy.GetRenderProfiler().StartProfilingBlock("MyCamera-Update");
            Zoom.Update(updateStepTime);
            VRageRender.MyRenderProxy.GetRenderProfiler().EndProfilingBlock();

            Vector3 newCameraPosOffset = Vector3.Zero;

            // spring
            if (CameraSpring.Enabled)
            {
                CameraSpring.Update(updateStepTime, out newCameraPosOffset);
            }
            // shake
            if (CameraShake.ShakeEnabled)
            {
                Vector3 shakePos, shakeDir;
                CameraShake.UpdateShake(updateStepTime, out shakePos, out shakeDir);
                newCameraPosOffset += shakePos;
            }
            // apply
            if (newCameraPosOffset != Vector3.Zero)
            {
                Vector3D newCameraPosOffsetD = newCameraPosOffset;
                Vector3D newCameraPosOffsetRotatedD;
                Vector3D.Rotate(ref newCameraPosOffsetD, ref ViewMatrix, out newCameraPosOffsetRotatedD);
                ViewMatrix.Translation += newCameraPosOffsetRotatedD;
            }

            UpdatePropertiesInternal(ViewMatrix);
        }
        public void Extend(VRageMath.Vector3 dir, int id, float value)
        {
            if (!XUtils.Directions.Contains(dir))
            {
                throw new Exception("Invalid direction vector used: " + dir);
            }

            if (id < 0 || id >= CountSensors)
            {
                throw new Exception("Parameter id (= " + id + ") out of range [" + 0 + ", " + CountSensors + ").");
            }

            if (value < Min || value > Max)
            {
                throw new Exception("Parameter value (= " + value + ") out of range [" + Min + ", " + Max + "].");
            }

            IMySensorBlock sensor = sensorBlocks[id];

            VRageMath.Matrix toSensor;
            sensor.Orientation.GetMatrix(out toSensor);
            VRageMath.Matrix.Transpose(ref toSensor, out toSensor);
            VRageMath.Matrix toGrid;
            referenceBlock.Orientation.GetMatrix(out toGrid);
            VRageMath.Vector3.Transform(ref dir, ref toGrid, out dir);
            VRageMath.Vector3.Transform(ref dir, ref toSensor, out dir);

            string propteryId = extendDirections[dir];

            sensor.SetValue(propteryId, value);
        }
Example #4
0
 public BindableVector3DModel(VRageMath.Vector3 vector)
     : this()
 {
     X = vector.X;
     Y = vector.Y;
     Z = vector.Z;
 }
        private float GetRotate(VRageMath.Vector3 axis)
        {
            if (!XUtils.Directions.Contains(axis))
            {
                throw new Exception("Invalid axis vector used: " + axis);
            }

            VRageMath.Matrix local = new VRageMath.Matrix();
            referenceBlock.Orientation.GetMatrix(out local);
            axis = VRageMath.Vector3.Transform(axis, local);

            float totalValue = 0;

            for (int i = 0; i < gyroscopeBlocks.Count; ++i)
            {
                IMyGyro gyro = gyroscopeBlocks[i] as IMyGyro;
                gyro.Orientation.GetMatrix(out local);

                VRageMath.Matrix  toGyro          = VRageMath.Matrix.Transpose(local);
                VRageMath.Vector3 transformedAxis = VRageMath.Vector3.Transform(axis, toGyro);

                GyroAction action = GyroAction.getActionAroundAxis(transformedAxis);
                float      value  = gyro.GetValue <float>(action.Name);
                totalValue += action.Reversed ? -value : value;
            }

            return(totalValue);
        }
        public void UpdateThrusters(List <IMyTerminalBlock> blocks)
        {
            thrusterBlocks = new Dictionary <VRageMath.Vector3, List <IMyThrust> >();
            VRageMath.Matrix toReference = new VRageMath.Matrix();
            referenceBlock.Orientation.GetMatrix(out toReference);
            VRageMath.Matrix.Transpose(ref toReference, out toReference);
            VRageMath.Matrix tmp = new VRageMath.Matrix();
            for (int i = 0; i < blocks.Count; ++i)
            {
                IMyTerminalBlock block = blocks[i];
                if (block is IMyThrust)
                {
                    block.Orientation.GetMatrix(out tmp);
                    // The exhaust is directed to the Forward vector of the thruster, so it accelerates to Backward.
                    VRageMath.Vector3 dir = VRageMath.Vector3.Transform(tmp.Backward, toReference);
                    if (!thrusterBlocks.ContainsKey(dir))
                    {
                        thrusterBlocks[dir] = new List <IMyThrust>();
                    }
                    thrusterBlocks[dir].Add(block as IMyThrust);
                }
            }

            if (thrusterBlocks.Count == 0)
            {
                throw new Exception("There is no thruster within the given block list.");
            }
        }
Example #7
0
            /// <summary>
            /// Calculates a transformation matrix to transform grid coordinates to world coordinates.
            /// </summary>
            /// <param name="blocks"></param>
            /// <returns></returns>
            public static VRageMath.Matrix toWorld(List <IMyCubeBlock> blocks)
            {
                if (blocks == null)
                {
                    throw new Exception("The block list is null");
                }

                if (blocks.Count < 3)
                {
                    throw new Exception("Need at least 3 blocks.");
                }

                IMyCubeBlock origin = blocks[0];

                VRageMath.Vector3 localCoord = origin.Position;

                // first basis vector
                VRageMath.Vector3 u = blocks[1].Position - localCoord;

                // second basis vector
                int vIndex = 2;

                VRageMath.Vector3 v = blocks[vIndex].Position - localCoord;
                while (u.Dot(v) * u.Dot(v) == u.LengthSquared() * v.LengthSquared() && vIndex < blocks.Count)
                {
                    v = blocks[++vIndex].Position - localCoord;
                }

                if (u.Dot(v) * u.Dot(v) == u.LengthSquared() + v.LengthSquared())
                {
                    throw new Exception("All blocks are linear dependent => It's not possible to calculate a transformation matrix.");
                }

                debug.Append("choose: ").Append(u).Append(v).AppendLine();

                VRageMath.Matrix localBasis = VRageMath.Matrix.CreateWorld(localCoord, u, v);

                VRageMath.Vector3 worldCoord = origin.GetPosition();
                // world basis depending on the local bases (same coordinates)
                VRageMath.Vector3 ug = blocks[1].GetPosition() - worldCoord;
                VRageMath.Vector3 vg = blocks[vIndex].GetPosition() - worldCoord;

                VRageMath.Matrix worldBasis = VRageMath.Matrix.CreateWorld(worldCoord, ug, vg);

                VRageMath.Matrix inverseLocalBasis;
                // if local basis is orthogonal, take the transposed matrix, because then
                // the transposed and the inverse matrix are the same and it's obviously
                // easier to get the transposed matrix.
                if (VRageMath.Vector3.ArePerpendicular(ref u, ref v))
                {
                    inverseLocalBasis = VRageMath.Matrix.Transpose(localBasis);
                }
                else
                {
                    inverseLocalBasis = VRageMath.Matrix.Invert(localBasis);
                }

                return(inverseLocalBasis * worldBasis);
            }
Example #8
0
        public static double DistanceFrom(this VRageMath.Vector3 start, VRageMath.Vector3 end)
        {
            var x = Math.Pow(end.X - start.X, 2);
            var y = Math.Pow(end.Y - start.Y, 2);
            var z = Math.Pow(end.Z - start.Z, 2);

            return(Math.Abs(Math.Sqrt(x + y + z)));
        }
        /// <summary>
        /// Calculates a transformation matrix to transform grid coordinates to world coordinates.
        /// </summary>
        /// <param name="blocks"></param>
        /// <returns></returns>
        public static VRageMath.Matrix ToWorld(List <IMyCubeBlock> blocks)
        {
            if (blocks == null)
            {
                throw new Exception("The block list is null");
            }

            if (blocks.Count < 3)
            {
                throw new Exception("Need at least 3 blocks.");
            }

            IMyCubeBlock origin = blocks[0];

            VRageMath.Vector3 localCoord = origin.Position;

            // first basis vector
            VRageMath.Vector3 u = blocks[1].Position - localCoord;

            // second basis vector
            int vIndex = 2;

            VRageMath.Vector3 v = blocks[vIndex].Position - localCoord;
            // TODO use an epsilon value instead of 0, because of the precision error of floating point multiplication.
            while (u.Dot(v) == 0 && vIndex < blocks.Count)
            {
                v = blocks[++vIndex].Position - localCoord;
            }

            if (u.Dot(v) == 0)
            {
                throw new Exception("All blocks are linear dependent => It's not possible to calculate a transformation matrix.");
            }

            VRageMath.Matrix localBasis = VRageMath.Matrix.CreateWorld(localCoord, u, v);

            VRageMath.Vector3 worldCoord = origin.GetPosition();
            // world basis depending on the local bases (same coordinates)
            VRageMath.Vector3 ug = blocks[1].GetPosition() - worldCoord;
            VRageMath.Vector3 vg = blocks[vIndex].GetPosition() - worldCoord;

            VRageMath.Matrix worldBasis = VRageMath.Matrix.CreateWorld(worldCoord, ug, vg);

            VRageMath.Matrix inverseLocalBasis;
            // if local basis is orthogonal, take the transposed matrix, because then
            // the transposed and the inverse matrix are the same and it's obviously
            // easier to get the transposed matrix.
            if (VRageMath.Vector3.ArePerpendicular(ref u, ref v))
            {
                inverseLocalBasis = VRageMath.Matrix.Transpose(localBasis);
            }
            else
            {
                inverseLocalBasis = VRageMath.Matrix.Invert(localBasis);
            }

            return(inverseLocalBasis * worldBasis);
        }
 void IMyEntity.SetColorMaskForSubparts(VRageMath.Vector3 colorMaskHsv)
 {
     if (Subparts != null)
     {
         foreach (var subPart in Subparts)
         {
             subPart.Value.Render.ColorMaskHsv = colorMaskHsv;
         }
     }
 }
Example #11
0
        public void Handle(DrillEvent e)
        {
            Action <DrillEvent> action;

            if (_stateBehavior.TryGetValue(_state, out action))
            {
                action(e);
            }

            _lastTime          = DateTime.Now;
            _lastWorldPosition = ReferenceBlock.GetPosition();
        }
Example #12
0
        /*
         * private void thumbnailToolStripMenuItem_Click(object sender, EventArgs e)
         * {
         *  TreeNode node = SectorTree.SelectedNode;
         *  CubeGrid cg = (CubeGrid)node.Tag;
         *  pictureBox1.Image = cg.getThumbnail();
         * }
         *
         * private void loggingCheck_CheckedChanged(object sender, EventArgs e)
         * {
         *  loggingEnabled = loggingCheck.Checked;
         * }
         */



        private void importModuleToolStripMenuItem_Click(object sender, EventArgs e)
        {
            TreeNode     node   = SectorTree.SelectedNode;
            CubeGrid     cg     = (CubeGrid)node.Tag;
            DialogResult result = fileopen.ShowDialog();

            if (result == DialogResult.OK)
            {
                this.update_status("Importing Module");
                string    filename = fileopen.FileName;
                string    xml      = File.ReadAllText(filename);
                CubeGrid  module   = sector.loadCGFragment(xml, false);
                CubeBlock module_attachment_point = module.getBlock("LargeBlockArmorCornerInvWhite");
                if (module_attachment_point != null)
                {
                    //Console.WriteLine("Got module attachment");
                    TreeNode  main_node             = SectorTree.SelectedNode;
                    CubeGrid  main                  = (CubeGrid)main_node.Tag;
                    CubeBlock main_attachment_point = main.getBlock("LargeBlockArmorCornerInvWhite");
                    if (main_attachment_point != null)
                    {
                        Console.WriteLine("Before rotation!!");
                        VRageMath.Vector3 diff = Sector.diff_orientation(main_attachment_point, module_attachment_point);

                        //Console.WriteLine("Got module attachment");

                        //Console.WriteLine("Up :" + main_attachment_point.PositionAndOrientation.up.ToString() + " " + module_attachment_point.PositionAndOrientation.up.ToString());
                        //Console.WriteLine("Forward :" + main_attachment_point.PositionAndOrientation.forward.ToString() + " " + module_attachment_point.PositionAndOrientation.forward.ToString());
                        module.reOrient(module_attachment_point);
                        //Console.WriteLine("module attachment point after reorient: "+module_attachment_point.PositionAndOrientation.position.ToString());
                        main.reOrient(main_attachment_point);
                        //lets try some rotation
                        Console.WriteLine("Steps: " + vrageMath.AngleToSteps(diff.X) + " " + vrageMath.AngleToSteps(diff.Y) + " " + vrageMath.AngleToSteps(diff.Z));
                        module.rotate_grid("X", vrageMath.AngleToSteps(diff.X));
                        module.rotate_grid("Y", vrageMath.AngleToSteps(diff.Y));
                        module.rotate_grid("Z", vrageMath.AngleToSteps(diff.Z));
                        Console.WriteLine("After rotation!!");
                        diff = Sector.diff_orientation(module_attachment_point, main_attachment_point);


                        main.merge(module);
                        SectorTree.Nodes.Clear();
                        SectorTree.Nodes.Add(sector.getTreeNode());
                    }
                }
                else
                {
                    Console.WriteLine("Couldn't get module attachment");
                }
            }
            this.update_status("");
        }
Example #13
0
 public Drill(IMyShipController reference, float drillVelocity = 1.5f, float asteroidDetectSize = 1.5f, float epsilon = 0.1f)
     : base(reference)
 {
     _state             = _uninitializedState;
     _lastWorldPosition = reference.GetPosition();
     _stateBehavior[_uninitializedState] = UpdateUninitialized;
     _stateBehavior[_standbyState]       = UpdateStandby;
     _stateBehavior[_searchState]        = UpdateSearch;
     _stateBehavior[_drillState]         = UpdateDrill;
     _drillVelocity     = drillVelocity;
     _astroidDetectSize = asteroidDetectSize;
     _epsilon           = epsilon;
 }
Example #14
0
        private void StopDrilling()
        {
            for (int i = 0; i < _drills.Count; ++i)
            {
                IMyShipDrill block = _drills[i];
                block.GetActionWithName("OnOff_Off").Apply(block);
            }

            for (int i = 0; i < XUtils.Directions.Count; ++i)
            {
                VRageMath.Vector3 dir = XUtils.Directions[i];
                thrusts.SetThrustersEnabled(dir, true);
                thrusts.Accelerate(dir, thrusts.DefaultAcceleration);
            }
        }
Example #15
0
        internal void AddSphereRing(BoundingSphere sphere, Color color, Matrix onb)
        {
            float increment = 1.0f / 32;

            for (float i = 0; i < 1; i += increment)
            {
                float a0 = 2 * (float)Math.PI * i;
                float a1 = 2 * (float)Math.PI * (i + increment);

                Add(
                    Vector3.Transform(new Vector3(Math.Cos(a0), 0, Math.Sin(a0)) * sphere.Radius, onb) + sphere.Center,
                    Vector3.Transform(new Vector3(Math.Cos(a1), 0, Math.Sin(a1)) * sphere.Radius, onb) + sphere.Center,
                    color);
            }
        }
Example #16
0
        internal void AddQuad(Vector3 v0, Vector3 v1, Vector3 v2, Vector3 v3, Color color)
        {
            var bcolor = new Byte4(color.R, color.G, color.B, color.A);

            Add(new MyVertexFormatPositionColor(v0, bcolor));
            Add(new MyVertexFormatPositionColor(v1, bcolor));

            Add(new MyVertexFormatPositionColor(v1, bcolor));
            Add(new MyVertexFormatPositionColor(v2, bcolor));

            Add(new MyVertexFormatPositionColor(v2, bcolor));
            Add(new MyVertexFormatPositionColor(v3, bcolor));

            Add(new MyVertexFormatPositionColor(v3, bcolor));
            Add(new MyVertexFormatPositionColor(v0, bcolor));
        }
Example #17
0
        internal void AddQuad(Vector3 v0, Vector3 v1, Vector3 v2, Vector3 v3, Color color)
        {
            var bcolor = new Byte4(color.R, color.G, color.B, color.A);

            Add(new MyVertexFormatPositionColor(v0, bcolor));
            Add(new MyVertexFormatPositionColor(v1, bcolor));

            Add(new MyVertexFormatPositionColor(v1, bcolor));
            Add(new MyVertexFormatPositionColor(v2, bcolor));

            Add(new MyVertexFormatPositionColor(v2, bcolor));
            Add(new MyVertexFormatPositionColor(v3, bcolor));

            Add(new MyVertexFormatPositionColor(v3, bcolor));
            Add(new MyVertexFormatPositionColor(v0, bcolor));
        }
Example #18
0
        void IPrimitiveManagerBase.GetPrimitiveBox(int prim_index, out AABB primbox)
        {
            BoundingBox bbox = BoundingBox.CreateInvalid();
            Vector3     v1   = GetVertex(Triangles[prim_index].I0);
            Vector3     v2   = GetVertex(Triangles[prim_index].I1);
            Vector3     v3   = GetVertex(Triangles[prim_index].I2);

            bbox.Include(
                ref v1,
                ref v2,
                ref v3);

            primbox = new AABB()
            {
                m_min = bbox.Min.ToBullet(), m_max = bbox.Max.ToBullet()
            };
        }
Example #19
0
            public static void CalculateRotation(ref VRageMath.Vector3 a, ref VRageMath.Vector3 b, out VRageMath.Matrix rotation)
            {
                if (!VRageMath.Vector3.IsUnit(ref a))
                {
                    a.Normalize();
                }
                if (!VRageMath.Vector3.IsUnit(ref b))
                {
                    b.Normalize();
                }

                VRageMath.Vector3 v = a.Cross(b);
                float             s = v.Length(); // sine
                float             c = a.Dot(b);   // cosine

                VRageMath.Matrix cross = Utils.CreateSkewSymmetricMatrix(v);
                rotation = Identity + cross + cross * cross * (1 - c) / s;
            }
Example #20
0
        public void SetThrustersEnabled(VRageMath.Vector3 dir, bool value)
        {
            if (!thrusterBlocks.ContainsKey(dir))
            {
                throw new Exception("Warning! No thruster in direction " + dir + ".");
            }

            var list = thrusterBlocks[dir];

            for (int i = 0; i < list.Count; ++i)
            {
                IMyThrust block = list[i];
                if (block.Enabled ^ value)
                {
                    block.GetActionWithName("OnOff").Apply(block);
                }
            }
        }
Example #21
0
        public bool AreThrustersEnabled(VRageMath.Vector3 dir)
        {
            if (!thrusterBlocks.ContainsKey(dir))
            {
                throw new Exception("Warning! No thruster in direction " + dir + ".");
            }

            bool enabled = false;
            var  list    = thrusterBlocks[dir];
            int  i       = 0;

            while (!enabled && i < list.Count)
            {
                enabled |= list[i].Enabled;
                i++;
            }
            return(enabled);
        }
Example #22
0
        public void ApplyAction(VRageMath.Vector3 dir, string name)
        {
            if (!XUtils.Directions.Contains(dir))
            {
                throw new Exception("Invalid direction vector used: " + dir);
            }

            VRageMath.Matrix local = new VRageMath.Matrix();
            referenceBlock.Orientation.GetMatrix(out local);
            dir = VRageMath.Vector3.Transform(dir, local);

            var list = thrusterBlocks[dir];

            for (int i = 0; i < list.Count; ++i)
            {
                IMyThrust thruster = list[i];
                thruster.GetActionWithName(name).Apply(thruster);
            }
        }
Example #23
0
        /// <summary>
        /// Accelerates the ship relative to the reference block.
        /// </summary>
        /// <param name="dir">The direction relative to the reference block in which the ship should be accelerated.</param>
        /// <param name="value">The amount of force to accelerate in Newton.</param>
        public void Accelerate(VRageMath.Vector3 dir, float value)
        {
            if ((value < MinAcceleration || value > MaxAcceleration) && value != DefaultAcceleration)
            {
                throw new Exception("Value '" + value + "' out of range [" + MinAcceleration + ", " + MaxAcceleration + "] + " + DefaultAcceleration + ".");
            }

            if (!thrusterBlocks.ContainsKey(dir))
            {
                throw new Exception("Warning! No thruster in direction " + dir + ".");
            }

            var list = thrusterBlocks[dir];

            for (int i = 0; i < list.Count; ++i)
            {
                IMyThrust thruster = list[i];
                thruster.SetValueFloat("Override", value);
            }
        }
Example #24
0
        internal void AddCone(Vector3 translation, Vector3 directionVec, Vector3 baseVec, int tessalation, Color color)
        {
            var axis = directionVec;
            axis.Normalize();

            var apex = translation + directionVec;

            var steps = tessalation;
            var stepsRcp = (float)(Math.PI * 2 / steps);
            for (int i = 0; i < 32; i++)
            {
                float a0 = i * stepsRcp;
                float a1 = (i + 1) * stepsRcp;

                var A = translation + Vector3.Transform(baseVec, Matrix.CreateFromAxisAngle(axis, a0));
                var B = translation + Vector3.Transform(baseVec, Matrix.CreateFromAxisAngle(axis, a1));

                Add(A, B, color);
                Add(A, apex, color);
            }
        }
Example #25
0
            public void UpdateBlocks(List <IMyTerminalBlock> list)
            {
                gyros     = new List <IMyGyro>();
                thrusters = new Dictionary <VRageMath.Vector3, List <IMyThrust> >();
                VRageMath.Matrix tmp = new VRageMath.Matrix();
                for (int i = 0; i < list.Count; ++i)
                {
                    var block = list[i];
                    if (block is IMyGyro)
                    {
                        IMyGyro gyro = (IMyGyro)block;
                        if (gyros.Count == 0)
                        {
                            gyroRotateMin = gyro.GetMininum <float>(GyroAction.Pitch.GetName());
                            gyroRotateMax = gyro.GetMaximum <float>(GyroAction.Pitch.GetName());
                        }
                        gyros.Add(gyro);
                    }
                    else if (block is IMyThrust)
                    {
                        IMyThrust thruster = block as IMyThrust;

                        if (thrusters.Count == 0)
                        {
                            thrusterOverrideMin = thruster.GetMininum <float>("Override");
                            thrusterOverrideMax = thruster.GetMaximum <float>("Override");
                        }

                        block.Orientation.GetMatrix(out tmp);
                        // The exhaust is directed to the Forward vector of the thruster, so it accelerates to Backward.
                        VRageMath.Vector3 dir = tmp.Backward;
                        if (!thrusters.ContainsKey(dir))
                        {
                            thrusters[dir] = new List <IMyThrust>();
                        }
                        thrusters[dir].Add(thruster);
                    }
                }
            }
Example #26
0
        public int GetClosestSensor(VRageMath.Vector3 point, List <int> exclude)
        {
            if (sensorBlocks.Count == 0)
            {
                throw new Exception("Cannot get the closest sensor, because there exists no sensor.");
            }

            int i = 0;

            while (exclude.Contains(i) && i < CountSensors)
            {
                ++i;
            }
            if (i == CountSensors)
            {
                return(i);
            }

            int   id = i;
            float dist2NearestBlock = (sensorBlocks[i].Position - point).LengthSquared();

            for (; i < sensorBlocks.Count; ++i)
            {
                if (exclude.Contains(i))
                {
                    continue;
                }

                float dist2 = (sensorBlocks[i].Position - point).LengthSquared();
                if (dist2 < dist2NearestBlock)
                {
                    id = i;
                    dist2NearestBlock = dist2;
                }
            }

            return(id);
        }
Example #27
0
        internal void AddCone(Vector3 translation, Vector3 directionVec, Vector3 baseVec, int tessalation, Color color)
        {
            var axis = directionVec;

            axis.Normalize();

            var apex = translation + directionVec;

            var steps    = tessalation;
            var stepsRcp = (float)(Math.PI * 2 / steps);

            for (int i = 0; i < 32; i++)
            {
                float a0 = i * stepsRcp;
                float a1 = (i + 1) * stepsRcp;

                var A = translation + Vector3.Transform(baseVec, Matrix.CreateFromAxisAngle(axis, a0));
                var B = translation + Vector3.Transform(baseVec, Matrix.CreateFromAxisAngle(axis, a1));

                Add(A, B, color);
                Add(A, apex, color);
            }
        }
Example #28
0
        /// <summary>
        /// Rotates the ship relative to the reference block.
        /// A positive Yaw value rotates around the Up vector, such that the Right vector is moved to the Backward vector on the shortest way.
        /// A positive Pitch value rotates around the Right vector, such that the Up vector is moved to the Backward vector on the shortest way.
        /// A positive Roll value rotates around the Backward vector, such that the Up vector is moved to the Right vector on the shortest way.
        /// </summary>
        /// <param name="axis"></param>
        /// <param name="value"></param>
        private void Rotate(VRageMath.Vector3 axis, float value)
        {
            if (value < Min || value > Max)
            {
                throw new Exception("Value '" + value + "' out of range [" + Min + ", " + Max + "].");
            }

            VRageMath.Matrix local = new VRageMath.Matrix();
            referenceBlock.Orientation.GetMatrix(out local);
            axis = VRageMath.Vector3.Transform(axis, local);

            for (int i = 0; i < gyroscopeBlocks.Count; ++i)
            {
                IMyGyro gyro = gyroscopeBlocks[i] as IMyGyro;
                gyro.Orientation.GetMatrix(out local);

                VRageMath.Matrix  toGyro          = VRageMath.Matrix.Transpose(local);
                VRageMath.Vector3 transformedAxis = VRageMath.Vector3.Transform(axis, toGyro);

                GyroAction action = GyroAction.getActionAroundAxis(transformedAxis);
                gyro.SetValue(action.Name, action.Reversed ? -value : value);
            }
        }
Example #29
0
            /// <summary>
            /// Rotates the ship relative to the reference block.
            /// A positive Yaw value rotates around the Up vector, such that the Right vector is moved to the Backward vector on the shortest way.
            /// A positive Pitch value rotates around the Right vector, such that the Up vector is moved to the Backward vector on the shortest way.
            /// A positive Roll value rotates around the Backward vector, such that the Up vector is moved to the Right vector on the shortest way.
            /// </summary>
            /// <param name="axis"></param>
            /// <param name="value"></param>
            public void Rotate(VRageMath.Vector3 axis, float value)
            {
                if (value < gyroRotateMin || value > gyroRotateMax)
                {
                    throw new Exception("Value out of range [" + gyroRotateMin + ", " + gyroRotateMax + "].");
                }

                VRageMath.Matrix local = new VRageMath.Matrix();
                referenceBlock.Orientation.GetMatrix(out local);
                axis = VRageMath.Vector3.Transform(axis, local);

                for (int i = 0; i < gyros.Count; ++i)
                {
                    IMyGyro gyro = gyros[i] as IMyGyro;
                    gyro.Orientation.GetMatrix(out local);

                    VRageMath.Matrix  toGyro          = VRageMath.Matrix.Transpose(local);
                    VRageMath.Vector3 transformedAxis = VRageMath.Vector3.Transform(axis, toGyro);

                    GyroAction action = gyroActions[transformedAxis];
                    gyro.SetValue(action.GetName(), action.Reversed ? -value : value);
                }
            }
Example #30
0
            /// <summary>
            /// Accelerates the ship relative to the reference block.
            /// </summary>
            /// <param name="dir">The direction relative to the reference block in which the ship should be accelerated.</param>
            /// <param name="value">The amount of force to accelerate in Newton.</param>
            public void Accelerate(VRageMath.Vector3 dir, float value)
            {
                if (value < thrusterOverrideMin || value > thrusterOverrideMax)
                {
                    throw new Exception("Value out of range [" + thrusterOverrideMin + ", " + thrusterOverrideMax + "].");
                }

                VRageMath.Matrix local = new VRageMath.Matrix();
                referenceBlock.Orientation.GetMatrix(out local);
                dir = VRageMath.Vector3.Transform(dir, local);

                if (!thrusters.ContainsKey(dir))
                {
                    throw new Exception("Warning! No thruster in direction " + dir + ".");
                }

                var list = thrusters[dir];

                for (int i = 0; i < list.Count; ++i)
                {
                    IMyThrust thruster = list[i];
                    thruster.SetValueFloat("Override", value);
                }
            }
Example #31
0
        //  Sends input (keyboard/mouse) to screen which has focus (top-most)
        public void HandleInputAfterSimulation()
        {
            if (MySession.Static != null)
            {
                bool cameraControllerMovementAllowed = MyScreenManager.GetScreenWithFocus() == MyGuiScreenGamePlay.Static && MyGuiScreenGamePlay.Static != null && !MyScreenManager.InputToNonFocusedScreens;
                bool lookAroundEnabled = MyInput.Static.IsGameControlPressed(MyControlsSpace.LOOKAROUND) || (MySession.Static.ControlledEntity != null && MySession.Static.ControlledEntity.PrimaryLookaround);

                //After respawn, the controlled object might be null
                bool shouldStopControlledObject = MySession.Static.ControlledEntity != null && (!cameraControllerMovementAllowed && m_cameraControllerMovementAllowed != cameraControllerMovementAllowed);

                bool movementAllowedInPause = MySession.Static.GetCameraControllerEnum() == MyCameraControllerEnum.Spectator ||
                                              MySession.Static.GetCameraControllerEnum() == MyCameraControllerEnum.SpectatorDelta ||
                                              MySession.Static.GetCameraControllerEnum() == MyCameraControllerEnum.SpectatorFixed;
                bool rotationAllowedInPause = movementAllowedInPause;   //GK: consider removing if in the future is not different from movementAllowed
                bool devScreenFlag          = MyScreenManager.GetScreenWithFocus() is MyGuiScreenDebugBase && !MyInput.Static.IsAnyAltKeyPressed();
                MyCameraControllerEnum cce  = MySession.Static.GetCameraControllerEnum();

                float             rollIndicator     = MyInput.Static.GetRoll();
                Vector2           rotationIndicator = MyInput.Static.GetRotation();
                VRageMath.Vector3 moveIndicator     = MyInput.Static.GetPositionDelta();

                var focusScreen = MyScreenManager.GetScreenWithFocus();

                if (MySandboxGame.IsPaused && focusScreen is MyGuiScreenGamePlay)
                {
                    if (!movementAllowedInPause && !rotationAllowedInPause)
                    {
                        return;
                    }

                    if (!movementAllowedInPause)
                    {
                        moveIndicator = VRageMath.Vector3.Zero;
                    }
                    if (!rotationAllowedInPause || devScreenFlag)
                    {
                        rollIndicator     = 0.0f;
                        rotationIndicator = Vector2.Zero;
                    }

                    MySession.Static.CameraController.Rotate(rotationIndicator, rollIndicator);
                }
                else if (lookAroundEnabled)
                {
                    if (cameraControllerMovementAllowed)
                    {
                        //Then move camera (because it can be dependent on control object)
                        MySession.Static.CameraController.Rotate(rotationIndicator, rollIndicator);

                        if (!m_lookAroundEnabled && shouldStopControlledObject)
                        {
                            MySession.Static.ControlledEntity.MoveAndRotateStopped();
                        }
                    }

                    if (shouldStopControlledObject)
                    {
                        MySession.Static.CameraController.RotateStopped();
                    }
                }
                //Hack to make spectators work until they are made entities
                else if (MySession.Static.CameraController is MySpectatorCameraController && MySpectatorCameraController.Static.SpectatorCameraMovement == MySpectatorCameraMovementEnum.ConstantDelta)
                {
                    if (cameraControllerMovementAllowed)
                    {
                        MySpectatorCameraController.Static.MoveAndRotate(moveIndicator, rotationIndicator, rollIndicator);
                    }
                }

                if (shouldStopControlledObject)
                {
                    MySession.Static.ControlledEntity.MoveAndRotateStopped();
                }

                m_cameraControllerMovementAllowed = cameraControllerMovementAllowed;
                m_lookAroundEnabled = lookAroundEnabled;
            }
        }
Example #32
0
        void Main()
        {
            // initialize
            var blocks = new List <IMyTerminalBlock>();

            if (counter == 0)
            {
                GridTerminalSystem.GetBlocksOfType <IMyShipController>(blocks, FilterShipController);

                if (blocks.Count == 0)
                {
                    throw new Exception("Did not find any cockpit.");
                }

                controller = blocks[0] as IMyShipController;
                debug.Append("use ").Append(controller.CustomName).Append(':').AppendLine();

                perpBlocks = Utils.FindPerpendicularTo(controller);

                ship       = new ShipController(controller);
                worldCoord = controller.GetPosition();
                debug.Append("POSITION = ").Append(worldCoord).AppendLine();

                Debug(debug.ToString());
                debug.Clear();
                counter++;
                return;
            }

            worldCoord = new VRageMath.Vector3D(0, 0, 0);

            bool orthogonal = perpBlocks.Count == 3;

            VRageMath.Matrix toWorld = orthogonal ? Utils.toWorld(GridTerminalSystem.Blocks) : Utils.toWorld(perpBlocks);

            blocks = new List <IMyTerminalBlock>();
            GridTerminalSystem.GetBlocksOfType <IMyThrust>(blocks);
            GridTerminalSystem.GetBlocksOfType <IMyGyro>(blocks);

            debug.Append("worldCoord = ").Append(VRageMath.Vector3I.Round(worldCoord)).AppendLine();
            debug.Append("controller.GetPosition() = ").Append(VRageMath.Vector3I.Round(controller.GetPosition())).AppendLine();
            debug.Append("controller.Position = ").Append(controller.Position).AppendLine();

            debug.Append("transfrom controller.Position = ").Append(VRageMath.Vector3I.Round(VRageMath.Vector3.Transform(controller.Position, toWorld))).AppendLine();
            debug.Append("transfrom controller.Position = ").Append(VRageMath.Vector3I.Round(VRageMath.Vector3.Transform(controller.GetPosition(), VRageMath.Matrix.Invert(toWorld)))).AppendLine();

            VRageMath.Vector3 worldDir = worldCoord - controller.GetPosition();
            float             distance = worldDir.LengthSquared() > 0 ? worldDir.Normalize() : 0;

            debug.Append("distance = ").Append(distance).AppendLine();
            debug.Append("direction = ").Append(worldDir).AppendLine();

            VRageMath.Matrix worldController = new VRageMath.Matrix();
            controller.Orientation.GetMatrix(out worldController);
            worldController = worldController * toWorld;
            debug.Append("worldController = ").AppendLine();
            debug.Append(worldController.Right).AppendLine();
            debug.Append(worldController.Up).AppendLine();
            debug.Append(worldController.Backward).AppendLine();
            debug.Append(worldController.Translation).AppendLine();
            debug.Append("origin worldController = ").Append(VRageMath.Vector3I.Round(VRageMath.Vector3.Transform(new VRageMath.Vector3(), worldController))).AppendLine();
            //VRageMath.Vector3 n = orthogonal ? worldController.Right : worldController.Up.Cross(worldController.Backward);
            //VRageMath.Vector3 projDir = worldDir - worldDir.Dot(n) / n.Dot(n) * n;
            //if (projDir.LengthSquared() > 0)
            //    projDir.Normalize();

            //VRageMath.Vector3 eY = worldController.Up;
            //eY.Normalize();
            //VRageMath.Vector3 eZ = worldController.Backward;
            //eZ.Normalize();

            //float cosinePhiY = eY.Dot(projDir);
            //float cosinePhiZ = eZ.Dot(projDir);

            //float pitch = (float)(cosinePhiY > 0 ? -Math.Acos(cosinePhiZ) : Math.Acos(cosinePhiZ));
            ////VRageMath.Matrix.AlignRotationToAxes();
            //debug.Append("pitch = ").Append(pitch).AppendLine();

            debug.Append("worldController.IsRotation() = ").Append(worldController.IsRotation());
            VRageMath.Matrix  toAlign = VRageMath.Matrix.CreateFromDir(worldDir, worldController.Up);
            VRageMath.Matrix  align   = VRageMath.Matrix.AlignRotationToAxes(ref toAlign, ref worldController);
            VRageMath.Vector3 xyz     = new VRageMath.Vector3();
            VRageMath.Matrix.GetEulerAnglesXYZ(ref align, out xyz);
            xyz = 0.1f * xyz;

            debug.Append(xyz).AppendLine();
            ship.UpdateBlocks(blocks);
            ship.Stop();
            ship.Rotate(Identity.Left, xyz.GetDim(0));
            ship.Rotate(Identity.Down, xyz.GetDim(1));
            ship.Rotate(Identity.Forward, xyz.GetDim(2));

            Debug(debug.ToString());
            debug.Clear();
        }
Example #33
0
 internal void Add6FacedConvex(Vector3 [] vertices, Color color)
 {
     AddQuad(vertices[0], vertices[1], vertices[2], vertices[3], color);
     AddQuad(vertices[4], vertices[5], vertices[6], vertices[7], color);
     AddQuad(vertices[0], vertices[1], vertices[5], vertices[4], color);
     AddQuad(vertices[0], vertices[3], vertices[7], vertices[4], color);
     AddQuad(vertices[3], vertices[2], vertices[6], vertices[7], color);
     AddQuad(vertices[2], vertices[1], vertices[5], vertices[6], color);
 }
Example #34
0
        public void LoadAnimationData()
        {
            if (m_loadedData) return;

            lock (this)
            {
                VRageRender.MyRenderProxy.GetRenderProfiler().StartProfilingBlock("MyModel::LoadAnimationData");


                MyLog.Default.WriteLine("MyModel.LoadData -> START", LoggingOptions.LOADING_MODELS);
                MyLog.Default.IncreaseIndent(LoggingOptions.LOADING_MODELS);

                MyLog.Default.WriteLine("m_assetName: " + m_assetName, LoggingOptions.LOADING_MODELS);

                //  Read data from model TAG parameter. There are stored vertex positions, triangle indices, vectors, ... everything we need.
                VRageRender.MyRenderProxy.GetRenderProfiler().StartProfilingBlock("Model - load data - import data");

                MyLog.Default.WriteLine(String.Format("Importing asset {0}, path: {1}", m_assetName, AssetName), LoggingOptions.LOADING_MODELS);
                try
                {
                    m_importer.ImportData(AssetName);
                }
                catch
                {
                    MyLog.Default.WriteLine(String.Format("Importing asset failed {0}", m_assetName));
                    throw;
                }
                VRageRender.MyRenderProxy.GetRenderProfiler().EndProfilingBlock();

                VRageRender.MyRenderProxy.GetRenderProfiler().StartProfilingBlock("Model - load data - load tag data");
                Dictionary<string, object> tagData = m_importer.GetTagData();
                Debug.Assert(tagData.Count != 0, String.Format("Uncompleted tagData for asset: {0}, path: {1}", m_assetName, AssetName));
                if (tagData.Count != 0)
                {
                    DataVersion = m_importer.DataVersion;

                    Animations = (ModelAnimations)tagData[MyImporterConstants.TAG_ANIMATIONS];
                    Bones = (MyModelBone[])tagData[MyImporterConstants.TAG_BONES];

                    BoundingBox = (BoundingBox)tagData[MyImporterConstants.TAG_BOUNDING_BOX];
                    BoundingSphere = (BoundingSphere)tagData[MyImporterConstants.TAG_BOUNDING_SPHERE];
                    BoundingBoxSize = BoundingBox.Max - BoundingBox.Min;
                    BoundingBoxSizeHalf = BoundingBoxSize / 2.0f;
                    Dummies = tagData[MyImporterConstants.TAG_DUMMIES] as Dictionary<string, MyModelDummy>;
                    BoneMapping = tagData[MyImporterConstants.TAG_BONE_MAPPING] as VRageMath.Vector3I[];
                    if (BoneMapping.Length == 0)
                        BoneMapping = null;
                }
                else
                {
                    DataVersion = 0;

                    Animations = null;
                    Bones = null;

                    BoundingBox = default(BoundingBox);
                    BoundingSphere = default(BoundingSphere);
                    BoundingBoxSize = default(Vector3);
                    BoundingBoxSizeHalf = default(Vector3);
                    Dummies = null;
                    BoneMapping = null;
                }

                VRageRender.MyRenderProxy.GetRenderProfiler().EndProfilingBlock();

                ModelInfo = new MyModelInfo(GetTrianglesCount(), GetVerticesCount(), BoundingBoxSize);

                if (tagData.Count != 0)
                    m_loadedData = true;

                MyLog.Default.DecreaseIndent(LoggingOptions.LOADING_MODELS);
                MyLog.Default.WriteLine("MyModel.LoadAnimationData -> END", LoggingOptions.LOADING_MODELS);

                VRageRender.MyRenderProxy.GetRenderProfiler().EndProfilingBlock();
            }
        }
Example #35
0
        //  Sort of lazy-load, where constructor just saves information about what this model should be, but real load is done here - and only one time.
        //  This loads only vertex data, doesn't touch GPU
        //  Can be called from main and background thread
        public void LoadData()
        {
            if (m_loadedData) return;

            lock (this)
            {
                VRageRender.MyRenderProxy.GetRenderProfiler().StartProfilingBlock("MyModel::LoadData");


                MyLog.Default.WriteLine("MyModel.LoadData -> START", LoggingOptions.LOADING_MODELS);
                MyLog.Default.IncreaseIndent(LoggingOptions.LOADING_MODELS);

                MyLog.Default.WriteLine("m_assetName: " + m_assetName, LoggingOptions.LOADING_MODELS);

                //  Read data from model TAG parameter. There are stored vertex positions, triangle indices, vectors, ... everything we need.
                VRageRender.MyRenderProxy.GetRenderProfiler().StartProfilingBlock("Model - load data - import data");

                MyLog.Default.WriteLine(String.Format("Importing asset {0}, path: {1}", m_assetName, AssetName), LoggingOptions.LOADING_MODELS);


                string assetForImport = AssetName;
                var fsPath = Path.IsPathRooted(AssetName) ? AssetName : Path.Combine(MyFileSystem.ContentPath, AssetName);
                if (!MyFileSystem.FileExists(fsPath))
                {
                    assetForImport = @"Models\Debug\Error.mwm";
                }

                try
                {
                    m_importer.ImportData(assetForImport);
                }
                catch
                {
                    MyLog.Default.WriteLine(String.Format("Importing asset failed {0}", m_assetName));
                    VRageRender.MyRenderProxy.GetRenderProfiler().EndProfilingBlock();
                    VRageRender.MyRenderProxy.GetRenderProfiler().EndProfilingBlock();
                    throw;
                }
                VRageRender.MyRenderProxy.GetRenderProfiler().EndProfilingBlock();

                DataVersion = m_importer.DataVersion;

                VRageRender.MyRenderProxy.GetRenderProfiler().StartProfilingBlock("Model - load data - load tag data");
                Dictionary<string, object> tagData = m_importer.GetTagData();
                if (tagData.Count == 0)
                {
                    VRageRender.MyRenderProxy.GetRenderProfiler().EndProfilingBlock();
                    VRageRender.MyRenderProxy.GetRenderProfiler().EndProfilingBlock();
                    throw new Exception(String.Format("Uncompleted tagData for asset: {0}, path: {1}", m_assetName, AssetName));
                }
                VRageRender.MyRenderProxy.GetRenderProfiler().EndProfilingBlock();

                VRageRender.MyRenderProxy.GetRenderProfiler().StartProfilingBlock("Model - load data - vertex, normals, texture coords");


                HalfVector4[] vertices = (HalfVector4[])tagData[MyImporterConstants.TAG_VERTICES];

                System.Diagnostics.Debug.Assert(vertices.Length > 0);

                Byte4[] normals = (Byte4[])tagData[MyImporterConstants.TAG_NORMALS];
                m_vertices = new MyCompressedVertexNormal[vertices.Length];
                if (normals.Length > 0)
                {
                    for (int v = 0; v < vertices.Length; v++)
                    {
                        m_vertices[v] = new MyCompressedVertexNormal()
                        {
                            Position = vertices[v],// VF_Packer.PackPosition(ref vertices[v]),
                            Normal = normals[v]//VF_Packer.PackNormalB4(ref normals[v])
                        };
                    }
                }
                else
                {
                    for (int v = 0; v < vertices.Length; v++)
                    {
                        m_vertices[v] = new MyCompressedVertexNormal()
                        {
                            Position = vertices[v],// VF_Packer.PackPosition(ref vertices[v]),
                        };
                    }
                }


                m_verticesCount = vertices.Length;

                VRageRender.MyRenderProxy.GetRenderProfiler().EndProfilingBlock();

                VRageRender.MyRenderProxy.GetRenderProfiler().StartProfilingBlock("Model - load data - mesh");

                var materials = new Dictionary<string, MyMeshMaterial>();
                m_meshContainer.Clear();
                if (tagData.ContainsKey(MyImporterConstants.TAG_MESH_PARTS))
                {
                    List<int> indices = new List<int>(GetVerticesCount()); // Default capacity estimation
                    int maxIndex = 0;

                    List<MyMeshPartInfo> meshParts = tagData[MyImporterConstants.TAG_MESH_PARTS] as List<MyMeshPartInfo>;
                    foreach (MyMeshPartInfo meshPart in meshParts)
                    {
                        MyMesh mesh = new MyMesh(meshPart, m_assetName);
                        mesh.IndexStart = indices.Count;
                        mesh.TriCount = meshPart.m_indices.Count / 3;

                        if (mesh.Material.Name != null)
                            materials.Add(mesh.Material.Name, mesh.Material);

                        if (m_loadUV && false == m_hasUV)
                        {
                            m_texCoords = (HalfVector2[])tagData[MyImporterConstants.TAG_TEXCOORDS0];
                            m_hasUV = true;
                            m_loadUV = false;
                        }

                        if (meshPart.m_MaterialDesc != null && meshPart.Technique == MyMeshDrawTechnique.GLASS)
                        {
                            GlassData = mesh;

                            HalfVector2[] forLoadingTexCoords0 = (HalfVector2[])tagData[MyImporterConstants.TAG_TEXCOORDS0];
                            List<HalfVector2> neededTexCoords = new List<HalfVector2>();

                            for (int t = 0; t < meshPart.m_indices.Count; t++)
                            {
                                int index = meshPart.m_indices[t];
                                neededTexCoords.Add(forLoadingTexCoords0[index]);
                            }

                            GlassTexCoords = neededTexCoords.ToArray();
                        }

                        System.Diagnostics.Debug.Assert(mesh.TriCount > 0);

                        if (mesh.TriCount == 0)
                        {
                            VRageRender.MyRenderProxy.GetRenderProfiler().EndProfilingBlock();
                            VRageRender.MyRenderProxy.GetRenderProfiler().EndProfilingBlock();
                            return;
                        }

                        foreach (var i in meshPart.m_indices)
                        {
                            indices.Add(i);
                            if (i > maxIndex)
                            {
                                maxIndex = i;
                            }
                        }



                        m_meshContainer.Add(mesh);
                    }

                    if (maxIndex <= ushort.MaxValue)
                    {
                        // create 16 bit indices
                        m_Indices_16bit = new ushort[indices.Count];
                        for (int i = 0; i < indices.Count; i++)
                        {
                            m_Indices_16bit[i] = (ushort)indices[i];
                        }
                    }
                    else
                    {
                        // use 32bit indices
                        m_Indices = indices.ToArray();
                    }
                }

                m_meshSections.Clear();
                if (tagData.ContainsKey(MyImporterConstants.TAG_MESH_SECTIONS))
                {
                    List<MyMeshSectionInfo> sections = tagData[MyImporterConstants.TAG_MESH_SECTIONS] as List<MyMeshSectionInfo>;
                    int sectionindex = 0;
                    foreach (MyMeshSectionInfo sectinfo in sections)
                    {
                        MyMeshSection section = new MyMeshSection() { Name = sectinfo.Name, Index = sectionindex };
                        m_meshSections.Add(section.Name, section);
                        sectionindex++;
                    }
                }

                if (tagData.ContainsKey(MyImporterConstants.TAG_MODEL_BVH))
                {
                    m_bvh = new MyQuantizedBvhAdapter(tagData[MyImporterConstants.TAG_MODEL_BVH] as GImpactQuantizedBvh, this);
                }

                VRageRender.MyRenderProxy.GetRenderProfiler().EndProfilingBlock();

                VRageRender.MyRenderProxy.GetRenderProfiler().StartProfilingBlock("Model - load data - other data");

                Animations = (ModelAnimations)tagData[MyImporterConstants.TAG_ANIMATIONS];
                Bones = (MyModelBone[])tagData[MyImporterConstants.TAG_BONES];

                BoundingBox = (BoundingBox)tagData[MyImporterConstants.TAG_BOUNDING_BOX];
                BoundingSphere = (BoundingSphere)tagData[MyImporterConstants.TAG_BOUNDING_SPHERE];
                BoundingBoxSize = BoundingBox.Max - BoundingBox.Min;
                BoundingBoxSizeHalf = BoundingBoxSize / 2.0f;
                Dummies = tagData[MyImporterConstants.TAG_DUMMIES] as Dictionary<string, MyModelDummy>;
                BoneMapping = tagData[MyImporterConstants.TAG_BONE_MAPPING] as VRageMath.Vector3I[];

                if (tagData.ContainsKey(MyImporterConstants.TAG_MODEL_FRACTURES))
                    ModelFractures = (MyModelFractures)tagData[MyImporterConstants.TAG_MODEL_FRACTURES];

                object patternScale;
                if (tagData.TryGetValue(MyImporterConstants.TAG_PATTERN_SCALE, out patternScale))
                {
                    PatternScale = (float)patternScale;
                }

                if (BoneMapping.Length == 0)
                    BoneMapping = null;

                if (tagData.ContainsKey(MyImporterConstants.TAG_HAVOK_COLLISION_GEOMETRY))
                {
                    HavokData = (byte[])tagData[MyImporterConstants.TAG_HAVOK_COLLISION_GEOMETRY];
                    byte[] tagCollisionData = (byte[])tagData[MyImporterConstants.TAG_HAVOK_COLLISION_GEOMETRY];
                    if (tagCollisionData.Length > 0 && HkBaseSystem.IsThreadInitialized)
                    {
                        bool containsSceneData;
                        bool containsDestructionData;
                        List<HkShape> shapesList = new List<HkShape>();
                        if (!HkShapeLoader.LoadShapesListFromBuffer(tagCollisionData, shapesList, out containsSceneData, out containsDestructionData))
                        {
                            MyLog.Default.WriteLine(string.Format("Model {0} - Unable to load collision geometry", AssetName), LoggingOptions.LOADING_MODELS);
                        //Debug.Fail("Collision model was exported in wrong way: " + m_assetName);
                        }

                        if (shapesList.Count > 10)
                            MyLog.Default.WriteLine(string.Format("Model {0} - Found too many collision shapes, only the first 10 will be used", AssetName), LoggingOptions.LOADING_MODELS);

                        if (HavokCollisionShapes != null)
                        {
                            Debug.Fail("Shapes already loaded");
                        }
                        if (shapesList.Count > 0)
                        {
                            HavokCollisionShapes = shapesList.ToArray();
                        }
                        else
                        {
                            MyLog.Default.WriteLine(string.Format("Model {0} - Unable to load collision geometry from file, default collision will be used !", AssetName));
                        }

                        if (containsDestructionData)
                            HavokDestructionData = tagCollisionData;

                        ExportedWrong = !containsSceneData;
                    }
                }


                if (tagData.ContainsKey(MyImporterConstants.TAG_HAVOK_DESTRUCTION))
                {
                    if (((byte[])tagData[MyImporterConstants.TAG_HAVOK_DESTRUCTION]).Length > 0)
                        HavokDestructionData = (byte[])tagData[MyImporterConstants.TAG_HAVOK_DESTRUCTION];
                }

                VRageRender.MyRenderProxy.GetRenderProfiler().EndProfilingBlock();

                VRageRender.MyRenderProxy.GetRenderProfiler().StartProfilingBlock("Model - load data - copy triangle indices");
                //  Prepare data
                CopyTriangleIndices();
                m_trianglesCount = Triangles.Length;

                //  Remember this numbers as list may be cleared at the end of this method
                VRageRender.MyRenderProxy.GetRenderProfiler().EndProfilingBlock();

                MyLog.Default.WriteLine("Triangles.Length: " + Triangles.Length, LoggingOptions.LOADING_MODELS);
                MyLog.Default.WriteLine("Vertexes.Length: " + GetVerticesCount(), LoggingOptions.LOADING_MODELS);
                MyLog.Default.WriteLine("Centered: " + (bool)tagData[MyImporterConstants.TAG_CENTERED], LoggingOptions.LOADING_MODELS);
                MyLog.Default.WriteLine("UseChannelTextures: " + (bool)tagData[MyImporterConstants.TAG_USE_CHANNEL_TEXTURES], LoggingOptions.LOADING_MODELS);
                MyLog.Default.WriteLine("Length in meters: " + (float)tagData[MyImporterConstants.TAG_LENGTH_IN_METERS], LoggingOptions.LOADING_MODELS);
                MyLog.Default.WriteLine("Rescale to length in meters?: " + (bool)tagData[MyImporterConstants.TAG_RESCALE_TO_LENGTH_IN_METERS], LoggingOptions.LOADING_MODELS);
                MyLog.Default.WriteLine("BoundingBox: " + BoundingBox, LoggingOptions.LOADING_MODELS);
                MyLog.Default.WriteLine("BoundingSphere: " + BoundingSphere, LoggingOptions.LOADING_MODELS);

                VRage.Utils.Stats.PerAppLifetime.MyModelsCount++;
                VRage.Utils.Stats.PerAppLifetime.MyModelsMeshesCount += m_meshContainer.Count;
                VRage.Utils.Stats.PerAppLifetime.MyModelsVertexesCount += GetVerticesCount();
                VRage.Utils.Stats.PerAppLifetime.MyModelsTrianglesCount += Triangles.Length;

                ModelInfo = new MyModelInfo(GetTrianglesCount(), GetVerticesCount(), BoundingBoxSize);

                m_loadedData = true;
                m_loadingErrorProcessed = false;
                MyLog.Default.DecreaseIndent(LoggingOptions.LOADING_MODELS);
                MyLog.Default.WriteLine("MyModel.LoadData -> END", LoggingOptions.LOADING_MODELS);

                VRageRender.MyRenderProxy.GetRenderProfiler().EndProfilingBlock();
            }
        }
Example #36
0
 public void GetVertex(int vertexIndex1, int vertexIndex2, int vertexIndex3, out Vector3 v1, out Vector3 v2, out Vector3 v3)
 {
     v1 = GetVertex(vertexIndex1);
     v2 = GetVertex(vertexIndex2);
     v3 = GetVertex(vertexIndex3);
 }
Example #37
0
 internal void Add(Vector3 from, Vector3 to, Color colorFrom, Color? colorTo = null)
 {
     List.Add(new MyVertexFormatPositionColor(from, new Byte4(colorFrom.PackedValue)));
     List.Add(new MyVertexFormatPositionColor(to, colorTo.HasValue ? new Byte4(colorTo.Value.PackedValue) : new Byte4(colorFrom.PackedValue)));
 }