Tuesday, October 30, 2012

MySQL DEFAULT CHARACTER SET utf8 change

ALTER DATABASE `db_name` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci 
 
CREATE TABLE `test`.`table1` (
`content` VARCHAR( 2000 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL
) ENGINE = InnoDB CHARACTER SET utf8 COLLATE utf8_general_ci; 
ALTER TABLE table_name CONVERT TO CHARACTER SET 'utf8';  

Monday, October 22, 2012

Silverlight 5 3d view position change by mouse move

MainPage.cs

using System.Windows.Controls;
using System.Windows.Graphics;
using System.Windows;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using System;
using System.Windows.Input;

namespace Silverlight3dApp
{
    public static class State
    {
        public static float sliderYawVal = new float();
        public static float sliderPitchVal = new float();
        public static float sliderRollVal = new float();
    }

    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
        }

        const float zoomZ = 400;
        const float targetY = 50;
        float cameraX = 0;
        float cameraY = zoomZ;
        float cameraZ = zoomZ;

        ContentManager contentManager;
        Machine machine;
       
        private void OnLoaded(object sender, RoutedEventArgs e)
        {
            contentManager = new ContentManager(null)
            {
                RootDirectory = "Content"
            };

            machine = new Machine();
            machine.Load(contentManager);
           
            string sb = string.Empty;

            hoDrawingSurface.SizeChanged += new SizeChangedEventHandler(hoDrawingSurface_SizeChanged);
        }

        void hoDrawingSurface_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            if (machine != null)
            {
                machine.AspectRatio = (float)(hoDrawingSurface.ActualWidth / hoDrawingSurface.ActualHeight);
            }
        }

        void machine_Events(object sender, EventArgs e)
        {
            title.Text = sender.ToString();
        }
       
        private void OnViewportDraw(object sender, DrawEventArgs e)
        {
            GraphicsDevice graphicsDevice = GraphicsDeviceManager.Current.GraphicsDevice;
            Color cornflowerBlue = new Color(0x64, 0x95, 0xED, 0xFF);
            graphicsDevice.Clear(cornflowerBlue);

            float time = (float)e.TotalTime.TotalSeconds;

            Matrix world = Matrix.Identity;

            Matrix view = Matrix.CreateLookAt(new Vector3(cameraX, cameraY, cameraZ),
                                              new Vector3(0, targetY, 0),
                                              Vector3.Up);
           
           
            Matrix projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4,
                                                                    graphicsDevice.Viewport.AspectRatio,
                                                                    100,
                                                                    10000);

            machine.Draw(graphicsDevice, world, view, projection, e.TotalTime);
           
            e.InvalidateSurface();
        }
       
        private double oldPositionX;
        private double oldPositionY;
        private bool clicked;
        double WorldDegreesX = 0;
        double WorldDegreesY = 0;
        double WorldDegreesZ = 0;
        float currentZoom = zoomZ;
        bool zoomChanged = false;
        float zoomInMax = 230;
        float zoomOutMax = 600;

        private void OnMouseLeftDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            oldPositionX = e.GetPosition(hoDrawingSurface).X;
            oldPositionY = e.GetPosition(hoDrawingSurface).Y;
            clicked = true;
        }

        private void OnMouseLeftUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            oldPositionX = 0;
            oldPositionY = 0;
            clicked = false;
        }

        private void OnMouseMove(object sender, System.Windows.Input.MouseEventArgs e)
        {
            if (clicked)
            {
                rotateManual(e.GetPosition(hoDrawingSurface).X, e.GetPosition(hoDrawingSurface).Y);
            }
        }

        void rotateManual(double posX, double posY)
        {
            float x = System.Convert.ToSingle(oldPositionX - posX);
            float y = System.Convert.ToSingle(oldPositionY - posY);

            float num = (2 * MathHelper.Pi * currentZoom) / 360;
            double xxyy = Math.Sqrt(x * x + y * y);

            if (Math.Abs(x) > num || zoomChanged)
            {
                if (!zoomChanged)
                {
                    oldPositionX = posX;

                    double gradus = (x / num);

                    WorldDegreesX += gradus;
                    if (WorldDegreesX < 0) WorldDegreesX = 360;
                    if (WorldDegreesX > 360) WorldDegreesX = WorldDegreesX % 360;
                    double angle = Math.PI * WorldDegreesX / 180.0;
                    double sin = Math.Sin(angle);
                    cameraX = (float)(sin * currentZoom);

                    WorldDegreesZ += gradus;
                    if (WorldDegreesZ < 0) WorldDegreesZ = 360;
                    if (WorldDegreesZ > 360) WorldDegreesZ = WorldDegreesZ % 360;
                    double angleZ = Math.PI * WorldDegreesZ / 180.0;
                    double cos = Math.Cos(angleZ);
                    cameraZ = (float)(cos * currentZoom);
                }
                else
                {
                    double angle = Math.PI * WorldDegreesX / 180.0;
                    double sin = Math.Sin(angle);
                    cameraX = (float)(sin * currentZoom);

                    double angleZ = Math.PI * WorldDegreesZ / 180.0;
                    double cos = Math.Cos(angleZ);
                    cameraZ = (float)(cos * currentZoom);
                }
            }

            if (Math.Abs(y) > num || zoomChanged)
            {
                if (!zoomChanged)
                {
                    oldPositionY = posY;

                    double gradus = (y / num);

                    WorldDegreesY += gradus;
                    if (WorldDegreesY < 0) WorldDegreesY = 360;
                    if (WorldDegreesY > 360) WorldDegreesY = WorldDegreesY % 360;
                    double angle = Math.PI * WorldDegreesY / 180.0;
                    double cosY = Math.Cos(angle);
                    cameraY = (float)(cosY * currentZoom);
                }
                else
                {
                    double angle = Math.PI * WorldDegreesY / 180.0;
                    double cosY = Math.Cos(angle);
                    cameraY = (float)(cosY * currentZoom);
                }
                //WorldDegreesZ += gradus;
                //if (WorldDegreesZ < 0) WorldDegreesZ = 360;
                //if (WorldDegreesZ > 360) WorldDegreesZ = WorldDegreesZ % 360;
                //double angleZ = Math.PI * WorldDegreesZ / 180.0;
                //double cos = Math.Sin(angleZ);
                //cameraZ = (float)(cos * currentZoom);
            }

            hoDrawingSurface.Invalidate();
        }

        private void OnMouseWheel(object sender, System.Windows.Input.MouseWheelEventArgs e)
        {
            currentZoom += (e.Delta / 10);
            if (currentZoom < zoomInMax) currentZoom = zoomInMax;
            if (currentZoom > zoomOutMax) currentZoom = zoomOutMax;

            zoomChanged = true;
            rotateManual(0, 0);
            zoomChanged = false;
        }

        private void OnSelectCarColor(object sender, RoutedEventArgs e)
        {
            string[] colorSs = (sender as Button).Tag.ToString().Split(new char[] { ',' });
            Color color = Color.FromNonPremultiplied(
                Convert.ToInt32(colorSs[0]), Convert.ToInt32(colorSs[1]), Convert.ToInt32(colorSs[2]), 255);
            if (machine != null)
            {
                if (machine.ChangeColors.ContainsKey(Machine.CARCOLOR))
                    machine.ChangeColors[Machine.CARCOLOR] = color;
                else
                    machine.ChangeColors.Add(Machine.CARCOLOR, color);
            }
        }

        private void OnSelectRimColor(object sender, RoutedEventArgs e)
        {
            string[] colorSs = (sender as Button).Tag.ToString().Split(new char[] { ',' });
            Color color = Color.FromNonPremultiplied(
                Convert.ToInt32(colorSs[0]), Convert.ToInt32(colorSs[1]), Convert.ToInt32(colorSs[2]), 255);
            if (machine != null)
            {
                if (machine.ChangeColors.ContainsKey(Machine.RIMCOLOR))
                    machine.ChangeColors[Machine.RIMCOLOR] = color;
                else
                    machine.ChangeColors.Add(Machine.RIMCOLOR, color);
            }
        }
    }
}

