Dec 18, 2007

memo of VB.Net 2005 II-Kaleidoscope

Purpose
  A kaleidoscope I created by VB.Net. Just simulating the scope by mirroring the track of mouse in the window. The length and the number of mirrors are controllable.

Coordinate System Transform:
Rectangular->Polar:
ρ = Math.Sqrt(X ^ 2 + Y ^ 2)
θ= Math.Atan2(Y, X)

Polar->Rectangular:
X=ρ * Math.Cos(θ)
Y=ρ * Math.Sin(θ)

Even Numbers:
If k Mod 2 = 0 Then
Return k
ElseIf k Mod 2 = 1 Then
Return k + 1
End If


Random Colors:
Dim r, g, b, a As Short
Dim rnd As New Random
Dim rancolorpen As Pen
a = rnd.Next(1, 255)
r = rnd.Next(1, 255)
g = rnd.Next(1, 255)
b = rnd.Next(1, 255)
rancolorpen = New Pen(Color.FromArgb(a, r, g, b))

Change the form of Object:
Dim p As GraphicsPath = New GraphicsPath

Event: Form_Load or Resize
p.Reset()
p.AddEllipse(0, 0, Panel1.Width - 1, Panel1.Height - 1) 'draw a figure
Panel1.Region = New Region(p) 'change the object's form(Region)

Draw mirror points:
Const length As Integer = 100 'max track points
Const n As Short = 40 'max mirrors
Dim
θ(length, n), ρ(length) As Single 'θ to record points' radians, ρ to record points' distances

Dim ptArray(length, n), temppt(length) As PointF
'ptArray to record points' in
Rectangular, n∈1,2…k, [1] as original,[2,k] as mirror points
'temppt to use as a temp array for loading points
Dim tracklength,n1 As Short 'tracklength to control length, n1 to control mirrors

Event: Object_MouseMove
1).Record [num of length] mouse's track points:

Dim mouseX = e.X - Panel1.Width / 2
Dim mouseY = e.Y - Panel1.Height / 2
For
i = 0 To tracklength - 1
ptArray(i, 1) = ptArray(i + 1, 1)
Next
'record new location
ptArray(tracklength, 1) = New Point(mouseX, mouseY)

2).Transform to Polar & Caculate the mirror points
For i = 0 To tracklength
'transform
ρ(i) = Math.Sqrt(ptArray(i, 1).X ^ 2 + ptArray(i, 1).Y ^ 2)
θ(i, 1) = Math.Atan2(ptArray(i, 1).Y, ptArray(i, 1).X)
'calculate the mirror points
For k = 1 To j - 1
θ(i, k + 1) = 2 * Math.PI * evennum(k) / j + ((-1) ^ k) *θ(i, 1)
Next
Next

3).Transform mirror points to
Rectangular

For i = 0 To tracklength
For k = 2 To n1
ptArray(i, k).X = polartoX(rho(i), theta(i, k))
ptArray(i, k).Y = polartoY(rho(i), theta(i, k))
Next
Next

Event: Object_Paint
'
Translates the local geometric transformation by the specified dimensions

e.Graphics.TranslateTransform(Object.Width / 2,
Object.Width
/ 2)
For k = 1 To n1
For i = 0 To tracklength
temppt(i) = ptArray(i, k)
Next
e.Graphics.DrawLines(rancolorpen, temppt)
Next


No comments: