Inheritance: MonoBehaviour
        public void RecalulateLocationTest()
        {
            var t0 = new DateTime(2013, 7, 17, 0, 0, 0); // UTC
            EPuzzleTime.Now = t0;
            var star = new Star()
            {
                Left = 100f,
                Top = 10f,
                Velocity = 10d,
                Acceleration = 10d,
                Radian = 0d,
            };
            Assert.AreEqual(EPuzzleColors.ShootingStars, star.Color);
            Assert.AreEqual(t0, star.StartTime);
            //			Assert.AreEqual(20d, star.Width);
            //			Assert.AreEqual(20d, star.Height);

            star.Recalculate();
            Assert.AreEqual(100f, star.BorderLeft);
            Assert.AreEqual(10f, star.BorderTop);

            EPuzzleTime.Now += TimeSpan.FromSeconds(1d);
            star.Recalculate();
            Assert.AreEqual(110f, star.BorderLeft);
            Assert.AreEqual(15f, star.BorderTop);
        }
Example #2
0
 public void SetCurrentStar(Star star)
 {
     if (currentStar) {
         currentStar.HidePlanetarySystem();
     }
     currentStar = star;
 }
Example #3
0
    // Use this for initialization
    void Start()
    {
        Material earthMaterial = Resources.Load("Materials/Earth/Earth") as Material;
        Material sunMaterial = Resources.Load("Materials/Sun") as Material;
        Material moonMaterial = Resources.Load("Materials/Moon/Moon") as Material;

        Star sun = new Star("Sun", new Vector3(0,0,0), 10, sunMaterial);
        IList planets = new ArrayList();

        for(int i = 0; i < 10; i++) {
            // TODO Change x/z random to randomize within a radius of sun instead of square
            int x = Random.Range(-200, 200);
            int y = 0;
            int z = Random.Range(-200, 200);
            float r = Random.Range(1, 4);
            float spinSpeed = Random.Range(-20, 21);

            Planet p = new Planet("Planet" + i, new Vector3(x, y, z), r, earthMaterial, spinSpeed, sun);
            planets.Add(p);

            int nSatellites = Random.Range(0, 4);
            for(int j = 0; j < nSatellites; j++) {
                float d = Random.Range(2*r, 8*r);
                Vector3 satellitePosition = new Vector3(x+d, y, z);
                float satelliteRadius = (float)Random.Range(r, r*5) / 10;
                float satelliteSpinSpeed = Random.Range(-20, 21);
                p.addSatellite("Satellite"+j+p.name,satellitePosition, satelliteRadius, moonMaterial, satelliteSpinSpeed);
            }
        }

        startUI();
    }
Example #4
0
	/// <summary>
	/// Creates an instance of star prefab. Stars will be placed according to the info that has been stored 
	/// in this class. If something will be added upon the stars then it should be hook into the star prefab.
	/// </summary>
	/// <param name="createStar">Star information.</param>
	public void CreateStar(Star createStar){
		// int starType = createStar.type;
		int starType = 0; // REMOVE THIS AFTER STAR TYPES ARE ADDED TO DB FOR DIFFERENT ICONS
		Sprite starSprite = starSprites[starType];

		string starName = createStar.starInfo.name;	
		//string starInfo = createStar.info;
		string starInfo = "Tita"; // REMOVE THIS AFTER STAR TYPES ARE ADDED TO DB FOR DIFFERENT ICONS

		int starX = createStar.starInfo.coordinates [0];
		int starY = createStar.starInfo.coordinates[1];

		GameObject newStar = (GameObject)Instantiate (starPrefab, new Vector3 (starX, starY, 0), Quaternion.identity);
		newStar.name = starName;
		//newStar.GetComponent<Starx>().starName = starName; //Obsolete

		// Attached components unto the prefab.
		newStar.GetComponent<Star>().starInfo = createStar.starInfo;
		newStar.GetComponent<SpriteRenderer> ().sprite = starSprite;
		newStar.GetComponent<BoxCollider>().size = starSprite.bounds.size / 2;  //For some reason, this doesn't take scale into account

		textObject = newStar.GetComponentInChildren<TextMesh> ();
		textObject.text = "\t" + newStar.name +
						"\n\t" + starInfo;
		textObject.color = Color.cyan;
	}
Example #5
0
 protected override AvailableEffects InitializeEffect(GraphicsDevice device, Star.GameManagement.Options options)
 {
     height_to_width = (float)options.ScreenHeight / (float)options.ScreenWidth;
     screenwidth = options.ScreenWidth;
     screenheight = options.ScreenHeight;
     return AvailableEffects.Wave;
 }
Example #6
0
        public SpaceGame(GraphicsDevice graphicsDevice)
        {
            this.graphicsDevice = graphicsDevice;
            sb = new SpriteBatch(graphicsDevice);

            pushAlienTimer = 0;

            killCount = 0;

            stars = new Star[100];
            for (int i = 0; i < 100; i++)
            {
                stars[i] = new Star(Game1.GameRandom.Next() % 3000);
            }

            ein = Game1.ein;

            aliens = new List<Alien>();
            bullets = new List<PlayerBullet>();
            particles = new List<Particle>();

            for (int i = 0; i < 4; i++)
            {
                aliens.Add(new Alien(this));
            }
        }
Example #7
0
    // Use this for initialization
    void Start()
    {
        stars = new Star[numStars];

        //Create a game object to hold all of the stars
        GameObject starContainer = new GameObject ();
        starContainer.name = "Stars";
        starContainer.transform.parent = transform;

        GameObject star = (GameObject)Resources.Load ("Prefabs/Star", typeof(GameObject));

        float minX = -10;
        float maxX = 10;
        float minY = -10;
        float maxY = 10;

        for (int i = 0; i < stars.Length; i++) {
            stars[i] = new Star();
            Vector2 starPos = new Vector2(
                    Random.Range (minX, maxX),
                    Random.Range (minY, maxY)
                );

            GameObject newStar = (GameObject)Instantiate (star, new Vector2(0, 0), Quaternion.identity);

            stars[i].init (newStar, starPos, starContainer.transform);
            stars[i].setStarLayer(starLayer);
        }
    }
Example #8
0
        protected override void UpdateLayer(GameTime gametime, Vector2 player_difference,Star.GameManagement.Options options,Vector2 relativePosition)
        {
            foreach (LayerObject lo in LayerObjects)
            {
                lo.Position -= new Vector2(lo.SpecialValue * (float)gametime.ElapsedGameTime.TotalSeconds,0);
                lo.Position -= new Vector2(player_difference.X, 0);

                if (lo.Rectangle.Right < 0)
                {
                    lo.Position = new Vector2(options.ScreenWidth,
                        getRandom(0,(int)(options.ScreenHeight * PercentageOfScreen)));
                    lo.SpecialValue = getRandom(20, 80);
                    lo.SpecialValue2 = (float)getRandom(0, 6000) / 3000f;
                    lo.SpecialValue3 = (float)getRandom(500, 3000) / 1000f;
                }
                else if (lo.Rectangle.Left > options.ScreenWidth)
                {
                    lo.Position = new Vector2(-lo.Rectangle.Width,
                        getRandom(0,(int)(options.ScreenHeight * PercentageOfScreen)));
                    lo.SpecialValue = getRandom(20, 80);
                    lo.SpecialValue2 = (float)getRandom(0, 6000) / 3000f;
                    lo.SpecialValue3 = (float)getRandom(500, 3000) / 1000f;
                }
                lo.SpecialValue2 += lo.SpecialValue3* (float)gametime.ElapsedGameTime.TotalSeconds;
                if (lo.SpecialValue2 >= 2 * MathHelper.Pi)
                {
                    lo.SpecialValue2 = 0;
                }
                lo.Rectangle = new Rectangle(lo.SpecialRect.X, (int)(lo.SpecialRect.Y + Math.Sin(lo.SpecialValue2) * 10), lo.SpecialRect.Width, (int)(lo.SpecialRect.Height +10 * -Math.Sin(lo.SpecialValue2)));
            }
        }
Example #9
0
        public static Planet CreatePlanet(ref Star star, int seed = 0)
        {
            /*
            var go = (GameObject.Instantiate(Resources.Load("Body")) as GameObject);
            if (go == null) return null;
            var p = go.AddComponent<Planet>();

            var rand = seed == 0 ? new Random() : new Random(seed);

            p._orbitalInfo.parentBody = star;
            p.Randomise(ref rand);

            var mesh = go.GetComponentInChildren<MeshPlane>();

            BuildSurfaceMesh(ref mesh, ref rand);

            mesh.Size = 1.0f;// p.Mass * 0.1f;
            //var height = (float)p.Mass / p.MaxMass;
            //TODO: These will need set.
            //mesh.gameObject.renderer.material.SetFloat("Height", height);
            //mesh.gameObject.renderer.material.SetVector("ColorA", Color.white);
            //mesh.gameObject.renderer.material.SetVector("ColorB", Color.black);

            mesh.Build();

            star.Add(p);

            return p;
            */
            return null;
        }
Example #10
0
 public void LikeStar(Star star)
 {
     Console.ForegroundColor = ConsoleColor.White;
     Console.WriteLine($"Actor: {star.Name} ({star.Birthdate:yyyy-MM-dd}) by {star.Sender.Name} \r\n\t{star.Sender.ImageUrl}");
     Console.WriteLine();
     Console.ResetColor();
 }
Example #11
0
 private Star AddStar(Random random, Rectangle boundaries)
 {
     Star starToAdd = new Star();
     starToAdd.point = new Point(random.Next(0, boundaries.Width),
                                     random.Next(0, boundaries.Height));
     starToAdd.pen = RandomPen(random);
     return starToAdd;
 }
        public MilkyWay(string comment) : base(comment)
        {
            var rnd = new Random();
            _stars = new Star[30];

            for (int i = 0; i < _stars.Length; i++)
                _stars[i] = new Star(rnd);
        }
Example #13
0
        //RenderTarget2D target1;
        protected override AvailableEffects InitializeEffect(Microsoft.Xna.Framework.Graphics.GraphicsDevice device, Star.GameManagement.Options options)
        {
            PresentationParameters pp = device.PresentationParameters;
            //3_1
            //target1 = new RenderTarget2D(device, pp.BackBufferWidth, pp.BackBufferHeight, pp.BackBufferCount, pp.BackBufferFormat);

            return AvailableEffects.GaussianBlur;
        }
Example #14
0
 protected override void Awake() {
     base.Awake();
     _orbitalPlane = gameObject.GetSafeFirstMonoBehaviourInChildren<OrbitalPlaneInputEventRouter>();
     _systemGraphics = gameObject.GetSafeMonoBehaviour<SystemGraphics>();
     _star = gameObject.GetSafeFirstMonoBehaviourInChildren<Star>();
     _planetsAndMoons = gameObject.GetSafeMonoBehavioursInChildren<FollowableItem>();
     _eventMgr = GameEventManager.Instance;
     _selectionMgr = SelectionManager.Instance;
 }
Example #15
0
        public static Rectangle ReCenterSpecialRects(Star.Game.Enemy.SpecialRect rect,Point newCenter)
        {
            Rectangle temp = rect.Rectangle;
            temp.Location = new Point(
                newCenter.X + rect.OriginalRectangle.Location.X,
                newCenter.Y + rect.OriginalRectangle.Location.Y);

            return temp;
        }
Example #16
0
		public static void Main(string[] args)
		{
			ManualResetEvent Terminated = new ManualResetEvent(false);
			int i;

			Initialize();

			ForegroundColor = Color.Gray;
			Console.Out.WriteLine("Press LEFT or RIGHT to rotate.");
			Console.Out.WriteLine("Press ESC to quit.");

			OnKeyDown += (sender, e) =>
			{
				if (e.Key == Key.Escape || (e.Key == Key.C && e.Control))
					Terminated.Set();
			};

			xc = RasterWidth / 2;
			yc = RasterHeight / 2;
			d2 = (xc + 1) * (xc + 1) + (yc + 1) * (yc + 1);

			Star[] Stars = new Star[NrStars];
			for (i = 0; i < NrStars; i++)
				Stars[i] = new Star();

			OnUpdateModel += (sender, e) =>
			{
				Star Star;

				if (IsPressed(KeyCode.Left))
					vangle -= 0.001;

				else if (IsPressed(KeyCode.Right))
					vangle += 0.001;

				angle += vangle;

				m11 = Math.Cos(angle);
				m12 = -Math.Sin(angle);
				m21 = Math.Sin(angle);
				m22 = Math.Cos(angle);

				for (i = 0; i < NrStars; i++)
				{
					Star = Stars[i];
					if (!Star.Move())
						Stars[i] = new Star();
				}
			};

			while (!Terminated.WaitOne(1000))
				;

			Terminate();
		}
Example #17
0
    public static GameObject CreatePlanet(GameObject obj, string name, PlanetType type, Star host, int orbit, Vector3 pos, Quaternion quat)
    {
        obj = (GameObject)Instantiate(obj, pos, quat);
        host.AssignPlanet(obj.GetComponent<Planet>(), orbit);

        obj.AddComponent<Planet>();
        obj.GetComponent<Planet>().nickname = name;
        obj.GetComponent<Planet>().type = type;

        return obj;
    }