Silverlight 5 using 3d max Car.FBX model

Machine.cs


namespace Silverlight3dApp
{

    public class Machine
    {
        public const string CARCOLOR = "CARCOLOR";
        public const string RIMCOLOR = "RIMCOLOR";

        static readonly GraphicsDevice ResourceDevice = GraphicsDeviceManager.Current.GraphicsDevice;

        Model wallModel;
        Model model;
        Matrix[] boneTransforms;
        Matrix[] wallBoneTransforms;

        public Vector3 SpecularColor { get; set; }
        public float AspectRatio { get; set; }
        public float CurrentEnvMap { get; set; }
        public float CurrentSpecular { get; set; }
        public float CurrentFresnel { get; set; }
        public Dictionary<string,Color> ChangeColors { get; set; }
        public Dictionary<string,BoneProperty> BoneProperties { get; set; }

        UserControl page = new UserControl();
        Texture2D _texture;
        VertexPositionNormalTexture[] _vertices;
       
        /// <summary>
        /// Loads the model.
        /// </summary>
        public void Load(ContentManager content)
        {
            model = content.Load<Model>("Car");
            boneTransforms = new Matrix[model.Bones.Count];
           
            wallModel = content.Load<Model>("Car");
            wallBoneTransforms = new Matrix[wallModel.Bones.Count];

            AspectRatio = 1f;
            SpecularColor = new Vector3(1f, 1f, 1f);
            CurrentEnvMap = 1;
            CurrentSpecular = 1;
            CurrentFresnel = 0;

            ChangeColors = new Dictionary<string, Color>();
            BoneProperties = ContentUtils.ParseCarList(Resource1.Car);

            _vertices = Polyhedron.CreateVertices(Polyhedra.CubeCorners, Polyhedra.CubeFaces);
            _texture = content.Load<Texture2D>("studio");
        }
               
