示例#1
0
    //==============================================================

    #region Mono

    // TODO Extraer subinicializaicones
    private void Awake()
    {
        _isControllable = true;

        Debug.Assert(_setup.Right != Vector3.zero, "BoomonController::Awake>> Right move direction not defined!!");

        _role = (BoomonRole)Enum.Parse(typeof(BoomonRole), name.Split('(')[0]);

        _goToCallbacks = new List <Action>();
        _stateActions  = new Dictionary <State, StateActions>
        {
            { State.Driven, new StateActions(OnDrivenStart, OnDrivenEnd, DrivenUpdate) },
            { State.Emotion, new StateActions(OnEmotionStart, OnEmotionEnd) },
            { State.Idle, new StateActions(OnIdleStart, OnIdleEnd, MoveUpdate) },
            { State.Move, new StateActions(OnMoveStart, OnMoveEnd, MoveUpdate, OnMoveCollision) },
            { State.Throw, new StateActions(OnThrowStart, OnThrowEnd) },
            { State.StandUp, new StateActions(OnStandUpStart, OnStandUpEnd) },
            { State.Tickles, new StateActions(OnTickleStart, OnTickleEnd) },
        };


        _refSystem   = new ReferenceSystem(transform.position, _setup.Right);
        transform.up = _refSystem.Up;

        _animator   = GetComponent <Animator>();
        _controller = GetComponent <CharacterController>();
        _toucher    = GetComponent <Toucher>();
        _face       = GetComponent <FacialAnimator>();

        _groundSlopeCosine = Mathf.Cos(_controller.slopeLimit * Mathf.Deg2Rad);
        _animator.SetFloat(_setup.MoveMultiplierParamName, _setup.MoveAnimSpeed);
    }
示例#2
0
        public void ShouldRecongizeChristmasTree()
        {
            // Arrange
            var touchpoints = new List <Point2D> {
                new Point2D(1, 0),
                new Point2D(2, 0),
                new Point2D(0, 1),
                new Point2D(1, 1),
                new Point2D(2, 1),
                new Point2D(3, 1),
                new Point2D(0, 2),
                new Point2D(1, 2),
                new Point2D(2, 2),
                new Point2D(3, 2),
                new Point2D(1, 3),
                new Point2D(2, 3)
            };

            // System Under Test
            var referenceSystem = new ReferenceSystem(new Point2D(0, 0), new Vector2D(3, 0), new Vector2D(0, 3));

            // Act
            var touchcode = referenceSystem.MapPointsToTouchcode(touchpoints).Value;

            // Assert
            Assert.AreEqual(0xFFF, touchcode);
        }
示例#3
0
 public ReferenceSystem rs;                    //空间坐标系
 public Schema(String name, OSGeo.OGR.wkbGeometryType type, ReferenceSystem spatialreference, Dictionary <string, FieldDefn> _fields)
 {
     this.name         = name;
     this.geometryType = type;
     this.rs           = spatialreference;
     this.fields       = _fields;
 }
        /// <summary>
        /// Creates a strategy for converting coordinates between reference systems.
        /// </summary>
        /// <param name="source">The source.</param>
        /// <param name="target">The target.</param>
        /// <returns>The produced transformation strategy.</returns>
        /// <exception cref="System.NotSupportedException">Conversion does not exist between the specified reference systems.</exception>
        public ICoordinateOperationStrategy CreateStrategy(ReferenceSystem source, ReferenceSystem target)
        {
            ICoordinateOperationStrategy <Coordinate, GeoCoordinate>    conversionToGeographic   = null;
            ICoordinateOperationStrategy <GeoCoordinate, GeoCoordinate> transformation           = null;
            ICoordinateOperationStrategy <GeoCoordinate, Coordinate>    conversionFromGeographic = null;

            switch (source.Type)
            {
            case ReferenceSystemType.Projected:
                conversionToGeographic = new ReverseCoordinateProjectionStrategy(source as ProjectedCoordinateReferenceSystem);
                break;

            case ReferenceSystemType.Geographic2D:
            case ReferenceSystemType.Geographic3D:
                conversionToGeographic = this.CreateReverseConversion(source as CoordinateReferenceSystem);
                break;
            }

            switch (target.Type)
            {
            case ReferenceSystemType.Projected:
                conversionFromGeographic = new ForwardCoordinateProjectionStrategy(target as ProjectedCoordinateReferenceSystem);
                break;

            case ReferenceSystemType.Geographic2D:
            case ReferenceSystemType.Geographic3D:
                conversionFromGeographic = this.CreateForwardConversion(target as CoordinateReferenceSystem);
                break;
            }

            // if no transformation is needed
            if (conversionFromGeographic.TargetReferenceSystem.Equals(conversionToGeographic.SourceReferenceSystem))
            {
                return(new CoordinateConversionStrategy(conversionToGeographic, conversionFromGeographic));
            }

            GeographicCoordinateReferenceSystem conversionTargetReferenceSystem = conversionToGeographic.TargetReferenceSystem as GeographicCoordinateReferenceSystem;
            GeographicCoordinateReferenceSystem conversionSourceReferenceSystem = conversionFromGeographic.SourceReferenceSystem as GeographicCoordinateReferenceSystem;

            // load matching forward transformation
            IEnumerable <CoordinateTransformation <GeoCoordinate> > transformations = this.provider.GeoCoordinateTransformations.WithProperties(conversionTargetReferenceSystem, conversionSourceReferenceSystem);

            if (transformations.Any())
            {
                transformation = new ForwardGeographicCoordinateTransformationStrategy(conversionTargetReferenceSystem, conversionSourceReferenceSystem, transformations.First());
                return(new CompoundCoordinateConversionStrategy(conversionToGeographic, transformation, conversionFromGeographic));
            }

            // if none found, load matching reverse transformation
            transformations = this.provider.GeoCoordinateTransformations.WithProperties(conversionSourceReferenceSystem, conversionTargetReferenceSystem);
            if (transformations.Any())
            {
                transformation = new ReverseGeographicCoordinateTransformationStrategy(conversionTargetReferenceSystem, conversionSourceReferenceSystem, transformations.First());
                return(new CompoundCoordinateConversionStrategy(conversionToGeographic, transformation, conversionFromGeographic));
            }

            throw new NotSupportedException(ReferenceMessages.ConversionDoesNotExistBetweenReferenceSystems);
        }
