public Explosion(Texture2D textrue, Vector3 position)
 {
     sprite = new SimpleSprite( AppMain.graphics, textrue);
     sprite.Center.X = 0.5f;
     sprite.Center.Y = 0.5f;
     sprite.Position = position;
 }
Beispiel #2
0
        public override void Initialize()
        {
            this.game = new Lines.Game ();
            this.game.Initialize (this);

            #region WAVE SOFTWARE LICENSE AGREEMENT
            this.backgroundSplashColor = new Color ("#ebebeb");
            this.spriteBatch = new SpriteBatch (WaveServices.GraphicsDevice);

            var resourceNames = Assembly.GetExecutingAssembly ().GetManifestResourceNames ();
            string name = string.Empty;

            foreach (string item in resourceNames) {
                if (item.Contains ("SplashScreen.wpk")) {
                    name = item;
                    break;
                }
            }

            if (string.IsNullOrWhiteSpace (name)) {
                throw new InvalidProgramException ("License terms not agreed.");
            }

            using (Stream stream = Assembly.GetExecutingAssembly ().GetManifestResourceStream (name)) {
                this.splashScreen = WaveServices.Assets.Global.LoadAsset<Texture2D> (name, stream);
            }
            #endregion
        }
Beispiel #3
0
        protected override void Initialize()
        {
            UITexture = Content.Load<Texture2D> ("TDUserInterface.png", TextureConfiguration.Nearest);
            SpriteSheet = new SpriteSheet2D (Content.Load<Texture2D> ("TDSheet.png", TextureConfiguration.Nearest), 16, 16);

            TileMap = new TileMap (Vector2.Zero, 26 / 2, 18 / 2, new Vector2 (16, 16), 4);
            TileMap.AddLayer ("GrassLayer", SpriteSheet);

            for (int y = 0; y < TileMap.Height; y++)
                for (int x = 0; x < TileMap.Width; x++)
                    TileMap.SetTile ("GrassLayer", x, y, new Tile { TileId = SpriteSheet.GetTileId(1, 1) });

            TileMap.AddLayer ("Track", SpriteSheet);
            var tiles = new int[][] {
                new int[] { },
                new int[] { 20, 1, 1, 2 },
                new int[] { -1, -1, -1, 32, 1, 2 },
                new int[] { 0, 1, 2, -1, -1, 16, -1, 16 },
                new int[] { 16, -1, 16, -1, -1, 18, -1, 16 },
                new int[] { 16, -1, 32, 1, 1, 34, -1, 16 },
                new int[] { 16, -1, -1, -1, -1, -1, -1, 16 },
                new int[] { 32, 1, 1, 1, 1, 1, 1, 34 }
            };

            for (int y = 0; y < tiles.Length; y++)
                for (int x = 0; x < tiles[y].Length; x++)
                    TileMap.SetTile ("Track", x, y, new Tile { TileId = tiles[y][x] });

            Font = Content.Load<Font> ("durselinvenice2015.ttf", 15f);

            base.Initialize ();
        }
Beispiel #4
0
		public void LoadResources()
		{
			if (m_Disposed == true)
			{
				Buffer = new Texture2D(GameEnvironment.Device, new Texture2DDescription()
				{
					Format = m_Format,
					Width = m_Width,
					Height = m_Height,
					OptionFlags = ResourceOptionFlags.None,
					MipLevels = 1,
					ArraySize = 1,
					BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource,
					CpuAccessFlags = CpuAccessFlags.None,
					SampleDescription = new SampleDescription(1, 0),
					Usage = ResourceUsage.Default
				});

				View = new RenderTargetView(GameEnvironment.Device, Buffer);
				ResourceView = new ShaderResourceView(GameEnvironment.Device, Buffer);
				Viewport = new Viewport(0, 0, Buffer.Description.Width, Buffer.Description.Height);

				m_Disposed = false;
			}
		}
        public TitleScene()
        {
            this.Camera.SetViewFromViewport();
            _texture = new Texture2D("Application/images/title.png",false);
            _ti = new TextureInfo(_texture);
            SpriteUV titleScreen = new SpriteUV(_ti);
            titleScreen.Scale = _ti.TextureSizef;
            titleScreen.Pivot = new Vector2(0.5f,0.5f);
            titleScreen.Position = new Vector2(Director.Instance.GL.Context.GetViewport().Width/2,
                                              Director.Instance.GL.Context.GetViewport().Height/2);
            this.AddChild(titleScreen);

            Vector4 origColor = titleScreen.Color;
            titleScreen.Color = new Vector4(0,0,0,0);
            var tintAction = new TintTo(origColor,10.0f);
            ActionManager.Instance.AddAction(tintAction,titleScreen);
            tintAction.Run();

            _titleSong = new Bgm("/Application/audio/titlesong.mp3");

            if(_songPlayer != null)
            _songPlayer.Dispose();
            _songPlayer = _titleSong.CreatePlayer();

            Scheduler.Instance.ScheduleUpdateForTarget(this,0,false);

            // Clear any queued clicks so we dont immediately exit if coming in from the menu
            Touch.GetData(0).Clear();
        }
Beispiel #6
0
        public static Texture2D TextureFromBitmap(Bitmap image)
        {
            BitmapData data = image.LockBits(new Rectangle(0, 0, image.Width, image.Height),
                                             ImageLockMode.ReadWrite, image.PixelFormat);
            int bytes = data.Stride*image.Height;
            DataStream stream = new DataStream(bytes, true, true);
            stream.WriteRange(data.Scan0, bytes);
            stream.Position = 0;
            DataRectangle dRect = new DataRectangle(data.Stride, stream);

            Texture2DDescription texDesc = new Texture2DDescription
                                               {
                                                   ArraySize = 1,
                                                   MipLevels = 1,
                                                   SampleDescription = new SampleDescription(1, 0),
                                                   Format = Format.B8G8R8A8_UNorm,
                                                   CpuAccessFlags = CpuAccessFlags.None,
                                                   BindFlags = BindFlags.ShaderResource,
                                                   Usage = ResourceUsage.Immutable,
                                                   Height = image.Height,
                                                   Width = image.Width
                                               };

            image.UnlockBits(data);
            image.Dispose();
            Texture2D texture = new Texture2D(Game.Context.Device, texDesc, dRect);
            stream.Dispose();
            return texture;
        }
        public void AddTextureAsset(String path, Object user, Int32 u, Int32 v)
        {
            if (String.IsNullOrWhiteSpace(path))
                throw new ArgumentException();

            if (user == null)
                throw new ArgumentNullException();

            Vector2i tiles = new Vector2i(u, v);

            if (TextureAssetsByUsers.ContainsKey(path))
            {
                if (TextureAssetsByUsers[path].TextureInfo.NumTiles != tiles)
                    throw new ArgumentException("Duplicate texture asset with different tiles: " + path);

                TextureAssetsByUsers[path].AddUser(user);
            }
            else
            {
                Texture2D t = new Texture2D(path, false);
                TextureInfo ti = new TextureInfo(t, tiles);

                TextureAssetsByUsers[path] = new TextureUsers(ti, user);
            }
        }
Beispiel #8
0
        public void Render( Texture2D texture, Scene scene)
        {
            TextureInfo ti1 = new TextureInfo();

            //if(flip)
                ti1.Texture = texture;
            //	else
            //		ti1.Texture = texture1;

               		SpriteUV sprite1 = new SpriteUV();
               		sprite1.TextureInfo = ti1;

               		if(type==0)
            sprite1.Quad.S = ti1.TextureSizef.Multiply(.3f);

            if(type==1)
            sprite1.Quad.S = ti1.TextureSizef.Multiply(.05f);

               		sprite1.CenterSprite();
               		sprite1.Position = position;// scene.Camera.CalcBounds().Center;

            sprite1.Rotate(-rotation);//*Sce.PlayStation.HighLevel.GameEngine2D.Base.Math.Pi/180);

               		scene.AddChild(sprite1);
        }
Beispiel #9
0
        protected D3DApp(IntPtr hInstance)
        {
            AppInst = hInstance;
            MainWindowCaption = "D3D11 Application";
            DriverType = DriverType.Hardware;
            ClientWidth = 800;
            ClientHeight = 600;
            Enable4XMsaa = false;
            Window = null;
            AppPaused = false;
            Minimized = false;
            Maximized = false;
            Resizing = false;
            Msaa4XQuality = 0;
            Device = null;
            ImmediateContext = null;
            SwapChain = null;
            DepthStencilBuffer = null;
            RenderTargetView = null;
            DepthStencilView = null;
            Viewport = new Viewport();
            Timer = new GameTimer();

            GD3DApp = this;
        }
Beispiel #10
0
 public override void OnLoad()
 {
     _planetTexture = TextureManager.Load("Images/Misc/VortexSky/Planet");
     _bgTexture = TextureManager.Load("Images/Misc/VortexSky/Background");
     _boltTexture = TextureManager.Load("Images/Misc/VortexSky/Bolt");
     _flashTexture = TextureManager.Load("Images/Misc/VortexSky/Flash");
 }
Beispiel #11
0
 public static Texture2D MakePixel(Color color)
 {
     Texture2D tex = new Texture2D(1, 1, TextureFormat.RGBA32, false);
     tex.SetPixel(0, 0, color);
     tex.Apply();
     return tex;
 }
Beispiel #12
0
		public void LoadResources()
		{
			if (m_Disposed == true)
			{
				if (m_Filename != null)
				{
					m_ImposterTexture = Texture2D.FromFile(GameEnvironment.Device, Helper.ResolvePath(m_Filename));
					TextureView = new ShaderResourceView(GameEnvironment.Device, m_ImposterTexture);
				}

				m_Vertices = new SlimDX.Direct3D11.Buffer(GameEnvironment.Device, new BufferDescription()
				{
					BindFlags = BindFlags.VertexBuffer,
					CpuAccessFlags = CpuAccessFlags.Write,
					OptionFlags = ResourceOptionFlags.None,
					SizeInBytes = 4 * Marshal.SizeOf(typeof(Vertex2D)),
					Usage = ResourceUsage.Dynamic
				});

				m_VerticesBindings = new VertexBufferBinding(m_Vertices, Marshal.SizeOf(typeof(Vertex2D)), 0);

				WriteRectangle(); 		

				m_Disposed = false;
			}
		}
        public TextureAtlas(string filename)
        {
            sprites = new Dictionary<string, Bounds2>();
            sizes = new Dictionary<string, Vector2i>();

            XDocument doc = XDocument.Load(filename + ".xml");

            var lines = from sprite in doc.Root.Elements("sprite")
                select new
                {
                    Name = sprite.Attribute("n").Value,
                    X1 = (float)sprite.Attribute("x"),
                    Y1 = (float)sprite.Attribute("y"),
                    Height = (float)sprite.Attribute("h"),
                    Width = (float)sprite.Attribute("w")
                };

            texAtlas = new Texture2D(filename + ".png", false);
            texAtlasInfo = new TextureInfo(texAtlas);

            foreach (var curLine in lines)
            {
                sprites.Add(curLine.Name, new Bounds2(new Vector2(curLine.X1 / texAtlas.Width, 1 - (curLine.Y1 / texAtlas.Height)), new Vector2((curLine.X1 + curLine.Width) / texAtlas.Width, 1 -((curLine.Y1 + curLine.Height) / texAtlas.Height))));
                sizes.Add(curLine.Name, new Vector2i((int)curLine.Width, (int)curLine.Height));
            }
        }
 public TextureFactory(Engine engine)
 {
     _missingTexture = engine.Content.Load<Texture2D>("Textures\\missing-texture");
     _landCache = new Cache<int, Texture2D>(TimeSpan.FromMinutes(5), 0x1000);
     _lastCacheClean = DateTime.MinValue;
     _textures = new Textures(engine);
 }
Beispiel #15
0
        public Sprite(GraphicsContext graphics, Texture2D texture)
        {
            if(shaderProgram == null)
            {
                shaderProgram = new ShaderProgram("/Application/shaders/Sprite.cgx");
                shaderProgram.SetUniformBinding(0, "u_WorldMatrix");
            }

            if (texture == null)
            {
                throw new Exception("ERROR: texture is null.");
            }

            this.graphics = graphics;
            this.texture = texture;
            this.width = texture.Width;
            this.height = texture.Height;

            indices = new ushort[indexSize];
            indices[0] = 0;
            indices[1] = 1;
            indices[2] = 2;
            indices[3] = 3;

            vertexBuffer = new VertexBuffer(4, indexSize, VertexFormat.Float3,
                                            VertexFormat.Float2, VertexFormat.Float4);
        }