        /// <summary>
        /// Draws the tank model, using the current animation settings.
        /// </summary>
        public void Draw(GraphicsDevice device, Matrix world, Matrix view, Matrix projection, TimeSpan totolTime)
        {
            model.CopyAbsoluteBoneTransformsTo(boneTransforms);
            wallModel.CopyAbsoluteBoneTransformsTo(wallBoneTransforms);

            Matrix view0 = Matrix.CreateLookAt(new Vector3(-1, 1000, 0),
                                              new Vector3(0, 0, 0),
                                              Vector3.Up);
            Matrix scale0 = Matrix.CreateScale(4f,8f,8f);

            ModelMesh mesh0 = wallModel.Meshes["suuri"];
            foreach (EnvironmentMapEffect effect in mesh0.Effects)
            {
                effect.EnvironmentMapAmount = 0.2f;//CurrentEnvMap;
                effect.EnvironmentMapSpecular = SpecularColor * 0.8f;//CurrentSpecular;
                effect.FresnelFactor = CurrentFresnel;

                effect.Texture = _texture;

                effect.View = view0;
                effect.Projection = projection;
                effect.World = wallBoneTransforms[mesh0.ParentBone.Index] * scale0;
                effect.EnableDefaultLighting();
            }
            mesh0.Draw();

            // Draw the model.
            foreach (ModelMesh mesh in model.Meshes)
            {
                //BoneProperty prop = BoneProperties[model.Bones[i].Name];
                Color color = Color.FromNonPremultiplied(0, 0, 0, 255);
                bool envMap = false;
                BoneProperty prop = null;

                if (BoneProperties.ContainsKey(mesh.ParentBone.Name))
                {
                    prop = BoneProperties[mesh.ParentBone.Name];
                    color = prop.TextureColor;
                    envMap = prop.EnvironmentMapEnabled;
                    if (!string.IsNullOrEmpty(prop.ChangeColorKey) && ChangeColors != null
                        && ChangeColors.ContainsKey(prop.ChangeColorKey))
                    {
                        color = ChangeColors[prop.ChangeColorKey];
                    }
                }

                foreach (EnvironmentMapEffect effect in mesh.Effects)
                {
                    if (envMap)
                    {
                        effect.EnvironmentMapAmount = 0.2f;//CurrentEnvMap;
                        effect.EnvironmentMapSpecular = SpecularColor * 0.8f;//CurrentSpecular;
                        effect.FresnelFactor = CurrentFresnel;
                    }
                    else
                    {
                        effect.EnvironmentMapAmount = 0.0f;//CurrentEnvMap;
                        effect.EnvironmentMapSpecular = SpecularColor * 0.1f;//CurrentSpecular;
                        effect.FresnelFactor = CurrentFresnel;
                    }

                    Texture2D texture = new Texture2D(device, 1, 1, false, SurfaceFormat.Color);
                    texture.SetData<Color>(new Color[1] { color });
                    effect.Texture = texture;

                    effect.View = view;
                    effect.Projection = projection;
                    effect.World = boneTransforms[mesh.ParentBone.Index];

                    effect.EnableDefaultLighting();
                }
                mesh.Draw();
            }

            //model.Draw(world, view, projection);
        }