示例#5
0
        /// <summary>
        /// 哈希数。
        /// </summary>
        /// <returns></returns>
        public override int GetHashCode()
        {
            int code = ReferenceSystem.GetHashCode() * 13;

            foreach (var item in this.CoordDic.Values)
            {
                code += item.GetHashCode();
            }
            return(code);
        }
示例#6
0
    public void TeleportTo(Teleport target)
    {
        IsTeleporting = true;
        CurrentState  = State.Driven;

        transform.position = target.transform.position;
        _refSystem         = new ReferenceSystem(transform.position, target.Right);

        GoTo(target.ExitPoint);
    }
示例#7
0
        private void HandleUnityEngineLog(string logString, string stackTrace, LogType type)
        {
            LogWrapper wrapper = ReferenceSystem.Spawn <LogWrapper>();

            wrapper.Type = type;
            wrapper.Log  = $"[{type}] {logString}";
            _logs.Add(wrapper);

            if (_logs.Count > LOG_MAX_COUNT)
            {
                ReferenceSystem.Release(_logs[0]);
                _logs.RemoveAt(0);
            }
        }
示例#8
0
        public ReferenceSystem getReference()
        {
            var             rect = getEnvelopofLayer();
            ReferenceSystem srs  = this.featuresource.schema.rs;

            if (rect.minX < -180.0)
            {
                srs.srid = 0;
            }
            else
            {
                srs.srid = 4326;
            }
            return(srs);
        }
示例#9
0
        public void ShouldRecongizeEmptyTouchcode()
        {
            // Arrange
            var touchpoints     = new List <Point2D>();
            var referenceSystem = new ReferenceSystem(new Point2D(0, 0), new Vector2D(3, 0), new Vector2D(0, 3));

            // System Under Test
            var api = new TouchcodeAPI();

            // Act
            var touchcode = referenceSystem.MapPointsToTouchcode(touchpoints).Value;

            // Assert
            Assert.AreEqual(touchcode, 0);
        }
示例#10
0
        /// <summary>
        /// 是否为同类坐标,主要是通过参考系判断。
        /// </summary>
        /// <param name="other"></param>
        /// <returns></returns>
        public bool IsHomogenized(ICoordinate other)
        {
            //同为野坐标也为同质坐标
            if (IsEmpty != other.IsEmpty)
            {
                return(false);
            }

            if (!ReferenceSystem.Equals(other.ReferenceSystem))
            {
                return(false);
            }

            return(true);
        }
示例#11
0
        public void ShouldRecongizeTouchcode0x80(double x, double y, int expectedTouchcode)
        {
            // Arrange
            var touchpoints = new List <Point2D> {
                new Point2D(x, y)
            };

            // System Under Test
            var referenceSystem = new ReferenceSystem(new Point2D(0, 0), new Vector2D(3, 0), new Vector2D(0, 3));

            // Act
            var touchcode = referenceSystem.MapPointsToTouchcode(touchpoints).Value;

            // Assert
            Assert.AreEqual(touchcode, expectedTouchcode);
        }
示例#12
0
 private void button8_Click(object sender, EventArgs e)
 {
     ts2  = new CancellationTokenSource();
     ct2  = ts2.Token;
     ct_p = ts_p.Token;
     tabControl1.SelectedTab = tabControl1.TabPages[1];
     this.Refresh();
     ReferenceSystem.Default def = (ReferenceSystem.Default)listBox1.SelectedItem;
     відмінитиПоточнуОпераціюToolStripMenuItem.Enabled = true;
     var task = Task.Factory.StartNew(() =>
     {
         addText("Обчислення розпочато...\r\n");
         string file     = SphericalHarmonicAnalyze.Properties.Settings.Default.inGravityModel;
         GravityModel gm = new GravityModel(SphericalHarmonicAnalyze.Properties.Settings.Default.modelMaxOrder);
         gm.loadFromFile(SphericalHarmonicAnalyze.Properties.Settings.Default.inGravityModel, new setProgressDel(addVal));
         ReferenceSystem elipsoid                 = new ReferenceSystem(def);
         elipsoid.gridParameters.cellSize         = SphericalHarmonicAnalyze.Properties.Settings.Default.GridCellSize;
         elipsoid.gridParameters.coLatitudeBounds = SphericalHarmonicAnalyze.Properties.Settings.Default.minCoLatitude;
         elipsoid.maxDegree = SphericalHarmonicAnalyze.Properties.Settings.Default.modelMaxOrder;
         int greedColumnsCount, greedRowsCount;
         List <double[]> greed = MathFunc.generateGrid(elipsoid.gridParameters.cellSize, out greedColumnsCount, out greedRowsCount, SphericalHarmonicAnalyze.Properties.Settings.Default.minCoLatitude, SphericalHarmonicAnalyze.Properties.Settings.Default.maxCoLatitude, SphericalHarmonicAnalyze.Properties.Settings.Default.longW, SphericalHarmonicAnalyze.Properties.Settings.Default.longE);
         addText("Колонок: {0}\r\n", greed.Count);
         double[][] h_dg = GravityModel.getGeoidHeightAndAnomalys(elipsoid, gm, greed, d: new setProgressDel(addVal), ct: ct2, ct2: ct_p);
         if (ct2.IsCancellationRequested)
         {
             addText("Перервано...\r\n"); addVal(0, 1, ""); Thread.CurrentThread.Abort();
         }
         ;
         addText("dg обчислено\r\n");
         IOFunc.writeGeoidHeightsAndAnomalysToTxt(greed, h_dg[0], h_dg[1], elipsoid, file + "B_L_N_dg.txt");
         addText("Готово...\r\nРезультати записано в файл: " + file + "NEW____________B_L_N_dg.txt\r\n");
     }, ct2);
     var t3 = Task.Factory.StartNew(() => {
         label1:  if (task.IsCompleted)
         {
             if (checkBox1.Checked)
             {
                 System.Diagnostics.Process.Start("rundll32.exe", "powrprof.dll,SetSuspendState 0,1,0");
             }
             ;
         }
         else
         {
             task.Wait(); goto label1;
         }
     });
 }