Example #18
0
 public override void GraphicsChanged(GraphicsDevice device, Star.GameManagement.Options options)
 {
     for (int i = 0; i < LayerObjects.Length; i++)
     {
         LayerObjects[i].Rectangle = new Rectangle(LayerObjects[i].Rectangle.X, LayerObjects[i].Rectangle.Y,
             (int)(100 * options.ScaleFactor),
             (int)(80 * options.ScaleFactor));
         LayerObjects[i].SpecialRect = new Rectangle(LayerObjects[i].Rectangle.X, LayerObjects[i].Rectangle.Y,
             (int)(100 * options.ScaleFactor),
             (int)(80 * options.ScaleFactor));
     }
 }
 public void Update(GameTime gameTime)
 {
     sinceLastSendt += gameTime.ElapsedGameTime.TotalSeconds;
     if(sinceLastSendt >= nextTime)
     {
         int startXPos = random.Next(0, game.Window.ClientBounds.Width);
         Star temp = new Star(game, new Vector2(startXPos, game.Window.ClientBounds.Height + 20), spriteBatch);
         objectManager.RegisterObject(temp);
         collisionManager.RegisterObject(temp);
         sinceLastSendt = 0;
         nextTime = random.Next(0, 10);
     }
 }
	void Start() {

		oneStar = Prefabs.CreateNewStar ().GetComponent<Star>();
		twoStar = Prefabs.CreateNewStar ().GetComponent<Star>();
		threeStar = Prefabs.CreateNewStar ().GetComponent<Star>();

		oneStar.pos.x = 193;
		oneStar.pos.y = 13;

		
		twoStar.pos.x = 214;
		twoStar.pos.y = 13;
		
		threeStar.pos.x = 236;
		threeStar.pos.y = 13;
	}
Example #21
0
 protected override void InitializeGraphX(Star.GameManagement.Options options,LevelVariables levelvariables)
 {
     string[] clouds = levelvariables.Dictionary[LV.CloudLayerImgs].Split(',');
     LayerObjects = new LayerObject[clouds.Length];
     for (int i = 0; i < LayerObjects.Length; i++)
     {
         LayerObjects[i] = new LayerObject(Content.Load<Texture2D>(GameManagement.GameConstants.GraphXPacksPath + levelvariables.Dictionary[LV.GraphXPack] + GraphXPath + clouds[i]),
             new Rectangle(getRandom(0, options.ScreenWidth),
                 getRandom(0, (int)(options.ScreenHeight * PercentageOfScreen)),
                 (int)(100*options.ScaleFactor),
                 (int)(80*options.ScaleFactor)));
         LayerObjects[i].SpecialRect = new Rectangle(LayerObjects[i].Rectangle.X,LayerObjects[i].Rectangle.Y,LayerObjects[i].Rectangle.Width,LayerObjects[i].Rectangle.Height);
         LayerObjects[i].SpecialValue = getRandom(20,80);
         LayerObjects[i].SpecialValue2 = (float)getRandom(0, 6000) / 3000f;
         LayerObjects[i].SpecialValue3 = (float)getRandom(500, 3000) / 1000f;
     }
 }
Example #22
0
    public Planet(string name, Vector3 position, float radius, Material material, float spinSpeed, Star star)
        : base(name)
    {
        this.radius = radius;
        this.sphere = new Sphere(name, position, radius, Constants.planetLongitudeSegments, Constants.planetLatitudeSegments, material);
        this.sphere.gameObject.AddComponent<Spin>().speed = spinSpeed;
        Orbit orbit = this.sphere.gameObject.AddComponent<Orbit>();
        orbit.center = star.sphere.gameObject;
        float distance = Vector3.Distance(sphere.gameObject.transform.position, star.sphere.gameObject.transform.position);
        orbit.speed = Constants.planetOrbitConstant / distance;
        satellites = new ArrayList();

        sphere.gameObject.transform.SetParent(star.sphere.gameObject.transform);

        SimpleHoverInfo simpleHoverInfo = this.sphere.gameObject.AddComponent<SimpleHoverInfo>();
        simpleHoverInfo.bodyRadius = radius;

        DetailedView detailedView = this.sphere.gameObject.AddComponent<DetailedView>();
        detailedView.bodyRadius = radius;
    }
Example #23
0
        public void Main(string[] args)
        {
            Startup startup = new Startup();
            startup.ConfigureServices();

            Star star = new Star();
            star.Start();

            string input;
            while ((input = Console.ReadLine()) != null)
            {
                input = input.ToLower();

                star.RaiseConsoleInputEvent(input);

                if (input == "exit")
                    break;
            }

            star.Stop();
        }
Example #24
0
	public void Spawn() {
		star = GameMaster.gameMaster.selectedStar;

		// Create the star at the center
		GameObject newStar = (GameObject)Instantiate (star3DPrefab, new Vector3 (-500, 0, 0), Quaternion.identity);
		newStar.name = star.starInfo.name;
		textObject = newStar.GetComponentInChildren<TextMesh> ();
		textObject.text = "\t" + newStar.name;
		textObject.color = Color.cyan;

		// Create planets one by one
		int amountOfPlanets = star.starInfo.planets.Count;
		for (int i = 0; i < amountOfPlanets; i++) {
			planet = star.planets [i];
			GameObject newPlanet = (GameObject)Instantiate (planet3DPrefab, new Vector3 (-500 + (i+1)*2, 0, 0), Quaternion.identity);
			newPlanet.name = planet.planetInfo.name;
			textObject = newPlanet.GetComponentInChildren<TextMesh> ();
			textObject.text = "\t" + newPlanet.name;
			textObject.color = Color.cyan;
		}

	}
Example #25
0
        protected override void InitializeGraphX(Star.GameManagement.Options options, LevelVariables levelvariables)
        {
            layerObjects = new List<LayerObject>();
            if(!string.IsNullOrEmpty(LayerName.Trim()))
            {
                try
                {
                    DecorationsLayer decorationLayerType = (DecorationsLayer)Enum.Parse(typeof(DecorationsLayer), LayerName);
                    if (decorationLayerType == DecorationsLayer.Rear && !string.IsNullOrEmpty(levelvariables.Dictionary[LV.RearDecorationsLayerData]))
                        ParseData(levelvariables.Dictionary[LV.RearDecorationsLayerData], levelvariables);
                    else if (decorationLayerType == DecorationsLayer.Front && !string.IsNullOrEmpty(levelvariables.Dictionary[LV.FrontDecorationsLayerData]))
                        ParseData(levelvariables.Dictionary[LV.FrontDecorationsLayerData], levelvariables);
                }
                catch (Exception)
                {
                    LayerObjects = new LayerObject[1];
                    LayerObjects[0] = new LayerObject(Content.Load<Texture2D>("Stuff/Blank"), new Rectangle());
                    Debug.DebugManager.AddItem("Failed to Parse Decorations Layer " + LayerName, this.ToString(), new System.Diagnostics.StackTrace(),System.Drawing.Color.Red);
                    throw;
                }

            }
        }
Example #26
0
        public virtual void Start(StarEffectType type)
        {
            int seed = (int)DateTime.Now.Ticks;

            for (int i = 0; i < GlobalValue.Dots_NUM; i++)
            {
                double size = GlobalValue.SIZE_MIN + (GlobalValue.SIZE_MAX - GlobalValue.SIZE_MIN) * GlobalValue.random.NextDouble();
                double xVelocity = GlobalValue.X_VELOCITY - 2 * GlobalValue.X_VELOCITY * GlobalValue.random.NextDouble();
                double yVelocity = -GlobalValue.Y_VELOCITY * GlobalValue.random.NextDouble();
                Star star = null;

                switch (type)
                {
                    case StarEffectType.YellowStar:
                        star = new Star(GlobalValue.YellowStarImage, size);
                        break;
                    case StarEffectType.RedStar:
                        star = new Star(GlobalValue.RedStarImage, size);
                        break;
                    case StarEffectType.ColorfullPiece:
                        star = new Star(size);
                        break;
                    default:
                        break;
                }

                star.Gravity = GlobalValue.GRAVITY;
                star.VelocityX = xVelocity;
                star.VelocityY = yVelocity;
                star.X = 22.5;
                star.Y = 22.5;
                _dotGroup.Add(star);
                Children.Insert(0, star);
                star.RunLoop();
            }
        }
Example #27
0
 public CreditsScene()
 {
     GameEngine.Game.CurrentMap = new GameMap("test2.txt", 1);
     base.drawStatusBar = false;
     this.heartTexture = new GameTexture("items.bmp", new Size(0x10, 0x10), TextureDisposePolicy.NeverDispose);
     this.starTexture = new GameTexture("stars.bmp", new Size(8, 8), TextureDisposePolicy.DisposeOnSceneChange);
     this.stars = new List<Star>();
     for (int i = 0; i < 50; i++)
     {
         Star item = new Star {
             loc = new PointF((float) Utility.RandomInt(0, 320), (float) Utility.RandomInt(0, 240)),
             speed = 0.1f * (i + 1),
             cell = Utility.RandomInt(0, 2)
         };
         this.stars.Add(item);
     }
     this.objects = new List<NamedObject>();
     this.sectionHeaders = new List<SectionHeader>();
     this.sectionHeaders.Add(new SectionHeader("WONDER BOY 3: THE DRAGON'S TRAP", 0x20, 320, false));
     this.sectionHeaders.Add(new SectionHeader("CAST", 0x38, 350, false));
     this.sectionHeaders.Add(new SectionHeader("ORIGINAL GAME BY WESTONE", 0x20, 0x60e, false));
     this.sectionHeaders.Add(new SectionHeader("COPYRIGHT 1990 HUDSON SOFT", 0x20, 0x672, false));
     this.sectionHeaders.Add(new SectionHeader("THANK YOU FOR PLAYING ! ! !", 0x40, 0x6d6, true));
 }
        private static Star GetSunByName(string planetSunName, MassDefectContext context)
        {
            Star desiredSun = context.Stars.FirstOrDefault(star => star.Name == planetSunName);

            return(desiredSun);
        }
Example #29
0
 // Use this for initialization
 void Start()
 {
     //rb.isKinematic = false;
     star = GameObject.Find("StarPlayer").GetComponent <Star>();
     rb   = GetComponent <Rigidbody2D>();
 }
Example #30
0
 private static int GetPlanetsAmaunt(Star star)
 {
     return(star.subStarClass);
 }
 public void DeleteStar(Star star)
 {
     _spaceDbContext.Remove(star);
 }
