Neat Mandelbrot and Shaders
In my surfing around to learn various things for XNA I started looking into procedural textures. Of course, anything that can be generated by the computer instead of my art is great :)
One thing that I found is the Mandelbrot. After a combination of techniques from Shawn Hargreaves’ Blog and Mike’s Code Blog I was able to get something up and running. It uses HLSL shaders and does all the “rendering” on the GPU. I have yet to try it on the Xbox 360, but I think it will work. It’s pretty interesting and I’ve already learned a bunch about how Pixel Shaders work from it (which they have been a complete mystery to me before).
Here I’ll post the shader file to demonstrate my changes:
#define Iterations 128
float2 Pan;
float Zoom;
float Aspect;
float2 JuliaSeed = float2(0.39, -0.2);
float2 RandomSeed = float2(0.88, 1);
float3 ColorScale = float3(4, 5, 6);
float ComputeValue(float2 v, float2 offset)
{
float vxsquare = 0;
float vysquare = 0;
int iteration = 0;
int lastIteration = Iterations;
do
{
vxsquare = v.x * v.x;
vysquare = v.y * v.y;
v = float2(vxsquare - vysquare, v.x * v.y * 2) + offset;
iteration++;
if ((lastIteration == Iterations) && (vxsquare + vysquare) > 4.0)
{
lastIteration = iteration + 1;
}
}
while (iteration < lastIteration);
return (float(iteration) - (log(log(sqrt(vxsquare + vysquare))) / log(2.0))) / float(Iterations);
}
float4 Mandelbrot_PixelShader(float2 texCoord : TEXCOORD0) : COLOR0
{
float2 v = (texCoord - 0.5) * Zoom * float2(1, Aspect) - Pan;
float val = ComputeValue(v, v);
return float4(sin(val * ColorScale.x), sin(val * ColorScale.y), sin(val * ColorScale.z), 1);
}
float4 Julia_PixelShader(float2 texCoord : TEXCOORD0) : COLOR0
{
float2 v = (texCoord - 0.5) * Zoom * float2(1, Aspect) - Pan;
float val = ComputeValue(v, JuliaSeed);
return float4(sin(val * ColorScale.x), sin(val * ColorScale.y), sin(val * ColorScale.z), 1);
}
float4 Random_PixelShader(float2 texCoord : TEXCOORD0) : COLOR0
{
float2 v = (texCoord - 0.5) * Zoom * float2(1, Aspect) - Pan;
float val = ComputeValue(v, RandomSeed);
return float4(sin(val * ColorScale.x), sin(val * ColorScale.y), sin(val * ColorScale.z), 1);
}
technique Mandelbrot
{
pass
{
PixelShader = compile ps_3_0 Mandelbrot_PixelShader();
}
}
technique Julia
{
pass
{
PixelShader = compile ps_3_0 Julia_PixelShader();
}
}
technique Random
{
pass
{
PixelShader = compile ps_3_0 Random_PixelShader();
}
}
As you can see, all I really did is add a RandomSeed and a new technique. In the Xna code I setup a timer so that the random seed will generate every 30 seconds, and in between that the seed will increment so you can see how it flows. I also added some keys to view the various techniques.
Here is the game code that makes all that go:
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;
namespace MandlebrotTest
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
Effect mandelbrot;
SpriteBatch spriteBatch;
Texture2D dummyTexture;
string tech = "Mandelbrot";
Vector2 pan = new Vector2(0.25f, 0);
float zoom = 3;
Random rand = new Random();
double[] speeds = { 1 / 10f, 1 / 25f, 1 / 50f, 1 / 100f, 1 / 200f, 1 / 500f, 1 / 1000f };//{1 / 100f, 1 / 50f, 1 / 25f, 1 / 10f, 1 / 5f, 1 };
int speedIndex = 3;
float cycleTimer = 0f;
Vector2 randomSeed = Vector2.Zero;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
IsFixedTimeStep = true;
TargetElapsedTime = TimeSpan.FromSeconds( speeds[speedIndex] );
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
// TODO: Add your initialization logic here
base.Initialize();
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
mandelbrot = Content.Load<Effect>("Mandelbrot");
int w = graphics.GraphicsDevice.Viewport.Width;
int h = graphics.GraphicsDevice.Viewport.Height;
dummyTexture = new Texture2D(graphics.GraphicsDevice, w, h, 1,
TextureUsage.None, SurfaceFormat.Color);
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// all content.
/// </summary>
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed ||
Keyboard.GetState(PlayerIndex.One).IsKeyDown(Keys.Escape))
this.Exit();
GamePadState pad = GamePad.GetState(PlayerIndex.One);
KeyboardState kb = Keyboard.GetState(PlayerIndex.One);
// swap techniques
if (kb.IsKeyDown(Keys.T))
tech = "Julia";
if (kb.IsKeyDown(Keys.R))
tech = "Mandelbrot";
if (kb.IsKeyDown(Keys.E))
tech = "Random";
cycleTimer += (float)gameTime.ElapsedGameTime.TotalMilliseconds;
// start new random every 30 secs
if (cycleTimer > 30000f)
{
randomSeed = new Vector2((float)rand.NextDouble(), -(float)rand.NextDouble());
cycleTimer = 0.0f;
}
mandelbrot.Parameters["RandomSeed"].SetValue(randomSeed);
// update seed
randomSeed += new Vector2(-0.00075f, 0.00075f);
if (pad.Buttons.A == ButtonState.Pressed || kb.IsKeyDown(Keys.Z))
zoom /= 1.05f;
if (pad.Buttons.B == ButtonState.Pressed || kb.IsKeyDown(Keys.X))
zoom *= 1.05f;
float panSensitivity = 0.01f * (float)Math.Log(zoom + 1);
pan += new Vector2(pad.ThumbSticks.Left.X, -pad.ThumbSticks.Left.Y) * panSensitivity;
base.Update(gameTime);
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
GraphicsDevice device = graphics.GraphicsDevice;
float aspectRatio = (float)device.Viewport.Height / (float)device.Viewport.Width;
mandelbrot.Parameters["Pan"].SetValue(pan);
mandelbrot.Parameters["Zoom"].SetValue(zoom);
mandelbrot.Parameters["Aspect"].SetValue(aspectRatio);
spriteBatch.Begin(SpriteBlendMode.None, SpriteSortMode.Immediate, SaveStateMode.None);
mandelbrot.CurrentTechnique = mandelbrot.Techniques[tech];
mandelbrot.Begin();
mandelbrot.CurrentTechnique.Passes[0].Begin();
spriteBatch.Draw(dummyTexture, Vector2.Zero, Color.White);
spriteBatch.End();
mandelbrot.CurrentTechnique.Passes[0].End();
mandelbrot.End();
base.Draw(gameTime);
}
}
}
Of course another reason besides art that I am interested in all this is that it can be helpful for random map generation in my project (which is still under way). I’ve made some improvements on that front, and I’ll post an update on it soon.