示例#13
0
        public void ShouldRecongizeTouchcode0x18()
        {
            // Arrange
            var touchpoints = new List <Point2D> {
                new Point2D(1.1, 2.0),
                new Point2D(1.8, 2.2)
            };

            // System Under Test
            var referenceSystem = new ReferenceSystem(new Point2D(0, 0), new Vector2D(3, 0), new Vector2D(0, 3));

            // Act
            var touchcode = referenceSystem.MapPointsToTouchcode(touchpoints).Value;

            // Assert
            Assert.AreEqual(touchcode, 0x18);
        }
示例#14
0
        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            ReferenceSystem elipsoid = new ReferenceSystem(ReferenceSystem.Default.WGS84);

            elipsoid.gridParameters.cellSize         = 30d;
            elipsoid.gridParameters.coLatitudeBounds = 15D;
            elipsoid.maxDegree = 100;
            double[]     gmN = GravityModel.generateNormalModel(elipsoid, 10);
            GravityModel gm  = new GravityModel(100);

            gm.loadFromFile(SphericalHarmonicAnalyze.Properties.Settings.Default.inGravityModel, new setProgressDel(addVal));
            int             greedColumnsCount, greedRowsCount;
            GravityModel    gm2   = new GravityModel(gm);
            List <double[]> greed = MathFunc.generateGrid(elipsoid.gridParameters.cellSize, out greedColumnsCount, out greedRowsCount, elipsoid.gridParameters.coLatitudeBounds);

            double[] h  = GravityModel.getGeoidHeight(elipsoid, gm2, greed);
            double[] dg = GravityModel.getAnomaly(elipsoid, gm, greed);
            IOFunc.writeGeoidHeightsAndAnomalysToTxt(greed, h, dg, elipsoid, "result.txt");
        }
示例#15
0
        public MetaData(FeatureSource featuresource, string layername)
        {
            InitializeComponent();
            Schema schema = featuresource.schema;

            textBox1.Text      = layername;
            textBox1_Copy.Text = schema.name;
            GisSmartTools.Geometry.Rectangle rect = featuresource.features.getEnvelop();
            textBox_maxx.Text = rect.maxX.ToString("0.000");
            textBox_minx.Text = rect.minX.ToString("0.000");
            textBox_maxy.Text = rect.maxY.ToString("0.000");
            textBox_miny.Text = rect.minY.ToString("0.000");
            ReferenceSystem rs     = schema.rs;
            string          rstext = "";

            rs.spetialReference.ExportToWkt(out rstext);

            textBlock.Text = rstext;
        }
示例#16
0
        public GisSmartTools.Geometry.Rectangle GetRefernectRectangle()
        {
            if (layerlist.Count == 0)
            {
                return(new Geometry.Rectangle(0, 0, 100, 100));
            }
            Geometry.Rectangle rect = new Geometry.Rectangle(Utils.double_max, Utils.double_max, Utils.double_min, Utils.double_min);
            foreach (Layer layer in layerlist)
            {
                if (!layer.visible)
                {
                    continue;
                }

                Geometry.Rectangle layerrect = layer.getEnvelopofLayer();
                // if(layer.featuresource.schema.rs.spetialReference.)///////////////?????????????此处判断数据坐标系统与map坐标系统是否一致,如果不一致,需要转换
                //layerrect = transform...
                ReferenceSystem rs        = layer.getReference();
                RSTransform     transform = RSTransformFactory.getRSTransform(rs, this.srs);
                PointD          minxy     = transform.sourceToTarget(new PointD(layerrect.minX, layerrect.minY));
                PointD          maxxy     = transform.sourceToTarget(new PointD(layerrect.maxX, layerrect.maxY));

                if (minxy.X < rect.minX)
                {
                    rect.minX = minxy.X;
                }
                if (maxxy.X > rect.maxX)
                {
                    rect.maxX = maxxy.X;
                }
                if (minxy.Y < rect.minY)
                {
                    rect.minY = minxy.Y;
                }
                if (maxxy.Y > rect.maxY)
                {
                    rect.maxY = maxxy.Y;
                }
            }
            return(rect);
        }
示例#17
0
 private void обчисленняЗаВихідноюМоделлюToolStripMenuItem_Click(object sender, EventArgs e)
 {
     tabControl1.SelectedTab = tabControl1.TabPages[1];
     this.Refresh();
     var task = Task.Factory.StartNew(() => {
         addText("Обчислення розпочато...\r\n");
         string file     = SphericalHarmonicAnalyze.Properties.Settings.Default.inGravityModel;
         GravityModel gm = new GravityModel(SphericalHarmonicAnalyze.Properties.Settings.Default.modelMaxOrder);
         gm.loadFromFile(SphericalHarmonicAnalyze.Properties.Settings.Default.inGravityModel, new setProgressDel(addVal));
         ReferenceSystem elipsoid                 = new ReferenceSystem(ReferenceSystem.Default.WGS84);
         elipsoid.gridParameters.cellSize         = SphericalHarmonicAnalyze.Properties.Settings.Default.GridCellSize;
         elipsoid.gridParameters.coLatitudeBounds = SphericalHarmonicAnalyze.Properties.Settings.Default.minCoLatitude;
         elipsoid.maxDegree = SphericalHarmonicAnalyze.Properties.Settings.Default.modelMaxOrder;
         int greedColumnsCount, greedRowsCount;
         List <double[]> greed = MathFunc.generateGrid(elipsoid.gridParameters.cellSize, out greedColumnsCount, out greedRowsCount, elipsoid.gridParameters.coLatitudeBounds);
         double[] h            = GravityModel.getGeoidHeight(elipsoid, gm, greed);
         double[] dg           = GravityModel.getAnomaly(elipsoid, gm, greed);
         IOFunc.writeGeoidHeightsAndAnomalysToTxt(greed, h, dg, elipsoid, file + "B_L_N_dg.txt");
         addText("Готово...\r\nРезультати записано в файл: " + file + "B_L_N_dg.txt");
     });
 }