Beispiel #16
0
 public int this[Texture2D tex]
 {
     get {
         var texture = Textures.FirstOrDefault (t => t.tex == tex);
         return texture != default (WrappedTexture) ? texture.texindex : -1;
     }
 }
Beispiel #17
0
		/// <summary>
		///
		/// </summary>
		/// <param name="rs"></param>
		/// <param name="texture"></param>
		private DiscTexture ( RenderSystem rs, Texture2D texture )
		{
			this.texture	=	texture;
			this.Width		=	texture.Width;
			this.Height		=	texture.Height;
			this.Srv		=	texture;
		}
Beispiel #18
0
    /// <summary>
    /// Loads graphics content
    /// </summary>
    public void LoadContent()
    {
      // Load textures
      DirectoryInfo gfxDirectory = new DirectoryInfo("gfx");
      foreach (FileInfo file in gfxDirectory.EnumerateFiles("tex_*.png", SearchOption.AllDirectories))
      {
        int start = file.FullName.LastIndexOf("\\gfx\\");
        string id = file.FullName.Substring(start + 5, file.FullName.Length - start - 4 - 5);
        id = id.Substring(4);
        texDict.Add(id, LoadTexture(file.FullName));
      }
      
      texPoint = GetTexture("point");

      // Load files
      foreach (FileInfo file in gfxDirectory.EnumerateFiles("*.fnt", SearchOption.AllDirectories))
      {
        fntDict.Add(file.Name.Substring(0, file.Name.Length - 4), LoadFont(file.FullName));
      }

      // Load skins(styles)
      foreach (FileInfo file in gfxDirectory.EnumerateFiles("*.skn", SearchOption.AllDirectories))
      {
        guiTexDict.Add(file.Name.Substring(0, file.Name.Length - 4), LoadGuiTexture(file.FullName));
      }
    }
 protected override void LoadContent()
 {
     _mouseIcon = Game.Content.Load<Texture2D>("mouse");
     //_spriteBatch = new SpriteBatch(GraphicsDevice);
     _spriteBatch = new SpriteBatch(GraphicsDevice);
     base.LoadContent();
 }
        /// <summary>
        /// Constructor
        /// Creates the texture we will render to based on the supplied width and height
        /// </summary>
        /// <param name="device">The device we will create the texture with</param>
        /// <param name="texWidth"></param>
        /// <param name="texHeight"></param>
        public RenderTexture(Device device, int texWidth, int texHeight)
        {
            Texture2DDescription textureDescription = new Texture2DDescription()
                {
                    Width = texWidth,
                    Height = texHeight,
                    MipLevels = 1,
                    ArraySize = 1,
                    Format = SlimDX.DXGI.Format.R32G32B32A32_Float,
                    SampleDescription = new SlimDX.DXGI.SampleDescription(1, 0),
                    BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource,
                    CpuAccessFlags = CpuAccessFlags.None,
                    OptionFlags = ResourceOptionFlags.None,
                    Usage = ResourceUsage.Default,
                };
            Texture = new Texture2D(device, textureDescription);
            RenderTargetViewDescription renderTargetViewDescription = new RenderTargetViewDescription()
            {
                Format = textureDescription.Format,
                Dimension = RenderTargetViewDimension.Texture2D,
                MipSlice = 0,
            };

            renderTargetView = new RenderTargetView(device, Texture, renderTargetViewDescription);

            ShaderResourceViewDescription shaderResourceViewDescription = new ShaderResourceViewDescription()
            {
                Format = textureDescription.Format,
                Dimension = ShaderResourceViewDimension.Texture2D,
                MostDetailedMip = 0,
                MipLevels = 1
            };

            shaderResourceView = new ShaderResourceView(device, Texture, shaderResourceViewDescription);
        }
Beispiel #21
0
 public Saucer(GraphicsContext g, Texture2D t, Vector3 p, Player pl)
     : base(g,t,p, pl)
 {
     player = pl;
     vel= (new Vector3(.5f*(float)gen.Next(3,5),.7f*(float)gen.Next(3,5),0));
     graphics=g;
 }
Beispiel #22
0
        public Skybox(GraphicsDevice device)
        {
            float x = 0.525731f;
            float z = 0.850651f;

            var vertices = new SkyboxVertex[12]
            {
                new SkyboxVertex(-x, 0f, z), new SkyboxVertex(x, 0f, z),
                new SkyboxVertex(-x, 0f, -z), new SkyboxVertex(x, 0f, -z),
                new SkyboxVertex(0f, z, x), new SkyboxVertex(0f, z, -x),
                new SkyboxVertex(0f, -z, x), new SkyboxVertex(0f, -z, -x),
                new SkyboxVertex(z, x, 0f), new SkyboxVertex(-z, x, 0f),
                new SkyboxVertex(z, -x, 0f), new SkyboxVertex(-z, -x, 0f),
            };

            var indices = new int[60]
            {
                1,4,0,  4,9,0,  4,5,9,  8,5,4,  1,8,4,
                1,10,8, 10,3,8, 8,3,5,  3,2,5,  3,7,2,
                3,10,7, 10,6,7, 6,11,7, 6,0,11, 6,1,0,
                10,1,6, 11,0,9, 2,11,9, 5,2,9,  11,2,7
            };

            vertexBuffer = Buffer<SkyboxVertex>.New(device, vertices, BufferFlags.VertexBuffer);
            indexBuffer = Buffer<int>.New(device, indices, BufferFlags.IndexBuffer);
            skyboxEffect = EffectLoader.Load(@"Graphics/Shaders/Skybox.fx");
            skyboxTex = Texture2D.Load(device, @"G:\Users\Athrun\Documents\Stratum\trunk\src\Stratum\WorldEngine\Earth\milkyWay.tif");
        }
Beispiel #23
0
 protected override void LoadContent()
 {
     tex = Content.Load<Texture2D>("Logo.jpg");
     mouse = Content.Load<Texture2D>("Mouse.png");
     BasicFont = this.Content.Load<SpriteFont>("wryh");
     base.LoadContent();
 }
Beispiel #24
0
		/// <summary>
		/// Creates texture from file in memory 
		/// </summary>
		/// <param name="rs"></param>
		/// <param name="texture"></param>
		public UserTexture ( RenderSystem rs, byte[] data, bool forceSRgb )
		{
			this.texture	=	new Texture2D( rs.Device, data, forceSRgb );
			this.Width		=	texture.Width;
			this.Height		=	texture.Height;
			this.Srv		=	texture;
		}
        protected override void OnInit(object sender, EventArgs e)
        {
            //OdysseyUI.RemoveHooks(Global.FormOwner);

            ImageLoadInformation imageLoadInfo = new ImageLoadInformation()
            {
                BindFlags = BindFlags.None,
                CpuAccessFlags = CpuAccessFlags.Read,
                FilterFlags = FilterFlags.None,
                Format = SlimDX.DXGI.Format.R8G8B8A8_UNorm,
                MipFilterFlags = FilterFlags.None,
                OptionFlags = ResourceOptionFlags.None,
                Usage = ResourceUsage.Staging,
                MipLevels = 1
            };

            // Make texture 3D
            Texture2D sourceTexture = Texture2D.FromFile(Game.Context.Device, "medusa.jpg", imageLoadInfo);
            stereoTexture = Stereo.Make3D(sourceTexture);
            backBuffer = Game.Context.GetBackBuffer();

            stereoSourceBox = new ResourceRegion
                                  {
                                      Front = 0,
                                      Back = 1,
                                      Top = 0,
                                      Bottom = Game.Context.Settings.ScreenHeight,
                                      Left = 0,
                                      Right = Game.Context.Settings.ScreenWidth
                                  };
        }
 public void Initialize(Device device, Effect effect)
 {
     this.device = device;
     this.effect = effect;
     image = ImageConverter.GetNullTexture(device);
     Update();
 }
Beispiel #27
0
		/// <summary>
		/// Creates texture from stream.
		/// </summary>
		/// <param name="rs"></param>
		/// <param name="texture"></param>
		public UserTexture ( RenderSystem rs, Stream stream, bool forceSRgb  )
		{
			this.texture	=	new Texture2D( rs.Device, stream, forceSRgb );
			this.Width		=	texture.Width;
			this.Height		=	texture.Height;
			this.Srv		=	texture;
		}
        public FighterCarrier(Texture2D texture, Vector2 location, SpriteBatch spriteBatch, Texture2D droneTexture, bool isAlly)
            : base(texture, location, spriteBatch, isAlly)
        {
            //UseCenterAsOrigin = true;

            //Init drones
            if (!StateManager.NetworkData.IsMultiplayer)
            {
                Drones.Add(new Drone(droneTexture, location, spriteBatch, this) { DroneState = CoreTypes.DroneState.Stowed });
                Drones[0].Rotation.Radians = MathHelper.Pi;

                Drones.Add(new Drone(droneTexture, location, spriteBatch, this) { DroneState = CoreTypes.DroneState.Stowed });
                Drones[1].Rotation.Radians = MathHelper.TwoPi;

                StateManager.InputManager.DebugControlManager.DroneSuicide += new EventHandler<DroneEventArgs>(DebugControlManager_DroneSuicide);
            }
            //BulletTexture = GameContent.Assets.Images.Ships.Bullets[ShipType.FighterCarrier, ShipTier.Tier1];
            DelayBetweenShots = TimeSpan.FromMilliseconds(100);
            DamagePerShot = 2;
            _initHealth = 100;
            MovementSpeed = Vector2.One * 2f;
            this.TierChanged += new EventHandler(FighterCarrier_TierChanged);
            DamagePerShot = 2;
            this.PlayerType = PlayerType.Ally;
            ShootSound = GameContent.Assets.Sound[SoundEffectType.FighterCarrierFire];
        }
Beispiel #29
0
        /// <summary>コンストラクタ。</summary>
        public SimpleSprite(GraphicsContext graphics, Texture2D texture)
        {
            if(shaderProgram == null)
            {
                shaderProgram=CreateSimpleSpriteShader();
            }

            if (texture == null)
            {
                throw new Exception("ERROR: texture is null.");
            }

            this.graphics = graphics;
            this.texture = texture;
            this.width = texture.Width;
            this.height = texture.Height;

            indices = new ushort[indexSize];
            indices[0] = 0;
            indices[1] = 1;
            indices[2] = 2;
            indices[3] = 3;

            //@e                                                Vertex coordinate,               Texture coordinate,     Vertex color
            //@j                                                頂点座標,                テクスチャ座標,     頂点色
            vertexBuffer = new VertexBuffer(4, indexSize, VertexFormat.Float3, VertexFormat.Float2, VertexFormat.Float4);
        }
 protected override void LoadContent()
 {
     texture = game.Content.Load<Texture2D>(textureFilename);
     origin.X = texture.Width / 2;
     origin.Y = texture.Height / 2;
     base.LoadContent();
 }
