Code Optimization

Interesting things in software development and code optimization

Swap two variables without using a third one

Hello friends,


Going to ask you - do you know how to swap two variables without of using another one variable?

If your answer is no then here you are:

- we need two variables

- we need three XOR operations

int a = 1;

int b = 2;

a ^= b;

b ^= a;

a ^= b;

now b = 1 and a = 2


Thank you ;)


1vqHSTrq1GEoEF7QsL8dhmJfRMDVxhv2y



Silverligh 3D Icons

Hello,


Today, I'm going to share my experience with the Silverlight and 3D. One time I saw a Microsoft presentation about a game platform or something, and there were 3D buttons like you see bellow, they did attract my attention so much that I started to make something similar. After a few days video review and thinking I started to implement it myself.

The main thing here is adding image layers and rotate them at once, plus some additional visual effects. So, here is the mouse move handler:

p = e.GetPosition(LayoutRoot);

ry = (mx - p.X) / 2;

rx = -((my - p.Y) / 2);

degree = Math.Atan2(p.Y - my, p.X - mx) * -180 / Math.PI;

degree = 180.0 + degree;

LayoutRoot.Effect.SetValue(DropShadowEffect.DirectionProperty, degree);

BorderControl.Projection.SetValue(PlaneProjection.RotationXProperty, rx);

BorderControl.Projection.SetValue(PlaneProjection.RotationYProperty, ry);

bgTranslate.X = offsetBackgroundX + ry / k;

bgTranslate.Y = offsetBackgroundY + (-rx / k);

foreach (IconImage ii in images)

{

ii.Image.Projection.SetValue(PlaneProjection.RotationXProperty, rx + (ii.ZIndex / globalZIndexStart));

ii.Image.Projection.SetValue(PlaneProjection.RotationYProperty, ry + (ii.ZIndex / globalZIndexStart));

ii.Image.Effect.SetValue(DropShadowEffect.DirectionProperty, degree);

}

So, you calculate angle from two points and rotate each image by the angle value.

Source code is bellow, thank you :)

Icon3D.zip (9.3KB)

1vqHSTrq1GEoEF7QsL8dhmJfRMDVxhv2y



C#.Net - Perspective Image Transform

Hello,


Today, I'm going to share one interesting thing that everyone may need - perspective image transformation.

Its 2D transformation that makes image look like in perspective view like 3D but without any 3D:


So, the main thing there is math. We take an image, specify four points and math will do the trick.

First step is to create and calculate matrices from the new four points:

//original points

Point p1 = new Point(0, 0);

Point p2 = new Point(width, 0);

Point p3 = new Point(width, height);

Point p4 = new Point(0, height);

//create matrix

A = Matrix3x3.Homogenous(p1, p2, p3, p4);

//new points

Point n1 = points[0];

Point n2 = points[1];

Point n3 = points[2];

Point n4 = points[3];

B = Matrix3x3.Homogenous(n1, n2, n3, n4);

A.Inverse();

C = B.MultMat(A);

C.Inverse();

Second step is to go through each pixel on your image and calculate new pixel:

Point ptDest = new Point(0, 0);

PointF ptOriginF = new Point(0, 0);

int iOrigX = 0;

Color pix = new Color();

for (int x = 0; x < width; ++x)