示例#18
0
        private void FilterInfos()
        {
            // 回收引用
            ReferenceSystem.Release(_cacheInfos);

            // 清空列表
            _cacheInfos.Clear();

            // 绘制显示列表
            var fileLoaders = AssetSystem.DebugAllLoaders();

            _loaderTotalCount = fileLoaders.Count;
            foreach (var loader in fileLoaders)
            {
                // 只搜索关键字
                if (string.IsNullOrEmpty(_filterKey) == false)
                {
                    if (loader.LoadPath.Contains(_filterKey) == false)
                    {
                        continue;
                    }
                }

                string info = Substring(loader.LoadPath, "/assets/");
                info = info.Replace(".unity3d", string.Empty);
                info = $"{info} = {loader.RefCount}";

                InfoWrapper element = ReferenceSystem.Spawn <InfoWrapper>();
                element.Info                = info;
                element.LoadState           = loader.States;
                element.ProviderFailedCount = loader.GetFailedProviderCount();

                // 添加到显示列表
                _cacheInfos.Add(element);
            }

            // 重新排序
            _cacheInfos.Sort();
        }
示例#19
0
	//========================================================================

	#region Public Methods

	public virtual void Init(Transform refTransform, RagdollSetup setup, ReferenceSystem  refSystem = null)
	{
		Setup = setup;
		ReferenceSystem = refSystem;
		IsTeleporting = false;

		_pelvis.Init(this);

		var refNodes = refTransform.GetComponentsInChildren<Transform>(true);
		for(int i = 0; i < refNodes.Length; ++i)
		{
			Debug.Assert(i == 0 || _nodes[i].name == refNodes[i].name, 
				"Ragdoll::Init>> Hierarchy does not match: " 
				+ _nodes[i].name + " VS " + refNodes[i].name, gameObject);

			if (!_nodes[i].name.Contains(_eyebrowKeyWord)) { // TODO FRS 161027 Mejorar con hashSet configurable (blacklist)
				_nodes[i].localPosition=refNodes[i].localPosition;
				_nodes[i].localRotation=refNodes[i].localRotation;
			}
		}

		gameObject.SetActive(true);
	}
        /// <summary>
        /// Creates a transformation strategy between reference systems.
        /// </summary>
        /// <param name="source">The source.</param>
        /// <param name="target">The target.</param>
        /// <returns>The produced transformation strategy.</returns>
        /// <exception cref="System.NotSupportedException">Conversion is not supported between the specified coordinate reference systems.</exception>
        public static ITransformationStrategy CreateStrategy(ReferenceSystem source, ReferenceSystem target)
        {
            ITransformationStrategy <Coordinate, GeoCoordinate>    conversionToGeographic   = null;
            ITransformationStrategy <GeoCoordinate, GeoCoordinate> transformation           = null;
            ITransformationStrategy <GeoCoordinate, Coordinate>    conversionFromGeographic = null;

            switch (source.Type)
            {
            case ReferenceSystemType.Projected:
                conversionToGeographic = new ReverseProjectionStrategy(source as ProjectedCoordinateReferenceSystem);
                break;

            case ReferenceSystemType.Geographic2D:
            case ReferenceSystemType.Geographic3D:
                conversionToGeographic = CreateReverseConversion(source as CoordinateReferenceSystem);
                break;
            }

            switch (target.Type)
            {
            case ReferenceSystemType.Projected:
                conversionFromGeographic = new ForwardProjectionStrategy(target as ProjectedCoordinateReferenceSystem);
                break;

            case ReferenceSystemType.Geographic2D:
            case ReferenceSystemType.Geographic3D:
                conversionFromGeographic = CreateForwardConversion(target as CoordinateReferenceSystem);
                break;
            }

            // if no transformation is needed
            if (conversionFromGeographic.TargetReferenceSystem.Equals(conversionToGeographic.SourceReferenceSystem))
            {
                return(new ConversionStrategy(conversionToGeographic, conversionFromGeographic));
            }

            // load matching forward transformation
            IList <GeographicTransformation> transformations = GeographicTransformations.FromReferenceSystems(conversionToGeographic.TargetReferenceSystem as GeographicCoordinateReferenceSystem,
                                                                                                              conversionFromGeographic.SourceReferenceSystem as GeographicCoordinateReferenceSystem);

            if (transformations.Count > 0)
            {
                transformation = new ForwardGeographicStrategy(conversionToGeographic.TargetReferenceSystem as GeographicCoordinateReferenceSystem,
                                                               conversionFromGeographic.SourceReferenceSystem as GeographicCoordinateReferenceSystem,
                                                               transformations[0]);
                return(new CompoundTransformationStrategy(conversionToGeographic, transformation, conversionFromGeographic));
            }

            // if none found, load matching reverse transformation
            transformations = GeographicTransformations.FromReferenceSystems(conversionFromGeographic.SourceReferenceSystem as GeographicCoordinateReferenceSystem,
                                                                             conversionToGeographic.TargetReferenceSystem as GeographicCoordinateReferenceSystem);
            if (transformations.Count > 0)
            {
                transformation = new ReverseGeographicStrategy(conversionToGeographic.TargetReferenceSystem as GeographicCoordinateReferenceSystem,
                                                               conversionFromGeographic.SourceReferenceSystem as GeographicCoordinateReferenceSystem,
                                                               transformations[0]);
                return(new CompoundTransformationStrategy(conversionToGeographic, transformation, conversionFromGeographic));
            }

            throw new NotSupportedException("Conversion is not supported between the specified coordinate reference systems.");
        }