        internal VertexShader CompileVertexShader(GraphicsDevice device, Uri shaderUri)
        {
            VertexShader result;
            Stream vertexShaderStream = Application.GetResourceStream(shaderUri).Stream;
            result = VertexShader.FromStream(device, vertexShaderStream);
            return result;
        }

        internal PixelShader CompilePixelShader(GraphicsDevice device, Uri shaderUri)
        {
            PixelShader result;
            Stream vertexShaderStream = Application.GetResourceStream(shaderUri).Stream;
            result = PixelShader.FromStream(device, vertexShaderStream);
            return result;
        }

        void InitEffect(GraphicsDevice device, string assemblyName, string vertexRootName, string pixelRootName)
        {
            // Uri
            string vertexRootUri = string.Format(@"/{0};component/{1}.vs", assemblyName, vertexRootName);
            string pixelRootUri = string.Format(@"/{0};component/{1}.ps", assemblyName, pixelRootName);

            // Shaders
            Stream vertexShaderStream = Application.GetResourceStream(new Uri(vertexRootUri, UriKind.Relative)).Stream;
            Stream pixelShaderStream = Application.GetResourceStream(new Uri(pixelRootUri, UriKind.Relative)).Stream;

            //_vertexShader = CompileVertexShader(device, new Uri(vertexRootUri, UriKind.Relative));
            //_pixelShader = CompilePixelShader(device, new Uri(pixelRootUri, UriKind.Relative));

            vertexShaderStream.Dispose();
            pixelShaderStream.Dispose();

            // Assembly codes
            //ExtractConstantsRegisters(vertexRootUri + ".constants", false);
            //ExtractConstantsRegisters(pixelRootUri + ".constants", true);
        }
    }
}

Car.Xml resources

<?xml version="1.0" encoding="utf-8" ?>
<root>
  <item Name="suuri" TextureColor="200,200,200" EnvironmentMapEnabled="true" />
  <item Name="mashin" ChangeColorKey="CARCOLOR" TextureColor="255,0,0" EnvironmentMapEnabled="true" />
  <item Name="dugui_1" TextureColor="30,30,30" EnvironmentMapEnabled="false"/>
  <item Name="dugui_2" TextureColor="30,30,30" EnvironmentMapEnabled="false"/>
  <item Name="dugui_3" TextureColor="30,30,30" EnvironmentMapEnabled="false"/>
  <item Name="dugui_4" TextureColor="30,30,30" EnvironmentMapEnabled="false"/>
  <item Name="obud_1" ChangeColorKey="RIMCOLOR" TextureColor="250,250,250" EnvironmentMapEnabled="true"/>
  <item Name="obud_2" ChangeColorKey="RIMCOLOR" TextureColor="250,250,250" EnvironmentMapEnabled="true" />
  <item Name="obud_3" ChangeColorKey="RIMCOLOR" TextureColor="250,250,250" EnvironmentMapEnabled="true" />
  <item Name="obud_4" ChangeColorKey="RIMCOLOR" TextureColor="250,250,250" EnvironmentMapEnabled="true" />
  <item Name="urd_tsonh" TextureColor="0,0,0" EnvironmentMapEnabled="true" />
  <item Name="hoid_tsonh" TextureColor="0,0,0" EnvironmentMapEnabled="true" />
</root>

Images


it is not use Shader Compiler,
good simple