Beispiel #31
0
 /// <summary>
 /// Luo uuden bittikartan tekstuurin pohjalta oletusläpinäkyvyysehdoilla.
 /// Ks. <see cref="IsOpaqueColor"/>
 /// </summary>
 /// <param name="texture">Tekstuuri.</param>
 public TextureBitmap(Texture2D texture)
     : this(texture, IsOpaqueColor)
 {
 }
        public unsafe static int Main()
        {
            // Initialization
            //--------------------------------------------------------------------------------------
            const int screenWidth = 800;
            const int screenHeight = 450;

            InitWindow(screenWidth, screenHeight, "raylib [models] example - cubesmap loading and drawing");

            // Define the camera to look into our 3d world
            Camera3D camera = new Camera3D(new Vector3(16.0f, 14.0f, 16.0f), new Vector3(0.0f, 0.0f, 0.0f), new Vector3(0.0f, 1.0f, 0.0f), 45.0f, 0);

            Image image = LoadImage("resources/cubicmap.png");      // Load cubicmap image (RAM)
            Texture2D cubicmap = LoadTextureFromImage(image);       // Convert image to texture to display (VRAM)

            Mesh mesh = GenMeshCubicmap(image, new Vector3(1.0f, 1.0f, 1.0f));
            Model model = LoadModelFromMesh(mesh);

            // NOTE: By default each cube is mapped to one part of texture atlas
            Texture2D texture = LoadTexture("resources/cubicmap_atlas.png");    // Load map texture

            // Set map diffuse texture
            Utils.SetMaterialTexture(ref model, 0, MAP_ALBEDO, ref texture);

            Vector3 mapPosition = new Vector3(-16.0f, 0.0f, -8.0f);          // Set model position

            UnloadImage(image);     // Unload cubesmap image from RAM, already uploaded to VRAM

            SetCameraMode(camera, CAMERA_ORBITAL);  // Set an orbital camera mode

            SetTargetFPS(60);                       // Set our game to run at 60 frames-per-second
            //--------------------------------------------------------------------------------------

            // Main game loop
            while (!WindowShouldClose())            // Detect window close button or ESC key
            {
                // Update
                //----------------------------------------------------------------------------------
                UpdateCamera(ref camera);              // Update camera
                //----------------------------------------------------------------------------------

                // Draw
                //----------------------------------------------------------------------------------
                BeginDrawing();

                ClearBackground(RAYWHITE);

                BeginMode3D(camera);

                DrawModel(model, mapPosition, 1.0f, WHITE);

                EndMode3D();

                DrawTextureEx(cubicmap, new Vector2(screenWidth - cubicmap.width * 4 - 20, 20), 0.0f, 4.0f, WHITE);
                DrawRectangleLines(screenWidth - cubicmap.width * 4 - 20, 20, cubicmap.width * 4, cubicmap.height * 4, GREEN);

                DrawText("cubicmap image used to", 658, 90, 10, GRAY);
                DrawText("generate map 3d model", 658, 104, 10, GRAY);

                DrawFPS(10, 10);

                EndDrawing();
                //----------------------------------------------------------------------------------
            }

            // De-Initialization
            //--------------------------------------------------------------------------------------
            UnloadTexture(cubicmap);    // Unload cubicmap texture
            UnloadTexture(texture);     // Unload map texture
            UnloadModel(model);         // Unload map model

            CloseWindow();              // Close window and OpenGL context
            //--------------------------------------------------------------------------------------

            return 0;
        }
 public Character(Texture2D I, Vector2 S = default(Vector2), IBehaviors b = null, Vector2 P = default(Vector2), int _Lives = 1, Vector2 V = default(Vector2)) : base(I, S, b, P, V)
 {
     UpdateLives(_Lives);
 }
 private void InitializeGameObject()
 {
     texture2D = new Texture2D(resolutionWidth, resolutionHeight, TextureFormat.RGB24, false);
     rect      = new Rect(0, 0, resolutionWidth, resolutionHeight);
     controlCam.targetTexture = new RenderTexture(resolutionWidth, resolutionHeight, 24);
 }
Beispiel #35
0
 public IGMDataItem_Texture(Texture2D data, Rectangle?pos = null) : base(pos) => this.Data = data;
Beispiel #36
0
        async Task <string> CaptureAndAnalyze(bool readText = false)
        {
            var imgFormat = ImageEncodingProperties.CreateJpeg();

            //NOTE: this is how you can save a frame to the CameraRoll folder:
            //var file = await KnownFolders.CameraRoll.CreateFileAsync($"MCS_Photo{DateTime.Now:HH-mm-ss}.jpg", CreationCollisionOption.GenerateUniqueName);
            //await mediaCapture.CapturePhotoToStorageFileAsync(imgFormat, file);
            //var stream = await file.OpenStreamForReadAsync();

            // Capture a frame and put it to MemoryStream
            var memoryStream = new MemoryStream();

            using (var ras = new InMemoryRandomAccessStream())
            {
                await mediaCapture.CapturePhotoToStreamAsync(imgFormat, ras);

                ras.Seek(0);
                using (var stream = ras.AsStreamForRead())
                    stream.CopyTo(memoryStream);
            }

            var imageBytes = memoryStream.ToArray();

            memoryStream.Position = 0;

            if (withPreview)
            {
                InvokeOnMain(() =>
                {
                    var image = new Image();
                    image.Load(new Urho.MemoryBuffer(imageBytes));

                    Node child     = Scene.CreateChild();
                    child.Position = LeftCamera.Node.WorldPosition + LeftCamera.Node.WorldDirection * 2f;
                    child.LookAt(LeftCamera.Node.WorldPosition, Vector3.Up, TransformSpace.World);

                    child.Scale = new Vector3(1f, image.Height / (float)image.Width, 0.1f) / 10;
                    var texture = new Texture2D();
                    texture.SetData(image, true);

                    var material = new Material();
                    material.SetTechnique(0, CoreAssets.Techniques.Diff, 0, 0);
                    material.SetTexture(TextureUnit.Diffuse, texture);

                    var box = child.CreateComponent <Box>();
                    box.SetMaterial(material);

                    child.RunActions(new EaseBounceOut(new ScaleBy(1f, 5)));
                });
            }

            try
            {
                var client = new VisionServiceClient(VisionApiKey);
                if (readText)
                {
                    var ocrResult = await client.RecognizeTextAsync(memoryStream, detectOrientation : false);

                    var words = ocrResult.Regions.SelectMany(region => region.Lines).SelectMany(line => line.Words).Select(word => word.Text);
                    return("it says: " + string.Join(" ", words));
                }
                else
                {
                    // just describe the picture, you can also use cleint.AnalyzeImageAsync method to get more info
                    var result = await client.DescribeAsync(memoryStream);

                    return(result?.Description?.Captions?.FirstOrDefault()?.Text);
                }
            }
            catch (ClientException exc)
            {
                return(exc?.Error?.Message ?? "Failed");
            }
            catch (Exception exc)
            {
                return("Failed");
            }
        }
Beispiel #37
0
    public void CalculateHistogramTexture(int channel)
    {
        Texture2D materialTex = (Texture2D)GetComponent <MeshRenderer>().sharedMaterial.mainTexture;

        int[] channelHist = new int[256];

        for (int x = 0; x < materialTex.width; x++)
        {
            for (int y = 0; y < materialTex.height; y++)
            {
                if (channel == 0)
                {
                    channelHist[(int)(255f * materialTex.GetPixel(x, y).r)]++;
                }
                else if (channel == 1)
                {
                    channelHist[(int)(255f * materialTex.GetPixel(x, y).g)]++;
                }
                else if (channel == 2)
                {
                    channelHist[(int)(255f * materialTex.GetPixel(x, y).b)]++;
                }
                else if (channel == 3)
                {
                    channelHist[(int)(255f * materialTex.GetPixel(x, y).a)]++;
                }
            }
        }


        int maxValue = 0;

        for (int i = 0; i < channelHist.Length; i++)
        {
            if (channelHist[i] > maxValue)
            {
                maxValue = channelHist[i];
            }
        }

        for (int i = 0; i < channelHist.Length; i++)
        {
            channelHist[i] = (int)(150 * (channelHist[i] * 1.0f / (1.1f * maxValue)));
        }


        int sizeX = 300;
        int sizeY = 150;

        Texture2D tex = new Texture2D(sizeX, sizeY);

        for (int x = 0; x < sizeX; x++)
        {
            for (int y = 0; y < sizeY; y++)
            {
                if (x > (sizeX - 256) / 2f && x < (sizeX - 256) / 2f + 256 && y <= channelHist[(int)(x - (sizeX - 256) / 2f)])
                {
                    tex.SetPixel(x, y, Color.black);
                }
                else
                {
                    tex.SetPixel(x, y, Color.white);
                }
            }
        }
        tex.Apply();

        histogram[channel] = tex;

        alreadyCalculated[channel] = true;
    }
        /// <summary>
        /// Raises the web cam texture to mat helper initialized event.
        /// </summary>
        public void OnWebCamTextureToMatHelperInitialized()
        {
            Debug.Log("OnWebCamTextureToMatHelperInitialized");

            Mat webCamTextureMat = webCamTextureToMatHelper.GetMat();

            texture = new Texture2D(webCamTextureMat.cols(), webCamTextureMat.rows(), TextureFormat.RGBA32, false);

            gameObject.GetComponent <Renderer>().material.mainTexture = texture;

            gameObject.transform.localScale = new Vector3(webCamTextureMat.cols(), webCamTextureMat.rows(), 1);

            Debug.Log("Screen.width " + Screen.width + " Screen.height " + Screen.height + " Screen.orientation " + Screen.orientation);

            if (fpsMonitor != null)
            {
                fpsMonitor.Add("width", webCamTextureMat.width().ToString());
                fpsMonitor.Add("height", webCamTextureMat.height().ToString());
                fpsMonitor.Add("orientation", Screen.orientation.ToString());
                fpsMonitor.consoleText = "Please touch the area of the open hand.";
            }

            float width  = webCamTextureMat.width();
            float height = webCamTextureMat.height();

            float imageSizeScale = 1.0f;
            float widthScale     = (float)Screen.width / width;
            float heightScale    = (float)Screen.height / height;

            if (widthScale < heightScale)
            {
                Camera.main.orthographicSize = (width * (float)Screen.height / (float)Screen.width) / 2;
                imageSizeScale = (float)Screen.height / (float)Screen.width;
            }
            else
            {
                Camera.main.orthographicSize = height / 2;
            }

            //set cameraparam
            int    max_d = (int)Mathf.Max(width, height);
            double fx    = max_d;
            double fy    = max_d;
            double cx    = width / 2.0f;
            double cy    = height / 2.0f;

            camMatrix = new Mat(3, 3, CvType.CV_64FC1);
            camMatrix.put(0, 0, fx);
            camMatrix.put(0, 1, 0);
            camMatrix.put(0, 2, cx);
            camMatrix.put(1, 0, 0);
            camMatrix.put(1, 1, fy);
            camMatrix.put(1, 2, cy);
            camMatrix.put(2, 0, 0);
            camMatrix.put(2, 1, 0);
            camMatrix.put(2, 2, 1.0f);
            Debug.Log("camMatrix " + camMatrix.dump());

            distCoeff = new MatOfDouble(0, 0, 0, 0);
            Debug.Log("distCoeffs " + distCoeff.dump());

            //calibration camera
            Size   imageSize      = new Size(width * imageSizeScale, height * imageSizeScale);
            double apertureWidth  = 0;
            double apertureHeight = 0;

            double[] fovx           = new double[1];
            double[] fovy           = new double[1];
            double[] focalLength    = new double[1];
            Point    principalPoint = new Point(0, 0);

            double[] aspectratio = new double[1];

            Calib3d.calibrationMatrixValues(camMatrix, imageSize, apertureWidth, apertureHeight, fovx, fovy, focalLength, principalPoint, aspectratio);

            Debug.Log("imageSize " + imageSize.ToString());
            Debug.Log("apertureWidth " + apertureWidth);
            Debug.Log("apertureHeight " + apertureHeight);
            Debug.Log("fovx " + fovx[0]);
            Debug.Log("fovy " + fovy[0]);
            Debug.Log("focalLength " + focalLength[0]);
            Debug.Log("principalPoint " + principalPoint.ToString());
            Debug.Log("aspectratio " + aspectratio[0]);


            //To convert the difference of the FOV value of the OpenCV and Unity.
            double fovXScale = (2.0 * Mathf.Atan((float)(imageSize.width / (2.0 * fx)))) / (Mathf.Atan2((float)cx, (float)fx) + Mathf.Atan2((float)(imageSize.width - cx), (float)fx));
            double fovYScale = (2.0 * Mathf.Atan((float)(imageSize.height / (2.0 * fy)))) / (Mathf.Atan2((float)cy, (float)fy) + Mathf.Atan2((float)(imageSize.height - cy), (float)fy));

            Debug.Log("fovXScale " + fovXScale);
            Debug.Log("fovYScale " + fovYScale);


            //Adjust Unity Camera FOV https://github.com/opencv/opencv/commit/8ed1945ccd52501f5ab22bdec6aa1f91f1e2cfd4
            if (widthScale < heightScale)
            {
                ARCamera.fieldOfView = (float)(fovx[0] * fovXScale);
            }
            else
            {
                ARCamera.fieldOfView = (float)(fovy[0] * fovYScale);
            }


            invertYM = Matrix4x4.TRS(Vector3.zero, Quaternion.identity, new Vector3(1, -1, 1));
            Debug.Log("invertYM " + invertYM.ToString());

            invertZM = Matrix4x4.TRS(Vector3.zero, Quaternion.identity, new Vector3(1, 1, -1));
            Debug.Log("invertZM " + invertZM.ToString());


            detector            = new ColorBlobDetector();
            spectrumMat         = new Mat();
            blobColorRgba       = new Scalar(255);
            blobColorHsv        = new Scalar(255);
            SPECTRUM_SIZE       = new Size(200, 64);
            CONTOUR_COLOR       = new Scalar(255, 0, 0, 255);
            CONTOUR_COLOR_WHITE = new Scalar(255, 255, 255, 255);
            rectPoints          = new MatOfPoint2f();
        }