Example #32
0
        private async void ButtonWrite_OnClick(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.SaveFileDialog FileDialog = new System.Windows.Forms.SaveFileDialog
            {
                Filter = "STAR Files|*.star"
            };
            System.Windows.Forms.DialogResult Result = FileDialog.ShowDialog();

            if (Result.ToString() == "OK")
            {
                ExportPath = FileDialog.FileName;
            }
            else
            {
                return;
            }

            bool Relative = (bool)CheckRelative.IsChecked;
            bool Filter   = (bool)CheckFilter.IsChecked;
            bool Manual   = (bool)CheckManual.IsChecked;

            ProgressWrite.Visibility = Visibility.Visible;
            PanelButtons.Visibility  = Visibility.Hidden;

            await Task.Run(() =>
            {
                List <Movie> ValidMovies = Movies.Where(v =>
                {
                    if (!Filter && v.UnselectFilter && v.UnselectManual == null)
                    {
                        return(false);
                    }
                    if (!Manual && v.UnselectManual != null && (bool)v.UnselectManual)
                    {
                        return(false);
                    }
                    if (Options.Tasks.MicListMakePolishing && (v.OptionsMovement == null || v.GridMovementX.Dimensions.Z <= 1))
                    {
                        return(false);
                    }
                    return(true);
                }).ToList();

                string PathPrefix = "", PathPrefixAverage = "", GainPath = "";
                if (ValidMovies.Count > 0 && Relative)
                {
                    Uri UriStar = new Uri(ExportPath);

                    PathPrefix = Helper.PathToFolder(UriStar.MakeRelativeUri(new Uri(ValidMovies[0].Path)).ToString());
                    if (PathPrefix == ValidMovies[0].Name)
                    {
                        PathPrefix = "";
                    }
                    PathPrefixAverage = Helper.PathToFolder(UriStar.MakeRelativeUri(new Uri(ValidMovies[0].AveragePath)).ToString());

                    if (!string.IsNullOrEmpty(Options.Import.GainPath) && Options.Import.CorrectGain)
                    {
                        // Since RELION can't read DM4 or flip/transpose the gain, save a transformed version as MRC.

                        string TransformedGainPath = Helper.PathToFolder(Options.Import.GainPath) + "gain/transformed.mrc";
                        Directory.CreateDirectory(Helper.PathToFolder(TransformedGainPath));

                        Image TransformedGain = MainWindow.LoadAndPrepareGainReference();
                        TransformedGain.WriteMRC(TransformedGainPath, (float)Options.PixelSizeMean, true);
                        TransformedGain.Dispose();

                        GainPath = UriStar.MakeRelativeUri(new Uri(TransformedGainPath)).ToString();
                    }
                }

                Dispatcher.Invoke(() => ProgressWrite.Maximum = ValidMovies.Count);

                bool IncludeCTF       = ValidMovies.Any(v => v.OptionsCTF != null);
                bool IncludePolishing = ValidMovies.Any(v => v.OptionsMovement != null) && Options.Tasks.MicListMakePolishing;

                Star TableOut = new Star(new[] { "rlnMicrographName" });
                if (IncludeCTF)
                {
                    TableOut.AddColumn("rlnMagnification");
                    TableOut.AddColumn("rlnDetectorPixelSize");
                    TableOut.AddColumn("rlnVoltage");
                    TableOut.AddColumn("rlnSphericalAberration");
                    TableOut.AddColumn("rlnAmplitudeContrast");
                    TableOut.AddColumn("rlnPhaseShift");
                    TableOut.AddColumn("rlnDefocusU");
                    TableOut.AddColumn("rlnDefocusV");
                    TableOut.AddColumn("rlnDefocusAngle");
                    TableOut.AddColumn("rlnCtfMaxResolution");
                    TableOut.AddColumn("rlnBeamTiltX");
                    TableOut.AddColumn("rlnBeamTiltY");
                }
                if (IncludePolishing)
                {
                    TableOut.AddColumn("rlnMicrographMetadata");
                }

                List <Action> TablesToWrite = new List <Action>();

                if (IncludePolishing && ValidMovies.Count > 0)
                {
                    Directory.CreateDirectory(ValidMovies[0].DirectoryName + "motion");
                }

                int r = 0;
                Parallel.ForEach(ValidMovies, new ParallelOptions()
                {
                    MaxDegreeOfParallelism = 4
                }, movie =>
                {
                    List <string> Row = new List <string>()
                    {
                        PathPrefixAverage + movie.RootName + ".mrc"
                    };

                    if (movie.OptionsCTF != null)
                    {
                        Row.AddRange(new[]
                        {
                            (1e4M / movie.OptionsCTF.BinnedPixelSizeMean).ToString("F1", CultureInfo.InvariantCulture),
                            "1.0",
                            movie.CTF.Voltage.ToString("F1", CultureInfo.InvariantCulture),
                            movie.CTF.Cs.ToString("F4", CultureInfo.InvariantCulture),
                            movie.CTF.Amplitude.ToString("F3", CultureInfo.InvariantCulture),
                            (movie.CTF.PhaseShift * 180M).ToString("F1", CultureInfo.InvariantCulture),
                            ((movie.CTF.Defocus + movie.CTF.DefocusDelta / 2) * 1e4M).ToString("F1", CultureInfo.InvariantCulture),
                            ((movie.CTF.Defocus - movie.CTF.DefocusDelta / 2) * 1e4M).ToString("F1", CultureInfo.InvariantCulture),
                            movie.CTF.DefocusAngle.ToString("F1", CultureInfo.InvariantCulture),
                            movie.CTFResolutionEstimate.ToString("F1", CultureInfo.InvariantCulture),
                            movie.CTF.BeamTilt.X.ToString("F2", CultureInfo.InvariantCulture),
                            movie.CTF.BeamTilt.Y.ToString("F2", CultureInfo.InvariantCulture)
                        });
                    }
                    else
                    {
                        Row.AddRange(Helper.ArrayOfFunction(i => "0.0", 12));
                    }

                    if (IncludePolishing)
                    {
                        Row.Add(PathPrefix + "motion/" + movie.RootName + ".star");
                    }

                    lock (TableOut)
                        TableOut.AddRow(Row);

                    if (IncludePolishing)
                    {
                        MapHeader Header = MapHeader.ReadFromFile(movie.Path);

                        List <string> HeaderNames = new List <string>()
                        {
                            "rlnImageSizeX",
                            "rlnImageSizeY",
                            "rlnImageSizeZ",
                            "rlnMicrographMovieName",
                            "rlnMicrographBinning",
                            "rlnMicrographOriginalPixelSize",
                            "rlnMicrographDoseRate",
                            "rlnMicrographPreExposure",
                            "rlnVoltage",
                            "rlnMicrographStartFrame",
                            "rlnMotionModelVersion"
                        };

                        List <string> HeaderValues = new List <string>()
                        {
                            Header.Dimensions.X.ToString(),
                            Header.Dimensions.Y.ToString(),
                            Header.Dimensions.Z.ToString(),
                            PathPrefix + movie.Name,
                            Math.Pow(2.0, (double)Options.Import.BinTimes).ToString("F5"),
                            Options.PixelSizeMean.ToString("F5"),
                            Options.Import.DosePerAngstromFrame.ToString("F5"),
                            "0",
                            Options.CTF.Voltage.ToString(),
                            "1",
                            "0"
                        };

                        if (!string.IsNullOrEmpty(GainPath))
                        {
                            HeaderNames.Add("rlnMicrographGainName");
                            HeaderValues.Add(GainPath);
                        }

                        StarParameters ParamsTable = new StarParameters(HeaderNames.ToArray(), HeaderValues.ToArray());

                        float2[] MotionTrack = movie.GetMotionTrack(new float2(0.5f, 0.5f), 1).Select(v => v / (float)Options.PixelSizeMean).ToArray();
                        Star TrackTable      = new Star(new[]
                        {
                            Helper.ArrayOfSequence(1, MotionTrack.Length + 1, 1).Select(v => v.ToString()).ToArray(),
                            MotionTrack.Select(v => (-v.X).ToString("F5")).ToArray(),
                            MotionTrack.Select(v => (-v.Y).ToString("F5")).ToArray()
                        },
                                                        new[]
                        {
                            "rlnMicrographFrameNumber",
                            "rlnMicrographShiftX",
                            "rlnMicrographShiftY"
                        });

                        Star.SaveMultitable(movie.DirectoryName + "motion/" + movie.RootName + ".star", new Dictionary <string, Star>()
                        {
                            { "general", ParamsTable },
                            { "global_shift", TrackTable },
                        });
                    }

                    lock (this)
                    {
                        r++;
                        if (r % 10 == 0 || r == ValidMovies.Count)
                        {
                            Dispatcher.Invoke(() => ProgressWrite.Value = r);
                        }
                    }
                });

                TableOut.Save(ExportPath);
            });

            Close?.Invoke();
        }
 public StarEditingWindow(Star oldStar) : this()
 {
     this.vm.Star = oldStar;
 }
Example #34
0
    public static Dictionary <String, Texture2D> allTextures = LoadTextures(); // Game Textures
    static void Main(string[] args)
    {
        Raylib.InitWindow(1900, 1000, "SpaceGame");
        Raylib.SetTargetFPS(120);
        Raylib.ToggleFullscreen();

        new Player(new Vector2(0, 0), 90, 500);

        RoundManager.GetCurrentRound(0);
        new TextBox(999, new Vector2(Raylib.GetScreenWidth() / 3 + 120, 25), 40, "Welcome to SpaceGame!", Color.WHITE);
        new TextBox(999, new Vector2(Raylib.GetScreenWidth() / 5, 80), 25, "You move around with WASD\nYou shoot lasers with left mouse button and explosive bullets with right mouse button\nYou'll have to dodge the enemies which comes in rounds with increasing difficulty.\nKill the dummy enemy when you're ready!", Color.WHITE);

        while (!Raylib.WindowShouldClose())
        {
            // New round after pause
            if (Raylib.GetTime() > RoundManager.timeTillNextRound && !RoundManager.roundActive)
            {
                RoundManager.NewRound();
            }

            // Spawn enemies during round
            if (RoundManager.roundActive)
            {
                RoundManager.SpawnEnemies();
            }

            // Event manager code
            EventManager.ManagerCode();

            // Draw logic
            Star.StarLogic();

            // Update bullets position
            Bullet.Move();

            // Control player and spawn bullets
            if (Player.ship.isDead == false)
            {
                Player.ship.PlayerControl();

                // Enemy AI
                Enemy.EnemyLogic();
            }
            else
            {
                if (Raylib.IsKeyPressed(KeyboardKey.KEY_R))
                {
                    ResetGame();
                }
            }

            // Render Frame
            Raylib.BeginDrawing();
            Raylib.ClearBackground(new Color(2, 2, 2, 255));

            // Render world
            RenderWorld(allTextures);

            Raylib.EndDrawing();
        }
    }
Example #35
0
//    void InitStars(double sigma)
    void InitStars()
    {
        //m_pDust = new Star[m_numDust];

        //m_pStars = new Star[m_numStars];

        //m_pH2 = new Star[m_numH2 * 2];
        m_pDust.Clear();
        m_pStars.Clear();
        m_pH2.Clear();

        Star star, dust, H2;

        star = new Star();
        m_pStars.Add(star);
        // The first three stars can be used for aligning the
        // camera with the galaxy rotation.

        // First star ist the black hole at the centre
        m_pStars[0].m_a        = 0;
        m_pStars[0].m_b        = 0;
        m_pStars[0].m_angle    = 0;
        m_pStars[0].m_theta    = 0;
        m_pStars[0].m_velTheta = 0;
        m_pStars[0].m_center   = new Vector2(0, 0);
        m_pStars[0].m_velTheta = 0; //= GetOrbitalVelocity((m_pStars[0].m_a + m_pStars[0].m_b) / 2.0);
        m_pStars[0].m_temp     = 6000;

        // second star is at the edge of the core area
        star = new Star();
        m_pStars.Add(star);

        m_pStars[1].m_a        = m_radCore;
        m_pStars[1].m_b        = m_radCore * GetExcentricity(m_radCore);
        m_pStars[1].m_angle    = GetAngularOffset(m_radCore);
        m_pStars[1].m_theta    = 0;
        m_pStars[1].m_center   = new Vector2(0, 0);
        m_pStars[1].m_velTheta = GetOrbitalVelocity((m_pStars[1].m_a + m_pStars[1].m_b) / 2.0);
        m_pStars[1].m_temp     = 6000;

        star = new Star();
        m_pStars.Add(star);

        // third star is at the edge of the disk
        m_pStars[2].m_a        = m_radGalaxy;
        m_pStars[2].m_b        = m_radGalaxy * GetExcentricity(m_radGalaxy);
        m_pStars[2].m_angle    = GetAngularOffset(m_radGalaxy);
        m_pStars[2].m_theta    = 0;
        m_pStars[2].m_center   = new Vector2(0, 0);
        m_pStars[2].m_velTheta = GetOrbitalVelocity((m_pStars[2].m_a + m_pStars[2].m_b) / 2.0);
        m_pStars[2].m_temp     = 6000;

        // cell width of the histogramm
        //double dh = (double)m_radFarField / 100.0;

        // Initialize the stars
        CumulativeDistributionFunction cdf = new CumulativeDistributionFunction();

        cdf.SetupRealistic(1.0,               // Maximalintensität
                           0.02,              // k (bulge)
                           m_radGalaxy / 3.0, // disc skalenlänge
                           m_radCore,         // bulge radius
                           0,                 // start der intensitätskurve
                           m_radFarField,     // ende der intensitätskurve
                           1000);             // Anzahl der stützstellen
        for (int i = 3; i < m_numStars; ++i)
        {
            // random value between -1 and 1
            //double sum = -6;
            //for (int j = 0; j < 12; ++j)
            //{
            //    sum += UnityEngine.Random.Range(0, RAND_MAX) / (double)RAND_MAX;
            //}
            //double rad = Math.Abs(sum) * m_radGalaxy;

            double rad = cdf.ValFromProb((double)UnityEngine.Random.Range(0, RAND_MAX) / (double)RAND_MAX);
            star = new Star();

            star.m_a        = rad;
            star.m_b        = rad * GetExcentricity(rad);
            star.m_angle    = GetAngularOffset(rad);
            star.m_theta    = 360.0 * ((double)UnityEngine.Random.Range(0, RAND_MAX) / (double)RAND_MAX);
            star.m_velTheta = GetOrbitalVelocity(rad);
            star.m_center   = new Vector2(0, 0);
            star.m_temp     = 6000 + (4000 * ((double)UnityEngine.Random.Range(0, RAND_MAX) / (double)RAND_MAX)) - 2000;
            star.m_mag      = 0.1 + 0.2 * (double)UnityEngine.Random.Range(0, RAND_MAX) / (double)RAND_MAX;

            //int idx = (int)Math.Min(1.0 / dh * (star.m_a + star.m_b) / 2.0, 99.0);
            m_pStars.Add(star);
            //m_numberByRad[idx]++;
        }

        // Initialise Dust
        double x, y;

        for (int i = 0; i < m_numDust; ++i)
        {
            dust = new Star();
            if (i % 4 == 0)
            {
                rad = cdf.ValFromProb((double)UnityEngine.Random.Range(0, RAND_MAX) / (double)RAND_MAX);
            }
            else
            {
                x   = 2 * m_radGalaxy * ((double)UnityEngine.Random.Range(0, RAND_MAX) / (double)RAND_MAX) - m_radGalaxy;
                y   = 2 * m_radGalaxy * ((double)UnityEngine.Random.Range(0, RAND_MAX) / (double)RAND_MAX) - m_radGalaxy;
                rad = Math.Sqrt(x * x + y * y);
            }

            dust.m_a        = rad;
            dust.m_b        = rad * GetExcentricity(rad);
            dust.m_angle    = GetAngularOffset(rad);
            dust.m_theta    = 360.0 * ((double)UnityEngine.Random.Range(0, RAND_MAX) / (double)RAND_MAX);
            dust.m_velTheta = GetOrbitalVelocity((dust.m_a + dust.m_b) / 2.0);
            dust.m_center   = new Vector2(0, 0);

            // I want the outer parts to appear blue, the inner parts yellow. I'm imposing
            // the following temperature distribution (no science here it just looks right)
            dust.m_temp = 5000 + rad / 4.5;

            dust.m_mag = 0.015 + 0.01 * (double)UnityEngine.Random.Range(0, RAND_MAX) / (double)RAND_MAX;

            m_pDust.Add(dust);
        }

        // Initialise H2

        for (int i = 0; i < m_numH2 * 2; ++i)
        {
            H2 = new Star();
            m_pH2.Add(H2);
        }
        for (int i = 0; i < m_numH2; ++i)
        {
            x   = 2 * (m_radGalaxy) * ((double)UnityEngine.Random.Range(0, RAND_MAX) / (double)RAND_MAX) - (m_radGalaxy);
            y   = 2 * (m_radGalaxy) * ((double)UnityEngine.Random.Range(0, RAND_MAX) / (double)RAND_MAX) - (m_radGalaxy);
            rad = Math.Sqrt(x * x + y * y);

            int k1 = 2 * i;
            m_pH2[k1].m_a        = rad;
            m_pH2[k1].m_b        = rad * GetExcentricity(rad);
            m_pH2[k1].m_angle    = GetAngularOffset(rad);
            m_pH2[k1].m_theta    = 360.0 * ((double)UnityEngine.Random.Range(0, RAND_MAX) / (double)RAND_MAX);
            m_pH2[k1].m_velTheta = GetOrbitalVelocity((m_pH2[k1].m_a + m_pH2[k1].m_b) / 2.0);
            m_pH2[k1].m_center   = new Vector2(0, 0);
            m_pH2[k1].m_temp     = 6000 + (6000 * ((double)UnityEngine.Random.Range(0, RAND_MAX) / (double)RAND_MAX)) - 3000;
            m_pH2[k1].m_mag      = 0.1 + 0.05 * (double)UnityEngine.Random.Range(0, RAND_MAX) / (double)RAND_MAX;

            int k2 = 2 * i + 1;
            m_pH2[k2].m_a        = rad + 1000;
            m_pH2[k2].m_b        = rad * GetExcentricity(rad);
            m_pH2[k2].m_angle    = GetAngularOffset(rad);
            m_pH2[k2].m_theta    = m_pH2[k1].m_theta;
            m_pH2[k2].m_velTheta = m_pH2[k1].m_velTheta;
            m_pH2[k2].m_center   = m_pH2[k1].m_center;
            m_pH2[k2].m_temp     = m_pH2[k1].m_temp;
            m_pH2[k2].m_mag      = m_pH2[k1].m_mag;
        }
    }