Saturday, October 20, 2012

Silverlight XNA sound effect

standart

var laserStream =
    Application.GetResourceStream(
        new Uri("laser_shot.wav", UriKind.RelativeOrAbsolute));
 
var effect = SoundEffect.FromStream(laserStream.Stream);
effect.Play();



multiple instance


var engineStream =
    Application.GetResourceStream(
         new Uri("engine_rumble4.wav", UriKind.RelativeOrAbsolute));
 
_engineEffect = SoundEffect.FromStream(engineStream.Stream);
 
SoundEffectInstance engineInstance = _engineEffect.CreateInstance();
engineInstance.IsLooped = true;
engineInstance.Pitch = -1.0f;   // low sound
engineInstance.Volume = 0.75f;
engineInstance.Play();
 
// offset a second instance by 1 second, helps mask my bad loop point
DispatcherTimer timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromSeconds(1);
timer.Tick += (s, ea) =>
    {
        timer.Stop();
        SoundEffectInstance engineInstance2 = _engineEffect.CreateInstance();
        engineInstance2.IsLooped = true;
        engineInstance2.Pitch = -.75f;   // slightly higher sound
        engineInstance2.Volume = 0.5f;
        engineInstance2.Play();
    };
 
timer.Start();

Wednesday, October 10, 2012

asp.net custom FormsAuthentication CustomPrincipal

in MembershipService class


                    if (b)
            {
                 Create the cookie that contains the forms authentication ticket
                HttpCookie authCookie = FormsAuthentication.GetAuthCookie(userName, rememberMe);

                 Get the FormsAuthenticationTicket out of the encrypted cookie
                FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);

                 Create a new FormsAuthenticationTicket that includes our custom User Data
                FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket(
                    ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, string.Empty);

                 Update the authCookie's Value to use the encrypted version of newTicket
                authCookie.Value = FormsAuthentication.Encrypt(newTicket);

                 Manually add the authCookie to the Cookies collection
                HttpContext.Current.Response.Cookies.Add(authCookie);
            }
or
            if (b)
            {
                CustomPrincipalSerializeModel serializeModel = new CustomPrincipalSerializeModel();
                serializeModel.UserName = userName;

                JavaScriptSerializer serializer = new JavaScriptSerializer();
                string userData = serializer.Serialize(serializeModel);

                DateTime expired = DateTime.Now.AddMinutes(FormsAuthentication.Timeout.TotalMinutes);

                FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
                         1,
                         userName,
                         DateTime.Now,
                         expired,
                         rememberMe,
                         userData);

                string encTicket = FormsAuthentication.Encrypt(authTicket);
                HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
                HttpContext.Current.Response.Cookies.Add(faCookie);
            }





in Global.asax


protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
        {
            //HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
           
            //if (authCookie != null)
            //{
            //    Response.Cookies.Add(authCookie);
            //    try
            //    {
            //        FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);

            //        JavaScriptSerializer serializer = new JavaScriptSerializer();

            //        CustomPrincipalSerializeModel serializeModel = serializer.Deserialize<CustomPrincipalSerializeModel>(authTicket.UserData);

            //        CustomPrincipal newUser = new CustomPrincipal(authTicket.Name);
            //        newUser.UserName = serializeModel.UserName;

            //        HttpContext.Current.User = newUser;
            //    }
            //    catch { HttpContext.Current.User = null; }
            //}
        }
       
        protected void Session_Start(object sender, EventArgs e)
        {
            Application.Lock();
            WebSites.Current.ConnectedUsers++;
            Application.UnLock();
        }

        protected void Session_End(object sender, EventArgs e)
        {
            Application.Lock();
            WebSites.Current.ConnectedUsers--;
            Application.UnLock();
        }


in login controller


                    //FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                    //1,
                    //model.UserName,
                    //DateTime.Now,
                    //DateTime.Now.AddMinutes(FormsAuthentication.Timeout.TotalMinutes),
                    //model.RememberMe,
                    //null);

                    //string encryptedTicket = FormsAuthentication.Encrypt(ticket);
                    //HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);

                    //this.Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
                    //this.Response.Cookies.Add(cookie);