Beispiel #39
0
 public Jellyfish(Texture2D tex, Vector2 centre, Vector2 pos, Rectangle sourceRect, Vector2 vel) :
     base(tex, centre, pos, sourceRect, vel)
 {
     Velocity = new Vector2(0, 1);
     health   = 3;
 }
Beispiel #40
0
 public void RenderToTexture(Texture2D texture)
 {
     this.RenderToTexture(texture, Matrix4.Identity);
 }
Beispiel #41
0
        public static tk2dSpriteCollectionData HandleAnimations(tk2dBaseSprite sprite, Texture2D playerSheet)
        {
            tk2dSpriteCollectionData orig = sprite.Collection;

            var copyCollection = GameObject.Instantiate(orig);

            GameObject.DontDestroyOnLoad(copyCollection);

            tk2dSpriteDefinition[] copyDefinitions = new tk2dSpriteDefinition[orig.spriteDefinitions.Length];
            for (int i = 0; i < copyCollection.spriteDefinitions.Length; i++)
            {
                copyDefinitions[i] = Copy(orig.spriteDefinitions[i]);
            }
            copyCollection.spriteDefinitions = copyDefinitions;

            if (playerSheet != null)
            {
                var materialsToCopy = orig.materials;
                copyCollection.materials = new Material[orig.materials.Length];
                for (int i = 0; i < copyCollection.materials.Length; i++)
                {
                    if (materialsToCopy[i] == null)
                    {
                        continue;
                    }
                    var mat = new Material(materialsToCopy[i]);
                    GameObject.DontDestroyOnLoad(mat);
                    mat.mainTexture             = playerSheet;
                    mat.name                    = materialsToCopy[i].name;
                    copyCollection.materials[i] = mat;
                }

                for (int i = 0; i < copyCollection.spriteDefinitions.Length; i++)
                {
                    foreach (var mat in copyCollection.materials)
                    {
                        if (mat != null && copyDefinitions[i].material.name.Equals(mat.name))
                        {
                            copyDefinitions[i].material     = mat;
                            copyDefinitions[i].materialInst = new Material(mat);
                        }
                    }
                }
            }

            return(copyCollection);
        }
Beispiel #42
0
        public IEnumerator GetTextureAtlas(Texture2D[] textures, Action <TextureAtlas> callback)
        {
            TextureAtlas atlas = null;

            // Clear out any atlases that were removed
            m_Atlases.RemoveAll(a => a == null);
            yield return(null);

            foreach (var a in m_Atlases)
            {
                // At a minimum the atlas should have all of the textures requested, but can be a superset
                if (!textures.Except(a.textures).Any())
                {
                    atlas = a;
                    break;
                }

                yield return(null);
            }

            if (!atlas)
            {
                atlas = ScriptableObject.CreateInstance <TextureAtlas>();

                foreach (var t in textures)
                {
                    var assetImporter   = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(t));
                    var textureImporter = assetImporter as TextureImporter;
                    if (textureImporter && !textureImporter.isReadable)
                    {
                        textureImporter.isReadable = true;
                        textureImporter.SaveAndReimport();
                    }
                    else if (!assetImporter)
                    {
                        // In-memory textures need to be saved to disk in order to be referenced by the texture atlas
                        SaveUniqueAtlasAsset(t);
                    }
                    yield return(null);
                }

                var textureAtlas = new Texture2D(0, 0, TextureFormat.RGB24, true, PlayerSettings.colorSpace == ColorSpace.Linear);
                var uvs          = textureAtlas.PackTextures(textures.ToArray(), 0, 1024, true);

                if (uvs != null)
                {
                    atlas.textureAtlas = textureAtlas;
                    atlas.uvs          = uvs;
                    atlas.textures     = textures;

                    SaveUniqueAtlasAsset(textureAtlas);
                    SaveUniqueAtlasAsset(atlas);

                    m_Atlases.Add(atlas);
                }

                yield return(null);
            }

            if (callback != null)
            {
                callback(atlas);
            }
        }
Beispiel #43
0
 protected override void LoadContent()
 {
     // TODO: Change sprite for paddle.
     debugTexture = RectangleTexture.Create(Color.Red);
     PaddleTexture = Game.Content.Load<Texture2D>("textures/ship");
 }
Beispiel #44
0
        //internal static void ReplaceShader(Renderer renderer)
        //{
        //    if (shaderSubstitutions.ContainsKey(renderer.material.shader.name))
        //    {
        //        Shader newShader = GetShader(shaderSubstitutions[renderer.material.shader.name]);
        //        if (newShader != null)
        //        {
        //            renderer.material.shader = newShader;
        //            if (renderer.material.mainTexture != null)
        //            {
        //                AdvancedTextures.CheckForExistingMaterial(renderer);
        //            }

        //        }
        //    }
        //}



        /// <summary>
        /// return a buildin or GameDatabase Texture
        /// </summary>
        /// <param name="textureName"></param>
        /// <returns></returns>
        internal static Texture2D GetTexture(string textureName, bool asNormal = false, int index = 0, bool createMibMaps = false)
        {
            if (string.IsNullOrEmpty(textureName))
            {
                Log.UserWarning("Empty texture Name");
                return(null);
            }
            string textureKey;

            textureName.Replace("\\", "/");
            if (textureName.StartsWith("BUILTIN:"))
            {
                {
                    textureKey = Regex.Replace(textureName, "BUILTIN:/", "") + index.ToString();
                }
            }
            else
            {
                textureKey = Regex.Replace(textureName, "/", "_") + index.ToString();
            }

            if (cachedTextures.ContainsKey(textureKey))
            {
                return(cachedTextures[textureKey]);
            }
            Texture2D foundTexture = null;

            if (textureName.StartsWith("BUILTIN:"))
            {
                foundTexture = GetBuiltinTexture(textureName, index);
            }
            else
            {
                Texture2D tmpTexture = null;

                //// Otherwise search the game database for one loaded from GameData/
                if (GameDatabase.Instance.ExistsTexture(textureName) && (GetImageExtention(textureName) != null))
                {
                    // Get the texture URL
                    tmpTexture = GameDatabase.Instance.GetTexture(textureName, asNormal);


                    foundTexture = new Texture2D(tmpTexture.width, tmpTexture.height, TextureFormat.ARGB32, createMibMaps);
                    foundTexture.LoadImage(System.IO.File.ReadAllBytes("GameData/" + textureName + GetImageExtention(textureName)), false);
                    foundTexture.Apply(createMibMaps, false);
                }
                else
                {
                    Log.UserWarning("AdvTexture: TextureLoader faild. Fallback to GameDatabase");
                    foundTexture = GameDatabase.Instance.GetTexture(textureName, asNormal);
                }

                //// Otherwise search the game database for one loaded from GameData/
                //if (GameDatabase.Instance.ExistsTexture(textureName))
                //{
                //    // Get the texture URL
                //    foundTexture = GameDatabase.Instance.GetTexture(textureName, asNormal);
                //}
            }
            cachedTextures.Add(textureKey, foundTexture);
            return(foundTexture);
        }
Beispiel #45
0
 //creates button without resizing it
 public AnimatedButton(Texture2D texture, Vector2 size)
     : this(texture, new Vector2(0, 0), size, 0.0f)
 {
 }
		void TakePicture ()	{

			switch (textureFormat)
			{
			
			case Mode.ARGB32:
				modeSelect = TextureFormat.ARGB32;
				break;
			case Mode.DXT1:
				modeSelect = TextureFormat.DXT1;
				break;
			case Mode.DXT1Crunched:
				modeSelect = TextureFormat.DXT1Crunched;
				break;
			case Mode.DXT5:
				modeSelect = TextureFormat.DXT5;
				break;
			case Mode.DXT5Crunched:
				modeSelect = TextureFormat.DXT5Crunched;
				break;
			case Mode.ETC_RGB4:
				modeSelect = TextureFormat.ETC_RGB4;
				break;
			case Mode.ETC_RGB4_3DS:
				modeSelect = TextureFormat.ETC_RGB4_3DS;
				break;
			case Mode.ETC_RGBA8_3DS:
				modeSelect = TextureFormat.ETC_RGBA8_3DS;
				break;
			case Mode.ETC2_RGB:
				modeSelect = TextureFormat.ETC2_RGB;
				break;
			case Mode.ETC2_RGBA1:
				modeSelect = TextureFormat.ETC2_RGBA1;
				break;
			case Mode.ETC2_RGBA8:
				modeSelect = TextureFormat.ETC2_RGBA8;
				break;
			case Mode.PVRTC_RGB2:
				modeSelect = TextureFormat.PVRTC_RGB2;
				break;
			case Mode.PVRTC_RGB4:
				modeSelect = TextureFormat.PVRTC_RGB4;
				break;
			case Mode.PVRTC_RGBA2:
				modeSelect = TextureFormat.PVRTC_RGBA2;
				break;
			case Mode.PVRTC_RGBA4:
				modeSelect = TextureFormat.PVRTC_RGBA4;
				break;
			case Mode.RGB24:
				modeSelect = TextureFormat.RGB24;
				break;
			case Mode.RGB565:
				modeSelect = TextureFormat.RGB565;
				break;
			}

			webcamTextTemp = new Texture2D(webCamTex.width, webCamTex.height, modeSelect,false);

			switch (filterModeselect)
			{
			case FilterModeSelect.Bilinear:
				webcamTextTemp.filterMode = FilterMode.Bilinear;
				break;
			case FilterModeSelect.Point:
				webcamTextTemp.filterMode = FilterMode.Point;
				break;
			case FilterModeSelect.Trilinear:
				webcamTextTemp.filterMode = FilterMode.Trilinear;;
				break;
			}

			if (useCrop.Value == true){
	
				cropTex = new Texture2D (cropSize.Value,cropSize.Value);

				if (webCamTex.height < cropSize.Value && webCamTex.width < cropSize.Value){
					Debug.LogWarning("<b>[WebcamController]</b><color=#FF9900ff>The Webcam picture is smaller than the crop - set to "+webCamTex.height+" -  Please review!</color>", this.Owner);

				}

				else {

					Color[] data = webCamTex.GetPixels(((webcamTextTemp.width - cropSize.Value) / 2)+offsetY.Value,((webcamTextTemp.height - cropSize.Value) / 2)+offsetX.Value,cropSize.Value, cropSize.Value);//((webcamTextTemp.width - cropSize.Value) / 2, (webcamTextTemp.height - cropSize.Value) / 2, cropSize.Value, cropSize.Value, 0);
					cropTex.SetPixels(0,0,cropSize.Value, cropSize.Value,data,0);
				}

				cropTex.Apply();
				webcamTexture.Value = cropTex;
			}

			else {

			Color32[] pix = webCamTex.GetPixels32();
			webcamTextTemp.SetPixels32(pix);
			webcamTextTemp.Apply();
	
			webcamTexture.Value = webcamTextTemp;

			}


			webcamTextTemp = null;
			cropTex = null;

			takePicture.Value = false;

			return;


	}