{

for (int y = 0; y < height; ++y)

{

ptDest.X = x;

ptDest.Y = y;

ptOriginF = C.Update(ptDest);

if (ptOriginF.X >= -5 && ptOriginF.X < width && ptOriginF.Y >= -5 && ptOriginF.Y < height)

{


iOrigX = (int)ptOriginF.X; // round to lowest integer

int iOrigY = (int)ptOriginF.Y; // round to lowest integer

double dx = ptOriginF.X - iOrigX;

double dy = ptOriginF.Y - iOrigY;

Point ptOrigin = new Point(iOrigX, iOrigY);

if (dx != 0.0f || dy != 0.0)

{

Color pix1 = Color.FromArgb(0, 255, 255, 255);

Color pix2 = Color.FromArgb(0, 255, 255, 255);

Color pix3 = Color.FromArgb(0, 255, 255, 255);

Color pix4 = Color.FromArgb(0, 255, 255, 255);

//

// Correct square's direction

//

int idx = (dx >= 0.0) ? 1 : -1;

int idy = (dy >= 0.0) ? 1 : -1;


dx = Math.Abs(dx);

dy = Math.Abs(dy);

//

// Get pixels of square

//

if (ptOrigin.X >= 0 && ptOrigin.X < width && ptOrigin.Y >= 0 && ptOrigin.Y < height)

pix1 = src.GetPixel(ptOrigin.X, ptOrigin.Y);

if (ptOrigin.X + idx >= 0 && ptOrigin.X + idx < width && ptOrigin.Y >= 0 && ptOrigin.Y < height)

pix2 = src.GetPixel(ptOrigin.X + idx, ptOrigin.Y);

if (ptOrigin.X >= 0 && ptOrigin.X < width && ptOrigin.Y + idy >= 0 && ptOrigin.Y + idy < height)

pix3 = src.GetPixel(ptOrigin.X, ptOrigin.Y + idy);

if (ptOrigin.X + idx >= 0 && ptOrigin.X + idx < width && ptOrigin.Y + idy >= 0 && ptOrigin.Y + idy < height)

pix4 = src.GetPixel(ptOrigin.X + idx, ptOrigin.Y + idy);

//

// Use bilinear interpolation

//

double r = pix1.R + (pix2.R - pix1.R) * dx + (pix3.R - pix1.R) * dy + (pix1.R - pix2.R - pix3.R + pix4.R) * dx * dy;

double g = pix1.G + (pix2.G - pix1.G) * dx + (pix3.G - pix1.G) * dy + (pix1.G - pix2.G - pix3.G + pix4.G) * dx * dy;

double b = pix1.B + (pix2.B - pix1.B) * dx + (pix3.B - pix1.B) * dy + (pix1.B - pix2.B - pix3.B + pix4.B) * dx * dy;

double a = pix1.A + (pix2.A - pix1.A) * dx + (pix3.A - pix1.A) * dy + (pix1.A - pix2.A - pix3.A + pix4.A) * dx * dy;

pix = Color.FromArgb((byte)a, (byte)r, (byte)g, (byte)b);

}

else

{

pix = src.GetPixel(ptOrigin.X, ptOrigin.Y);

}

dst.SetPixel(ptDest.X, ptDest.Y, pix);

}

}

}

So this is bilinear interpolation is the main thing to transform your image.


Thank you.

PS

will extend this and provide source code if you will request.




1vqHSTrq1GEoEF7QsL8dhmJfRMDVxhv2y



Microsoft Expression Encoder - How to use and without installation

Hello friends,


Today I will share my experience with the Microsoft Expression Encoder 4 free version.

Download it and install from the link above, add references to the libraries:


- Microsoft.Expression.Encoder.dll

- Microsoft.Expression.Encoder.Api2.dll

- Microsoft.Expression.Encoder.Types.dll

- Microsoft.Expression.Encoder.Utilities.dll


So the minimum code you need to implement to be able to preview and capture video and audio and list devices is the following:

video.Clear();

audio.Clear();

foreach (var dev in EncoderDevices.FindDevices(EncoderDeviceType.Video))

{

video.Add(new ComboboxItem() { Text = dev.Name, Value = dev })

}


foreach (var dev in EncoderDevices.FindDevices(EncoderDeviceType.Audio))

{

audio.Add(new ComboboxItem() { Text = dev.Name, Value = dev });

}

try

{

if (ljob == null)

{

ljob = new LiveJob();

source = ljob.AddDeviceSource((EncoderDevice)((ComboboxItem)cbVideoDevice.SelectedItem).Value,

(EncoderDevice)((ComboboxItem)cbAudioDevice.SelectedItem).Value);

source.PickBestVideoFormat(videoSize, 400000); //in 100 nanoseconds = 40 ms = 25 frames per seconds

source.SetTransportMode(TransportMode.FastForward);


ljob.OutputFormat.VideoProfile = new Microsoft.Expression.Encoder.Profiles.AdvancedVC1VideoProfile() { };

ljob.OutputFormat.VideoProfile.Size = videoSize;

ljob.OutputFormat.VideoProfile.FrameRate = 25;

ljob.OutputFormat.AudioProfile = new Microsoft.Expression.Encoder.Profiles.WmaAudioProfile() { };

ljob.OutputFormat.AudioProfile.Codec = Microsoft.Expression.Encoder.Profiles.AudioCodec.Wma;

}

source.PreviewWindow = new PreviewWindow(new System.Runtime.InteropServices.HandleRef(capForm.Panel, ca pForm.Panel.Handle));

ljob.ActivateSource(source);

}

catch (Microsoft.Expression.Encoder.SystemErrorException ex)

{

if (ex.ErrorCode == -2126905299)

{

MessageBox.Show("Device in use by another application.", "Test EE 4");

}

}

and to start capture:

ljob.PublishFormats.Add(new FileArchivePublishFormat(System.IO.Path.GetFullPath(filePath + fileName)));

