using System;
using System.Collections.Generic;
using System.Text;
using Vortex.Drawing;

namespace Vortex.Tutorials.RenderTargetAndOverlays {

    ///<summary>Tutorial about using render targets and overlays</summary>
    class RenderTargetAndOverlays : Game {
        const int SPLIT_COUNT = 2;

        TargetTexture _RenderTarget;
        Texture _StencilTexture;
        Texture _BackgroundTexture;
        Texture _DropTexture;

        protected override void Load() {
            //load all textures
            _RenderTarget = new TargetTexture(Window.Size.Width / SPLIT_COUNT, Window.Size.Height / SPLIT_COUNT, PixelFormat.X8R8G8B8);
            _BackgroundTexture = new Texture(@"{graphics}\flower.jpg");
            _DropTexture = new Texture(@"{graphics}\drop.png");
            _StencilTexture = new Texture(@"{graphics}\stencil.png");
        }

        protected override void Unload() {
            //free all textures
            _BackgroundTexture.Dispose();
            _DropTexture.Dispose();
            _StencilTexture.Dispose();
            _RenderTarget.Dispose();
        }

        protected override void Render(Canvas2D canvas) {
            //draw on render target first
			DrawOnTarget(_RenderTarget.Canvas);

            Vector2 cellSize = canvas.Size / SPLIT_COUNT;

            //clear main target background
            canvas.Clear(ColorU.Black);

            //draw render target on entire background with 25% opacity
            canvas.DrawSprite(canvas.Region, _RenderTarget.ToSprite(), ColorU.White.MultiplyAlpha(0.25f));

            //apply stencil via overlay for all sprite output
            using (canvas <= new SpriteBrush(_StencilTexture.ToSprite())) {
                //make loop and draw many render target sprites, all of them will be stenciled
                for (int n = 0; n < SPLIT_COUNT; ++n) {
                    for (int m = 0; m < SPLIT_COUNT; ++m) {
                        Rect target = Rect.FromBox(m * cellSize.X, n * cellSize.Y, cellSize.X, cellSize.Y);
                        canvas.DrawSprite(target, _RenderTarget.ToSprite(), ColorU.White);
                    }
                }

            }
            
        }

		private void DrawOnTarget(Canvas2D canvas) {
			//draw flower background
			canvas.DrawSprite(canvas.Region, _BackgroundTexture.ToSprite(), ColorU.White);

			//draw drops
			float radiusX = (float)canvas.Width * 0.35f, radiusY = (float)canvas.Height * 0.35f;
			float step = (float)Math.PI / 10;
			float offset = Time.TotalGameTime;
			for (float n = 0; n < Math.PI * 2; n += step) {
				Vector2 position = new Vector2(canvas.Width * 0.5f + radiusX * (float)Math.Cos(n + offset), canvas.Height * 0.5f + radiusY * (float)Math.Sin(n + offset));
				canvas.DrawSprite(position, (Vector2)_DropTexture.Size / SPLIT_COUNT, _DropTexture.ToSprite(), ColorU.White);
			}
		}
    }

}