Beispiel #47
0
 public void BeginTargeting(Func <GlobalTargetInfo, bool> action, bool canTargetTiles, Texture2D mouseAttachment = null, bool closeWorldTabWhenFinished = false, Action onUpdate = null, Func <GlobalTargetInfo, string> extraLabelGetter = null)
 {
     this.action                    = action;
     this.canTargetTiles            = canTargetTiles;
     this.mouseAttachment           = mouseAttachment;
     this.closeWorldTabWhenFinished = closeWorldTabWhenFinished;
     this.onUpdate                  = onUpdate;
     this.extraLabelGetter          = extraLabelGetter;
 }
Beispiel #48
0
 //constructor for a basic button and resizes it to the specified size
 public AnimatedButton(Texture2D texture, Vector2 position, Vector2 size)
     : this(texture, position, size, 0.0f)
 {
 }
Beispiel #49
0
 /// <summary>
 /// Helper for drawing a texture into the current rendertarget,
 /// using a custom shader to apply postprocessing effects.
 /// </summary>
 void DrawFullscreenQuad(Texture2D texture, int width, int height, Effect effect)
 {
     SpriteBatch.Begin(0, BlendState.Opaque, null, null, null, effect);
     SpriteBatch.Draw(texture, new Rectangle(0, 0, width, height), Color.White);
     SpriteBatch.End();
 }
Beispiel #50
0
 public Projectile(Rectangle rectangle, Texture2D texture)
 {
     this.rectangle = rectangle;
     this.texture   = texture;
     hasHit         = false;
 }