Example #36
0
    private void OnTriggerEnter2D(Collider2D collision)
    {
        GameObject other = collision.gameObject;

        if (collision.CompareTag("Checkpoint"))
        {
            respawnPos = other.transform.position;
        }

        Star star = other.GetComponent <Star>();

        if (star != null)
        {
            bool newStar = gm.CollectStar(star);
            Destroy(other);
            if (newStar)
            {
                audioSrc.PlayOneShot(starCollectSound);
            }
            else
            {
                audioSrc.PlayOneShot(oldStarCollectSound);
            }
        }

        Door door = other.GetComponent <Door>();

        if (door != null)
        {
            gm.ShowHUDDoorStars(door);
            door.TryOpen();
        }

        PowerUp powerUp = other.GetComponent <PowerUp>();

        if (powerUp != null)
        {
            powerUp.Activate(this);
        }

        if (other.layer == LayerMask.NameToLayer("Water") && movement is PlayerLand)
        {
            //enter swim state
            movement = new PlayerSwim(this);
        }

        /*Portal portalCollided = other.GetComponent<Portal>();
         * if (portalCollided != null)
         * {
         *      int starType = (int)gm.levelStarPrefab.GetComponent<Star>().starType;
         *      if (gm.starsCollected[starType] >= portalCollided.starsRequired)
         *      {
         *              NextLevel();
         *      }
         * }
         *
         * StarSpot starSpot = other.GetComponent<StarSpot>();
         * if (starSpot != null && !starSpot.touched)
         * {
         *      starSpot.Fill();
         * }*/
    }
Example #37
0
        /// <summary>
        /// Inserts star into the world's list of stars based on settings from the game settings xml file
        /// </summary>
        public static void InsertStars()
        {
            //If the fancy game mode is off, loads stars from the settings file
            if ((string)gameSettings["FancyGame"] != "Yes" && (string)gameSettings["FancyGame"] != "yes")
            {
                // getting the star information from the game settings
                List <double[]> tempStarList = new List <double[]>();
                tempStarList = (List <double[]>)(gameSettings["stars"]);

                // looping through each of the stars stored in game settings and creating them
                int StarIdCounter = 0;
                lock (TheWorld)
                {
                    foreach (double[] s in tempStarList)
                    {
                        Star star = new Star();
                        star.SetID(StarIdCounter);
                        Vector2D loc = new Vector2D(s[0], s[1]);
                        star.SetLoc(loc);
                        star.SetMass(s[2]);
                        TheWorld.AddStar(star);
                        StarIdCounter++;
                    }
                }
            }
            //If the fancy game mode is on, loads 4 stars and prepares them for orbit
            else
            {
                // the radius away from the center of the world.
                double radius = (int)gameSettings["UniverseSize"] / 3.5;

                // creating 4 stars at specified locations away from the center
                Star star1 = new Star();
                star1.SetID(1);
                Vector2D loc1 = new Vector2D(0, radius);
                star1.SetLoc(loc1);
                star1.SetDir(new Vector2D(1, 0));
                star1.SetMass(.01);
                TheWorld.AddStar(star1);

                Star star2 = new Star();
                star2.SetID(2);
                Vector2D loc2 = new Vector2D(0, -radius);
                star2.SetLoc(loc2);
                star2.SetDir(new Vector2D(-1, 0));
                star2.SetMass(.01);
                TheWorld.AddStar(star2);

                Star star3 = new Star();
                star3.SetID(3);
                Vector2D loc3 = new Vector2D(radius, 0);
                star3.SetLoc(loc3);
                star3.SetDir(new Vector2D(0, -1));
                star3.SetMass(.01);
                TheWorld.AddStar(star3);

                Star star4 = new Star();
                star4.SetID(4);
                Vector2D loc4 = new Vector2D(-radius, 0);
                star4.SetLoc(loc4);
                star4.SetDir(new Vector2D(0, 1));
                star4.SetMass(.01);
                TheWorld.AddStar(star4);
            }
        }
Example #38
0
 public static FRange EcosphereZone(GameObject star)
 {
     return(Star.EcosphereZone(star.GetComponent <Star>()));
 }
 public void TestSetUp()
 {
     testRace = new TestRace();
     star     = new Star();
 }
Example #40
0
    private void CreateStars()
    {
        starFieldAnchor = GameObject.Find("StarFieldAnchor");
        Stars.Clear();

        char[] splitChars = new char[] { ' ' };

        using (var memStream = new MemoryStream(starsTextAsset.bytes))
        {
            using (var reader = new StreamReader(memStream))
            {
                while (!reader.EndOfStream)
                {
                    string   line    = reader.ReadLine();
                    string[] lineArr = line.Split(splitChars, StringSplitOptions.RemoveEmptyEntries);
                    if (lineArr.Length < 6)
                    {
                        continue;
                    }

                    var star = new Star();

                    star.Index    = Convert.ToInt32(lineArr[0]);
                    star.Ra       = Mathf.Deg2Rad * Convert.ToSingle(lineArr[1]);
                    star.Dec      = Mathf.Deg2Rad * Convert.ToSingle(lineArr[2]);
                    star.Distance = 500; //Convert.ToSingle(lineArr[3]);
                    star.Mag      = Convert.ToSingle(lineArr[4]);
                    star.type     = lineArr[5];

                    //if (star.Mag < 3)
                    //{
                    Stars.Add(star);
                    //}
                }
            }
        }

        using (var memStream = new MemoryStream(asterismsTextAsset.bytes))
        {
            using (var reader = new StreamReader(memStream))
            {
                while (!reader.EndOfStream)
                {
                    string   line    = reader.ReadLine();
                    string[] lineArr = line.Split(splitChars, StringSplitOptions.RemoveEmptyEntries);
                    if (lineArr.Length < 4)
                    {
                        continue;
                    }

                    var asterism = new Asterism();
                    Asterisms.Add(asterism);

                    asterism.Name = lineArr[0];

                    asterism.NumSegments = Convert.ToInt32(lineArr[1]);
                    asterism.StarsA      = new Star[asterism.NumSegments];
                    asterism.StarsB      = new Star[asterism.NumSegments];

                    int index = 2;
                    for (int i = 0; i < asterism.NumSegments; i++)
                    {
                        int a = Convert.ToInt32(lineArr[index++]);
                        int b = Convert.ToInt32(lineArr[index++]);

                        asterism.StarsA[i] = Stars.Find(s => s.Index == a);
                        asterism.StarsB[i] = Stars.Find(s => s.Index == b);
                    }

                    Debug.Log("Processed asterism: " + asterism.Name);
                }
            }
        }


        points = new ParticleSystem.Particle[Stars.Count];

        for (int i = 0; i < points.Length; i++)
        {
            var star = Stars[i];

            points[i].position = new Vector3(star.Distance * Mathf.Cos(star.Dec) * Mathf.Cos(star.Ra),
                                             star.Distance * Mathf.Cos(star.Dec) * Mathf.Sin(star.Ra),
                                             star.Distance * Mathf.Sin(star.Dec));


            //points[i].startSize = 30f;

            float size = 15f - star.Mag * 2;
            if (size < 5f)
            {
                size = 5f;
            }
            //points[i].startColor = new Color(1, 1, 1, 1);
            points[i].startSize3D = new Vector3(size, size, size);

            star.particle = points[i];
        }

        starParticleSystem.SetParticles(points, points.Length);



        foreach (var asterism in Asterisms)
        {
            for (int i = 0; i < asterism.NumSegments; i++)
            {
                if (asterism.StarsA[i] == null || asterism.StarsB[i] == null)
                {
                    continue;
                }

                var lineObj = new GameObject();
                lineObj.transform.parent = starFieldAnchor.transform;

                var lineRenderer = lineObj.AddComponent <LineRenderer>();

                lineRenderer.material   = asterismsMaterial;
                lineRenderer.startWidth = 1f;
                lineRenderer.endWidth   = 1f;
                lineRenderer.SetPosition(0, asterism.StarsA[i].particle.position);
                lineRenderer.SetPosition(1, asterism.StarsB[i].particle.position);
                lineRenderer.startColor = new Color(0f, 0.2f, 0.7f);
                lineRenderer.endColor   = new Color(0f, 0.2f, 0.7f);

                Debug.Log("Adding line: " + asterism.StarsA[i].particle.position + "  :  " + asterism.StarsB[i].particle.position);
            }
        }
    }
Example #41
0
        public void AddEnemy(string type, Vector2 position,Star.Game.Enemy.Enemy.StandardDirection startdirection,Options options)
        {
            Enemy newenemy;

            newenemy = new Enemy();
            newenemy.Initialize(type, serviceProvider,(byte)currentThreadtoAdd,options);
            //preloadedEnemies.Add(newenemy);
            newenemy.Pos = position;
            //newenemy.RunDirection = startdirection;
            if (!textures.ContainsKey(type))
            {
                LoadTextures(content, newenemy.Variables, type);
            }
            newenemy.Alive = true;
            enemies[currentThreadtoAdd].Add(newenemy);
            currentThreadtoAdd++;
            if (currentThreadtoAdd >= numThreads)
                currentThreadtoAdd = 0;
            refreshAllEnemies();
        }
Example #42
0
 private void SeletColor(Star star)
 {
     Debug.Log(star.GetColor().ToString());
     m_changeColor = star.GetColor();
     changeStarRoot.gameObject.SetActive(false);
 }