示例#21
0
 public static void checkMap(double[][] SGG_data, List <int>[] map, List <double[]> greed, ReferenceSystem el)
 {
     Parallel.For(0, map.Length, (i) =>
     {
         if (map[i].Count > 0)
         {
             foreach (int p in map[i])
             {
                 double d_phi = greed[i][0] - SGG_data[p][1];
                 double d_lam = greed[i][1] - SGG_data[p][2];
                 if (d_phi > MathFunc.deg2rad(el.gridParameters.cellSize) || d_lam > MathFunc.deg2rad(el.gridParameters.cellSize))
                 {
                     System.Windows.Forms.MessageBox.Show(string.Format("F**k!\r\np{0},l{1}__{2}", MathFunc.rad2deg(d_phi), MathFunc.rad2deg(d_lam), i));
                 }
             }
         }
         ;
     });
 }
示例#22
0
        private void button4_Click(object sender, EventArgs e)
        {
            Action fileProc = () =>
            {
                System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
                MathNet.Numerics.Control.LinearAlgebraProvider         = new MathNet.Numerics.Algorithms.LinearAlgebra.Mkl.MklLinearAlgebraProvider();
                MathNet.Numerics.Control.NumberOfParallelWorkerThreads = Environment.ProcessorCount;
                addText("Обробка файлу вимірювань...\r\n");
                double[][] SGG_data = null;
                if (System.IO.File.Exists("sgg_data.bin"))
                {
                    SGG_data = IOFunc.binLoad_SGG_data("sgg_data.bin");
                }
                else
                {
                    SGG_data = Data.IOFunc.read_SGG_data(SphericalHarmonicAnalyze.Properties.Settings.Default.SGG_measures, new setProgressDel(addVal));
                    IOFunc.binwrite_SGG_data("sgg_data.bin", SGG_data);
                }
                addText("Дані вимірювань оброблено: {0} шт.\r\n", SGG_data.Length); Thread.Sleep(500);
                ReferenceSystem elipsoid = new ReferenceSystem(ReferenceSystem.Default.TideFree);
                elipsoid.gridParameters.cellSize         = SphericalHarmonicAnalyze.Properties.Settings.Default.GridCellSize;
                elipsoid.gridParameters.coLatitudeBounds = SphericalHarmonicAnalyze.Properties.Settings.Default.minCoLatitude;
                elipsoid.maxDegree = SphericalHarmonicAnalyze.Properties.Settings.Default.modelMaxOrder;
                int             greedColumnsCount, greedRowsCount;
                List <double[]> greed = MathFunc.generateGrid(elipsoid.gridParameters.cellSize, out greedColumnsCount, out greedRowsCount, elipsoid.gridParameters.coLatitudeBounds, 180 - elipsoid.gridParameters.coLatitudeBounds);
                addText("Сітку згенеровано: {0} комірок \r\n", greed.Count);
                double       avgR = MathFunc.getAvgRadius(SGG_data);
                List <int>[] map  = MathFunc.getMappingOfPoints(elipsoid, SGG_data, greed.ToArray(), greedRowsCount, greedColumnsCount, avgR); sw.Stop(); addText("Точки віднесено до комірок сітки за: {0}.\r\n", sw.Elapsed.ToString());
                addText("Кількість клітинок сітки всього: {0}\r\n", greed.Count);
                int res1 = 0; foreach (var item in map)
                {
                    res1 += item.Count;
                }
                addText("Використано вимірів: {0}\r\nСер радіус: {1}\r\n", res1, avgR);
                test.checkMap(SGG_data, map, greed, elipsoid);
                List <int>[] newMap = null;
                MathFunc.checkGreed(ref greed, map, out newMap);
                addText("Кількість клітинок сітки, в яких присутні дані вимірювань: {0}\r\n", greed.Count);
                map = newMap; newMap = null;
                IOFunc.writeGreedToCsvFileWithMeasureCount(greed, map, "greed_new_map.txt");
                double[] avgRadius; sw.Restart();
                double[] regularisedValues = MathFunc.regularization(SGG_data, greed.ToArray(), map, out avgRadius); sw.Stop(); addText("Регуляризація (на основі сферичної відстані) виконана за: {0}.\r\n", sw.Elapsed.ToString());
                IOFunc.writeGreedToCsvFileWithMeasureS(greed, regularisedValues, "greed_regular_grad.txt");
                avgRadius[0]             = Math.Round(avgRadius[0]);
                elipsoid.satelliteSphere = avgRadius[0];
                addText("Середній радіус: {0,10:0.000}.\r\nМінімальний радіус: {1,10:0.0000}\r\nМаксимальний радіус:{2,10:0.0000}\r\n", avgRadius[0], avgRadius[1], avgRadius[2]);
                SGG_data = null; map = null;
                int[][] t_nm = MathFunc.get_nm(elipsoid.maxDegree);
                sw.Restart();
                MathNet.Numerics.LinearAlgebra.Double.DenseMatrix dm = new MathNet.Numerics.LinearAlgebra.Double.DenseMatrix(greed.Count, (MathFunc.getArraySize(elipsoid.maxDegree) - 3) * 2 - (elipsoid.maxDegree - 1));
                sw.Stop(); addText("Пам'ять для матриці коефіцієнтів виділено за: {0}.\r\n", sw.Elapsed.ToString());
                sw.Restart();
                int progress = 0;
                //Обчислення елементів матриці
                var p = Parallel.For(0, dm.RowCount, (i) =>
                {
                    double[] line = MathFunc.getCoefMatrixLineKoop(elipsoid, elipsoid.maxDegree, t_nm, elipsoid.satelliteSphere, greed[i][0], greed[i][1]);
                    lock (dm)
                    {
                        dm.SetRow(i, line);
                    }
                    progress++;
                    if (progress / 100D == Math.Round(progress / 100D))
                    {
                        addVal(progress, dm.RowCount, "Визначено");
                    }
                });

                if (!p.IsCompleted)
                {
                    throw new Exception("Parallel.For");
                }
                ;
                IOFunc.writeMatrixToMatLabFile(dm, @"matlab\A.mat", "A");
                sw.Stop();
                richTextBox1.Invoke(new setProgressDel(addVal), new object[] { 0, dm.RowCount, "" });
                addText("Матриця {0} на {1} ({2}MB) згенерована за: {3,10}\r\n", dm.RowCount, dm.ColumnCount, dm.ColumnCount * dm.RowCount * 8 / 1000000, sw.Elapsed.ToString() /* + "\r\nЗапис у файл...\r\n"*/);
                if (true)
                {
                    GravityModel gm08 = new GravityModel(elipsoid.maxDegree);
                    gm08.loadFromFile("GO_CONS_EGM_GCF_2.gfc", new setProgressDel(addVal));
                    MathNet.Numerics.LinearAlgebra.Double.DenseVector dmL = new MathNet.Numerics.LinearAlgebra.Double.DenseVector(gm08.getGradientForGrid(elipsoid, greed));//regularisedValues);
                    MathNet.Numerics.LinearAlgebra.Double.DenseVector dmL2;
                    GravityModel gm = new GravityModel(elipsoid.maxDegree);
                    if (radioButton1.Checked)
                    {
                        sw.Restart();
                        gm.loadFromFile(SphericalHarmonicAnalyze.Properties.Settings.Default.inGravityModel, new setProgressDel(addVal));
                        sw.Stop(); addText("Вихідна модель завантажена за: {0}.\r\n", sw.Elapsed.ToString());
                        sw.Restart();
                        dmL2 = new MathNet.Numerics.LinearAlgebra.Double.DenseVector(gm.getGradientForGrid(elipsoid, greed));
                        sw.Stop(); addText("Градієнти за вихідною моделлю обчислені для сітки за: {0}.\r\n", sw.Elapsed.ToString());
                    }
                    else
                    {
                        sw.Restart();
                        gm   = GravityModel.getNormalModel(elipsoid, elipsoid.maxDegree);
                        dmL2 = new MathNet.Numerics.LinearAlgebra.Double.DenseVector(gm.getGradientForGrid(elipsoid, greed));
                        sw.Stop(); addText("Нормальні градієнти обчислені для сітки за: {0}.\r\n", sw.Elapsed.ToString());
                    }
                    dmL  = dmL - dmL2;
                    dmL2 = null;
                    IOFunc.writeMatrixToMatLabFile(dmL.ToColumnMatrix(), @"matlab\L.mat", "L");
                    sw.Restart();
                    MathNet.Numerics.LinearAlgebra.Double.DenseVector dmLNormal = null;
                    dmLNormal = (MathNet.Numerics.LinearAlgebra.Double.DenseVector)dm.TransposeThisAndMultiply(dmL);
                    dmL       = null;
                    IOFunc.writeMatrixToMatLabFile(dmLNormal.ToColumnMatrix(), @"matlab\LNorm.mat", "LNorm");
                    sw.Stop(); addText("Стовпчик вільних членів обчислений за: {0}.\r\n", sw.Elapsed.ToString());
                    MathNet.Numerics.LinearAlgebra.Double.DenseMatrix dmANorm = null;
                    sw.Restart();
                    dmANorm = (MathNet.Numerics.LinearAlgebra.Double.DenseMatrix)dm.TransposeThisAndMultiply(dm); dm = null;
                    sw.Stop(); addText("Нормальна матриця коефіціэнтів обчислена за: {0}.\r\n", sw.Elapsed.ToString());
                    IOFunc.writeMatrixToMatLabFile(dmANorm, @"matlab\ANorm.mat", "ANorm");
                    //dmLNormal = (MathNet.Numerics.LinearAlgebra.Double.DenseVector)dmLNormal.Multiply(5e-8);
                    var x   = dmANorm.Inverse();
                    var res = (MathNet.Numerics.LinearAlgebra.Double.DenseVector)x.Multiply(dmLNormal);
                    IOFunc.writeModeVectorlToTxtFile(res, elipsoid, @"matlab\_out.AL");
                    addText(@"Результат за методом A\L знайдено...");
                    x = null;
                    GravityModel gm_R = new GravityModel(gm);
                    gm_R.addDeltaCoef(res.ToArray()); res = null;
                    double[] h  = GravityModel.getGeoidHeight(elipsoid, gm_R, greed);
                    double[] dg = GravityModel.getAnomaly(elipsoid, gm_R, greed);
                    IOFunc.writeGeoidHeightsAndAnomalysToTxt(greed, h, dg, elipsoid, @"output\result_AL.txt");
                    IOFunc.writeGravityModelToTxtFile(gm_R, @"output\model_AL.gcf");
                    sw.Restart();
                    addText(dmANorm.Rank().ToString() + "\r\n");
                    dmANorm   = null;
                    dmLNormal = null;
                    sw.Stop(); addText("Невідомі знайдено за: {0}.\r\n", sw.Elapsed.ToString());
                }
            };

            if (System.IO.File.Exists(SphericalHarmonicAnalyze.Properties.Settings.Default.inGravityModel))
            {
                tabControl1.SelectedTab = tabControl1.TabPages[1];
                this.UseWaitCursor      = true;
                ts  = new CancellationTokenSource();
                ct  = ts.Token;
                tsk = Task.Factory.StartNew(fileProc, ct);
                var setCur = Task.Factory.StartNew(() => { tsk.Wait(); this.UseWaitCursor = false; addText("Обчислення завершені!"); });
                richTextBox1.SaveFile(@"output\zvit.rtf");
            }
        }