Beispiel #51
0
 public static Background FromTexture2D(Texture2D t)
 {
     return new Background() { texture = t };
 }
	public override void OnInspectorGUI () {
        SetupAFS = new SerializedObject(target);
		GetProperties();
		SetupAdvancedFoliageShader script = (SetupAdvancedFoliageShader)target;

//	///////////////////////////////////////////////////
//	Style Settings
		// Colors for Pro
		Color myCol = new Color(.5f, .8f, .0f, 1f); // Light Green // new Color(.6f, .9f, .22f, 1f); // Light Green
		Color myBgCol = myCol; //new Color(.5f, .75f, .24f, 1f);
		Color SplitterCol = new Color(1f, 1f, 1f, 0.075f);
		Color SplitterCol1 = new Color(.6f, .9f, .22f, .005f);
		// Colors for Indie
		if (!EditorGUIUtility.isProSkin) {
			myCol = new Color(0.05f,0.45f,0.0f,1.0f); // Dark Green
			myBgCol = new Color(0.94f,0.94f,0.94f,1.0f);
			SplitterCol = new Color(0f, 0f, 0f, 0.125f);
			SplitterCol1 = new Color(1f, 1f, 1f, 0.5f);
		}
		//Color myBlue = new Color(0.5f,0.7f,1.0f,1.0f);

		// Custom Foldout
		GUIStyle myFoldoutStyle = new GUIStyle(EditorStyles.foldout);
		myFoldoutStyle.fontStyle = FontStyle.Bold;
		myFoldoutStyle.fontSize = 12;

		myFoldoutStyle.normal.textColor = myCol;
		myFoldoutStyle.onNormal.textColor = myCol;
		//myFoldoutStyle.hover.textColor = Color.white;
		//myFoldoutStyle.onHover.textColor = Color.white;
		myFoldoutStyle.active.textColor = myCol;
		myFoldoutStyle.onActive.textColor = myCol;
		myFoldoutStyle.focused.textColor = myCol;
		myFoldoutStyle.onFocused.textColor = myCol;

		GUIStyle myRegularFoldoutStyle = new GUIStyle(myFoldoutStyle);
		myRegularFoldoutStyle.fontStyle = FontStyle.Normal;

		// Custom Label
		GUIStyle myLabel = new GUIStyle(EditorStyles.label);
		myLabel.normal.textColor = myCol;
		myLabel.onNormal.textColor = myCol;

		// Default icon Size
		EditorGUIUtility.SetIconSize( new Vector2(16,16));

		// Help Boxes
		//GUIStyle helpBoxes = GUI.skin.GetStyle("HelpBox");
		//RectOffset helpOffeset = new RectOffset(2, 3, 10, 10);
		//helpBoxes.richText = true;
		//helpBoxes.fontSize = 10;
		//helpBoxes.padding = helpOffeset;


//	///////////////////////////////////////////////////
		//CheckShaderFeatures ();

		MainCamera = Camera.main;
		if (MainCamera != null) {
			if(MainCamera.actualRenderingPath == RenderingPath.DeferredShading && !disableFoginShader.boolValue) {
				GUI.backgroundColor = Color.red;
				EditorGUILayout.HelpBox("Your Main Camera uses deferred shading but the AFS shaders still apply fog. That might end up in fog being applied two times to all plants and leaves.\nYou may want to update the shaders using the Fog Settings.", MessageType.Error, true);
				GUI.backgroundColor = Color.white;
			}
			GUILayout.Space(4);
		}

//	///////////////////////////////////////////////////
//	Lighting settings
		GUILayout.Space(4);
		GUI.backgroundColor = myBgCol;
		EditorGUILayout.BeginVertical("Box");
		// Foldout incl. Icon
		EditorGUILayout.BeginHorizontal();
			GUILayout.Space(-2);
			EditorGUI.indentLevel++;
			EditorGUILayout.BeginVertical();
				script.FoldLighting = EditorGUILayout.Foldout(script.FoldLighting, "Lighting Settings", myFoldoutStyle);
			EditorGUILayout.EndVertical();
			EditorGUI.indentLevel--;
			EditorGUILayout.BeginVertical(GUILayout.Width(20) );
				// Label needs width!
				EditorGUILayout.LabelField(new GUIContent(icnLight), GUILayout.Width(20), GUILayout.Height(20));
			EditorGUILayout.EndVertical();
			GUI.backgroundColor = Color.white;
		EditorGUILayout.EndHorizontal();
		GUILayout.Space(-2);
		EditorGUILayout.EndVertical();
		// FoldoutContent
		if (script.FoldLighting) {
			GUILayout.Space(-5);
			EditorGUILayout.BeginVertical("Box");
				DrawSplitter1(EditorGUILayout.GetControlRect(false, 4), SplitterCol1);
				EditorGUILayout.BeginHorizontal();
					GUILayout.Space(13);
					EditorGUILayout.BeginVertical();
						EditorGUILayout.LabelField("General Lighting Settings", myLabel);
						GUILayout.Space(2);
						EditorGUILayout.PropertyField(DirectionalLightReference, new GUIContent("Sun") );
						GUILayout.Space(6);
						EditorGUILayout.LabelField("Grass Lighting Settings", myLabel);
						if (DirectionalLightReference.objectReferenceValue == null) {
							GUI.enabled = false;
							GrassApproxTrans.boolValue = false;	
						}
						EditorGUILayout.BeginHorizontal();
							EditorGUILayout.PropertyField(GrassApproxTrans, GUIContent.none, GUILayout.Width(14) );
							EditorGUILayout.LabelField("Approximate Translucency on Grass");
						EditorGUILayout.EndHorizontal();
						if(GrassApproxTrans.boolValue){
							EditorGUILayout.HelpBox("Make sure you have assigned the 'Combined Normal/Translucency/Smoothness map' in the 'Terrain Vegetation Settings' below from which the translucency values will be picked.", MessageType.Warning, true);
						}
						GUI.enabled = true;

						//
						GUILayout.Space(6);
						EditorGUILayout.LabelField("Foliage specular Lighting Settings", myLabel);
						EditorGUI.BeginChangeCheck();
						specFade.x = EditorGUILayout.Slider("Specular Range", AfsSpecFade.vector2Value.x, 0.0f, 100.0f);
						specFade.y = EditorGUILayout.Slider("Specular Fade Lenght", AfsSpecFade.vector2Value.y, 0.0f, 100.0f);
						if (EditorGUI.EndChangeCheck()) {
							AfsSpecFade.vector2Value = specFade;
						}
						//
						GUILayout.Space(6);
						EditorGUILayout.LabelField("Tree Lighting Settings", myLabel);
						toolTip = "Fade length for translucency and real time shadows.";
						EditorGUILayout.PropertyField(BillboardFadeLenght, new GUIContent("Lighting Fade Length", toolTip) );
						//
					EditorGUILayout.EndVertical();
				EditorGUILayout.EndHorizontal();
				GUILayout.Space(2);
				EditorGUILayout.EndVertical();
		}

//	///////////////////////////////////////////////////
//	Wind settings
		GUILayout.Space(4);
		GUI.backgroundColor = myBgCol;
		EditorGUILayout.BeginVertical("Box");
		// Foldout incl. Icon
		EditorGUILayout.BeginHorizontal();
			GUILayout.Space(-2);
			EditorGUI.indentLevel++;
			EditorGUILayout.BeginVertical();
				script.FoldWind  = EditorGUILayout.Foldout(script.FoldWind, "Wind Settings", myFoldoutStyle);
			EditorGUILayout.EndVertical();
			EditorGUI.indentLevel--;
			EditorGUILayout.BeginVertical(GUILayout.Width(20) );
				// Label needs width!
				EditorGUILayout.LabelField(new GUIContent(icnWind), GUILayout.Width(20), GUILayout.Height(20));
			EditorGUILayout.EndVertical();
			GUI.backgroundColor = Color.white;
		EditorGUILayout.EndHorizontal();
		GUILayout.Space(-2);
		EditorGUILayout.EndVertical();
		// FoldoutContent
		if (script.FoldWind) {
			GUILayout.Space(-5);
			EditorGUILayout.BeginVertical("Box");
				DrawSplitter1(EditorGUILayout.GetControlRect(false, 4), SplitterCol1);
				EditorGUILayout.BeginHorizontal();
					GUILayout.Space(13);
					EditorGUILayout.BeginVertical();
						EditorGUILayout.LabelField("General Wind Settings", myLabel);
						GUILayout.Space(2);
						GUILayout.Label ("Wind Direction (XYZ) Strength (W)");
						tempWind = Wind.vector4Value;
						if (SyncWindDir.boolValue) {
							//GUILayout.Space(2);
							EditorGUILayout.BeginHorizontal();
								GUI.enabled = false;
									Vector3 temtempwind = new Vector3(tempWind.x, tempWind.y, tempWind.z);
										temtempwind = EditorGUILayout.Vector3Field("", temtempwind);
								GUI.enabled = true;
								EditorGUILayout.BeginHorizontal(GUILayout.MaxWidth(120));
									GUILayout.Label ("W", GUILayout.MaxWidth(14));
										EditorGUI.BeginChangeCheck();
										//tempWind.w = EditorGUILayout.FloatField("", tempWind.w, GUILayout.MaxWidth(104));
										tempWind.w = EditorGUILayout.Slider("", tempWind.w, 0.0f, 1.0f, GUILayout.MaxWidth(115));
										if (EditorGUI.EndChangeCheck()) {
											Wind.vector4Value = tempWind;
										}
								EditorGUILayout.EndHorizontal();	
							EditorGUILayout.EndHorizontal(); 
						}
						else {
							GUILayout.Space(-14);
							EditorGUI.BeginChangeCheck();
							tempWind = EditorGUILayout.Vector4Field("", Wind.vector4Value);
							if (EditorGUI.EndChangeCheck()) {
								Wind.vector4Value = tempWind;
							}
							GUILayout.Space(2);
						}
						EditorGUILayout.BeginHorizontal();
							EditorGUILayout.PropertyField(SyncWindDir, GUIContent.none, GUILayout.Width(14) );
							EditorGUILayout.LabelField("Sync Wind Direction to Rotation");
						EditorGUILayout.EndHorizontal();

						GUILayout.Space(4);
						toolTip = "Frequency the wind changes over time. Effects grass and foliage.";
						EditorGUILayout.PropertyField(WindFrequency, new GUIContent("Wind Frequency", toolTip) );
						
						GUILayout.Space(6);
						GUILayout.Label ("Wind Settings for Foliage Shaders", myLabel);
						GUILayout.Space(2);
						toolTip = "The shader adds some variation to the bending taking the vertex position in world space and the 'Wave Size Foliage' "+
							"parameter into account. So smaller wave sizes will add more variety to a given area but also lead to slightly different amounts of bending on each vertex even of a single mesh. This might cause some strange distortion of your models – especially large models. " +
							"For this reason you should set the 'Wave Size' to at least 2 or even 3 times the bounding box size of the largest model.";
						EditorGUILayout.PropertyField(WaveSizeFoliageShader, new GUIContent("Wave Size Foliage", toolTip) );
						toolTip = "Factor the original frequency of the secondary bending gets multiplied with. It determines the max frequency leaves might bend in when effected by strong winds.";
						EditorGUILayout.PropertyField(LeafTurbulenceFoliageShader, new GUIContent("Leaf Turbulence", toolTip) );
						GUILayout.Space(6);
						GUILayout.Label ("Wind Settings for Grass Shaders", myLabel);
						GUILayout.Space(2);
						
						toolTip = "Factor to make the main bending of the grass fit the bending of the foliage. " +
							"Effects both: grass placed manually and grass placed within the terrain engine (if you use the 'atsVxx.WavingGrass vertexAlpha' shader).";
						EditorGUILayout.PropertyField(WindMultiplierForGrassshader, new GUIContent("Main Wind Strength", toolTip) );

						toolTip = "Similar to the 'Wave Size Foliage' parameter, but as grass models usually are pretty small even low values might look good. "+
							"It effects both: grass placed manually and grass placed within the terrain engine (if you use the 'AfsGrassShader Terrain' shader).";
						EditorGUILayout.PropertyField(WaveSizeForGrassshader, new GUIContent("Wind Jitter Wave Size", toolTip) );

						toolTip = "Defines the Speed of the second wind animation that is added on top and gives you some more natural disturbance.";
						EditorGUILayout.PropertyField(WindJitterFrequencyForGrassshader, new GUIContent("Wind Jitter Frequency", toolTip) );

						toolTip = "Defines the Scale of the second wind animation that is added on top.";
						EditorGUILayout.PropertyField(WindJitterScaleForGrassshader, new GUIContent("Wind Jitter Amplitude", toolTip) );

						GUILayout.Space(6);
						GUILayout.Label ("Wind Multipliers for Tree Creator Shaders", myLabel);
						GUILayout.Space(2);

						toolTip = "Adjust bending of the tree creator shaders to match speedtree.";
						EditorGUILayout.PropertyField(WindMuliplierForTreeShaderPrimary, new GUIContent("Primary Bending", toolTip) );
						EditorGUILayout.PropertyField(WindMuliplierForTreeShaderSecondary, new GUIContent("Secondary Bending", toolTip) );
						Vector4 tempTreeWind = new Vector4(0.0f, 0.0f, WindMuliplierForTreeShaderPrimary.floatValue, WindMuliplierForTreeShaderSecondary.floatValue);
						WindMuliplierForTreeShader.vector4Value = tempTreeWind;


					EditorGUILayout.EndVertical();
				EditorGUILayout.EndHorizontal();
				GUILayout.Space(2);
				EditorGUILayout.EndVertical();
		}

//	///////////////////////////////////////////////////
//	Rain settings
		GUILayout.Space(4);
		GUI.backgroundColor = myBgCol;
		EditorGUILayout.BeginVertical("Box");
			// Foldout incl. Icon
			EditorGUILayout.BeginHorizontal();
				GUILayout.Space(-2);
				EditorGUI.indentLevel++;
				EditorGUILayout.BeginVertical();
					script.FoldRain  = EditorGUILayout.Foldout(script.FoldRain, "Rain Settings", myFoldoutStyle);
				EditorGUILayout.EndVertical();
				EditorGUI.indentLevel--;
				EditorGUILayout.BeginVertical(GUILayout.Width(20) );
					// Label needs width!
					EditorGUILayout.LabelField(new GUIContent(icnRain), GUILayout.Width(20), GUILayout.Height(20));
				EditorGUILayout.EndVertical();
				GUI.backgroundColor = Color.white;
			EditorGUILayout.EndHorizontal();
			GUILayout.Space(-2);
		EditorGUILayout.EndVertical();
		// FoldoutContent
		if (script.FoldRain) {
			GUILayout.Space(-5);
			EditorGUILayout.BeginVertical("Box");
				DrawSplitter1(EditorGUILayout.GetControlRect(false, 4), SplitterCol1);
				EditorGUILayout.BeginHorizontal();
					GUILayout.Space(13);
					EditorGUILayout.PropertyField(RainAmount, new GUIContent("Rain Amount") );
				EditorGUILayout.EndHorizontal();
			EditorGUILayout.EndVertical();
		}

//	///////////////////////////////////////////////////
//	Terrain Vegetation Settings	
		GUILayout.Space(4);
		GUI.backgroundColor = myBgCol;
		EditorGUILayout.BeginVertical("Box");
		// Foldout incl. Icon
		EditorGUILayout.BeginHorizontal();
			GUILayout.Space(-2);
			EditorGUI.indentLevel++;
			EditorGUILayout.BeginVertical();
				script.FoldVegTerrain  = EditorGUILayout.Foldout(script.FoldVegTerrain, "Terrain Vegetation Settings", myFoldoutStyle);
			EditorGUILayout.EndVertical();
			EditorGUI.indentLevel--;
			EditorGUILayout.BeginVertical(GUILayout.Width(20) );
				// GUILayout.Space(2);
				// Label needs width!
				EditorGUILayout.LabelField(new GUIContent(icnTerr), GUILayout.Width(20), GUILayout.Height(20));
			EditorGUILayout.EndVertical();
			GUI.backgroundColor = Color.white;
		EditorGUILayout.EndHorizontal();
		GUILayout.Space(-2);
		EditorGUILayout.EndVertical();
		// FoldoutContent
		if (script.FoldVegTerrain) {
			GUILayout.Space(-5);
			EditorGUILayout.BeginVertical("Box");
				DrawSplitter1(EditorGUILayout.GetControlRect(false, 4), SplitterCol1);
				EditorGUILayout.BeginHorizontal();
					GUILayout.Space(13);

					EditorGUILayout.BeginVertical();
						// General Billboard settings
						EditorGUILayout.LabelField("Sync Settings to Terrain", myLabel);
						GUILayout.Space(2);
					
						EditorGUILayout.BeginHorizontal();
							//script.AutoSyncToTerrain = EditorGUILayout.Toggle("", script.AutoSyncToTerrain, GUILayout.Width(14) );
							EditorGUILayout.PropertyField(AutoSyncToTerrain, GUIContent.none, GUILayout.Width(14) );
							EditorGUILayout.LabelField("Automatically sync with Terrain");
						EditorGUILayout.EndHorizontal();
					
						if(AutoSyncToTerrain.boolValue) {
							EditorGUILayout.PropertyField(SyncedTerrain, new GUIContent("Specify Terrain") );
							if(SyncedTerrain.objectReferenceValue != null){
								GUI.enabled = false;
							}
							else {
								EditorGUILayout.HelpBox("Please assign a terrain.", MessageType.Warning, true);
							}
						}
						GUILayout.Space(4);
							toolTip = "The distance (from camera) at which 3D tree objects will be replaced by billboard images (should fit your terrain’s settings).";
						EditorGUILayout.PropertyField(BillboardStart, new GUIContent("Billboard Start", toolTip));
						//if(TreeBillboardShadows.boolValue){
						//	GUI.enabled = true;
						//}
						GUI.enabled = true;
						
						if(AutoSyncToTerrain.boolValue) {
							GUI.enabled = false;
						}
							toolTip = "The distance (from camera) towards which grass will fade out (should fit your terrain’s settings).";
						EditorGUILayout.PropertyField(DetailDistanceForGrassShader, new GUIContent("Grass Fadeout Distance", toolTip));
							toolTip = "Overall color tint applied to grass objects (should fit your terrain’s settings).";
						EditorGUILayout.PropertyField(GrassWavingTint, new GUIContent("Grass Waving Tint", toolTip));
						if(AutoSyncToTerrain.boolValue) {
							GUI.enabled = true;
						}

						EditorGUILayout.BeginVertical();
							// General Vegetation settings
							GUILayout.Space(6);
							EditorGUILayout.LabelField("Terrain Detail Vegetation Settings", myLabel);
							GUILayout.Space(2);
								toolTip = "Cut off value for all models placed as 'detail mesh' using the built in terrain engine.";
							EditorGUILayout.PropertyField(VertexLitAlphaCutOff, new GUIContent("Alpha Cut Off", toolTip));
								toolTip = "Translucency Color for all models placed as 'detail mesh' using the built in terrain engine.";
							EditorGUILayout.PropertyField(VertexLitTranslucencyColor, new GUIContent("Translucency Color", toolTip));
								toolTip = "Translucency view dependency for all models placed as 'detail mesh' using the built in terrain engine.";
							EditorGUILayout.PropertyField(VertexLitTranslucencyViewDependency, new GUIContent("Translucency View Dependency", toolTip));
							//EditorGUILayout.PropertyField(VertexLitShadowStrength, new GUIContent("Shadow Strength") );
								toolTip = "Specular Reflectivity for all models placed as 'detail mesh' using the built in terrain engine.";
							EditorGUILayout.PropertyField(VertexLitSpecularReflectivity, new GUIContent("Specular Reflectivity", toolTip));
							//script.TerrainBendingMode = (TerrainBendingModes)EditorGUILayout.EnumPopup("Bending Parameters", script.TerrainBendingMode);
							GUILayout.Space(4);
							EditorGUILayout.BeginHorizontal();
								EditorGUI.BeginChangeCheck();
								tempTex = (Texture2D)EditorGUILayout.ObjectField(TerrainFoliageNrmSpecMap.objectReferenceValue, typeof(Texture2D), false, GUILayout.MinHeight(64), GUILayout.MinWidth(64), GUILayout.MaxWidth(64));
								if (EditorGUI.EndChangeCheck()) {
									TerrainFoliageNrmSpecMap.objectReferenceValue = tempTex;
								}
								EditorGUILayout.LabelField("Combined Normal/Translucency/Smoothness Map");
							EditorGUILayout.EndHorizontal();
							GUILayout.Space(2);
						EditorGUILayout.EndVertical();
					EditorGUILayout.EndVertical();
				EditorGUILayout.EndHorizontal();
			EditorGUILayout.EndVertical();
		}
		
//	///////////////////////////////////////////////////
//	Tree and Billboard settings
		GUILayout.Space(4);
		GUI.backgroundColor = myBgCol;
		EditorGUILayout.BeginVertical("Box");
		// Foldout incl. Icon
		EditorGUILayout.BeginHorizontal();
			GUILayout.Space(-2);
			EditorGUI.indentLevel++;
			EditorGUILayout.BeginVertical();
				script.FoldBillboard  = EditorGUILayout.Foldout(script.FoldBillboard, "Tree and Billboard Settings", myFoldoutStyle);
			EditorGUILayout.EndVertical();
			EditorGUI.indentLevel--;
			EditorGUILayout.BeginVertical(GUILayout.Width(20) );
				// GUILayout.Space(2);
				// Label needs width!
				EditorGUILayout.LabelField(new GUIContent(icnTree), GUILayout.Width(20), GUILayout.Height(20));
			EditorGUILayout.EndVertical();
			GUI.backgroundColor = Color.white;
		EditorGUILayout.EndHorizontal();
		GUILayout.Space(-2);
		EditorGUILayout.EndVertical();
		// FoldoutContent
		if (script.FoldBillboard) {
			GUILayout.Space(-5);
			EditorGUILayout.BeginVertical("Box");
				DrawSplitter1(EditorGUILayout.GetControlRect(false, 4), SplitterCol1);
				EditorGUILayout.BeginHorizontal();
					GUILayout.Space(13);
					EditorGUILayout.BeginVertical();
					
						// Tree and Billboard Render settings
						// GUILayout.Space(4);
						EditorGUILayout.LabelField("Tree and Billboard Render Settings", myLabel);
						GUILayout.Space(2);
						//
						EditorGUILayout.BeginHorizontal();
								toolTip = "Usually tree are simply tinted with black if you set the „color variation“ > 0 while painting trees. You may replace this color by any one you like using this color field.";
							EditorGUILayout.PropertyField(TreeColor, new GUIContent("Tint Color", toolTip));
						EditorGUILayout.EndHorizontal();
						GUILayout.Space(2);
						EditorGUILayout.BeginHorizontal();
							EditorGUILayout.PropertyField(BillboardAdjustToCamera, GUIContent.none, GUILayout.Width(14) );
							EditorGUILayout.LabelField("Align Billboards to Camera");
						EditorGUILayout.EndHorizontal();
						if (BillboardAdjustToCamera.boolValue) {
								toolTip = "Defines the angle (when viewed from above) the billboard shader will fade to the 'classical' upright oriented billboards in order to reduce distortion artifacts. The standard value is '30'.";
							EditorGUILayout.PropertyField(BillboardAngleLimit, new GUIContent("Angle Limit", toolTip));
						}
						GUILayout.Space(2);
						//
							toolTip = "Instead of simply culling the billboards beyond the 'Tree distance' specified in the terrain settings you may define a length over which the billboards will be smoothly faded out.";
						EditorGUILayout.PropertyField(BillboardFadeOutLength, new GUIContent("Billboard Fade Out Length", toolTip));
						GUILayout.Space(4);
						
						// "Shaded" Billboard settings
/*						GUILayout.Space(4);
						EditorGUILayout.LabelField("Shaded Billboard Settings", myLabel);
						GUILayout.Space(2);

						EditorGUILayout.PropertyField(DirectionalLightReference, new GUIContent("Light Reference") );
						EditorGUILayout.PropertyField(BillboardShadowColor, new GUIContent("Shadow Color") );
*/

					EditorGUILayout.EndVertical();
				EditorGUILayout.EndHorizontal();
			EditorGUILayout.EndVertical();

		}

//	///////////////////////////////////////////////////
//	Fog Settings
		GUILayout.Space(4);
		EditorGUILayout.BeginVertical("Box");
		// Foldout incl. Icon
		EditorGUILayout.BeginHorizontal();
			GUILayout.Space(-2);
			EditorGUI.indentLevel++;
			EditorGUILayout.BeginVertical();
				script.FoldFog  = EditorGUILayout.Foldout(script.FoldFog, "Fog Settings", myRegularFoldoutStyle);
			EditorGUILayout.EndVertical();
			EditorGUI.indentLevel--;
			EditorGUILayout.BeginVertical(GUILayout.Width(20) );
				GUILayout.Space(3);
				// Label needs width!
				EditorGUILayout.LabelField(new GUIContent(icnFog), GUILayout.Width(20), GUILayout.Height(20));
			EditorGUILayout.EndVertical();
		EditorGUILayout.EndHorizontal();
		// FoldoutContent
		if (script.FoldFog) {
			GUILayout.Space(-2);
			DrawSplitter(EditorGUILayout.GetControlRect(false, 4), SplitterCol);
			EditorGUILayout.BeginHorizontal();
				GUILayout.Space(13);

				EditorGUILayout.BeginHorizontal();
					EditorGUILayout.PropertyField(disableFoginShader, new GUIContent(""), GUILayout.Width(14));
					GUILayout.Label("Disable Fog in all AFS Shaders using the forward path.");
				EditorGUILayout.EndHorizontal();


			/*	EditorGUILayout.BeginVertical();
					EditorGUILayout.BeginHorizontal();
						EditorGUILayout.PropertyField(AFSShader_Folder, new GUIContent("AFS Shader Path"));
					EditorGUILayout.EndHorizontal();
					EditorGUILayout.BeginHorizontal();
						EditorGUILayout.BeginVertical();
							GUILayout.Space(4);
							EditorGUI.BeginChangeCheck();
							m_fogMode = (fogMode)EditorGUILayout.EnumPopup("Fog Mode", (fogMode)AFSFog_Mode.intValue );
							if (EditorGUI.EndChangeCheck()) {
								AFSFog_Mode.intValue = (int)m_fogMode;
							}
						EditorGUILayout.EndVertical();
						if (GUILayout.Button("Update Shaders", GUILayout.MaxWidth(110) )) {
								SetFogFeatures ();
							}
					EditorGUILayout.EndHorizontal();
				EditorGUILayout.EndVertical(); */
			EditorGUILayout.EndHorizontal();
			GUILayout.Space(6);
		}
		GUILayout.Space(-2);
		EditorGUILayout.EndVertical();


//	///////////////////////////////////////////////////
//	Layer Culling Settings
		GUILayout.Space(4);
		EditorGUILayout.BeginVertical("Box");
		// Foldout incl. Icon
		EditorGUILayout.BeginHorizontal();
			GUILayout.Space(-2);
			EditorGUI.indentLevel++;
			EditorGUILayout.BeginVertical();
				script.FoldCulling  = EditorGUILayout.Foldout(script.FoldCulling, "Layer Culling Settings", myRegularFoldoutStyle);
			EditorGUILayout.EndVertical();
			EditorGUI.indentLevel--;
			EditorGUILayout.BeginVertical(GUILayout.Width(20) );
				GUILayout.Space(3);
				// Label needs width!
				EditorGUILayout.LabelField(new GUIContent(icnCulling), GUILayout.Width(20), GUILayout.Height(20));
			EditorGUILayout.EndVertical();
		EditorGUILayout.EndHorizontal();
		// FoldoutContent
		if (script.FoldCulling) {
			DrawSplitter(EditorGUILayout.GetControlRect(false, 4), SplitterCol);
			EditorGUILayout.BeginHorizontal();
				GUILayout.Space(13);
				EditorGUILayout.BeginVertical();
					EditorGUILayout.BeginHorizontal();
						EditorGUILayout.PropertyField(EnableCameraLayerCulling, GUIContent.none, GUILayout.Width(14) );
						EditorGUILayout.LabelField("Enable Layer Culling");
					EditorGUILayout.EndHorizontal();
					if (EnableCameraLayerCulling.boolValue) {
						EditorGUILayout.PropertyField(SmallDetailsDistance, new GUIContent("Small Detail Distance") );
						EditorGUILayout.PropertyField(MediumDetailsDistance, new GUIContent("Medium Detail Distance") );
					}
				EditorGUILayout.EndVertical();
			EditorGUILayout.EndHorizontal();
			GUILayout.Space(4);
		}
		GUILayout.Space(-2);
		EditorGUILayout.EndVertical();

	//	Special Render Settings
		GUILayout.Space(4);
		EditorGUILayout.BeginVertical("Box");
		// Foldout incl. Icon
		EditorGUILayout.BeginHorizontal();
			GUILayout.Space(-2);
			EditorGUI.indentLevel++;
			EditorGUILayout.BeginVertical();
				script.FoldRender  = EditorGUILayout.Foldout(script.FoldRender, "Special Render Settings", myRegularFoldoutStyle);
			EditorGUILayout.EndVertical();
			EditorGUI.indentLevel--;
			EditorGUILayout.BeginVertical(GUILayout.Width(20) );
				GUILayout.Space(3);
				// Label needs width!
				EditorGUILayout.LabelField(new GUIContent(icnCamera), GUILayout.Width(20), GUILayout.Height(20));
			EditorGUILayout.EndVertical();
		EditorGUILayout.EndHorizontal();
		// FoldoutContent
		if (script.FoldRender) {
			DrawSplitter(EditorGUILayout.GetControlRect(false, 4), SplitterCol);
			EditorGUILayout.BeginHorizontal();
				GUILayout.Space(13);
				EditorGUILayout.BeginVertical();
					EditorGUILayout.BeginHorizontal();
						EditorGUILayout.PropertyField(AllGrassObjectsCombined, GUIContent.none, GUILayout.Width(14) );
						EditorGUILayout.LabelField("All Grass Objects Combined");
					EditorGUILayout.EndHorizontal();
				EditorGUILayout.EndVertical();
			EditorGUILayout.EndHorizontal();
			GUILayout.Space(4);
		}
		GUILayout.Space(-2);
		EditorGUILayout.EndVertical();
		GUILayout.Space(4);

//	////////////////////////
		SetupAFS.ApplyModifiedProperties();
	}