Example #43
0
    static void RenderWorld(Dictionary <String, Texture2D> Textures) // RenderWorld
    {
        // https://www.raylib.com/examples/web/textures/loader.html?name=textures_srcrec_dstrec

        // Raylib.DrawRectangle((int)(-Player.ship.pos.X - 50f), (int)(Player.ship.pos.Y - 50f), 100, 100, Color.GREEN);

        // Draw stars
        Star.DrawStars();

        // Draw bosses
        if (RoundManager.bossAlive)
        {
            if (BossSun.boss != null)
            {
                BossSun.DrawBoss();
                DrawHealthBar(new Vector2(BossSun.boss.pos.X - Player.ship.pos.X, -BossSun.boss.pos.Y + Player.ship.pos.Y), BossSun.boss.width, BossSun.boss.height, BossSun.boss.health, BossSun.boss.maxHealth);
            }
        }

        // Draw all the enemies
        foreach (Enemy enemy in Enemy.allEnemies)
        {
            if (enemy.type == EnemyType.Easy)
            {
                DrawObjectRotation(Textures["EnemyEasy"], enemy.pos - Player.ship.pos, enemy.rotation, 1, 255);
            }
            else if (enemy.type == EnemyType.Hard)
            {
                DrawObjectRotation(Textures["EnemyHard"], enemy.pos - Player.ship.pos, enemy.rotation, 1, 255);
            }
            else if (enemy.type == EnemyType.Kamikaze)
            {
                DrawObjectRotation(Textures["EnemyKamikaze"], enemy.pos - Player.ship.pos, enemy.rotation, 1, 255);
            }
            else if (enemy.type == EnemyType.Dummy)
            {
                DrawObjectRotation(Textures["EnemyDummy"], enemy.pos - Player.ship.pos, enemy.rotation, 1, 255);
            }
        }
        // Draw all the enemy healthbars
        foreach (Enemy enemy in Enemy.allEnemies)
        {
            DrawHealthBar(new Vector2(enemy.pos.X - Player.ship.pos.X, -enemy.pos.Y + Player.ship.pos.Y), enemy.width, enemy.height, enemy.health, enemy.maxHealth);
        }

        // Draw bullets
        foreach (var bullet in Bullet.allBullets)
        {
            if (bullet.isExplosive)
            {
                DrawObjectRotation(Textures["Bomb"], bullet.pos - Player.ship.pos, bullet.rotation, 1, 255);
            }

            else
            {
                DrawObjectRotation(Textures["Laser"], bullet.pos - Player.ship.pos, bullet.rotation, 1, 255);
            }
        }

        // Draw player
        DrawObjectRotation(Textures["PlayerShip"], new Vector2(0, 0), Player.ship.rotation, 1, 255);

        // Draw player health bar
        DrawHealthBar(new Vector2(0, 0), Player.ship.width, Player.ship.height, Player.ship.health, Player.ship.maxHealth);

        // Display round
        // Raylib.DrawText("Round: " + RoundManager.currentRound.round.ToString(), Raylib.GetScreenWidth() / 2, 0, 15, Color.WHITE);

        // Display FPS
        Raylib.DrawText(Raylib.GetFPS().ToString(), Raylib.GetScreenWidth() - 50, 10, 30, Color.WHITE);

        // Display player stats
        // Raylib.DrawText(Player.ship.health.ToString() + ":" + Player.ship.maxHealth.ToString(), Raylib.GetScreenWidth() - 120, 50, 30, Color.WHITE);

        // Display player score
        Raylib.DrawText("Score : " + Player.ship.score.ToString(), 20, 10, 40, Color.YELLOW);

        // // Display enemy amounts
        // Raylib.DrawText(Enemy.allEnemies.Count.ToString(), Raylib.GetScreenWidth() - 100, 10, 30, Color.WHITE);

        // // Display bullet amounts
        // Raylib.DrawText(Bullet.allBullets.Count.ToString(), Raylib.GetScreenWidth() - 100, 35, 30, Color.WHITE);

        // Draw effects
        foreach (Effect effect in EventManager.allEffects)
        {
            DrawObjectRotation(effect.texture, effect.pos - Player.ship.pos, effect.rotation, effect.size, effect.transparency);
        }
        foreach (TextBox text in EventManager.allTexts)
        {
            Raylib.DrawText(text.text, (int)text.pos.X, (int)text.pos.Y, text.fontSize, text.color);
        }
    }
Example #44
0
        public IHttpActionResult Get()
        {
            List <Movie> movies = new List <Movie>();

            var     url     = "http://www.imdb.com/movies-coming-soon/?ref_=nv_mv_cs_4";
            HtmlWeb web     = new HtmlWeb();
            var     htmlDoc = web.Load(url);


            var liste = htmlDoc.DocumentNode.SelectNodes("//div[@class='list detail']/div");

            foreach (var item in liste)
            {
                var htmlSubDoc = new HtmlDocument();
                htmlSubDoc.LoadHtml(item.InnerHtml);


                Movie movie = new Movie();
                movie.MovieName   = htmlSubDoc.DocumentNode.SelectSingleNode("//h4[@itemprop='name']/a").InnerHtml;
                movie.ImageUrl    = htmlSubDoc.DocumentNode.SelectSingleNode("//img[@class='poster shadowed']").Attributes["src"].Value;
                movie.Description = htmlSubDoc.DocumentNode.SelectSingleNode("//div[@itemprop='description']").InnerHtml;

                var s = htmlSubDoc.DocumentNode.SelectSingleNode("//time");
                movie.Duration = s != null ? s.InnerHtml : ":(";
                try
                {
                    #region Stars
                    var NodesStar = htmlSubDoc
                                    .DocumentNode
                                    .SelectNodes("//div[@class='txt-block']/span[@itemprop='actors']/span/a");


                    List <Star> stars = new List <Star>();

                    foreach (var str in NodesStar)
                    {
                        Star star = new Star();
                        star.FullName = str.InnerHtml;
                        stars.Add(star);
                    }
                    movie.Stars = stars;
                    #endregion
                }
                catch (System.Exception)
                {
                    continue;
                }
                #region Directors
                var NodesDirector = htmlSubDoc
                                    .DocumentNode
                                    .SelectNodes("//div[@class='txt-block']/span[@itemprop='director']/span/a");

                List <Director> directors = new List <Director>();

                foreach (var drc in NodesDirector)
                {
                    Director director = new Director
                    {
                        FullName = drc.InnerHtml
                    };
                    directors.Add(director);
                }
                movie.Directors = directors;
                #endregion

                #region Genre
                var NodesGenre = htmlSubDoc
                                 .DocumentNode
                                 .SelectNodes("//span[@itemprop='genre']");

                List <Genre> genres = new List <Genre>();

                foreach (var gnr in NodesGenre)
                {
                    Genre genre = new Genre
                    {
                        Name = gnr.InnerHtml
                    };
                    genres.Add(genre);
                }
                movie.Genre = genres;
                #endregion

                movies.Add(movie);
            }

            return(Json(movies));
        }
        public void Draw()
        {
            if (ImageWrapper != null)
            {
                var width  = (int)ImageWrapper.ActualWidth;
                var height = (int)ImageWrapper.ActualHeight;

                using (image = new Image <Rgba32>(width, height))
                {
                    // Draw triangle
                    image.Mutate((x) =>
                    {
                        // Define pens and inks
                        var sss = new Pen(Rgba32.ParseHex("#FFC0CB"), 10, new float[] { 2f, 6f, 8f });

                        var pinkPen   = Pens.Solid(Rgba32.ParseHex("#FFC0CB"), 10);
                        var greenPen  = Pens.Solid(Rgba32.ParseHex("#228B22"), 10);
                        var blackPen  = Pens.Solid(Rgba32.ParseHex("#000000"), 10);
                        var pinkBrush = Brushes.Solid(Rgba32.ParseHex("#C71585"));


                        Image img = Image.Load("Resources\\cat.jpg");
                        img.Mutate((x) =>
                        {
                            x.Resize(
                                128,
                                (x.GetCurrentSize().Height / x.GetCurrentSize().Width) * 128);
                        });
                        var CatBrush = new ImageBrush(img);


                        // Draw a Line
                        x.DrawLines(pinkPen, new PointF[] {
                            new PointF(30, 30),
                            new PointF(100, 30)
                        });

                        // Draw a Triangle
                        x.FillPolygon(CatBrush, new PointF[] {
                            new PointF(50, 50),
                            new PointF(500, 30),
                            new PointF(555, 555),
                        });

                        // Draw a star x y numberofcorners innerradius outerradius
                        Star star       = new Star(50, 50, 5, 50, 100);
                        var staroutline = Outliner.GenerateOutline(star, 2, JointStyle.Round);
                        x.Fill(CatBrush, star);

                        // Draw an arc
                        var arc = new Polygon(new CubicBezierLineSegment(new PointF[] {
                            new PointF(10, 400),
                            new PointF(30, 10),
                            new PointF(240, 30),
                            new PointF(300, 400)
                        }));
                        x.Draw(blackPen, arc);

                        // Draw some Ellipse
                        var sector = new EllipsePolygon(200, 200, 10, 20).Scale(5);
                        x.Draw(blackPen, sector);
                    });

                    // Set the source
                    ImageControl.Source = Helpers.ImageToBitmap(image);
                }
            }
        }
Example #46
0
    void CreateStarObject(Star starData, Vector3 cartPosition)
    {
        GameObject starGO = SpaceObjects.CreateSphereObject(starData.starName, cartPosition, this.transform);

        starToObjectMap.Add(starData, starGO);
    }
Example #47
0
 public void Init()
 {
     // Build the stars list
     _stars = Aoc.Framework.Input.GetStringVector(this).Select(line => Star.Parse(line)).ToArray();
 }
Example #48
0
    IEnumerator StarSequence()
    {
        yield return(new WaitForSeconds(0.1f));

        //Check if last star clicked is one less than current star
        if (StarManager.previousStar == (starValue - 1))
        {
            //Check if Transition manager exists and check if a transition is already active
            if (transitionManager != null && !transitionManager.IsTransitionOpen)
            {
                //If a transition is not active then Create one
                transitionManager.CreateTransition();

                //Set the source for the transition
                transitionManager.TransitionSource = gameObject.name;
            }
            else
            {
                //Set the transitions destination ..only if its the correct destination
                transitionManager.TransitionDestination = gameObject.name;

                //End the transition and add it to the transition list
                Transition currentTransition = transitionManager.EndTransition();

                if (currentTransition != null)
                {
                    sessionManager.AddTransition(currentTransition);
                }

                //Start a new Transition.
                transitionManager.CreateTransition();
                //Set the source for the transition
                transitionManager.TransitionSource = gameObject.name;
            }

            //Set the star materials color to gold ( indicating success )
            //_material.color = successColour;

            if (GameManager.Instance.IsDemoMode)
            {
                Messenger <int> .Broadcast("PlaySound", 0);

                iTween.PunchScale(starSpriteRenderer.gameObject, iTween.Hash("x", -2, "y", -2, "time", 0.75f));
                starSpriteRenderer.color = new Color(0.9716f, 0.8722f, 0.1512f, 1);
                originalColour           = starSpriteRenderer.color;
                gameManager.UpdateScore();
            }
            else if (_drawLineHandler)
            {
                StarManager.lastSuccessPointCount = _drawLineHandler.PointCount;
                _drawLineHandler.DrawLine(_drawLineHandler.PointCount);
                _drawLineHandler.LastNode = _transform;

                //Refactor replace with message
                gameManager.UpdateScore();


                //Play Success sound effect
                //Message broadcast : PlaySound takes an int as a parameter
                //Subscribers : SoundManager
                //Messenger<int>.Broadcast( "RandomizePitch", 0 );
                Messenger <int> .Broadcast("PlaySound", 0);

                //Handheld.Vibrate();

                //Update the progress star with the current star
                //Progress star will display the current
                Messenger <string> .Broadcast("UpdateProgress", starText.text);

                //Punch animation when correct star is encountered
                iTween.PunchScale(starSpriteRenderer.gameObject, iTween.Hash("x", -2, "y", -2, "time", 0.75f));

                starSpriteRenderer.color = new Color(0.9716f, 0.8722f, 0.1512f, 1);

                originalColour = starSpriteRenderer.color;

                if (_drawLineHandler.IsMouseUp)
                {
                    _drawLineHandler.CanDraw = false;
                }
            }

            StarManager.previousStar       = starValue;
            StarManager.previousStarObject = this;
        }
        else if (StarManager.previousStar == starValue)
        {
            //Do Absolutely nothing for the moment...
        }
        else         //Error E.G. Player clicked on wrong star
        {
            Star previousStarObject = StarManager.previousStarObject;

            transitionManager.TransitionErrorCount++;              //Total number or errors for this transition

            // Error err = new Error(); //Create new instance of error class

            // err.Source = previousStarObject.name;
            // err.Destination = this.name;
            // err.ErrorTimeStamp = System.DateTime.Now.ToString();

            //Check previous stars list of proximity stars
            //if a player accidently hits a star contained in this list , then that constitutes a proximity error
            if (previousStarObject.ProximityStars[0] != null)
            {
                foreach (GameObject g in previousStarObject.ProximityStars)
                {
                    if (this.name.Equals(g.name) && g.name != null)
                    {
                        //err.ProximityError = true;
                        transitionManager.ProximityErrorCount++;
                    }
                }
            }


            //Check the type of error that occured
            if (previousStarObject.IsStarLetter && this.IsStarLetter)              //letter to letter error
            {
                //err.PreservativeError = true;
                transitionManager.PreservativeErrorCount++;
            }
            else if (!previousStarObject.IsStarLetter && !this.IsStarLetter)              //number to number error
            {
                //err.PreservativeError = true;
                transitionManager.PreservativeErrorCount++;
            }
            else if (!previousStarObject.IsStarLetter && this.IsStarLetter)              //number to letter error
            {
                //err.NumberToLetterError = true;
                transitionManager.NumToLetterErrorCount++;
            }
            else if (previousStarObject.IsStarLetter && !this.IsStarLetter)              //letter to number error
            {
                transitionManager.LetterToNumErrorCount++;
                //err.LetterToNumberError = true;
            }

            //transitionManager.AddError( err ); //Add the error to the error list for this transition

            //Consequences of picking the wrong star . Make star shake
            iTween.ShakePosition(_transform.parent.gameObject, new Vector2(0.2f, 0.2f), 0.75f);
            //Handheld.Vibrate();

            //Play Error Sound
            //Message broadcast : PlaySound takes an int as a parameter
            //Subscribers : SoundManager
            Messenger <int> .Broadcast("PlaySound", 1);

            //Tween between stars original colour and red and back
            //isOkToColor = true;
            iTween.ValueTo(gameObject, iTween.Hash(
                               "from", errorColour,
                               "to", originalColour,
                               "time", 1.25f,
                               "easetype", "easeInCubic",
                               "onUpdate", "UpdateColor"));

            _drawLineHandler.DestroyLine();
            _drawLineHandler.CreateLine();
        }
    }
        private async static Task SeedDiscoveriesAsync(StarStuffDbContext db, int discoveriesCount)
        {
            if (await db.Discoveries.AnyAsync())
            {
                return;
            }

            List <int> telescopeIds = await db.Telescopes
                                      .Select(t => t.Id)
                                      .ToListAsync();

            List <int> astronomerIds = await db.Users
                                       .Where(u => u.Roles.Any(r => r.Role.Name == WebConstants.AstronomerRole))
                                       .Select(u => u.Id)
                                       .ToListAsync();

            for (int i = 1; i <= discoveriesCount; i++)
            {
                Discovery discovery = new Discovery
                {
                    StarSystem = $"StarSystem{CreateGuid()}",
                    Distance   = random.Next(0, int.MaxValue),
                    DateMade   = DateTime.UtcNow
                                 .Date
                                 .AddMonths(-i)
                                 .AddDays(-i),
                    TelescopeId = telescopeIds[random.Next(0, telescopeIds.Count)]
                };

                discovery.Distance *= random.Next(1, 6);

                int planetsCount     = random.Next(0, 10);
                int starsCount       = random.Next(1, 4);
                int discoverersCount = random.Next(1, 6);
                int observersCount   = random.Next(0, 4);

                for (int j = 1; j <= planetsCount; j++)
                {
                    Planet planet = new Planet
                    {
                        Name = $"Planet{CreateGuid()}",
                        Mass = Math.Round((i + j) * Math.PI, 2)
                    };

                    discovery.Planets.Add(planet);
                }

                for (int j = 1; j <= starsCount; j++)
                {
                    Star star = new Star
                    {
                        Name        = $"Star{CreateGuid()}",
                        Temperature = random.Next(
                            DataConstants.StarConstants.TemperatureMinValue,
                            DataConstants.StarConstants.TemperatureMaxValue)
                    };

                    discovery.Stars.Add(star);
                }

                for (int j = 0; j < discoverersCount; j++)
                {
                    int pioneerId = astronomerIds[random.Next(0, astronomerIds.Count)];

                    if (discovery.Pioneers.Any(d => d.PioneerId == pioneerId))
                    {
                        j--;
                        continue;
                    }

                    discovery.Pioneers.Add(new Pioneers
                    {
                        PioneerId = pioneerId
                    });
                }

                for (int j = 0; j < observersCount; j++)
                {
                    int observerId = astronomerIds[random.Next(0, astronomerIds.Count)];

                    if (discovery.Observers.Any(d => d.ObserverId == observerId) ||
                        discovery.Pioneers.Any(d => d.PioneerId == observerId))
                    {
                        j--;
                        continue;
                    }

                    discovery.Observers.Add(new Observers
                    {
                        ObserverId = observerId
                    });
                }

                if (observersCount >= 3)
                {
                    discovery.IsConfirmed = true;
                }

                await db.Discoveries.AddAsync(discovery);
            }

            await db.SaveChangesAsync();
        }