示例#23
0
    public static void Save()
    {
        GeneralExecution general = SceneGlobals.general;

        System.DateTime t0 = System.DateTime.Now;
        DataStructure   save_datastructure = new DataStructure();

        DataStructure general_information = new DataStructure("GeneralInformation", save_datastructure);

        general_information.Set("original_path", general.battle_path);
        general_information.Set("in level progress", (int)general.mission_core.in_level_progress);
        general_information.Set("in stage progress", (int)general.mission_core.in_stage_progress);

        ReferenceSystem ref_sys = SceneGlobals.ReferenceSystem;

        if (ref_sys.HasParent)
        {
            general_information.Set("RS offset", ref_sys.Offset);
            general_information.Set("RS parent", ref_sys.ref_obj.ID);
        }
        else
        {
            general_information.Set("RS position", ref_sys.Position);
        }

        SceneObject[]       scene_array     = new SceneObject[SceneObject.TotObjectList.Count];
        Explosion[]         explosion_array = new Explosion[SceneGlobals.explosion_collection.Count];
        Bullet[]            bullet_array    = new Bullet[SceneGlobals.bullet_collection.Count];
        DestroyableTarget[] target_array    = new DestroyableTarget[SceneGlobals.destroyables.Count];

        SceneObject.TotObjectList.Values.CopyTo(scene_array, 0);
        SceneGlobals.bullet_collection.CopyTo(bullet_array);
        SceneGlobals.destroyables.CopyTo(target_array);

        scene_array = System.Array.FindAll(scene_array,
                                           x =>
                                           !(x is Missile && !(x as Missile).Released) &&
                                           !(x is Network && (x as Network).Name == "\"friendly rogue\"-Network" | (x as Network).Name == "\"hostile rogue\"-Network") &&
                                           !(x is Target)
                                           );

        ISavable[] savable_objects = new ISavable[scene_array.Length +
                                                  explosion_array.Length +
                                                  bullet_array.Length +
                                                  target_array.Length];

        int indx = 0;

        System.Array.ConvertAll(scene_array, x => x as ISavable).CopyTo(savable_objects, indx);
        indx += scene_array.Length;
        System.Array.ConvertAll(explosion_array, x => x as ISavable).CopyTo(savable_objects, indx);
        indx += explosion_array.Length;
        System.Array.ConvertAll(bullet_array, x => x as ISavable).CopyTo(savable_objects, indx);
        indx += bullet_array.Length;
        System.Array.ConvertAll(target_array, x => x as ISavable).CopyTo(savable_objects, indx);

        DataStructure object_states = new DataStructure("ObjectStates", save_datastructure);

        foreach (ISavable obj in savable_objects)
        {
            if (obj != null)
            {
                DataStructure ds = new DataStructure(obj.Name, object_states);
                obj.Save(ds);
            }
        }

        //save_datastructure.Save("saved/Saves/" + System.DateTime.Now.ToString("dd_MM_yyyy_hh_mm_ss"));
        save_datastructure.Save("saved/Saves/def_save");
        DeveloppmentTools.LogFormat("Saved: {0} ms", (System.DateTime.Now - t0).Milliseconds.ToString());
    }