Beispiel #53
0
 public static Sprite ToSprite(this Texture2D texture)
 {
     return(Sprite.Create(texture, new Rect(0f, 0f, texture.width, texture.height), new Vector2(0.5F, 0.5F)));
 }
Beispiel #54
0
        /// <summary>
        /// Helper for drawing a texture into a rendertarget, using
        /// a custom shader to apply postprocessing effects.
        /// </summary>
        void DrawFullscreenQuad(Texture2D texture, RenderTarget2D renderTarget, Effect effect)
        {
            GraphicsDevice.SetRenderTarget(renderTarget);

            DrawFullscreenQuad(texture, renderTarget.Width, renderTarget.Height, effect);
        }
Beispiel #55
0
    public void Initialize()
    {
        presetButtonStyle = new GUIStyle();
        presetButtonStyle.stretchWidth  = true;
        presetButtonStyle.stretchHeight = true;

        List <Object> particlePrefabs = new List <Object>();

        // Get all user presets (bound to resources)
        int userPrefabCount = 0;

        Object[] resourcePrefabs = (Object[])Resources.LoadAll("Presets", typeof(GameObject));
        foreach (Object thisResourcePrefab in resourcePrefabs)
        {
            particlePrefabs.Add(thisResourcePrefab);
            userPrefabCount++;
        }

        // Get all example presets
        string assetsDataPath   = Application.dataPath;
        string editorPresetPath = assetsDataPath + "/" + playgroundPath + examplePresetPath;

        string[] editorPresetPaths = Directory.GetFiles(editorPresetPath);

        foreach (string thisPresetPath in editorPresetPaths)
        {
            string convertedPresetPath = thisPresetPath.Substring(assetsDataPath.Length - 6);
            Object presetPathObject    = (Object)AssetDatabase.LoadAssetAtPath(convertedPresetPath, typeof(Object));
            if (presetPathObject != null && (presetPathObject.GetType().Name) == "GameObject")
            {
                particlePrefabs.Add(presetPathObject);
            }
        }

        Texture2D particleImageDefault = AssetDatabase.LoadAssetAtPath("Assets/" + playgroundPath + iconPath + "Default.png", typeof(Texture2D)) as Texture2D;
        Texture2D particleImage;

        presetObjects = new List <PresetObjectC>();
        int i = 0;

        for (; i < particlePrefabs.Count; i++)
        {
            presetObjects.Add(new PresetObjectC());
            presetObjects[i].presetObject = particlePrefabs[i];
            presetObjects[i].example      = (i >= userPrefabCount);
            particleImage = AssetDatabase.LoadAssetAtPath("Assets/" + playgroundPath + iconPath + presetObjects[i].presetObject.name + ".png", typeof(Texture2D)) as Texture2D;

            // Try the asset location if we didn't find it in regular editor folder
            if (particleImage == null)
            {
                particleImage = AssetDatabase.LoadAssetAtPath(Path.GetDirectoryName(AssetDatabase.GetAssetPath(presetObjects[i].presetObject as UnityEngine.Object)) + "/" + presetObjects[i].presetObject.name + ".png", typeof(Texture2D)) as Texture2D;
            }

            // Finally use the specified icon (or the default)
            if (particleImage != null)
            {
                presetObjects[i].presetImage = particleImage;
            }
            else if (particleImageDefault != null)
            {
                presetObjects[i].presetImage = particleImageDefault;
            }
        }
        presetNames = new string[presetObjects.Count];
        for (i = 0; i < presetNames.Length; i++)
        {
            presetNames[i] = presetObjects[i].presetObject.name;

            // Filter on previous search
            presetObjects[i].unfiltered = (searchString == ""?true:presetNames[i].ToLower().Contains(searchString.ToLower()));
        }

        if (!didSendVersionCheck)
        {
            versionRequest = new WWW(versionUrl);
        }
    }
Beispiel #56
0
 public Background(Texture2D t)
 {
     m_Texture = t;
     m_VectorImage = null;
 }
Beispiel #57
0
 // Use this for initialization
 void Start()
 {
     t2D = Resources.Load <Texture2D>("restart-text");
 }