Example #50
0
 public static Regex <T> operator ~(Regex <T> regex)
 => Star.Create(regex);
Example #51
0
        private void Scan(EmpireData empire)
        {
            foreach (Mappable scanner in empire.IterateAllMappables())
            {
                int scanRange    = 0;
                int penScanRange = 0;

                //Do some self scanning (Update reports) and set ranges..
                if (scanner is Star)
                {
                    scanRange    = (scanner as Star).ScanRange;
                    penScanRange = (scanner as Star).ScanRange; // TODO:(priority 6) Planetary Pen-Scan not implemented yet.
                    empire.StarReports[scanner.Name].Update(scanner as Star, ScanLevel.Owned, serverState.TurnYear);
                }
                else
                {
                    scanRange    = (scanner as Fleet).ScanRange;
                    penScanRange = (scanner as Fleet).PenScanRange;
                    empire.FleetReports[scanner.Key].Update(scanner as Fleet, ScanLevel.Owned, empire.TurnYear);
                }

                // Scan everything
                foreach (Mappable scanned in serverState.IterateAllMappables())
                {
                    // ...That isn't ours!
                    if (scanned.Owner == empire.Id)
                    {
                        continue;
                    }

                    ScanLevel scanLevel = ScanLevel.None;
                    double    range     = 0;
                    range = PointUtilities.Distance(scanner.Position, scanned.Position);

                    if (scanned is Star)
                    {
                        Star star = scanned as Star;

                        // There are two ways to get information from a Star:
                        // 1. In orbit with a fleet,
                        // 2. Not in orbit with a Pen Scan (fleet or star).
                        // Non penetrating distance scans won't tell anything about it.
                        if ((scanner is Fleet) && range == 0)
                        {
                            scanLevel = (scanner as Fleet).CanScan ? ScanLevel.InDeepScan : ScanLevel.InPlace;
                        }
                        else // scanner is Star or non orbiting Fleet
                        {
                            scanLevel = (range <= penScanRange) ? ScanLevel.InDeepScan : ScanLevel.None;
                        }

                        // Dont update if we didn't scan to allow report to age.
                        if (scanLevel == ScanLevel.None)
                        {
                            continue;
                        }

                        if (empire.StarReports.ContainsKey(scanned.Name))
                        {
                            empire.StarReports[scanned.Name].Update((scanned as Star), scanLevel, serverState.TurnYear);
                        }
                        else
                        {
                            empire.StarReports.Add(scanned.Name, (scanned as Star).GenerateReport(scanLevel, serverState.TurnYear));
                        }
                    }
                    else // scanned is Fleet
                    {
                        // Fleets are simple as scan levels (PenScan for example) won't affect them. We only
                        // care for non penetrating distance scans.
                        if (range > scanRange)
                        {
                            continue;
                        }

                        // Check if we have a record of this design(s).
                        foreach (ShipToken token in (scanned as Fleet).Composition.Values)
                        {
                            if (empire.EmpireReports[scanned.Owner].Designs.ContainsKey(token.Design.Key))
                            {
                                continue;
                            }

                            // If not, add just the empty Hull.
                            ShipDesign newDesign = new ShipDesign(token.Design);
                            newDesign.Key = token.Design.Key;
                            newDesign.ClearAllocated();
                            empire.EmpireReports[scanned.Owner].Designs.Add(newDesign.Key, newDesign);
                        }

                        if (!empire.FleetReports.ContainsKey(scanned.Key))
                        {
                            empire.FleetReports.Add(scanned.Key, (scanned as Fleet).GenerateReport(ScanLevel.InScan, serverState.TurnYear));
                        }
                        else
                        {
                            empire.FleetReports[scanned.Key].Update((scanned as Fleet), ScanLevel.InScan, serverState.TurnYear);
                        }
                    }
                }
            }
        }
        static void Main(string[] args)
        {
            /*
             * Accepts a single .star and one outdir as input and writes coordinateFiles to outdir for relion picking
             *
             * */
            if (args.Length != 2)
            {
                Console.WriteLine($"Usage: {System.AppDomain.CurrentDomain.FriendlyName} <starFile with orientations> <outdir for coordinates>");
                return;
            }
            string inFileName = args[0];
            string outDir     = args[1];


            Star particleOptics = new Star(inFileName, "optics");

            float pixelSize    = float.Parse(particleOptics.GetRowValue(0, "rlnImagePixelSize"), CultureInfo.InvariantCulture);
            Star  particleStar = new Star(inFileName, "particles");

            if (!Directory.Exists($@"{outDir}\PredictMonomers\average"))
            {
                Directory.CreateDirectory($@"{outDir}\PredictMonomers\average");
            }
            outDir = $@"{outDir}\PredictMonomers";
            var originalMicrographNames = particleStar.GetRelionMicrographNames().Select(v => "average/" + v.Replace(".tif", ".mrc")).ToArray();

            var imageNames = particleStar.GetColumn("rlnImageName").Select(s =>
            {
                string[] Parts = s.Split('@');
                return(Parts[1]);
            }).ToArray();
            var uniqueImages        = new HashSet <string>(imageNames);
            var angles              = particleStar.GetRelionAngles();
            var positions           = particleStar.GetRelionCoordinates();
            var origins             = GetRelionAngstromOffsets(particleStar);
            var NNMapping           = Helper.ArrayOfFunction(idx => - 1, positions.Count());
            var distances           = Helper.ArrayOfFunction(i => - 1.0f, positions.Count());
            var distanceX           = Helper.ArrayOfFunction(i => - 1.0f, positions.Count());
            var distanceY           = Helper.ArrayOfFunction(i => - 1.0f, positions.Count());
            var distanceZ           = Helper.ArrayOfFunction(i => - 1.0f, positions.Count());
            var matrixDists         = Helper.ArrayOfFunction(i => - 1.0f, positions.Count());
            var orientationDistance = Helper.ArrayOfFunction(i => - 1.0f, positions.Count());

            Particle[] particles = Helper.ArrayOfFunction(i => new Particle(positions[i] * pixelSize - origins[i], angles[i] * Helper.ToRad, i, originalMicrographNames[i], 0), imageNames.Length);

            List <int>[] particlesInMics = Helper.ArrayOfFunction(i => new List <int>(), uniqueImages.Count());

            for (int idxGlobal = 0, micrographIdx = 0; idxGlobal < imageNames.Length; micrographIdx++)
            {
                var micrographName = imageNames[idxGlobal];

                while (idxGlobal < imageNames.Length && micrographName == imageNames[idxGlobal])
                {
                    particlesInMics[micrographIdx].Add(idxGlobal);
                    particles[idxGlobal].micrographIdx = micrographIdx;
                    idxGlobal++;
                }
            }

            /*
             *  This loop calculates NN information for every particle, it is very similar to the NearestNeighbour module
             */
            Helper.ForCPU(0, particlesInMics.Count(), 30, null, (micrographIdx, t) =>
            {
                var particlesInMic = particlesInMics[micrographIdx];
                for (int idxInMic = 0; idxInMic < particlesInMic.Count(); idxInMic++)
                {
                    int globalIdx      = particlesInMic[idxInMic];
                    Particle particleI = particles[particlesInMic[idxInMic]];
                    float smallestD    = float.MaxValue;
                    float smallestO    = float.MaxValue;
                    float dX           = 0;
                    float dY           = 0;
                    float dZ           = 0;
                    float matrixDist   = 0;

                    int smallestGlobalJdx = -1;
                    for (int jdxInMic = 0; jdxInMic < particlesInMic.Count(); jdxInMic++)
                    {
                        Particle particleJ = particles[particlesInMic[jdxInMic]];
                        if (idxInMic == jdxInMic)
                        {
                            continue;
                        }
                        float d = (particleI.pos - particleJ.pos).Length();

                        if (d < smallestD)
                        {
                            smallestD         = d;
                            smallestGlobalJdx = particleJ.idx;
                            float3 direction  = particleJ.pos - particleI.pos;

                            direction.Y         = (float)(direction.Y / Math.Cos(30.0 / 360.0 * 2 * Math.PI));
                            float3 directionRot = particleI.orientation.Transposed() * direction;
                            dX = directionRot.X;
                            dY = directionRot.Y;
                            dZ = directionRot.Z;
                            if (dY > 0)
                            {
                                Matrix3 R = particleJ.orientation * particleI.orientation.Transposed();
                                smallestO = (float)Math.Acos((R.M11 + R.M22 + R.M33 - 1) / 2.0d);  //http://www.boris-belousov.net/2016/12/01/quat-dist/#using-rotation-matrices
                            }
                            else
                            {
                                Matrix3 R = particleI.orientation * particleJ.orientation.Transposed();
                                smallestO = (float)Math.Acos((R.M11 + R.M22 + R.M33 - 1) / 2.0d);  //http://www.boris-belousov.net/2016/12/01/quat-dist/#using-rotation-matrices
                            }
                        }
                    }
                    NNMapping[globalIdx]           = smallestGlobalJdx;
                    distances[globalIdx]           = smallestD;
                    distanceX[globalIdx]           = dX;
                    distanceY[globalIdx]           = dY;
                    distanceZ[globalIdx]           = dZ;
                    matrixDists[globalIdx]         = matrixDist;
                    orientationDistance[globalIdx] = smallestO;
                }
            }, null);

            int newParticleIdx = 1;

            /*
             * This is a very approximate expected orientation which we use to predict where a second monomer would have to be on the micrograph for a chance to form the dimer we have observed.
             * Note that we only predict the position on the micrograph for a new particle extraction. The pose that will be assigned to the extracted particles in the subsequent reconstruction will
             * be unbiased from this code and is not biased towards dimeric conformations
             */
            float3 TheoDir = new float3(25, -60, 60);

            Star filteredParticles = new Star(particleStar.GetColumnNames());

            Helper.ForCPU(0, particlesInMics.Count(), 15, null, (micrographIdx, t) =>
            {
                Star newParticles     = new Star(new string[] { "rlnCoordinateX", "rlnCoordinateY" });
                string micrographName = imageNames[particles[particlesInMics[micrographIdx][0]].idx];

                for (int idxInMic = 0; idxInMic < particlesInMics[micrographIdx].Count(); idxInMic++)
                {
                    int globalIdx      = particlesInMics[micrographIdx][idxInMic];
                    float3 thisTheoDir = particles[globalIdx].orientation * TheoDir;
                    newParticles.AddRow(new List <string>(new string[] { $"{particles[globalIdx].pos.X / pixelSize}", $"{particles[globalIdx].pos.Y / pixelSize}" }));
                    newParticleIdx++;

                    /*
                     * In case there is no NN that fullfills the dimer criterion, predict where a monomer would ahve to be based on the TheoDir
                     */
                    if (true && !(distances[globalIdx] < 90 && orientationDistance[globalIdx] > 2.9))
                    {
                        float3 newLoc = particles[globalIdx].pos + thisTheoDir;
                        newParticles.AddRow(new List <string>(new string[] { $"{(newLoc.X / pixelSize).ToString(CultureInfo.InvariantCulture)}", $"{(newLoc.Y / pixelSize).ToString(CultureInfo.InvariantCulture)}" }));

                        newParticleIdx++;
                        newLoc = particles[globalIdx].pos - thisTheoDir;
                        newParticles.AddRow(new List <string>(new string[] { $"{(newLoc.X / pixelSize).ToString(CultureInfo.InvariantCulture)}", $"{(newLoc.Y / pixelSize).ToString(CultureInfo.InvariantCulture)}" }));

                        newParticleIdx++;
                    }
                }
                newParticles.Save($@"{outDir}\{micrographName.Replace("particles", "average").Replace("_SARSCoV2_nsp12_net_5.mrcs", "")}_predictedpick.star");
            }, null);
            using (System.IO.StreamWriter file = new System.IO.StreamWriter($@"{outDir}\coords_suffix_predictedpick.star", false))
            {
                file.WriteLine("micrographs.star");
            }
        }