ljob.StartEncoding();


Another important thing is to avoid using the installation package of the Microsoft Expression Encoder but just use those four Dlls.

If you will try to run your app on another PC you will get error that Expression Encoder has no license key or something. So to avoid this you have to cases:


- bring the install package and install it on every PC where is your app

- make some changes into registry


I will show you what changes should we make to be able to use it on every PC without installation of Microsoft Expression Encoder, here is the code:

private void TellExpressionEncoderWhereItIs()

{

try

{

var key = "SOFTWARE\\Microsoft\\Expression\\Encoder\\4.0";

 

using (var registryKey = Registry.LocalMachine.OpenSubKey(key))

{

if (registryKey == null)

{

using (var newKey = Registry.LocalMachine.CreateSubKey(key))

{

CheckInstallKey(newKey);

}

}

}

key = "SOFTWARE\\Microsoft\\Expression\\Encoder\\eaa89a7c-d288-4a52-9b68-54930f18ffb7";


using (var registryKey = Registry.LocalMachine.OpenSubKey(key))

{

if (registryKey == null)

{

using (var newKey = Registry.LocalMachine.CreateSubKey(key))

{

CheckInstallKey(newKey);

}

}

}

}

catch (Exception ex)

{

MessageBox.Show(ex.ToString());

}

}

private void CheckInstallKey(RegistryKey registryKey)

{

var path = "c:\\Program Files\\Microsoft Expression\\Encoder 4\\";

var installKey = "InstallDir";

if (registryKey != null)

{

string text = registryKey.GetValue(installKey) as string;

if (string.IsNullOrEmpty(text))

{

registryKey.SetValue(installKey, path);

}

}

path = "4.0.4276.0";

installKey = "Version";

if (registryKey != null)

{

string text = registryKey.GetValue(installKey) as string;

if (string.IsNullOrEmpty(text))

{

registryKey.SetValue(installKey, path);

}

}

path = "c:\\Program Files\\Microsoft Expression\\Encoder 4\\Encoder.exe";

installKey = "Encoder";

if (registryKey != null)

{

string text = registryKey.GetValue(installKey) as string;

if (string.IsNullOrEmpty(text))

{

registryKey.SetValue(installKey, path);

}

}

path = "c:\\Program Files\\Microsoft Expression\\Encoder 4\\Encoder.exe";

installKey = "InstallPath";

if (registryKey != null)

{

string text = registryKey.GetValue(installKey) as string;

if (string.IsNullOrEmpty(text))

{

registryKey.SetValue(installKey, path);

}

}

}


Also, you will be able to select screen as a video device and capture your screen.


Thank you and let me know if you have questions or better idea :)


1vqHSTrq1GEoEF7QsL8dhmJfRMDVxhv2y



Bits, bytes and masks

Hello,


Today we are going to learn how to apply mask to any type of data. We will look into mask itself, and apply a mask to an image.

Lets look into the image below to get general idea of mask:


As you can see we took the star mask and an image and got imaged star in output. Cool? :)

Hmm, what is going on and how to do it? Everything is very simple if you have learned my post about bit manipulations.

So, to do it we need the following things:

- bit mask;

- an image;

- go through each byte and apply AND operation for each couple of bytes (actually Int32 in my case as it is much faster).

Here is how:

Int32[] rgba_source = new Int32[256 * 256];

Int32[] rgba_dest = new Int32[256 * 256];

for (int i = 0; i < rgba_source.Length; i++)

{

rgba_dest[i] = rgba_dest[i] & rgba_source[i];

}

Here is the result of masking two images:


That's it, you have got like textured object/figure :).


Now, just imagine where you can use such approach and with which kind of data, as well as other operations like XOR and OR.

In short - it can be used in hash, crypto, visualization algorithms and much more.

One easiest encryption algorithm is just apply XOR for each char of string, for example:

string origin = "hello world";

string encoded = string.Empty;

string decoded = string.Empty;

for (int i = 0; i < origin.Length; i++)

{

encoded += (char)(origin[i] ^ 0x003F);

}

And we will get "WZSSPHPMS[" in the encoded variable, that is equal to hello world but just encoded. To decrypt/decode it, just make the same XOR:

for (int i = 0; i < encoded.Length; i++)

{

decoded += (char)(encoded[i] ^ 0x003F);

}

And you got your "hello world" string back again in the decoded variable.

Think about it and a lot of things you can do with that ;)


Thank you and see you next time.


1vqHSTrq1GEoEF7QsL8dhmJfRMDVxhv2y