Beispiel #58
0
    public static Texture2D DrawLine(this Texture2D texture, Vector2 from, Vector2 to, float w, float f, Color32 col)
    {
        bool  stroke      = false;
        float strokeWidth = 0;
        Color strokeCol   = Color.white;

        w           = Mathf.Round(w);
        strokeWidth = Mathf.Round(strokeWidth);

        float sqrW  = w * w;
        float sqrF  = f * f;
        float sqrFS = (w - f) * (w - f);

        float extent = w + strokeWidth;


        strokeWidth = strokeWidth / 2;
        float strokeInner  = (w - strokeWidth) * (w - strokeWidth);
        float strokeOuter  = (w + strokeWidth) * (w + strokeWidth);
        float strokeOuter2 = (w + strokeWidth + 1) * (w + strokeWidth + 1);

        int startX = (int)Mathf.Clamp(Mathf.Min(from.x, to.x) - extent, 0, texture.width);
        int startY = (int)Mathf.Clamp(Mathf.Min(from.y, to.y) - extent, 0, texture.height);

        int endX = (int)Mathf.Clamp(Mathf.Max(from.x, to.x) + extent, 0, texture.width);
        int endY = (int)Mathf.Clamp(Mathf.Max(from.y, to.y) + extent, 0, texture.height);


        int lengthX = endX - startX;
        int lengthY = endY - startY;

        Vector2 start = new Vector2(startX, startY);

        Color[] pixels = texture.GetPixels(startX, startY, lengthX, lengthY, 0);


        Color c;
        Color pc;

        for (int x = 0; x < lengthX; x++)
        {
            for (int y = 0; y < lengthY; y++)
            {
                Vector2 p      = new Vector2(x, y) + start;
                Vector2 center = p + new Vector2(0.5f, 0.5f);
                float   dist   = (center - NearestPointStrict(from, to, center)).sqrMagnitude;        //The squared distance from the center of the pixels to the nearest point on the line

                if (dist <= strokeOuter2)
                {
                    if (dist < sqrFS)
                    {
                        c = col;
                    }
                    else
                    {
                        c = pixels [y * lengthX + x];
                        c = Color32.Lerp(col, c, (dist - sqrFS) / sqrF);
                    }

                    pixels[y * lengthX + x] = c;
                }
            }
        }


        texture.SetPixels(startX, startY, lengthX, lengthY, pixels, 0);
        texture.Apply();
        return(texture);
    }
        public override bool drawCircle(Vector3 center, float radius)
        {
            GraphicsDevice device = UWB_XNAGraphicsDevice.m_TheAPI.GraphicsDevice;
            Debug.Assert(device != null, "device not valid on DrawHelper drawCircle call");

            if (radius > 0)
            {
                int kNumTriangles = 40;
                if (mLod == eLevelofDetail.lodLow)
                    kNumTriangles = 10;
                else if (mLod == eLevelofDetail.lodMed)
                    kNumTriangles = 20;
                VertexPositionNormalTexture[] v = new VertexPositionNormalTexture[kNumTriangles * 3];

                float theta = (2.0f * (float)Math.PI) / kNumTriangles;

                v[0].Position = center;
                v[0].TextureCoordinate = new Vector2(0.5f, 0.5f);
                v[0].Normal = Vector3.UnitZ;
                float px = center.X + radius;
                float py = center.Y;
                Vector2 puv = new Vector2(1, 0);

                for (int i = 0; i < kNumTriangles; i++)
                {
                    int offset = i * 3;
                    float x = center.X + (radius * (float)Math.Cos((i + 1) * theta));
                    float y = center.Y + (radius * (float)Math.Sin((i + 1) * theta));
                    float tu = 0.5f + (0.5f * (float)Math.Cos((i + 1) * theta));
                    float tv = 0.5f - (0.5f * (float)Math.Sin((i + 1) * theta));
                    v[offset].Position = v[0].Position;
                    v[offset].TextureCoordinate = v[0].TextureCoordinate;
                    v[offset].Normal = Vector3.UnitZ;

                    v[offset + 1].Position = new Vector3(px, py, 0f);
                    v[offset + 1].TextureCoordinate = puv;
                    v[offset + 1].Normal = Vector3.UnitZ;

                    v[offset + 2].Position = new Vector3(x, y, 0f);
                    v[offset + 2].TextureCoordinate = new Vector2(tu, tv);
                    v[offset + 2].Normal = Vector3.UnitZ;

                    px = x;
                    py = y;
                    puv = v[offset + 2].TextureCoordinate;
                }

                UWB_XNAEffect effect = UWB_XNAGraphicsDevice.m_TheAPI.LightingEffect;

                Texture2D texture = null;

                if (m_bTexturingEnabled && m_TexFileName != "")
                    texture = UWB_XNAGraphicsDevice.m_TheAPI.RetrieveTexture(m_TexFileName);

                effect.Material = this.m_Material;

                if (texture != null)
                {
                    effect.Texture = texture;
                    effect.TextureEnabled = true;
                }
                else
                {
                    effect.Texture = texture;
                    effect.TextureEnabled = false;
                }

                foreach (EffectPass pass in effect.CurrentTechnique.Passes)
                {
                    pass.Apply();
                    device.DrawUserPrimitives(PrimitiveType.TriangleList, v, 0, kNumTriangles);
                }
            }

            return true;
        }
Beispiel #60
0
        /// <summary>
        /// Constructor of the ActionScene
        /// </summary>
        /// <param name="game">game</param>
        /// <param name="spriteBatch">spriteBatch</param>
        /// <param name="sound">sound</param>
        public ActionScene(Game game,
                           SpriteBatch spriteBatch) : base(game)
        {
            this.spriteBatch = spriteBatch;
            //this.sound = sound;

            energyCount        = Shared.ENERGY;
            Shared.isNextLevel = false;

            shipTex = game.Content.Load <Texture2D>("Images/ship");
            Texture2D giftTex  = game.Content.Load <Texture2D>("Images/gift");
            Texture2D enemyTex = game.Content.Load <Texture2D>("Images/enemy");
            Texture2D expTex   = game.Content.Load <Texture2D>("Images/explosion");
            Texture2D crashTex = game.Content.Load <Texture2D>("Images/boom");
            Texture2D bgTex    = game.Content.Load <Texture2D>("images/Back");

            bgmSound        = game.Content.Load <Song>("Sounds/game");
            crashSound      = game.Content.Load <Song>("Sounds/boom");
            takeEnergySound = game.Content.Load <Song>("Sounds/item");
            levelUp         = game.Content.Load <Song>("Sounds/levelup");
            gameOver        = game.Content.Load <Song>("Sounds/gameOver");
            gameFailSound   = game.Content.Load <Song>("Sounds/intro");

            ship = new Ship(game, spriteBatch, shipTex, ENERGY_SCORE, isCrash, isTakeEnergy);
            MediaPlayer.Play(bgmSound);
            // Set game level
            Shared.GameLevelInitialize();

            #region Game Object Generation
            int maxSpawnX = 800;
            int maxSpawnY = 600;

            Random r = new Random(120);
            //ramdomly enemy generate
            for (int i = 0; i < Shared.ENEMY; i++)
            {
                int speedX = r.Next(1, Shared.MAX_SPEED);
                int speedY = r.Next(1, Shared.MAX_SPEED);
                int signX  = r.Next(0, 2);
                int signY  = r.Next(0, 2);

                if (signX == 1)
                {
                    speedX = -speedX;
                }
                if (signY == 1)
                {
                    speedY = -speedY;
                }

                int xp = r.Next(0, maxSpawnX);
                int yp = r.Next(0, maxSpawnY);

                enemySpeed = new Vector2((float)speedX, (float)speedY);
                enemyPos   = new Vector2(xp, yp);
                enemy      = new Enemy(game, spriteBatch, enemyTex, enemyPos, enemySpeed);
                this.Components.Add(enemy);

                crash = new Crash(game, spriteBatch, expTex, Vector2.Zero);
                this.Components.Add(crash);

                CollisionManager cm = new CollisionManager(game, enemy, ship,
                                                           bgmSound, crashSound, crash, ENEMY_COLLISION);
                this.Components.Add(cm);
            }

            //ramdomly gift generate
            for (int i = 0; i < Shared.ENERGY; i++)
            {
                int speedX = r.Next(1, Shared.MAX_SPEED);
                int speedY = r.Next(1, Shared.MAX_SPEED);
                int signX  = r.Next(0, 2);
                int signY  = r.Next(0, 2);

                if (signX == 1)
                {
                    speedX = -speedX;
                }
                if (signY == 1)
                {
                    speedY = -speedY;
                }

                int xp = r.Next(0, maxSpawnX);
                int yp = r.Next(0, maxSpawnY);

                giftSpeed = new Vector2((float)speedX, (float)speedY);
                giftPos   = new Vector2(xp, yp);
                gift      = new Gift(game, spriteBatch, giftTex, giftPos, giftSpeed, Shared.stage);
                this.Components.Add(gift);

                crash = new Crash(game, spriteBatch, crashTex, giftPos);
                this.Components.Add(crash);

                CollisionManager cm = new CollisionManager(game, gift, ship, bgmSound,
                                                           takeEnergySound, crash, !ENEMY_COLLISION);
                this.Components.Add(cm);
            }

            #endregion

            #region Game Message Initialization
            SpriteFont infoFont    = game.Content.Load <SpriteFont>("fonts/infoFont");
            SpriteFont messageFont = game.Content.Load <SpriteFont>("fonts/MessageFont");

            //timer
            timerPos = new Vector2((Shared.stage.X - infoFont.MeasureString("Time remain: 30.0").X) / 2, 10);
            timer    = new GamePlayTime(game, spriteBatch, infoFont, GAME_DURATION, timerPos);
            this.Components.Add(timer);

            // level message
            levelMessage          = new GameMessage(game, spriteBatch, infoFont, Color.Yellow);
            levelMessage.Message  = string.Format("Level {0}", Shared.currentLevel);
            levelMessage.Position = new Vector2(Shared.stage.X - infoFont.MeasureString(levelMessage.Message).X - 40, 30);
            this.Components.Add(levelMessage);

            // score message
            scoreMessage          = new GameMessage(game, spriteBatch, infoFont, Color.Yellow);
            scoreMessage.Message  = string.Format("Energy Score: {0:D3}", 0);
            scoreMessage.Position = new Vector2(50 + infoFont.LineSpacing, 25);
            this.Components.Add(scoreMessage);

            // high score message
            highScoreMessage         = new GameMessage(game, spriteBatch, infoFont, Color.Yellow);
            highScoreMessage.Message = string.Format("High Score: {0:D3}", 0);
            //highScoreMessage.Position = new Vector2(50 + infoFont.LineSpacing, 15);
            highScoreMessage.Position = new Vector2(Shared.stage.X - infoFont.MeasureString(highScoreMessage.Message).X - 40, 10);
            this.Components.Add(highScoreMessage);

            // level complete message
            levelCompleteMessage         = new GameMessage(game, spriteBatch, messageFont, Color.LightGoldenrodYellow);
            levelCompleteMessage.Message = "LEVEL COMPLETE\nSPACE TO NEXT LEVEL";
            messageSize = messageFont.MeasureString(levelCompleteMessage.Message);
            levelCompleteMessage.Position = new Vector2((Shared.stage.X - messageSize.X) / 2, (Shared.stage.Y - messageSize.Y) / 2);
            this.Components.Add(levelCompleteMessage);
            levelCompleteMessage.Enabled = false;
            levelCompleteMessage.Visible = false;

            // game complete message
            gameCompleteMessage         = new GameMessage(game, spriteBatch, messageFont, Color.LightGoldenrodYellow);
            gameCompleteMessage.Message = "CONGRATURATION!!\n\nGAME COMPLETE\nSPACE TO RECORD SCORE, ESC TO MENU";
            messageSize = messageFont.MeasureString(gameCompleteMessage.Message);
            gameCompleteMessage.Position = new Vector2((Shared.stage.X - messageSize.X) / 2, (Shared.stage.Y - messageSize.Y) / 2);
            this.Components.Add(gameCompleteMessage);
            gameCompleteMessage.Enabled = false;
            gameCompleteMessage.Visible = false;

            // game over message
            gameOverMessage          = new GameMessage(game, spriteBatch, messageFont, Color.OrangeRed);
            gameOverMessage.Message  = "GAME OVER\nSPACE TO RE-PLAY, ESC TO MENU";
            messageSize              = messageFont.MeasureString(gameOverMessage.Message);
            gameOverMessage.Position = new Vector2((Shared.stage.X - messageSize.X) / 2, (Shared.stage.Y - messageSize.Y) / 2);
            this.Components.Add(gameOverMessage);
            gameOverMessage.Enabled = false;
            gameOverMessage.Visible = false;

            #endregion
        }