Example #53
0
        static void Main(string[] args)
        {
            CultureInfo.DefaultThreadCurrentCulture   = CultureInfo.InvariantCulture;
            CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.InvariantCulture;

            Options Options = new Options();
            string  WorkingDirectory;

            Dictionary <int, string> MaskOverrideNames = new Dictionary <int, string>();

            if (!Debugger.IsAttached)
            {
                Parser.Default.ParseArguments <Options>(args).WithParsed <Options>(opts => Options = opts);
                WorkingDirectory = Environment.CurrentDirectory + "/";
            }
            else
            {
                Options.PopulationPath  = "population/fine_align.population";
                Options.MinResolution   = 15;
                Options.DoTiltFrames    = true;
                Options.FitAnisotropy   = false;
                Options.ResolveLocation = false;
                Options.ResolveFrames   = true;
                Options.ResolveItems    = true;
                Options.GridWidth       = 5;
                Options.GridHeight      = 5;

                WorkingDirectory = @"Y:\data\dtegunov\20190731_2Dvs3D\3D\";
            }

            Options.PopulationPath = Path.Combine(WorkingDirectory, Options.PopulationPath);
            string RefinementDirectory = Path.Combine(Helper.PathToFolder(Options.PopulationPath), "refinement_temp");

            if (!Options.ResolveFrames && !Options.ResolveItems && !Options.ResolveLocation)
            {
                throw new Exception("No dimension chosen to resolve over.");
            }

            if (Options.ResolveLocation && (Options.ResolveFrames || Options.ResolveItems))
            {
                throw new Exception("Spatial resolution cannot be combined with other dimensions in the same run. Please execute separately with different dimensions.");
            }

            Population P = new Population(Options.PopulationPath);

            DataSource[] Sources = P.Sources.ToArray();

            float PixelSize = (float)P.Species[0].PixelSize;

            foreach (var source in Sources)
            {
                List <Movie> ItemsWithData = new List <Movie>();

                foreach (var item in source.Files.Values)
                {
                    if (Options.DoTiltFrames)
                    {
                        bool       SomethingMissing = false;
                        string     ItemPath         = Path.Combine(source.FolderPath, item);
                        TiltSeries Series           = new TiltSeries(ItemPath);

                        for (int t = 0; t < Series.NTilts; t++)
                        {
                            if (!File.Exists(Path.Combine(RefinementDirectory, $"{Helper.PathToName(item)}_tilt{t:D3}_fsc.mrc")))
                            {
                                SomethingMissing = true;
                                break;
                            }
                        }

                        if (SomethingMissing)
                        {
                            continue;
                        }

                        ItemsWithData.Add(Series);
                    }
                    else
                    {
                        if (Options.ResolveFrames || Options.ResolveItems)
                        {
                            if (!File.Exists(Path.Combine(RefinementDirectory, Helper.PathToName(item) + "_fsc.mrc")))
                            {
                                continue;
                            }
                        }
                        else if (Options.ResolveLocation)
                        {
                            if (!File.Exists(Path.Combine(RefinementDirectory, Helper.PathToName(item) + "_fscparticles.mrc")))
                            {
                                continue;
                            }
                            if (!File.Exists(Path.Combine(RefinementDirectory, Helper.PathToName(item) + "_fscparticles.star")))
                            {
                                continue;
                            }
                        }

                        string ItemPath = Path.Combine(source.FolderPath, item);

                        if (item.Contains(".tomostar"))
                        {
                            ItemsWithData.Add(new TiltSeries(ItemPath));
                        }
                        else
                        {
                            ItemsWithData.Add(new Movie(ItemPath));
                        }
                    }
                }

                if (ItemsWithData.Count == 0)
                {
                    Console.WriteLine($"No items with FSC data found for source {source.Name}!");
                }

                if (Options.DoTiltFrames)
                {
                    for (int t = 0; t < ((TiltSeries)ItemsWithData[0]).NTilts; t++)
                    {
                        int2 Dims;
                        int  MaxFrames = 1;
                        {
                            string FSCPath = Path.Combine(RefinementDirectory, $"{ItemsWithData[0].RootName}_tilt{t:D3}_fsc.mrc");
                            Image  FSC     = Image.FromFile(FSCPath);
                            Dims      = new int2(FSC.Dims.Y);
                            MaxFrames = FSC.Dims.Z / 3;
                            FSC.Dispose();
                        }

                        List <float[]> AllAB = new List <float[]>();
                        List <float[]> AllA2 = new List <float[]>();
                        List <float[]> AllB2 = new List <float[]>();

                        foreach (var parentItem in ItemsWithData.Select(v => (TiltSeries)v))
                        {
                            string MoviePath = Path.Combine(parentItem.DirectoryName, parentItem.TiltMoviePaths[t]);
                            Movie  item      = new Movie(MoviePath);

                            {
                                string FSCPath = Path.Combine(RefinementDirectory, $"{parentItem.RootName}_tilt{t:D3}_fsc.mrc");

                                Image     FSC     = Image.FromFile(FSCPath);
                                float[][] FSCData = FSC.GetHost(Intent.Read);

                                for (int z = 0; z < FSCData.Length / 3; z++)
                                {
                                    if (AllAB.Count <= z)
                                    {
                                        AllAB.Add(FSCData[z * 3 + 0]);
                                        AllA2.Add(FSCData[z * 3 + 1]);
                                        AllB2.Add(FSCData[z * 3 + 2]);
                                    }
                                    else
                                    {
                                        for (int i = 0; i < FSCData[0].Length; i++)
                                        {
                                            AllAB[z][i] += FSCData[z * 3 + 0][i];
                                            AllA2[z][i] += FSCData[z * 3 + 1][i];
                                            AllB2[z][i] += FSCData[z * 3 + 2][i];
                                        }
                                    }
                                }

                                FSC.Dispose();
                            }
                        }

                        int NItems = AllAB.Count;

                        Image CorrAB = new Image(AllAB.ToArray(), new int3(Dims.X, Dims.Y, NItems), true);
                        Image CorrA2 = new Image(AllA2.ToArray(), new int3(Dims.X, Dims.Y, NItems), true);
                        Image CorrB2 = new Image(AllB2.ToArray(), new int3(Dims.X, Dims.Y, NItems), true);

                        Image CTFWeights = CorrAB.GetCopyGPU();
                        CTFWeights.Fill(1f);

                        (float[] ResultScales, float3[] ResultBfactors) = FSC.FitBFactors2D(CorrAB, CorrA2, CorrB2, CTFWeights, PixelSize, Options.MinResolution, Options.FitAnisotropy);

                        CorrAB.Dispose();
                        CorrA2.Dispose();
                        CorrB2.Dispose();
                        CTFWeights.Dispose();

                        float MaxScale = MathHelper.Max(ResultScales);
                        ResultScales = ResultScales.Select(v => v / MaxScale).ToArray();

                        List <float> BfacsSorted = new List <float>(ResultBfactors.Select(v => v.X));
                        float        MaxBfac     = MathHelper.Max(BfacsSorted);
                        //float MaxBfac = MathHelper.Max(ResultBfactors.Select(v => v.X));
                        ResultBfactors = ResultBfactors.Select(v => new float3(Math.Min(0, v.X - MaxBfac), v.Y, v.Z)).ToArray();

                        List <float3> TableRows = new List <float3>();

                        foreach (var parentItem in ItemsWithData.Select(v => (TiltSeries)v))
                        {
                            string MoviePath = Path.Combine(parentItem.DirectoryName, parentItem.TiltMoviePaths[t]);
                            Movie  item      = new Movie(MoviePath);

                            int InThisItem = MaxFrames;

                            float[] Weights    = ResultScales;
                            float[] Bfacs      = ResultBfactors.Select(v => v.X).ToArray();
                            float[] BfacsDelta = ResultBfactors.Select(v => v.Y).ToArray();
                            float[] BfacsAngle = ResultBfactors.Select(v => v.Z).ToArray();

                            (int MaxIndex, float MaxB) = MathHelper.MaxElement(Bfacs);
                            TableRows.Add(new float3((float)item.CTF.Defocus,
                                                     Weights[MaxIndex],
                                                     MaxB));

                            item.GridDoseWeights = new CubicGrid(new int3(1, 1, InThisItem), Weights);

                            item.GridDoseBfacs      = new CubicGrid(new int3(1, 1, InThisItem), Bfacs);
                            item.GridDoseBfacsDelta = new CubicGrid(new int3(1, 1, InThisItem), BfacsDelta);
                            item.GridDoseBfacsAngle = new CubicGrid(new int3(1, 1, InThisItem), BfacsAngle);

                            item.SaveMeta();
                        }
                    }
                }
                else if (Options.ResolveFrames || Options.ResolveItems)
                {
                    int2 Dims;
                    int  MaxFrames = 1;
                    {
                        string FSCPath = Path.Combine(RefinementDirectory, ItemsWithData[0].RootName + "_fsc.mrc");
                        Image  FSC     = Image.FromFile(FSCPath);
                        Dims      = new int2(FSC.Dims.Y);
                        MaxFrames = FSC.Dims.Z / 3;
                        FSC.Dispose();
                    }

                    List <float[]> AllAB = new List <float[]>(); // (Helper.ArrayOfFunction(i => new float[Dims.ElementsFFT()], MaxFrames));
                    List <float[]> AllA2 = new List <float[]>(); // (Helper.ArrayOfFunction(i => new float[Dims.ElementsFFT()], MaxFrames));
                    List <float[]> AllB2 = new List <float[]>(); // (Helper.ArrayOfFunction(i => new float[Dims.ElementsFFT()], MaxFrames));

                    int NDone = 0;
                    foreach (var item in ItemsWithData)
                    {
                        //if (NDone++ >= 30)
                        //    break;

                        string FSCPath = Path.Combine(RefinementDirectory, item.RootName + "_fsc.mrc");

                        Image     FSC     = Image.FromFile(FSCPath);
                        float[][] FSCData = FSC.GetHost(Intent.Read);

                        for (int z = 0; z < FSCData.Length / 3; z++)
                        {
                            AllAB.Add(FSCData[z * 3 + 0]);
                            AllA2.Add(FSCData[z * 3 + 1]);
                            AllB2.Add(FSCData[z * 3 + 2]);
                            //for (int i = 0; i < FSCData[0].Length; i++)
                            //{
                            //    AllAB[z][i] += FSCData[z * 3 + 0][i];
                            //    AllA2[z][i] += FSCData[z * 3 + 1][i];
                            //    AllB2[z][i] += FSCData[z * 3 + 2][i];
                            //}
                        }

                        FSC.Dispose();
                    }

                    int NItems = AllAB.Count;

                    Image CorrAB = new Image(AllAB.ToArray(), new int3(Dims.X, Dims.Y, NItems), true);
                    Image CorrA2 = new Image(AllA2.ToArray(), new int3(Dims.X, Dims.Y, NItems), true);
                    Image CorrB2 = new Image(AllB2.ToArray(), new int3(Dims.X, Dims.Y, NItems), true);

                    Image CTFWeights = CorrAB.GetCopyGPU();
                    CTFWeights.Fill(1f);

                    (float[] ResultScales, float3[] ResultBfactors) = FSC.FitBFactors2D(CorrAB, CorrA2, CorrB2, CTFWeights, PixelSize, Options.MinResolution, Options.FitAnisotropy);

                    float MaxScale = MathHelper.Max(ResultScales);
                    ResultScales = ResultScales.Select(v => v / MaxScale).ToArray();

                    List <float> BfacsSorted = new List <float>(ResultBfactors.Select(v => v.X));
                    BfacsSorted.Sort();
                    float MaxBfac = BfacsSorted[(int)(BfacsSorted.Count * 0.99f)];
                    //float MaxBfac = MathHelper.Max(ResultBfactors.Select(v => v.X));
                    ResultBfactors = ResultBfactors.Select(v => new float3(Math.Min(0, v.X - MaxBfac), v.Y, v.Z)).ToArray();

                    List <float3> TableRows = new List <float3>();

                    int NFramesDone = 0;
                    foreach (var item in ItemsWithData)
                    {
                        int InThisItem = MaxFrames;
                        if (item.GetType() == typeof(TiltSeries))
                        {
                            InThisItem = ((TiltSeries)item).NTilts;
                        }

                        float[] Weights    = ResultScales.Skip(NFramesDone).Take(InThisItem).ToArray();
                        float[] Bfacs      = ResultBfactors.Skip(NFramesDone).Take(InThisItem).Select(v => v.X).ToArray();
                        float[] BfacsDelta = ResultBfactors.Skip(NFramesDone).Take(InThisItem).Select(v => v.Y).ToArray();
                        float[] BfacsAngle = ResultBfactors.Skip(NFramesDone).Take(InThisItem).Select(v => v.Z).ToArray();

                        (int MaxIndex, float MaxB) = MathHelper.MaxElement(Bfacs);
                        TableRows.Add(new float3((float)item.CTF.Defocus,
                                                 Weights[MaxIndex],
                                                 MaxB));

                        item.GridDoseWeights = new CubicGrid(new int3(1, 1, InThisItem), Weights);

                        item.GridDoseBfacs      = new CubicGrid(new int3(1, 1, InThisItem), Bfacs);
                        item.GridDoseBfacsDelta = new CubicGrid(new int3(1, 1, InThisItem), BfacsDelta);
                        item.GridDoseBfacsAngle = new CubicGrid(new int3(1, 1, InThisItem), BfacsAngle);

                        item.SaveMeta();

                        NFramesDone += InThisItem;
                    }

                    (new Star(TableRows.ToArray(), "wrpDefocus", "wrpMaxWeight", "wrpMaxB")).Save("d_defocus_vs_bfactor.star");
                }
                else if (Options.ResolveLocation)
                {
                    List <List <Movie> > ItemGroups = new List <List <Movie> >();
                    foreach (var item in ItemsWithData)
                    {
                        ItemGroups.Add(new List <Movie>()
                        {
                            item
                        });
                    }

                    int FSCLength = 0;
                    {
                        string FSCPath = Path.Combine(RefinementDirectory, ItemsWithData[0].RootName + "_fscparticles.mrc");
                        Image  FSC     = Image.FromFile(FSCPath);
                        FSCLength = FSC.Dims.X;
                        FSC.Dispose();
                    }

                    int NGroupsDone = 0;
                    foreach (var itemGroup in ItemGroups)
                    {
                        int2       DimsGrid       = new int2(Options.GridWidth, Options.GridHeight);
                        float2     GridMultiplier = new float2(DimsGrid - 1);
                        float3[][] AllFSCs        = Helper.ArrayOfFunction(i => new float3[FSCLength], (int)DimsGrid.Elements());
                        float[][]  AllCTFs        = Helper.ArrayOfFunction(i => Helper.ArrayOfConstant(1f, FSCLength), (int)DimsGrid.Elements());

                        foreach (var item in itemGroup)
                        {
                            string FSCPath  = Path.Combine(RefinementDirectory, item.RootName + "_fscparticles.mrc");
                            string StarPath = Path.Combine(RefinementDirectory, item.RootName + "_fscparticles.star");

                            Image   FSC     = Image.FromFile(FSCPath);
                            float[] FSCData = FSC.GetHost(Intent.Read)[0];

                            Star     TableIn = new Star(StarPath);
                            float2[] Coords  = TableIn.GetFloat2("wrpNormCoordinateX", "wrpNormCoordinateY");

                            if (Coords.Length * 3 != FSC.Dims.Y)
                            {
                                throw new Exception($"Number of particles does not match number of FSC lines");
                            }

                            for (int p = 0; p < Coords.Length; p++)
                            {
                                int2 CoordsRounded = new int2((int)Math.Round(Coords[p].X * GridMultiplier.X),
                                                              (int)Math.Round(Coords[p].Y * GridMultiplier.Y));
                                int      FSCID    = CoordsRounded.Y * DimsGrid.X + CoordsRounded.X;
                                float3[] LocalFSC = AllFSCs[FSCID];

                                for (int i = 0; i < FSCLength; i++)
                                {
                                    LocalFSC[i] += new float3(FSCData[(p * 3 + 0) * FSCLength + i],
                                                              FSCData[(p * 3 + 1) * FSCLength + i],
                                                              FSCData[(p * 3 + 2) * FSCLength + i]);
                                }
                            }

                            FSC.Dispose();
                        }

                        try
                        {
                            float2[] PositionFits = FSC.FitBFactors(AllFSCs, AllCTFs, PixelSize, Options.MinResolution);

                            float MaxWeight  = MathHelper.Max(PositionFits.Select(v => v.X));
                            float MaxBfactor = MathHelper.Max(PositionFits.Select(v => v.Y));

                            PositionFits = PositionFits.Select(v => new float2(v.X / MaxWeight, v.Y - MaxBfactor)).ToArray();

                            Image Fitted = new Image(new[] { PositionFits.Select(v => v.X).ToArray(), PositionFits.Select(v => v.Y).ToArray() }, new int3(DimsGrid.X, DimsGrid.Y, 2));
                            Fitted.WriteMRC($"d_fitted_{NGroupsDone}.mrc", true);

                            foreach (var item in itemGroup)
                            {
                                item.GridLocationWeights = new CubicGrid(new int3(DimsGrid.X, DimsGrid.Y, 1), PositionFits.Select(v => v.X).ToArray());
                                item.GridLocationBfacs   = new CubicGrid(new int3(DimsGrid.X, DimsGrid.Y, 1), PositionFits.Select(v => v.Y).ToArray());

                                item.SaveMeta();
                            }
                        }
                        catch { }

                        NGroupsDone++;
                    }
                }
            }
        }
 public void AddStar(Star star)
 {
     _spaceDbContext.Add(star);
 }