示例#24
0
    public static void Load(string path)
    {
        DataStructure saved = DataStructure.Load(path);
        DataStructure general_information = saved.GetChild("GeneralInformation");
        DataStructure original_file       = DataStructure.Load(general_information.Get <string>("original_path"), is_general: true);

        FileReader.FileLog("Begin Loading", FileLogType.loader);
        GameObject       placeholder = GameObject.Find("Placeholder");
        GeneralExecution general     = placeholder.GetComponent <GeneralExecution>();

        general.battle_path = path;

        // Initiate Operating system
        general.os = new NMS.OS.OperatingSystem(Object.FindObjectOfType <ConsoleBehaviour>(), null);

        // Initiate mission core
        Loader partial_loader = new Loader(original_file);

        general.mission_core = new MissionCore(general.console, partial_loader);

        general.mission_core.in_level_progress = (short)general_information.Get <int>("in level progress");
        general.mission_core.in_stage_progress = (short)general_information.Get <int>("in stage progress");
        DeveloppmentTools.Log("start loading");
        partial_loader.LoadEssentials();

        DataStructure objects = saved.GetChild("ObjectStates");

        Debug.Log(objects);
        foreach (DataStructure child in objects.AllChildren)
        {
            int id = child.Get <ushort>("type", 1000, quiet: true);
            switch (id)
            {
            case 0:
                // Ship
                Dictionary <string, Turret[]> weapon_arrays = new Dictionary <string, Turret[]>();

                string     config_path  = child.Get <string>("config path");
                bool       is_friendly  = child.Get <bool>("friendly");
                bool       is_player    = child.Get <bool>("player");
                int        given_id     = child.Get <int>("id");
                GameObject ship_chassis = Loader.SpawnShip(config_path, is_friendly, is_player, false, pre_id: given_id);

                //LowLevelAI ai = Loader.EnsureComponent<LowLevelAI>(ship_chassis);
                //ai.HasHigherAI = !is_player;

                ShipControl ship_control = ship_chassis.GetComponent <ShipControl>();
                Ship        ship         = ship_control.myship;
                //ship.control_script.ai_low = ai;
                //ship.low_ai = ai;

                int netID = child.Get("parent network", is_friendly ? 1 : 2);
                if (SceneObject.TotObjectList.ContainsKey(netID) && SceneObject.TotObjectList [netID] is Network)
                {
                    ship.high_ai.Net = SceneObject.TotObjectList [netID] as Network;
                }

                ship.Position        = child.Get <Vector3>("position");
                ship.Orientation     = child.Get <Quaternion>("orientation");
                ship.Velocity        = child.Get <Vector3>("velocity");
                ship.AngularVelocity = child.Get <Vector3>("angular velocity");

                foreach (DataStructure child01 in child.AllChildren)
                {
                    switch (child01.Get <ushort>("type", 9, quiet:true))
                    {
                    case 1:                     // weapon
                        Weapon.GetFromDS(child01.GetChild("description"), child01, ship.Transform);
                        break;

                    case 3:                     // fuel tank
                        FuelTank.GetFromDS(child01.GetChild("description"), child01, ship.Transform);
                        break;

                    case 4:                     // engine
                        Engine.GetFromDS(child01.GetChild("description"), child01, ship.Transform);
                        break;

                    case 10:                     // ammo box
                        AmmoBox.GetFromDS(child01.GetChild("description"), child01, ship.Transform);
                        break;

                    case 11:                     // missile launcher
                        MissileLauncher.GetFromDS(child01.GetChild("description"), child01, ship.Transform);
                        break;

                    case 12:                     // armor
                        Armor.GetFromDS(child01, ship);
                        break;

                    default:
                        if (child01.Name.StartsWith("turr-"))
                        {
                            var tg = TurretGroup.Load(child01, ship);
                            weapon_arrays [child01.Name.Substring(5)] = tg.TurretArray;
                            ship_control.turretgroup_list.Add(new TurretGroup(Target.None, tg.TurretArray, tg.name)
                            {
                                own_ship = ship
                            });
                        }
                        break;
                    }
                }


                // Initializes parts
                foreach (BulletCollisionDetection part in ship_chassis.GetComponentsInChildren <BulletCollisionDetection>())
                {
                    part.Initialize();
                }
                ship_control.turrets = weapon_arrays;

                ship.os.cpu.Execute(child.Get <ulong []>("code"));

                if (is_player)
                {
                    SceneGlobals.Player = ship;
                    SceneGlobals.ui_script.Start_();
                }

                break;

            case 1:             // Missile
                Missile.SpawnFlying(child);
                break;

            case 2:             // Bullet
                Bullet.Spawn(
                    Globals.ammunition_insts [child.Get <string>("ammunition")],
                    child.Get <Vector3>("position"),
                    Quaternion.FromToRotation(Vector3.forward, child.Get <Vector3>("velocity")),
                    child.Get <Vector3>("velocity"),
                    child.Get <bool>("is_friend")
                    );
                break;

            case 3:             // Destroyable target
                DestroyableTarget.Load(child);
                break;

            case 4:             // Explosion

                break;
            }
        }

        general.os.Attached = SceneGlobals.Player;

        ReferenceSystem ref_sys;

        if (general_information.Contains <Vector3>("RS position"))
        {
            ref_sys = new ReferenceSystem(general_information.Get <Vector3>("RS position"));
        }
        else
        {
            int parent_id = general_information.Get <int>("RS parent");
            if (SceneObject.TotObjectList.ContainsKey(parent_id))
            {
                ref_sys = new ReferenceSystem(SceneObject.TotObjectList [parent_id]);
            }
            else
            {
                ref_sys = new ReferenceSystem(Vector3.zero);
            }
            ref_sys.Offset = general_information.Get <Vector3>("RS offset");
        }
        SceneGlobals.ReferenceSystem = ref_sys;
    }