Example #55
0
 public void OnStarCollection(Star star)
 {
     StarsCollected[_starsIndexes[star]] = true;
     OnStarCollected?.Invoke(_starsIndexes[star]);
     Destroy(star.gameObject);
 }
Example #56
0
 public void AddEdge(Star from, Star to)
 {
     stars.AddEdge(stars.Nodes[from.index], stars.Nodes[to.index]);
 }
Example #57
0
    private float starSizeScale = 1.0f; // if modify this value that will update after click PLAY button in Editor

    #endregion Fields

    #region Methods

    public Mesh InitializeStarfield()
    {
        float starDistance = (Camera.main !=null)? Camera.main.farClipPlane - 10f : 990f ;
        float starSize = starDistance / 100 * starSizeScale;

        // Load star positions and colors from file with 9110 predefined stars.
        TextAsset data =  Resources.Load<TextAsset>("StarsData");
        if (data == null){
            Debug.Log("Can't find or read StarsData.bytes file.");
            return null;
        }

        const int numberOfStars = 9110;
        var stars = new Star[numberOfStars];

        using (BinaryReader reader = new BinaryReader(new MemoryStream(data.bytes)))
        {
            for (int i = 0; i < numberOfStars; i++)
            {
                stars[i].position.x = reader.ReadSingle();
                stars[i].position.z = reader.ReadSingle();
                stars[i].position.y = reader.ReadSingle(); // Z-up to Y-up

                stars[i].position = Vector3.Scale (stars[i].position,new Vector3(-1f,1f,-1f));

                stars[i].color.r = reader.ReadSingle();
                stars[i].color.g = reader.ReadSingle();
                stars[i].color.b = reader.ReadSingle();

                // Using luminance term to sort the brightness for magnitude
                float magnitude = Vector3.Dot(new Vector3(stars[i].color.r,stars[i].color.g,stars[i].color.b), new Vector3(0.22f,0.707f,0.071f));

                stars[i].color.a = magnitude ;

                // Note: To improve performance, we could sort stars by brightness and remove less important stars.
                // Generate static stars for upper hemi sky dome only and 1023 predefined stars.
                if (stars[i].position.y < 0.1f || stars[i].color.a < 1.7037e-2f)
                {
                    continue;
                }
                    CombineInstance ci = new CombineInstance();
                    ci.mesh = createQuad(starSize);

                    ci.transform = BillboardMatrix(stars[i].position * starDistance);

                    Color[] colors = {stars[i].color,stars[i].color,stars[i].color,stars[i].color};
                    ci.mesh.colors = colors;

                    starQuad.Add(ci);

            }
        }
        // -------------------------------------------
        // Combine Quad Meshes
        Mesh m = new Mesh();
        m.name = "StarsFieldMesh";
        m.CombineMeshes(starQuad.ToArray());
        m.Optimize();
        // over size mesh bounds to avoid camera Frustum Culling for Vertex transformation in shader
        m.bounds = new Bounds ( Vector3.zero, Vector3.one * 4e9f );

        return m;
    }
Example #58
0
 public void SetStar(Star s)
 {
     star = s;
     texts.ToArray()[0].text = s.GetName();
 }
Example #59
0
 private void pointStarToolStripMenuItem_Click(object sender, EventArgs e)
 {
     Star p = new Star(-world.Viewport.Y, -world.Viewport.X);
     addElement(p);
 }
Example #60
0
    public void GenerateSolarSystem()
    {
        System.Random rand = new System.Random();

        //for generating a new solar system on the fly
        if (_solarSystem.Planets != null)
        {
            foreach (Planet p in _solarSystem.Planets)
            {
                Destroy(p.gameObject);
            }
            _solarSystem.Planets.Clear();
        }


        if (_solarSystem.Star != null)
        {
            Destroy(_solarSystem.Star.gameObject);
        }

        GameObject starGameObject = Instantiate(SolarSystemPrefabs.StarPrefab, transform.position, Quaternion.identity, this.transform);

        Star star = starGameObject.GetComponent <Star>();

        star.Name = StarName.Generate(rand);

        float starSize = Random.Range(Settings.MinStarSize, Settings.MaxStarSize) * Settings.SizeScale;

        star.Size = new Vector3(starSize, starSize, starSize);

        _solarSystem.Star = star;


        int   planetAmount       = Random.Range(Settings.MinPlanets, Settings.MaxPlanets);
        float lastPlanetDistance = 0f;

        for (int i = 0; i < planetAmount; i++)
        {
            //Instantiate planets
            float distance = Random.Range(Settings.MinDistanceBetween, Settings.MaxDistanceBetween) + lastPlanetDistance;
            lastPlanetDistance = distance;

            GameObject planetGameObject = Instantiate(SolarSystemPrefabs.PlanetPrefab,
                                                      star.transform.position + new Vector3(distance * Settings.SizeScale, distance * Settings.SizeScale, 0),
                                                      Quaternion.identity, this.transform);

            Planet planet = planetGameObject.GetComponent <Planet>();

            //set Planet Name
            planet.Name = StarName.Generate(rand);

            //set Planet Size
            float planetSize = Random.Range(Settings.MinPlanetSize, Settings.MaxPlanetSize) * ((distance / 10000) / Settings.SizeScale);
            planet.Size = new Vector3(planetSize, planetSize, planetSize);

            planet.OrbitPeriod = (distance / Settings.SizeScale) * 2;
            _solarSystem.Planets.Add(planet);

            //determine if planet has satellites orbiting it and instantiate them
            bool hasSatellite = Random.Range(Settings.ChanceOfSatellite, 10) <= Settings.ChanceOfSatellite;

            if (hasSatellite)
            {
                int satelliteAmount = Random.Range(Settings.MinSatellites, Settings.MaxPlanets);

                float lastSatelliteDistance = 0f;

                //instantiate satellite
                for (int j = 0; j < satelliteAmount; j++)
                {
                    float distanceToPlanet = (((distance * Settings.SizeScale) + lastSatelliteDistance) + planetSize) / 20;

                    lastSatelliteDistance = distanceToPlanet;

                    GameObject satelliteGameObject = Instantiate(SolarSystemPrefabs.SattelitePrefab,
                                                                 planetGameObject.transform.position + new Vector3(distanceToPlanet, 0, distanceToPlanet),
                                                                 Quaternion.identity, planet.transform);

                    Satellite satellite = satelliteGameObject.GetComponent <Satellite>();
                    satellite.OrbitPeriod = distanceToPlanet * planetSize * 100;
                    satellite.Orbiter     = planet;

                    //set Satellite name
                    satellite.Name = StarName.Generate(rand);

                    float satelliteSize = Random.Range(Settings.MinPlanetSize, Settings.MaxPlanetSize) * ((distanceToPlanet / 1000) / Settings.SizeScale);
                    satellite.Size = new Vector3(satelliteSize, satelliteSize, satelliteSize);

                    planet.Sattelites.Add(satellite);
                }
            }
        }

        _solarSystem.AllignPlanets();
    }