示例#25
0
    ///<summary> This should be called from the third frame on </summary>
    private void BattleSymbolsUpdate()
    {
        // Defines Target
        Target          target  = player_script.target;
        ReferenceSystem ref_sys = SceneGlobals.ReferenceSystem;

        // Projects the player's "absolute" velocity (relative to the origin of the scene)
        if (PlayerShip != null && ref_sys.RelativeVelocity(PlayerShip.Velocity) != Vector3.zero)
        {
            Image prog = pointers["prograde_marker"];
            ProjectVecOnScreen(ref_sys.RelativeVelocity(PlayerShip.Velocity), camera_transform, ref prog);
        }

        // Projects the players relative velocity to his selected target
        if (target.Exists)
        {
            if (!target.virt_ship)
            {
                if (PlayerShip.Velocity - target.Ship.Velocity != Vector3.zero)
                {
                    Image tgt_vel = pointers["target_velocity_marker"];
                    ProjectVecOnScreen(PlayerShip.Velocity - target.Ship.Velocity, camera_transform, ref tgt_vel);
                }
            }
        }

        // Weapon indicators
        foreach (Weapon w in PlayerShip.Parts.GetAll <Weapon>())
        {
            Image   img     = weapon_states[w];
            Vector3 new_pos = MainCam.WorldToScreenPoint(player_transform.position + (player_transform.forward * 100000));
            new_pos.z = 0;
            img.rectTransform.position = new_pos;
            if (w.ooo_time > 0)
            {
                float ratio = 1 - (w.ooo_time / w.init_ooo_time) * .75f;
                img.color = new Color(ratio, ratio, ratio);
            }
            else
            {
                img.color = new Color(1f, 1 - w.heat, 1 - w.heat);
            }
        }

        // Turret Indicators
        foreach (Turret t in PlayerShip.Parts.GetAll <Turret>())
        {
            Image   img     = turret_states[t];
            Vector3 new_pos = MainCam.WorldToScreenPoint(transform.position + (t.BarrelRot * Vector3.forward * 100000f));
            new_pos.z = 0;
            img.rectTransform.position = new_pos;
            if (t.ooo_time > 0)
            {
                float ratio = 1 - (t.ooo_time / t.init_ooo_time) * .75f;
                img.color = new Color(ratio, ratio, ratio);
            }
            else
            {
                img.color = new Color(1f, 1 - t.heat, 1 - t.heat);
            }
        }

        // Draws the "direction pointer" (the velocity direction)
        Vector3 direction_projection = direction == Vector3.zero ? new Vector3(-200, -200) : MainCam.WorldToScreenPoint(direction + transform.position);

        direction_projection.z = 0;
        pointers ["direction_pointer"].transform.position = direction_projection;

        Vector3 velocity_dir = PlayerShip.Velocity == Vector3.zero ? new Vector3(-200, -200) : MainCam.WorldToScreenPoint(PlayerShip.Position + PlayerShip.Velocity.normalized * 1e9f);

        velocity_dir.z = 0;
        pointers ["prograde"].transform.position = velocity_dir;
        pointers ["prograde"].color = Vector3.Angle(PlayerShip.Velocity, camera_transform.forward) < 90f ? Color.green : Color.red;


        if (player_script.target != null)
        {
            if (player_script.target.Exists)
            {
                tgting_point = player_script.target.Position;
            }
        }

        if (group_follows_cursor)
        {
            if (current_group != null)
            {
                current_group.SetTgtDir(CursorWorldDirection);
            }
        }
    }