-using System;\r
-using System.Collections.Generic;\r
-using System.Collections;\r
-using System.Linq;\r
-using System.Text;\r
-using System.IO;\r
-using System.IO.Compression;\r
-using System.Xml;\r
-using System.Threading;\r
-using OpenTK.Graphics.OpenGL;\r
-using System.Runtime.InteropServices;\r
-using System.Drawing;\r
-using System.Drawing.Imaging;\r
-using OpenMetaverse;\r
-using OpenMetaverse.Rendering;\r
-\r
-namespace Radegast.Rendering\r
-{\r
- [StructLayout(LayoutKind.Sequential)]\r
- public struct Color4b\r
- {\r
- public byte R;\r
- public byte G;\r
- public byte B;\r
- public byte A;\r
- }\r
-\r
- [StructLayout(LayoutKind.Explicit)]\r
- public struct ColorVertex\r
- {\r
- [FieldOffset(0)]\r
- public Vertex Vertex;\r
- [FieldOffset(32)]\r
- public Color4b Color;\r
- public static int Size = 36;\r
- }\r
-\r
- public class FaceData\r
- {\r
- public float[] Vertices;\r
- public ushort[] Indices;\r
- public float[] TexCoords;\r
- public float[] Normals;\r
- public int PickingID = -1;\r
- public int VertexVBO = -1;\r
- public int IndexVBO = -1;\r
- public TextureInfo TextureInfo = new TextureInfo();\r
- public BoundingVolume BoundingVolume = new BoundingVolume();\r
- public static int VertexSize = 32; // sizeof (vertex), 2 x vector3 + 1 x vector2 = 8 floats x 4 bytes = 32 bytes \r
- public TextureAnimationInfo AnimInfo;\r
- public int QueryID = 0;\r
-\r
- public void CheckVBO(Face face)\r
- {\r
- if (VertexVBO == -1)\r
- {\r
- Vertex[] vArray = face.Vertices.ToArray();\r
- GL.GenBuffers(1, out VertexVBO);\r
- GL.BindBuffer(BufferTarget.ArrayBuffer, VertexVBO);\r
- GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(vArray.Length * VertexSize), vArray, BufferUsageHint.StaticDraw);\r
- }\r
-\r
- if (IndexVBO == -1)\r
- {\r
- ushort[] iArray = face.Indices.ToArray();\r
- GL.GenBuffers(1, out IndexVBO);\r
- GL.BindBuffer(BufferTarget.ElementArrayBuffer, IndexVBO);\r
- GL.BufferData(BufferTarget.ElementArrayBuffer, (IntPtr)(iArray.Length * sizeof(ushort)), iArray, BufferUsageHint.StaticDraw);\r
- }\r
- }\r
- }\r
-\r
- public class TextureAnimationInfo\r
- {\r
- public Primitive.TextureAnimation PrimAnimInfo;\r
- public float CurrentFrame;\r
- public float CurrentTime;\r
- public bool PingPong;\r
- float LastTime = 0f;\r
- float TotalTime = 0f;\r
-\r
- public void Step(float lastFrameTime)\r
- {\r
- float numFrames = 1f;\r
- float fullLength = 1f;\r
-\r
- if (PrimAnimInfo.Length > 0)\r
- {\r
- numFrames = PrimAnimInfo.Length;\r
- }\r
- else\r
- {\r
- numFrames = Math.Max(1f, (float)(PrimAnimInfo.SizeX * PrimAnimInfo.SizeY));\r
- }\r
-\r
- if ((PrimAnimInfo.Flags & Primitive.TextureAnimMode.PING_PONG) != 0)\r
- {\r
- if ((PrimAnimInfo.Flags & Primitive.TextureAnimMode.SMOOTH) != 0)\r
- {\r
- fullLength = 2f * numFrames;\r
- }\r
- else if ((PrimAnimInfo.Flags & Primitive.TextureAnimMode.LOOP) != 0)\r
- {\r
- fullLength = 2f * numFrames - 2f;\r
- fullLength = Math.Max(1f, fullLength);\r
- }\r
- else\r
- {\r
- fullLength = 2f * numFrames - 1f;\r
- fullLength = Math.Max(1f, fullLength);\r
- }\r
- }\r
- else\r
- {\r
- fullLength = numFrames;\r
- }\r
-\r
- float frameCounter;\r
- if ((PrimAnimInfo.Flags & Primitive.TextureAnimMode.SMOOTH) != 0)\r
- {\r
- frameCounter = lastFrameTime * PrimAnimInfo.Rate + LastTime;\r
- }\r
- else\r
- {\r
- TotalTime += lastFrameTime;\r
- frameCounter = TotalTime * PrimAnimInfo.Rate;\r
- }\r
- LastTime = frameCounter;\r
-\r
- if ((PrimAnimInfo.Flags & Primitive.TextureAnimMode.LOOP) != 0)\r
- {\r
- frameCounter %= fullLength;\r
- }\r
- else\r
- {\r
- frameCounter = Math.Min(fullLength - 1f, frameCounter);\r
- }\r
-\r
- if ((PrimAnimInfo.Flags & Primitive.TextureAnimMode.SMOOTH) == 0)\r
- {\r
- frameCounter = (float)Math.Floor(frameCounter + 0.01f);\r
- }\r
-\r
- if ((PrimAnimInfo.Flags & Primitive.TextureAnimMode.PING_PONG) != 0)\r
- {\r
- if (frameCounter > numFrames)\r
- {\r
- if ((PrimAnimInfo.Flags & Primitive.TextureAnimMode.SMOOTH) != 0)\r
- {\r
- frameCounter = numFrames - (frameCounter - numFrames);\r
- }\r
- else\r
- {\r
- frameCounter = (numFrames - 1.99f) - (frameCounter - numFrames);\r
- }\r
- }\r
- }\r
-\r
- if ((PrimAnimInfo.Flags & Primitive.TextureAnimMode.REVERSE) != 0)\r
- {\r
- if ((PrimAnimInfo.Flags & Primitive.TextureAnimMode.SMOOTH) != 0)\r
- {\r
- frameCounter = numFrames - frameCounter;\r
- }\r
- else\r
- {\r
- frameCounter = (numFrames - 0.99f) - frameCounter;\r
- }\r
- }\r
-\r
- frameCounter += PrimAnimInfo.Start;\r
-\r
- if ((PrimAnimInfo.Flags & Primitive.TextureAnimMode.SMOOTH) == 0)\r
- {\r
- frameCounter = (float)Math.Round(frameCounter);\r
- }\r
-\r
-\r
- GL.MatrixMode(MatrixMode.Texture);\r
- GL.LoadIdentity();\r
-\r
- if ((PrimAnimInfo.Flags & Primitive.TextureAnimMode.ROTATE) != 0)\r
- {\r
- GL.Translate(0.5f, 0.5f, 0f);\r
- GL.Rotate(Utils.RAD_TO_DEG * frameCounter, OpenTK.Vector3d.UnitZ);\r
- GL.Translate(-0.5f, -0.5f, 0f);\r
- }\r
- else if ((PrimAnimInfo.Flags & Primitive.TextureAnimMode.SCALE) != 0)\r
- {\r
- GL.Scale(frameCounter, frameCounter, 0);\r
- }\r
- else // Translate\r
- {\r
- float sizeX = Math.Max(1f, (float)PrimAnimInfo.SizeX);\r
- float sizeY = Math.Max(1f, (float)PrimAnimInfo.SizeY);\r
-\r
- GL.Scale(1f / sizeX, 1f / sizeY, 0);\r
- GL.Translate(frameCounter % sizeX, Math.Floor(frameCounter / sizeY), 0);\r
- }\r
-\r
- GL.MatrixMode(MatrixMode.Modelview);\r
- }\r
-\r
- [Obsolete("Use Step() instead")]\r
- public void ExperimentalStep(float time)\r
- {\r
- int reverseFactor = 1;\r
- float rate = PrimAnimInfo.Rate;\r
-\r
- if (rate < 0)\r
- {\r
- rate = -rate;\r
- reverseFactor = -reverseFactor;\r
- }\r
-\r
- if ((PrimAnimInfo.Flags & Primitive.TextureAnimMode.REVERSE) != 0)\r
- {\r
- reverseFactor = -reverseFactor;\r
- }\r
-\r
- CurrentTime += time;\r
- float totalTime = 1 / rate;\r
-\r
- uint x = Math.Max(1, PrimAnimInfo.SizeX);\r
- uint y = Math.Max(1, PrimAnimInfo.SizeY);\r
- uint nrFrames = x * y;\r
-\r
- if (PrimAnimInfo.Length > 0 && PrimAnimInfo.Length < nrFrames)\r
- {\r
- nrFrames = (uint)PrimAnimInfo.Length;\r
- }\r
-\r
- GL.MatrixMode(MatrixMode.Texture);\r
- GL.LoadIdentity();\r
-\r
- if (CurrentTime >= totalTime)\r
- {\r
- CurrentTime = 0;\r
- CurrentFrame++;\r
- if (CurrentFrame > nrFrames) CurrentFrame = (uint)PrimAnimInfo.Start;\r
- if ((PrimAnimInfo.Flags & Primitive.TextureAnimMode.PING_PONG) != 0)\r
- {\r
- PingPong = !PingPong;\r
- }\r
- }\r
-\r
- float smoothOffset = 0f;\r
-\r
- if ((PrimAnimInfo.Flags & Primitive.TextureAnimMode.SMOOTH) != 0)\r
- {\r
- smoothOffset = (CurrentTime / totalTime) * reverseFactor;\r
- }\r
-\r
- float f = CurrentFrame;\r
- if (reverseFactor < 0)\r
- {\r
- f = nrFrames - CurrentFrame;\r
- }\r
-\r
- if ((PrimAnimInfo.Flags & Primitive.TextureAnimMode.ROTATE) == 0) // not rotating\r
- {\r
- GL.Scale(1f / x, 1f / y, 0f);\r
- GL.Translate((f % x) + smoothOffset, f / y, 0);\r
- }\r
- else\r
- {\r
- smoothOffset = (CurrentTime * PrimAnimInfo.Rate);\r
- float startAngle = PrimAnimInfo.Start;\r
- float endAngle = PrimAnimInfo.Length;\r
- float angle = startAngle + (endAngle - startAngle) * smoothOffset;\r
- GL.Translate(0.5f, 0.5f, 0f);\r
- GL.Rotate(Utils.RAD_TO_DEG * angle, OpenTK.Vector3d.UnitZ);\r
- GL.Translate(-0.5f, -0.5f, 0f);\r
- }\r
-\r
- GL.MatrixMode(MatrixMode.Modelview);\r
- }\r
-\r
- }\r
-\r
-\r
- public class TextureInfo\r
- {\r
- public System.Drawing.Image Texture;\r
- public int TexturePointer;\r
- public bool HasAlpha;\r
- public bool FullAlpha;\r
- public bool IsMask;\r
- public UUID TextureID;\r
- public bool FetchFailed;\r
- }\r
-\r
- public class TextureLoadItem\r
- {\r
- public FaceData Data;\r
- public Primitive Prim;\r
- public Primitive.TextureEntryFace TeFace;\r
- public byte[] TextureData = null;\r
- public byte[] TGAData = null;\r
- public bool LoadAssetFromCache = false;\r
- }\r
-\r
- public enum RenderPass\r
- {\r
- Picking,\r
- Simple,\r
- Alpha\r
- }\r
-\r
- public enum SceneObjectType\r
- {\r
- None,\r
- Primitive,\r
- Avatar,\r
- }\r
-\r
- /// <summary>\r
- /// Base class for all scene objects\r
- /// </summary>\r
- public abstract class SceneObject : IComparable, IDisposable\r
- {\r
- #region Public fields\r
- /// <summary>Interpolated local position of the object</summary>\r
- public Vector3 InterpolatedPosition;\r
- /// <summary>Interpolated local rotation of the object/summary>\r
- public Quaternion InterpolatedRotation;\r
- /// <summary>Rendered position of the object in the region</summary>\r
- public Vector3 RenderPosition;\r
- /// <summary>Rendered rotationm of the object in the region</summary>\r
- public Quaternion RenderRotation;\r
- /// <summary>Per frame calculated square of the distance from camera</summary>\r
- public float DistanceSquared;\r
- /// <summary>Bounding volume of the object</summary>\r
- public BoundingVolume BoundingVolume;\r
- /// <summary>Was the sim position and distance from camera calculated during this frame</summary>\r
- public bool PositionCalculated;\r
- /// <summary>Scene object type</summary>\r
- public SceneObjectType Type = SceneObjectType.None;\r
- /// <summary>Libomv primitive</summary>\r
- public virtual Primitive BasePrim { get; set; }\r
- /// <summary>Were initial initialization tasks done</summary>\r
- public bool Initialized;\r
- public int AlphaQueryID = -1;\r
- public int SimpleQueryID = -1;\r
- public bool HasAlphaFaces;\r
- public bool HasSimpleFaces;\r
-\r
- #endregion Public fields\r
-\r
- /// <summary>\r
- /// Cleanup resources used\r
- /// </summary>\r
- public virtual void Dispose()\r
- {\r
- }\r
-\r
- /// <summary>\r
- /// Task performed the fist time object is set for rendering\r
- /// </summary>\r
- public virtual void Initialize()\r
- {\r
- RenderPosition = InterpolatedPosition = BasePrim.Position;\r
- RenderRotation = InterpolatedRotation = BasePrim.Rotation;\r
- Initialized = true;\r
- }\r
-\r
- /// <summary>\r
- /// Perform per frame tasks\r
- /// </summary>\r
- /// <param name="time">Time since the last call (last frame time in seconds)</param>\r
- public virtual void Step(float time)\r
- {\r
- // Linear velocity and acceleration\r
- if (BasePrim.Velocity != Vector3.Zero)\r
- {\r
- BasePrim.Position = InterpolatedPosition = BasePrim.Position + BasePrim.Velocity * time\r
- * 0.98f * RadegastInstance.GlobalInstance.Client.Network.CurrentSim.Stats.Dilation;\r
- BasePrim.Velocity += BasePrim.Acceleration * time;\r
- }\r
- else if (InterpolatedPosition != BasePrim.Position)\r
- {\r
- InterpolatedPosition = RHelp.Smoothed1stOrder(InterpolatedPosition, BasePrim.Position, time);\r
- }\r
-\r
- // Angular velocity (target omega)\r
- if (BasePrim.AngularVelocity != Vector3.Zero)\r
- {\r
- Vector3 angVel = BasePrim.AngularVelocity;\r
- float angle = time * angVel.Length();\r
- Quaternion dQ = Quaternion.CreateFromAxisAngle(angVel, angle);\r
- InterpolatedRotation = dQ * InterpolatedRotation;\r
- }\r
- else if (InterpolatedRotation != BasePrim.Rotation)\r
- {\r
- InterpolatedRotation = Quaternion.Slerp(InterpolatedRotation, BasePrim.Rotation, time * 10f);\r
- if (1f - Math.Abs(Quaternion.Dot(InterpolatedRotation, BasePrim.Rotation)) < 0.0001)\r
- InterpolatedRotation = BasePrim.Rotation;\r
- }\r
- }\r
-\r
- /// <summary>\r
- /// Implementation of the IComparable interface\r
- /// used for sorting by distance\r
- /// </summary>\r
- /// <param name="other">Object we are comparing to</param>\r
- /// <returns>Result of the comparison</returns>\r
- public virtual int CompareTo(object other)\r
- {\r
- SceneObject o = (SceneObject)other;\r
- if (this.DistanceSquared < o.DistanceSquared)\r
- return -1;\r
- else if (this.DistanceSquared > o.DistanceSquared)\r
- return 1;\r
- else\r
- return 0;\r
- }\r
-\r
- #region Occlusion queries\r
- public void StartQuery(RenderPass pass)\r
- {\r
- if (!RenderSettings.OcclusionCullingEnabled) return;\r
-\r
- if (pass == RenderPass.Simple)\r
- {\r
- StartSimpleQuery();\r
- }\r
- else if (pass == RenderPass.Alpha)\r
- {\r
- StartAlphaQuery();\r
- }\r
- }\r
-\r
- public void EndQuery(RenderPass pass)\r
- {\r
- if (!RenderSettings.OcclusionCullingEnabled) return;\r
-\r
- if (pass == RenderPass.Simple)\r
- {\r
- EndSimpleQuery();\r
- }\r
- else if (pass == RenderPass.Alpha)\r
- {\r
- EndAlphaQuery();\r
- }\r
- }\r
-\r
- public void StartAlphaQuery()\r
- {\r
- if (!RenderSettings.OcclusionCullingEnabled) return;\r
-\r
- if (AlphaQueryID == -1)\r
- {\r
- Compat.GenQueries(out AlphaQueryID);\r
- }\r
- if (AlphaQueryID > 0)\r
- {\r
- Compat.BeginQuery(QueryTarget.SamplesPassed, AlphaQueryID);\r
- }\r
- }\r
-\r
- public void EndAlphaQuery()\r
- {\r
- if (!RenderSettings.OcclusionCullingEnabled) return;\r
-\r
- if (AlphaQueryID > 0)\r
- {\r
- Compat.EndQuery(QueryTarget.SamplesPassed);\r
- }\r
- }\r
-\r
- public void StartSimpleQuery()\r
- {\r
- if (!RenderSettings.OcclusionCullingEnabled) return;\r
-\r
- if (SimpleQueryID == -1)\r
- {\r
- Compat.GenQueries(out SimpleQueryID);\r
- }\r
- if (SimpleQueryID > 0)\r
- {\r
- Compat.BeginQuery(QueryTarget.SamplesPassed, SimpleQueryID);\r
- }\r
- }\r
-\r
- public void EndSimpleQuery()\r
- {\r
- if (!RenderSettings.OcclusionCullingEnabled) return;\r
-\r
- if (SimpleQueryID > 0)\r
- {\r
- Compat.EndQuery(QueryTarget.SamplesPassed);\r
- }\r
- }\r
-\r
- public bool Occluded()\r
- {\r
- if (!RenderSettings.OcclusionCullingEnabled) return false;\r
-\r
- if ((SimpleQueryID == -1 && AlphaQueryID == -1))\r
- {\r
- return false;\r
- }\r
-\r
- if ((!HasAlphaFaces && !HasSimpleFaces)) return true;\r
-\r
- int samples = 1;\r
- if (HasSimpleFaces && SimpleQueryID > 0)\r
- {\r
- Compat.GetQueryObject(SimpleQueryID, GetQueryObjectParam.QueryResult, out samples);\r
- }\r
- if (HasSimpleFaces && samples > 0)\r
- {\r
- return false;\r
- }\r
-\r
- samples = 1;\r
- if (HasAlphaFaces && AlphaQueryID > 0)\r
- {\r
- Compat.GetQueryObject(AlphaQueryID, GetQueryObjectParam.QueryResult, out samples);\r
- }\r
- if (HasAlphaFaces && samples > 0)\r
- {\r
- return false;\r
- }\r
-\r
- return true;\r
- }\r
- #endregion Occlusion queries\r
- }\r
-\r
- public class RenderPrimitive : SceneObject\r
- {\r
- #region Public fields\r
- public Primitive Prim;\r
- public List<Face> Faces;\r
- /// <summary>Is this object attached to an avatar</summary>\r
- public bool Attached;\r
- /// <summary>Do we know if object is attached</summary>\r
- public bool AttachedStateKnown;\r
- /// <summary>Are meshes constructed and ready for this prim</summary>\r
- public bool Meshed;\r
- /// <summary>Process of creating a mesh is underway</summary>\r
- public bool Meshing;\r
- #endregion Public fields\r
-\r
- #region Private fields\r
- int prevTEHash;\r
- int prevSculptHash;\r
- int prevShapeHash;\r
- #endregion Private fields\r
-\r
- public RenderPrimitive()\r
- {\r
- Type = SceneObjectType.Primitive;\r
- }\r
-\r
- public override Primitive BasePrim\r
- {\r
- get { return Prim; }\r
- set\r
- {\r
- Prim = value;\r
-\r
- int TEHash = Prim.Textures == null ? 0 : Prim.Textures.GetHashCode();\r
- int sculptHash, shapeHash;\r
-\r
- if (Meshed)\r
- {\r
- if (Prim.Type == PrimType.Sculpt || Prim.Type == PrimType.Mesh)\r
- {\r
- sculptHash = Prim.Sculpt.GetHashCode();\r
- if (Prim.Sculpt.GetHashCode() != prevSculptHash || TEHash != prevTEHash)\r
- {\r
- Meshed = false;\r
- }\r
- prevSculptHash = sculptHash;\r
- }\r
- else\r
- {\r
- shapeHash = Prim.PrimData.GetHashCode();\r
- if (shapeHash != prevShapeHash)\r
- {\r
- Meshed = false;\r
- }\r
- else if (TEHash != prevTEHash)\r
- {\r
- Meshed = false;\r
- }\r
- prevShapeHash = shapeHash;\r
- }\r
- }\r
- prevTEHash = TEHash;\r
- }\r
- }\r
-\r
- public override void Initialize()\r
- {\r
- AttachedStateKnown = false;\r
- base.Initialize();\r
- }\r
-\r
- public override string ToString()\r
- {\r
- uint id = Prim == null ? 0 : Prim.LocalID;\r
- float distance = (float)Math.Sqrt(DistanceSquared);\r
- return string.Format("LocalID: {0}, distance {0.00}", id, distance);\r
- }\r
- }\r
-\r
- public static class RHelp\r
- {\r
- public static readonly Vector3 InvalidPosition = new Vector3(99999f, 99999f, 99999f);\r
- static float t1 = 0.075f;\r
- static float t2 = t1 / 5.7f;\r
-\r
- public static Vector3 Smoothed1stOrder(Vector3 curPos, Vector3 targetPos, float lastFrameTime)\r
- {\r
- int numIterations = (int)(lastFrameTime * 100);\r
- do\r
- {\r
- curPos += (targetPos - curPos) * t1;\r
- numIterations--;\r
- }\r
- while (numIterations > 0);\r
- if (Vector3.DistanceSquared(curPos, targetPos) < 0.00001f)\r
- {\r
- curPos = targetPos;\r
- }\r
- return curPos;\r
- }\r
-\r
- public static Vector3 Smoothed2ndOrder(Vector3 curPos, Vector3 targetPos, ref Vector3 accel, float lastFrameTime)\r
- {\r
- int numIterations = (int)(lastFrameTime * 100);\r
- do\r
- {\r
- accel += (targetPos - accel - curPos) * t1;\r
- curPos += accel * t2;\r
- numIterations--;\r
- }\r
- while (numIterations > 0);\r
- if (Vector3.DistanceSquared(curPos, targetPos) < 0.00001f)\r
- {\r
- curPos = targetPos;\r
- }\r
- return curPos;\r
- }\r
-\r
- public static OpenTK.Vector2 TKVector3(Vector2 v)\r
- {\r
- return new OpenTK.Vector2(v.X, v.Y);\r
- }\r
-\r
- public static OpenTK.Vector3 TKVector3(Vector3 v)\r
- {\r
- return new OpenTK.Vector3(v.X, v.Y, v.Z);\r
- }\r
-\r
- public static OpenTK.Vector4 TKVector3(Vector4 v)\r
- {\r
- return new OpenTK.Vector4(v.X, v.Y, v.Z, v.W);\r
- }\r
-\r
- public static Color WinColor(OpenTK.Graphics.Color4 color)\r
- {\r
- return Color.FromArgb((int)(color.A * 255), (int)(color.R * 255), (int)(color.G * 255), (int)(color.B * 255));\r
- }\r
-\r
- public static Color WinColor(Color4 color)\r
- {\r
- return Color.FromArgb((int)(color.A * 255), (int)(color.R * 255), (int)(color.G * 255), (int)(color.B * 255));\r
- }\r
-\r
- #region Cached image save and load\r
- public static readonly string RAD_IMG_MAGIC = "radegast_img";\r
-\r
- public static bool LoadCachedImage(UUID textureID, out byte[] tgaData, out bool hasAlpha, out bool fullAlpha, out bool isMask)\r
- {\r
- tgaData = null;\r
- hasAlpha = fullAlpha = isMask = false;\r
-\r
- try\r
- {\r
- string fname = System.IO.Path.Combine(RadegastInstance.GlobalInstance.Client.Settings.ASSET_CACHE_DIR, string.Format("{0}.rzi", textureID));\r
- //string fname = System.IO.Path.Combine(".", string.Format("{0}.rzi", textureID));\r
-\r
- using (var f = File.Open(fname, FileMode.Open, FileAccess.Read, FileShare.Read))\r
- {\r
- byte[] header = new byte[36];\r
- int i = 0;\r
- f.Read(header, 0, header.Length);\r
-\r
- // check if the file is starting with magic string\r
- if (RAD_IMG_MAGIC != Utils.BytesToString(header, 0, RAD_IMG_MAGIC.Length))\r
- return false;\r
- i += RAD_IMG_MAGIC.Length;\r
-\r
- if (header[i++] != 1) // check version\r
- return false;\r
-\r
- hasAlpha = header[i++] == 1;\r
- fullAlpha = header[i++] == 1;\r
- isMask = header[i++] == 1;\r
-\r
- int uncompressedSize = Utils.BytesToInt(header, i);\r
- i += 4;\r
-\r
- textureID = new UUID(header, i);\r
- i += 16;\r
-\r
- tgaData = new byte[uncompressedSize];\r
- using (var compressed = new DeflateStream(f, CompressionMode.Decompress))\r
- {\r
- int read = 0;\r
- while ((read = compressed.Read(tgaData, read, uncompressedSize - read)) > 0) ;\r
- }\r
- }\r
-\r
- return true;\r
- }\r
- catch (FileNotFoundException) { }\r
- catch (Exception ex)\r
- {\r
- Logger.DebugLog(string.Format("Failed to load radegast cache file {0}: {1}", textureID, ex.Message));\r
- }\r
- return false;\r
- }\r
-\r
- public static bool SaveCachedImage(byte[] tgaData, UUID textureID, bool hasAlpha, bool fullAlpha, bool isMask)\r
- {\r
- try\r
- {\r
- string fname = System.IO.Path.Combine(RadegastInstance.GlobalInstance.Client.Settings.ASSET_CACHE_DIR, string.Format("{0}.rzi", textureID));\r
- //string fname = System.IO.Path.Combine(".", string.Format("{0}.rzi", textureID));\r
-\r
- using (var f = File.Open(fname, FileMode.Create, FileAccess.Write, FileShare.None))\r
- {\r
- int i = 0;\r
- // magic header\r
- f.Write(Utils.StringToBytes(RAD_IMG_MAGIC), 0, RAD_IMG_MAGIC.Length);\r
- i += RAD_IMG_MAGIC.Length;\r
-\r
- // version\r
- f.WriteByte((byte)1);\r
- i++;\r
-\r
- // texture info\r
- f.WriteByte(hasAlpha ? (byte)1 : (byte)0);\r
- f.WriteByte(fullAlpha ? (byte)1 : (byte)0);\r
- f.WriteByte(isMask ? (byte)1 : (byte)0);\r
- i += 3;\r
-\r
- // texture size\r
- byte[] uncompressedSize = Utils.IntToBytes(tgaData.Length);\r
- f.Write(uncompressedSize, 0, uncompressedSize.Length);\r
- i += uncompressedSize.Length;\r
-\r
- // texture id\r
- byte[] id = new byte[16];\r
- textureID.ToBytes(id, 0);\r
- f.Write(id, 0, 16);\r
- i += 16;\r
-\r
- // compressed texture data\r
- using (var compressed = new DeflateStream(f, CompressionMode.Compress))\r
- {\r
- compressed.Write(tgaData, 0, tgaData.Length);\r
- }\r
- }\r
- return true;\r
- }\r
- catch (Exception ex)\r
- {\r
- Logger.DebugLog(string.Format("Failed to save radegast cache file {0}: {1}", textureID, ex.Message));\r
- return false;\r
- }\r
- }\r
- #endregion Cached image save and load\r
-\r
- #region Static vertices and indices for a cube (used for bounding box drawing)\r
- /**********************************************\r
- 5 --- 4\r
- /| /|\r
- 1 --- 0 |\r
- | 6 --| 7\r
- |/ |/\r
- 2 --- 3\r
- ***********************************************/\r
- public static readonly float[] CubeVertices = new float[]\r
- {\r
- 0.5f, 0.5f, 0.5f, // 0\r
- -0.5f, 0.5f, 0.5f, // 1\r
- -0.5f, -0.5f, 0.5f, // 2\r
- 0.5f, -0.5f, 0.5f, // 3\r
- 0.5f, 0.5f, -0.5f, // 4\r
- -0.5f, 0.5f, -0.5f, // 5\r
- -0.5f, -0.5f, -0.5f, // 6\r
- 0.5f, -0.5f, -0.5f // 7\r
- };\r
-\r
- public static readonly ushort[] CubeIndices = new ushort[]\r
- {\r
- 0, 1, 2, 3, // Front Face\r
- 4, 5, 6, 7, // Back Face\r
- 1, 2, 6, 5, // Left Face\r
- 0, 3, 7, 4, // Right Face\r
- 0, 1, 5, 4, // Top Face\r
- 2, 3, 7, 6 // Bottom Face\r
- };\r
- #endregion Static vertices and indices for a cube (used for bounding box drawing)\r
-\r
- public static int GLLoadImage(Bitmap bitmap, bool hasAlpha)\r
- {\r
- int ret = -1;\r
- GL.GenTextures(1, out ret);\r
- GL.BindTexture(TextureTarget.Texture2D, ret);\r
-\r
- Rectangle rectangle = new Rectangle(0, 0, bitmap.Width, bitmap.Height);\r
-\r
- BitmapData bitmapData =\r
- bitmap.LockBits(\r
- rectangle,\r
- ImageLockMode.ReadOnly,\r
- hasAlpha ? System.Drawing.Imaging.PixelFormat.Format32bppArgb : System.Drawing.Imaging.PixelFormat.Format24bppRgb);\r
-\r
- GL.TexImage2D(\r
- TextureTarget.Texture2D,\r
- 0,\r
- hasAlpha ? PixelInternalFormat.Rgba : PixelInternalFormat.Rgb8,\r
- bitmap.Width,\r
- bitmap.Height,\r
- 0,\r
- hasAlpha ? OpenTK.Graphics.OpenGL.PixelFormat.Bgra : OpenTK.Graphics.OpenGL.PixelFormat.Bgr,\r
- PixelType.UnsignedByte,\r
- bitmapData.Scan0);\r
-\r
- GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);\r
- GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.Repeat);\r
- GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.Repeat);\r
- if (RenderSettings.HasMipmap)\r
- {\r
- GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.LinearMipmapLinear);\r
- GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.GenerateMipmap, 1);\r
- GL.GenerateMipmap(GenerateMipmapTarget.Texture2D);\r
- }\r
- else\r
- {\r
- GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear);\r
- }\r
-\r
- bitmap.UnlockBits(bitmapData);\r
- return ret;\r
- }\r
-\r
- public static void Draw2DBox(float x, float y, float width, float height, float depth)\r
- {\r
- GL.Begin(BeginMode.Quads);\r
- {\r
- GL.TexCoord2(0, 1);\r
- GL.Vertex3(x, y, depth);\r
- GL.TexCoord2(1, 1);\r
- GL.Vertex3(x + width, y, depth);\r
- GL.TexCoord2(1, 0);\r
- GL.Vertex3(x + width, y + height, depth);\r
- GL.TexCoord2(0, 0);\r
- GL.Vertex3(x, y + height, depth);\r
- }\r
- GL.End();\r
- }\r
- }\r
-\r
- /// <summary>\r
- /// Represents camera object\r
- /// </summary>\r
- public class Camera\r
- {\r
- Vector3 mPosition;\r
- Vector3 mFocalPoint;\r
- bool mModified;\r
-\r
- /// <summary>Camera position</summary>\r
- public Vector3 Position { get { return mPosition; } set { mPosition = value; Modify(); } }\r
- /// <summary>Camera target</summary>\r
- public Vector3 FocalPoint { get { return mFocalPoint; } set { mFocalPoint = value; Modify(); } }\r
- /// <summary>Zoom level</summary>\r
- public float Zoom;\r
- /// <summary>Draw distance</summary>\r
- public float Far;\r
- /// <summary>Has camera been modified</summary>\r
- public bool Modified { get { return mModified; } set { mModified = value; } }\r
-\r
- public float TimeToTarget = 0f;\r
-\r
- public Vector3 RenderPosition;\r
- public Vector3 RenderFocalPoint;\r
-\r
- void Modify()\r
- {\r
- mModified = true;\r
- }\r
-\r
- public void Step(float time)\r
- {\r
- if (RenderPosition != Position)\r
- {\r
- RenderPosition = RHelp.Smoothed1stOrder(RenderPosition, Position, time);\r
- Modified = true;\r
- }\r
- if (RenderFocalPoint != FocalPoint)\r
- {\r
- RenderFocalPoint = RHelp.Smoothed1stOrder(RenderFocalPoint, FocalPoint, time);\r
- Modified = true;\r
- }\r
- }\r
-\r
- [Obsolete("Use Step(), left in here for reference")]\r
- public void Step2(float time)\r
- {\r
- TimeToTarget -= time;\r
- if (TimeToTarget <= time)\r
- {\r
- EndMove();\r
- return;\r
- }\r
-\r
- mModified = true;\r
-\r
- float pctElapsed = time / TimeToTarget;\r
-\r
- if (RenderPosition != Position)\r
- {\r
- float distance = Vector3.Distance(RenderPosition, Position);\r
- RenderPosition = Vector3.Lerp(RenderPosition, Position, distance * pctElapsed);\r
- }\r
-\r
- if (RenderFocalPoint != FocalPoint)\r
- {\r
- RenderFocalPoint = Interpolate(RenderFocalPoint, FocalPoint, pctElapsed);\r
- }\r
- }\r
-\r
- Vector3 Interpolate(Vector3 start, Vector3 end, float fraction)\r
- {\r
- float distance = Vector3.Distance(start, end);\r
- Vector3 direction = end - start;\r
- return start + direction * fraction;\r
- }\r
-\r
- public void EndMove()\r
- {\r
- mModified = true;\r
- TimeToTarget = 0;\r
- RenderPosition = Position;\r
- RenderFocalPoint = FocalPoint;\r
- }\r
-\r
- public void Pan(float deltaX, float deltaY)\r
- {\r
- Vector3 direction = Position - FocalPoint;\r
- direction.Normalize();\r
- Vector3 vy = direction % Vector3.UnitZ;\r
- Vector3 vx = vy % direction;\r
- Vector3 vxy = vx * deltaY + vy * deltaX;\r
- Position += vxy;\r
- FocalPoint += vxy;\r
- }\r
-\r
- public void Rotate(float delta, bool horizontal)\r
- {\r
- Vector3 direction = Position - FocalPoint;\r
- if (horizontal)\r
- {\r
- Position = FocalPoint + direction * new Quaternion(0f, 0f, (float)Math.Sin(delta), (float)Math.Cos(delta));\r
- }\r
- else\r
- {\r
- Position = FocalPoint + direction * Quaternion.CreateFromAxisAngle(direction % Vector3.UnitZ, delta);\r
- }\r
- }\r
-\r
- public void MoveToTarget(float delta)\r
- {\r
- Position += (Position - FocalPoint) * delta;\r
- }\r
-\r
- /// <summary>\r
- /// Sets the world in perspective of the camera\r
- /// </summary>\r
- public void LookAt()\r
- {\r
- OpenTK.Matrix4 lookAt = OpenTK.Matrix4.LookAt(\r
- RenderPosition.X, RenderPosition.Y, RenderPosition.Z,\r
- RenderFocalPoint.X, RenderFocalPoint.Y, RenderFocalPoint.Z,\r
- 0f, 0f, 1f);\r
- GL.MultMatrix(ref lookAt);\r
- }\r
- }\r
-\r
- public static class MeshToOBJ\r
- {\r
- public static bool MeshesToOBJ(Dictionary<uint, FacetedMesh> meshes, string filename)\r
- {\r
- StringBuilder obj = new StringBuilder();\r
- StringBuilder mtl = new StringBuilder();\r
-\r
- FileInfo objFileInfo = new FileInfo(filename);\r
-\r
- string mtlFilename = objFileInfo.FullName.Substring(objFileInfo.DirectoryName.Length + 1,\r
- objFileInfo.FullName.Length - (objFileInfo.DirectoryName.Length + 1) - 4) + ".mtl";\r
-\r
- obj.AppendLine("# Created by libprimrender");\r
- obj.AppendLine("mtllib ./" + mtlFilename);\r
- obj.AppendLine();\r
-\r
- mtl.AppendLine("# Created by libprimrender");\r
- mtl.AppendLine();\r
-\r
- int primNr = 0;\r
- foreach (FacetedMesh mesh in meshes.Values)\r
- {\r
- for (int j = 0; j < mesh.Faces.Count; j++)\r
- {\r
- Face face = mesh.Faces[j];\r
-\r
- if (face.Vertices.Count > 2)\r
- {\r
- string mtlName = String.Format("material{0}-{1}", primNr, face.ID);\r
- Primitive.TextureEntryFace tex = face.TextureFace;\r
- string texName = tex.TextureID.ToString() + ".tga";\r
-\r
- // FIXME: Convert the source to TGA (if needed) and copy to the destination\r
-\r
- float shiny = 0.00f;\r
- switch (tex.Shiny)\r
- {\r
- case Shininess.High:\r
- shiny = 1.00f;\r
- break;\r
- case Shininess.Medium:\r
- shiny = 0.66f;\r
- break;\r
- case Shininess.Low:\r
- shiny = 0.33f;\r
- break;\r
- }\r
-\r
- obj.AppendFormat("g face{0}-{1}{2}", primNr, face.ID, Environment.NewLine);\r
-\r
- mtl.AppendLine("newmtl " + mtlName);\r
- mtl.AppendFormat("Ka {0} {1} {2}{3}", tex.RGBA.R, tex.RGBA.G, tex.RGBA.B, Environment.NewLine);\r
- mtl.AppendFormat("Kd {0} {1} {2}{3}", tex.RGBA.R, tex.RGBA.G, tex.RGBA.B, Environment.NewLine);\r
- //mtl.AppendFormat("Ks {0} {1} {2}{3}");\r
- mtl.AppendLine("Tr " + tex.RGBA.A);\r
- mtl.AppendLine("Ns " + shiny);\r
- mtl.AppendLine("illum 1");\r
- if (tex.TextureID != UUID.Zero && tex.TextureID != Primitive.TextureEntry.WHITE_TEXTURE)\r
- mtl.AppendLine("map_Kd ./" + texName);\r
- mtl.AppendLine();\r
-\r
- // Write the vertices, texture coordinates, and vertex normals for this side\r
- for (int k = 0; k < face.Vertices.Count; k++)\r
- {\r
- Vertex vertex = face.Vertices[k];\r
-\r
- #region Vertex\r
-\r
- Vector3 pos = vertex.Position;\r
-\r
- // Apply scaling\r
- pos *= mesh.Prim.Scale;\r
-\r
- // Apply rotation\r
- pos *= mesh.Prim.Rotation;\r
-\r
- // The root prim position is sim-relative, while child prim positions are\r
- // parent-relative. We want to apply parent-relative translations but not\r
- // sim-relative ones\r
- if (mesh.Prim.ParentID != 0)\r
- pos += mesh.Prim.Position;\r
-\r
- obj.AppendFormat("v {0} {1} {2}{3}", pos.X, pos.Y, pos.Z, Environment.NewLine);\r
-\r
- #endregion Vertex\r
-\r
- #region Texture Coord\r
-\r
- obj.AppendFormat("vt {0} {1}{2}", vertex.TexCoord.X, vertex.TexCoord.Y,\r
- Environment.NewLine);\r
-\r
- #endregion Texture Coord\r
-\r
- #region Vertex Normal\r
-\r
- // HACK: Sometimes normals are getting set to <NaN,NaN,NaN>\r
- if (!Single.IsNaN(vertex.Normal.X) && !Single.IsNaN(vertex.Normal.Y) && !Single.IsNaN(vertex.Normal.Z))\r
- obj.AppendFormat("vn {0} {1} {2}{3}", vertex.Normal.X, vertex.Normal.Y, vertex.Normal.Z,\r
- Environment.NewLine);\r
- else\r
- obj.AppendLine("vn 0.0 1.0 0.0");\r
-\r
- #endregion Vertex Normal\r
- }\r
-\r
- obj.AppendFormat("# {0} vertices{1}", face.Vertices.Count, Environment.NewLine);\r
- obj.AppendLine();\r
- obj.AppendLine("usemtl " + mtlName);\r
-\r
- #region Elements\r
-\r
- // Write all of the faces (triangles) for this side\r
- for (int k = 0; k < face.Indices.Count / 3; k++)\r
- {\r
- obj.AppendFormat("f -{0}/-{0}/-{0} -{1}/-{1}/-{1} -{2}/-{2}/-{2}{3}",\r
- face.Vertices.Count - face.Indices[k * 3 + 0],\r
- face.Vertices.Count - face.Indices[k * 3 + 1],\r
- face.Vertices.Count - face.Indices[k * 3 + 2],\r
- Environment.NewLine);\r
- }\r
-\r
- obj.AppendFormat("# {0} elements{1}", face.Indices.Count / 3, Environment.NewLine);\r
- obj.AppendLine();\r
-\r
- #endregion Elements\r
- }\r
- }\r
- primNr++;\r
- }\r
-\r
- try\r
- {\r
- File.WriteAllText(filename, obj.ToString());\r
- File.WriteAllText(mtlFilename, mtl.ToString());\r
- }\r
- catch (Exception)\r
- {\r
- return false;\r
- }\r
-\r
- return true;\r
- }\r
- }\r
-\r
- public static class Math3D\r
- {\r
- // Column-major:\r
- // | 0 4 8 12 |\r
- // | 1 5 9 13 |\r
- // | 2 6 10 14 |\r
- // | 3 7 11 15 |\r
-\r
- public static float[] CreateTranslationMatrix(Vector3 v)\r
- {\r
- float[] mat = new float[16];\r
-\r
- mat[12] = v.X;\r
- mat[13] = v.Y;\r
- mat[14] = v.Z;\r
- mat[0] = mat[5] = mat[10] = mat[15] = 1;\r
-\r
- return mat;\r
- }\r
-\r
- public static float[] CreateRotationMatrix(Quaternion q)\r
- {\r
- float[] mat = new float[16];\r
-\r
- // Transpose the quaternion (don't ask me why)\r
- q.X = q.X * -1f;\r
- q.Y = q.Y * -1f;\r
- q.Z = q.Z * -1f;\r
-\r
- float x2 = q.X + q.X;\r
- float y2 = q.Y + q.Y;\r
- float z2 = q.Z + q.Z;\r
- float xx = q.X * x2;\r
- float xy = q.X * y2;\r
- float xz = q.X * z2;\r
- float yy = q.Y * y2;\r
- float yz = q.Y * z2;\r
- float zz = q.Z * z2;\r
- float wx = q.W * x2;\r
- float wy = q.W * y2;\r
- float wz = q.W * z2;\r
-\r
- mat[0] = 1.0f - (yy + zz);\r
- mat[1] = xy - wz;\r
- mat[2] = xz + wy;\r
- mat[3] = 0.0f;\r
-\r
- mat[4] = xy + wz;\r
- mat[5] = 1.0f - (xx + zz);\r
- mat[6] = yz - wx;\r
- mat[7] = 0.0f;\r
-\r
- mat[8] = xz - wy;\r
- mat[9] = yz + wx;\r
- mat[10] = 1.0f - (xx + yy);\r
- mat[11] = 0.0f;\r
-\r
- mat[12] = 0.0f;\r
- mat[13] = 0.0f;\r
- mat[14] = 0.0f;\r
- mat[15] = 1.0f;\r
-\r
- return mat;\r
- }\r
-\r
- public static float[] CreateSRTMatrix(Vector3 scale, Quaternion q, Vector3 pos)\r
- {\r
- float[] mat = new float[16];\r
-\r
- // Transpose the quaternion (don't ask me why)\r
- q.X = q.X * -1f;\r
- q.Y = q.Y * -1f;\r
- q.Z = q.Z * -1f;\r
-\r
- float x2 = q.X + q.X;\r
- float y2 = q.Y + q.Y;\r
- float z2 = q.Z + q.Z;\r
- float xx = q.X * x2;\r
- float xy = q.X * y2;\r
- float xz = q.X * z2;\r
- float yy = q.Y * y2;\r
- float yz = q.Y * z2;\r
- float zz = q.Z * z2;\r
- float wx = q.W * x2;\r
- float wy = q.W * y2;\r
- float wz = q.W * z2;\r
-\r
- mat[0] = (1.0f - (yy + zz)) * scale.X;\r
- mat[1] = (xy - wz) * scale.X;\r
- mat[2] = (xz + wy) * scale.X;\r
- mat[3] = 0.0f;\r
-\r
- mat[4] = (xy + wz) * scale.Y;\r
- mat[5] = (1.0f - (xx + zz)) * scale.Y;\r
- mat[6] = (yz - wx) * scale.Y;\r
- mat[7] = 0.0f;\r
-\r
- mat[8] = (xz - wy) * scale.Z;\r
- mat[9] = (yz + wx) * scale.Z;\r
- mat[10] = (1.0f - (xx + yy)) * scale.Z;\r
- mat[11] = 0.0f;\r
-\r
- //Positional parts\r
- mat[12] = pos.X;\r
- mat[13] = pos.Y;\r
- mat[14] = pos.Z;\r
- mat[15] = 1.0f;\r
-\r
- return mat;\r
- }\r
-\r
-\r
- public static float[] CreateScaleMatrix(Vector3 v)\r
- {\r
- float[] mat = new float[16];\r
-\r
- mat[0] = v.X;\r
- mat[5] = v.Y;\r
- mat[10] = v.Z;\r
- mat[15] = 1;\r
-\r
- return mat;\r
- }\r
-\r
- public static float[] Lerp(float[] matrix1, float[] matrix2, float amount)\r
- {\r
-\r
- float[] lerp = new float[16];\r
- //Probably not doing this as a loop is cheaper(unrolling)\r
- //also for performance we probably should not create new objects\r
- // but meh.\r
- for (int x = 0; x < 16; x++)\r
- {\r
- lerp[x] = matrix1[x] + ((matrix2[x] - matrix1[x]) * amount);\r
- }\r
-\r
- return lerp;\r
- }\r
-\r
-\r
- public static bool GluProject(OpenTK.Vector3 objPos, OpenTK.Matrix4 modelMatrix, OpenTK.Matrix4 projMatrix, int[] viewport, out OpenTK.Vector3 screenPos)\r
- {\r
- OpenTK.Vector4 _in;\r
- OpenTK.Vector4 _out;\r
-\r
- _in.X = objPos.X;\r
- _in.Y = objPos.Y;\r
- _in.Z = objPos.Z;\r
- _in.W = 1.0f;\r
-\r
- _out = OpenTK.Vector4.Transform(_in, modelMatrix);\r
- _in = OpenTK.Vector4.Transform(_out, projMatrix);\r
-\r
- if (_in.W <= 0.0)\r
- {\r
- screenPos = OpenTK.Vector3.Zero;\r
- return false;\r
- }\r
-\r
- _in.X /= _in.W;\r
- _in.Y /= _in.W;\r
- _in.Z /= _in.W;\r
- /* Map x, y and z to range 0-1 */\r
- _in.X = _in.X * 0.5f + 0.5f;\r
- _in.Y = _in.Y * 0.5f + 0.5f;\r
- _in.Z = _in.Z * 0.5f + 0.5f;\r
-\r
- /* Map x,y to viewport */\r
- _in.X = _in.X * viewport[2] + viewport[0];\r
- _in.Y = _in.Y * viewport[3] + viewport[1];\r
-\r
- screenPos.X = _in.X;\r
- screenPos.Y = _in.Y;\r
- screenPos.Z = _in.Z;\r
-\r
- return true;\r
- }\r
-\r
- public static double[] AbovePlane(double height)\r
- {\r
- return new double[] { 0, 0, 1, -height};\r
- }\r
-\r
- public static double[] BelowPlane(double height)\r
- {\r
- return new double[] { 0, 0, -1, height };\r
- }\r
- }\r
-\r
- public class attachment_point\r
- {\r
- public string name;\r
- public string joint;\r
- public Vector3 position;\r
- public Quaternion rotation;\r
- public int id;\r
- public int group;\r
-\r
- public GLMesh jointmesh;\r
- public int jointmeshindex;\r
-\r
- public attachment_point(XmlNode node)\r
- {\r
- name = node.Attributes.GetNamedItem("name").Value;\r
- joint = node.Attributes.GetNamedItem("joint").Value;\r
- position = VisualParamEx.XmlParseVector(node.Attributes.GetNamedItem("position").Value);\r
- rotation = VisualParamEx.XmlParseRotation(node.Attributes.GetNamedItem("rotation").Value);\r
- id = Int32.Parse(node.Attributes.GetNamedItem("id").Value);\r
- group = Int32.Parse(node.Attributes.GetNamedItem("group").Value);\r
- }\r
-\r
- }\r
-\r
- /// <summary>\r
- /// Subclass of LindenMesh that adds vertex, index, and texture coordinate\r
- /// arrays suitable for pushing direct to OpenGL\r
- /// </summary>\r
- public class GLMesh : LindenMesh\r
- {\r
- /// <summary>\r
- /// Subclass of LODMesh that adds an index array suitable for pushing\r
- /// direct to OpenGL\r
- /// </summary>\r
- /// \r
-\r
- public int teFaceID;\r
- public Dictionary<int, VisualParamEx> _evp = new Dictionary<int, VisualParamEx>();\r
-\r
- new public class LODMesh : LindenMesh.LODMesh\r
- {\r
- public ushort[] Indices;\r
-\r
- public override void LoadMesh(string filename)\r
- {\r
- base.LoadMesh(filename);\r
-\r
- // Generate the index array\r
- Indices = new ushort[_numFaces * 3];\r
- int current = 0;\r
- for (int i = 0; i < _numFaces; i++)\r
- {\r
- Indices[current++] = (ushort)_faces[i].Indices[0];\r
- Indices[current++] = (ushort)_faces[i].Indices[1];\r
- Indices[current++] = (ushort)_faces[i].Indices[2];\r
- }\r
- }\r
- }\r
-\r
- /// <summary>\r
- /// \r
- /// </summary>\r
- public struct GLData\r
- {\r
- public float[] Vertices;\r
- public float[] Normals;\r
- public ushort[] Indices;\r
- public float[] TexCoords;\r
- public Vector3 Center;\r
- public float[] weights; //strictly these are constant and don't need instancing with the GLMesh\r
- public string[] skinJoints; //strictly these are constant and don't need instancing with the GLMesh\r
- }\r
-\r
- public static GLData baseRenderData;\r
- public GLData RenderData;\r
- public GLData OrigRenderData;\r
- public GLData MorphRenderData;\r
-\r
- public GLAvatar av;\r
-\r
- public GLMesh(string name)\r
- : base(name)\r
- {\r
- }\r
-\r
- public GLMesh(GLMesh source, GLAvatar av)\r
- : base(source.Name)\r
- {\r
- this.av = av;\r
- // Make a new GLMesh copy from the supplied source\r
-\r
- RenderData.Vertices = new float[source.RenderData.Vertices.Length];\r
- RenderData.Normals = new float[source.RenderData.Normals.Length];\r
- RenderData.TexCoords = new float[source.RenderData.TexCoords.Length];\r
- RenderData.Indices = new ushort[source.RenderData.Indices.Length];\r
-\r
- RenderData.weights = new float[source.RenderData.weights.Length];\r
- RenderData.skinJoints = new string[source.RenderData.skinJoints.Length];\r
-\r
- Array.Copy(source.RenderData.Vertices, RenderData.Vertices, source.RenderData.Vertices.Length);\r
- Array.Copy(source.RenderData.Normals, RenderData.Normals, source.RenderData.Normals.Length);\r
-\r
- Array.Copy(source.RenderData.TexCoords, RenderData.TexCoords, source.RenderData.TexCoords.Length);\r
- Array.Copy(source.RenderData.Indices, RenderData.Indices, source.RenderData.Indices.Length);\r
- Array.Copy(source.RenderData.weights, RenderData.weights, source.RenderData.weights.Length);\r
- Array.Copy(source.RenderData.skinJoints, RenderData.skinJoints, source.RenderData.skinJoints.Length);\r
-\r
- RenderData.Center = new Vector3(source.RenderData.Center);\r
-\r
- teFaceID = source.teFaceID;\r
-\r
- _rotationAngles = new Vector3(source.RotationAngles);\r
- _scale = new Vector3(source.Scale);\r
- _position = new Vector3(source.Position);\r
-\r
- // We should not need to instance these the reference from the top should be constant\r
- _evp = source._evp;\r
- _morphs = source._morphs;\r
-\r
- OrigRenderData.Indices = new ushort[source.RenderData.Indices.Length];\r
- OrigRenderData.TexCoords = new float[source.RenderData.TexCoords.Length];\r
- OrigRenderData.Vertices = new float[source.RenderData.Vertices.Length];\r
-\r
- MorphRenderData.Vertices = new float[source.RenderData.Vertices.Length];\r
-\r
- Array.Copy(source.RenderData.Vertices, OrigRenderData.Vertices, source.RenderData.Vertices.Length);\r
- Array.Copy(source.RenderData.Vertices, MorphRenderData.Vertices, source.RenderData.Vertices.Length);\r
-\r
- Array.Copy(source.RenderData.TexCoords, OrigRenderData.TexCoords, source.RenderData.TexCoords.Length);\r
- Array.Copy(source.RenderData.Indices, OrigRenderData.Indices, source.RenderData.Indices.Length);\r
-\r
-\r
-\r
- }\r
-\r
- public void setMeshPos(Vector3 pos)\r
- {\r
- _position = pos;\r
- }\r
-\r
- public void setMeshRot(Vector3 rot)\r
- {\r
- _rotationAngles = rot;\r
- }\r
-\r
- public override void LoadMesh(string filename)\r
- {\r
- base.LoadMesh(filename);\r
-\r
- float minX, minY, minZ;\r
- minX = minY = minZ = Single.MaxValue;\r
- float maxX, maxY, maxZ;\r
- maxX = maxY = maxZ = Single.MinValue;\r
-\r
- // Generate the vertex array\r
- RenderData.Vertices = new float[_numVertices * 3];\r
- RenderData.Normals = new float[_numVertices * 3];\r
-\r
- Quaternion quat = Quaternion.CreateFromEulers(0, 0, (float)(Math.PI / 4.0));\r
-\r
- int current = 0;\r
- for (int i = 0; i < _numVertices; i++)\r
- {\r
-\r
- RenderData.Normals[current] = _vertices[i].Normal.X;\r
- RenderData.Vertices[current++] = _vertices[i].Coord.X;\r
- RenderData.Normals[current] = _vertices[i].Normal.Y;\r
- RenderData.Vertices[current++] = _vertices[i].Coord.Y;\r
- RenderData.Normals[current] = _vertices[i].Normal.Z;\r
- RenderData.Vertices[current++] = _vertices[i].Coord.Z;\r
-\r
- if (_vertices[i].Coord.X < minX)\r
- minX = _vertices[i].Coord.X;\r
- else if (_vertices[i].Coord.X > maxX)\r
- maxX = _vertices[i].Coord.X;\r
-\r
- if (_vertices[i].Coord.Y < minY)\r
- minY = _vertices[i].Coord.Y;\r
- else if (_vertices[i].Coord.Y > maxY)\r
- maxY = _vertices[i].Coord.Y;\r
-\r
- if (_vertices[i].Coord.Z < minZ)\r
- minZ = _vertices[i].Coord.Z;\r
- else if (_vertices[i].Coord.Z > maxZ)\r
- maxZ = _vertices[i].Coord.Z;\r
- }\r
-\r
- // Calculate the center-point from the bounding box edges\r
- RenderData.Center = new Vector3((minX + maxX) / 2, (minY + maxY) / 2, (minZ + maxZ) / 2);\r
-\r
- // Generate the index array\r
- RenderData.Indices = new ushort[_numFaces * 3];\r
- current = 0;\r
- for (int i = 0; i < _numFaces; i++)\r
- {\r
- RenderData.Indices[current++] = (ushort)_faces[i].Indices[0];\r
- RenderData.Indices[current++] = (ushort)_faces[i].Indices[1];\r
- RenderData.Indices[current++] = (ushort)_faces[i].Indices[2];\r
- }\r
-\r
- // Generate the texcoord array\r
- RenderData.TexCoords = new float[_numVertices * 2];\r
- current = 0;\r
- for (int i = 0; i < _numVertices; i++)\r
- {\r
- RenderData.TexCoords[current++] = _vertices[i].TexCoord.X;\r
- RenderData.TexCoords[current++] = _vertices[i].TexCoord.Y;\r
- }\r
-\r
- RenderData.weights = new float[_numVertices];\r
- for (int i = 0; i < _numVertices; i++)\r
- {\r
- RenderData.weights[i] = _vertices[i].Weight;\r
- }\r
-\r
- RenderData.skinJoints = new string[_skinJoints.Length + 3];\r
- for (int i = 1; i < _skinJoints.Length; i++)\r
- {\r
- RenderData.skinJoints[i] = _skinJoints[i];\r
- }\r
-\r
-\r
- }\r
-\r
- public override void LoadLODMesh(int level, string filename)\r
- {\r
- LODMesh lod = new LODMesh();\r
- lod.LoadMesh(filename);\r
- _lodMeshes[level] = lod;\r
- }\r
-\r
- public void applyjointweights()\r
- {\r
-\r
- /*Each weight actually contains two pieces of information. \r
- * The number to the left of the decimal point is the index of the joint and also \r
- * implicitly indexes to the following joint. The actual weight is to the right of \r
- * the decimal point and interpolates between these two joints. The index is into an \r
- * "expanded" list of joints, not just a linear array of the joints as defined in the \r
- * skeleton file. In particular, any joint that has more than one child will be repeated \r
- * in the list for each of its children.\r
- */\r
-\r
- float weight = -9999;\r
- int jointindex = 0;\r
- float factor;\r
-\r
- Bone ba = null;\r
- Bone bb = null;\r
-\r
- for (int v = 0, x = 0; v < RenderData.Vertices.Length; v = v + 3, x++)\r
- {\r
- if (weight != RenderData.weights[x])\r
- {\r
-\r
- jointindex = (int)Math.Floor(weight = RenderData.weights[x]);\r
- factor = RenderData.weights[x] - jointindex;\r
- weight = weight - jointindex;\r
-\r
- string jointname = "", jointname2 = "";\r
-\r
- if (this.Name == "upperBodyMesh")\r
- {\r
- jointname = skeleton.mUpperMeshMapping[jointindex];\r
- jointindex++;\r
- jointname2 = skeleton.mUpperMeshMapping[jointindex];\r
- }\r
- else if (Name == "lowerBodyMesh")\r
- {\r
- jointname = skeleton.mLowerMeshMapping[jointindex];\r
- jointindex++;\r
- jointname2 = skeleton.mLowerMeshMapping[jointindex];\r
- }\r
- else if (Name == "headMesh")\r
- {\r
- jointname = skeleton.mHeadMeshMapping[jointindex];\r
- jointindex++;\r
- jointname2 = skeleton.mHeadMeshMapping[jointindex];\r
- }\r
- else\r
- {\r
- return; // not interested in this mesh\r
- }\r
-\r
-\r
- if (jointname == "")\r
- {\r
- //Don't yet handle this, its a split joint to two children\r
- ba = av.skel.mBones[jointname2];\r
- bb = null;\r
-\r
- //continue;\r
- }\r
- else\r
- {\r
-\r
- ba = av.skel.mBones[jointname];\r
- }\r
-\r
- if (jointname2 == "")\r
- {\r
- bb = null;\r
- }\r
- else\r
- {\r
- bb = av.skel.mBones[jointname2];\r
- }\r
- }\r
-\r
- //Special cases 0 is not used\r
- // ON upper torso 5 and 10 are not used\r
- // 4 is neck and 6 and 11 are the left and right collar bones\r
-\r
-\r
- //TODO use the SRT matrix to do this!\r
-\r
- Vector3 lerpa;\r
- Vector3 offseta;\r
- Quaternion rota;\r
-\r
- Vector3 lerpb;\r
- Vector3 offsetb;\r
- Quaternion rotb;\r
-\r
- Vector3 pos;\r
-\r
- Vector3 posa = new Vector3(MorphRenderData.Vertices[v], MorphRenderData.Vertices[v + 1], MorphRenderData.Vertices[v + 2]);\r
-\r
-\r
- if (bb != null)\r
- {\r
- lerpa = ba.getDeltaOffset();\r
- offseta = ba.getTotalOffset();\r
- rota = ba.getTotalRotation();\r
-\r
- lerpb = bb.getDeltaOffset();\r
- offsetb = bb.getTotalOffset();\r
- rotb = bb.getTotalRotation();\r
-\r
- Vector3 posb = new Vector3(MorphRenderData.Vertices[v], MorphRenderData.Vertices[v + 1], MorphRenderData.Vertices[v + 2]);\r
-\r
- //move back to mesh local coords\r
- posa = posa - offseta;\r
- // apply rotated offset\r
- posa = (posa + lerpa)*rota;\r
- //move back to avatar local coords\r
- posa = posa + offseta;\r
-\r
- //move back to mesh local coords\r
- posb = posb - offsetb;\r
- // apply rotated offset\r
- posb = (posb + lerpb)*rotb;\r
- //move back to avatar local coords\r
- posb = posb + offsetb;\r
-\r
- //LERP the two points to produce smooth skinning ;-)\r
- pos = Vector3.Lerp(posa, posb, weight);\r
-\r
- }\r
- else\r
- {\r
- lerpa = ba.getDeltaOffset();\r
- offseta = ba.getTotalOffset();\r
- rota = ba.getTotalRotation();\r
-\r
- //move back to mesh local coords\r
- posa = posa - offseta;\r
- // apply rotated offset\r
- posa = (posa + lerpa)*rota;\r
- //move back to avatar local coords\r
- posa = posa + offseta;\r
-\r
- //Only one bone contributing so its 100% that one.\r
- pos = posa;\r
- \r
- }\r
-\r
- RenderData.Vertices[v] = pos.X;\r
- RenderData.Vertices[v + 1] = pos.Y;\r
- RenderData.Vertices[v + 2] = pos.Z;\r
- }\r
- }\r
-\r
- public void resetallmorphs()\r
- {\r
- for (int i = 0; i < OrigRenderData.Vertices.Length / 3; i++)\r
- {\r
-\r
- MorphRenderData.Vertices[i * 3] = OrigRenderData.Vertices[i * 3];\r
- MorphRenderData.Vertices[(i * 3) + 1] = OrigRenderData.Vertices[i * 3 + 1];\r
- MorphRenderData.Vertices[(i * 3) + 2] = OrigRenderData.Vertices[i * 3 + 2];\r
-\r
- //MorphRenderData.Normals[i * 3] = OrigRenderData.Normals[i * 3];\r
- //MorphRenderData.Normals[(i * 3) + 1] = OrigRenderData.Normals[i * 3 + 1];\r
- //MorphRenderData.Normals[(i * 3) + 2] = OrigRenderData.Normals[i * 3 + 2];\r
-\r
- RenderData.TexCoords[i * 2] = OrigRenderData.TexCoords[i * 2];\r
- RenderData.TexCoords[(i * 2) + 1] = OrigRenderData.TexCoords[i * 2 + 1];\r
-\r
- }\r
-\r
- }\r
-\r
- public void morphmesh(Morph morph, float weight)\r
- {\r
- for (int v = 0; v < morph.NumVertices; v++)\r
- {\r
- MorphVertex mvx = morph.Vertices[v];\r
-\r
- uint i = mvx.VertexIndex;\r
-\r
- MorphRenderData.Vertices[i * 3] = MorphRenderData.Vertices[i * 3] + mvx.Coord.X * weight;\r
- MorphRenderData.Vertices[(i * 3) + 1] = MorphRenderData.Vertices[i * 3 + 1] + mvx.Coord.Y * weight;\r
- MorphRenderData.Vertices[(i * 3) + 2] = MorphRenderData.Vertices[i * 3 + 2] + mvx.Coord.Z * weight;\r
-\r
- //MorphRenderData.Normals[i * 3] = MorphRenderData.Normals[i * 3] + mvx.Normal.X * weight;\r
- //MorphRenderData.Normals[(i * 3)+1] = MorphRenderData.Normals[(i * 3)+1] + mvx.Normal.Y * weight;\r
- //MorphRenderData.Normals[(i * 3)+2] = MorphRenderData.Normals[(i * 3)+2] + mvx.Normal.Z * weight;\r
-\r
- RenderData.TexCoords[i * 2] = OrigRenderData.TexCoords[i * 2] + mvx.TexCoord.X * weight;\r
- RenderData.TexCoords[(i * 2) + 1] = OrigRenderData.TexCoords[i * 2 + 1] + mvx.TexCoord.Y * weight;\r
-\r
- }\r
- }\r
- }\r
-\r
- public class GLAvatar\r
- {\r
- private static Dictionary<string, GLMesh> _defaultmeshes = new Dictionary<string, GLMesh>();\r
- public Dictionary<string, GLMesh> _meshes = new Dictionary<string, GLMesh>();\r
-\r
- public skeleton skel = new skeleton();\r
- public static Dictionary<int, attachment_point> attachment_points = new Dictionary<int, attachment_point>();\r
-\r
- public bool _wireframe = true;\r
- public bool _showSkirt = false;\r
-\r
- public VisualParamEx.EparamSex msex;\r
-\r
- public byte[] VisualAppearanceParameters = new byte[1024];\r
- bool vpsent = false;\r
- static bool lindenMeshesLoaded = false;\r
-\r
- public GLAvatar()\r
- {\r
- foreach (KeyValuePair<string, GLMesh> kvp in _defaultmeshes)\r
- {\r
- GLMesh mesh = new GLMesh(kvp.Value, this); // Instance our meshes\r
- _meshes.Add(kvp.Key, mesh);\r
-\r
- }\r
- }\r
-\r
- public static void dumptweaks()\r
- {\r
-\r
- for (int x = 0; x < VisualParamEx.tweakable_params.Count; x++)\r
- {\r
- VisualParamEx vpe = (VisualParamEx)VisualParamEx.tweakable_params.GetByIndex(x);\r
- Console.WriteLine(string.Format("{0} is {1}", x, vpe.Name));\r
- }\r
-\r
-\r
- }\r
-\r
- public static void loadlindenmeshes2(string LODfilename)\r
- {\r
- // Already have mashes loaded?\r
- if (lindenMeshesLoaded) return;\r
-\r
- attachment_points.Clear();\r
-\r
-\r
- string basedir = Directory.GetCurrentDirectory() + System.IO.Path.DirectorySeparatorChar + "character" + System.IO.Path.DirectorySeparatorChar;\r
-\r
- XmlDocument lad = new XmlDocument();\r
- lad.Load(basedir + LODfilename);\r
-\r
- //Firstly read the skeleton section this contains attachment point info and the bone deform info for visual params\r
- // And load the skeleton file in to the bones class\r
-\r
- XmlNodeList skeleton = lad.GetElementsByTagName("skeleton");\r
- string skeletonfilename = skeleton[0].Attributes.GetNamedItem("file_name").Value;\r
- Bone.loadbones(skeletonfilename);\r
-\r
- // Next read all the skeleton child nodes, we have attachment points and bone deform params\r
- // attachment points are an offset and rotation from a bone location\r
- // the name of the bone they reference is the joint paramater\r
- // params in the skeleton nodes are bone deforms, eg leg length changes the scale of the leg bones\r
-\r
- foreach (XmlNode skeletonnode in skeleton[0].ChildNodes)\r
- {\r
- if (skeletonnode.Name == "attachment_point")\r
- {\r
- attachment_point point = new attachment_point(skeletonnode);\r
- attachment_points.Add(point.id, point);\r
- }\r
-\r
- if (skeletonnode.Name == "param")\r
- {\r
- //Bone deform param\r
- VisualParamEx vp = new VisualParamEx(skeletonnode, VisualParamEx.ParamType.TYPE_BONEDEFORM);\r
- }\r
- }\r
-\r
- //Now we parse the mesh nodes, mesh nodes reference a particular LLM file with a LOD\r
- //and also list VisualParams for the various mesh morphs that can be applied\r
-\r
- XmlNodeList meshes = lad.GetElementsByTagName("mesh");\r
- foreach (XmlNode meshNode in meshes)\r
- {\r
- string type = meshNode.Attributes.GetNamedItem("type").Value;\r
- int lod = Int32.Parse(meshNode.Attributes.GetNamedItem("lod").Value);\r
- string fileName = meshNode.Attributes.GetNamedItem("file_name").Value;\r
-\r
- GLMesh mesh = (_defaultmeshes.ContainsKey(type) ? _defaultmeshes[type] : new GLMesh(type));\r
-\r
- if (meshNode.HasChildNodes)\r
- {\r
- foreach (XmlNode paramnode in meshNode.ChildNodes)\r
- {\r
- if (paramnode.Name == "param")\r
- {\r
- VisualParamEx vp = new VisualParamEx(paramnode, VisualParamEx.ParamType.TYPE_MORPH);\r
-\r
- mesh._evp.Add(vp.ParamID, vp); //Not sure we really need this may optimise out later\r
- vp.morphmesh = mesh.Name;\r
- }\r
- }\r
- }\r
-\r
- // Set up the texture elemenets for each mesh\r
- // And hack the eyeball position\r
- switch (mesh.Name)\r
- {\r
- case "lowerBodyMesh":\r
- mesh.teFaceID = (int)AvatarTextureIndex.LowerBaked;\r
- break;\r
-\r
- case "upperBodyMesh":\r
- mesh.teFaceID = (int)AvatarTextureIndex.UpperBaked;\r
- break;\r
-\r
- case "headMesh":\r
- mesh.teFaceID = (int)AvatarTextureIndex.HeadBaked;\r
- break;\r
-\r
- case "hairMesh":\r
- mesh.teFaceID = (int)AvatarTextureIndex.HairBaked;\r
- break;\r
-\r
- case "eyelashMesh":\r
- mesh.teFaceID = (int)AvatarTextureIndex.HeadBaked;\r
- break;\r
-\r
- case "eyeBallRightMesh":\r
- mesh.setMeshPos(Bone.mBones["mEyeLeft"].getTotalOffset());\r
- //mesh.setMeshRot(Bone.getRotation("mEyeLeft"));\r
- mesh.teFaceID = (int)AvatarTextureIndex.EyesBaked;\r
- break;\r
-\r
- case "eyeBallLeftMesh":\r
- mesh.setMeshPos(Bone.mBones["mEyeRight"].getTotalOffset());\r
- //mesh.setMeshRot(Bone.getRotation("mEyeRight"));\r
- mesh.teFaceID = (int)AvatarTextureIndex.EyesBaked;\r
- break;\r
-\r
- case "skirtMesh":\r
- mesh.teFaceID = (int)AvatarTextureIndex.SkirtBaked;\r
- break;\r
-\r
- default:\r
- mesh.teFaceID = 0;\r
- break;\r
- }\r
-\r
- if (lod == 0)\r
- mesh.LoadMesh(basedir + fileName);\r
- else\r
- mesh.LoadLODMesh(lod, basedir + fileName);\r
-\r
- _defaultmeshes[type] = mesh;\r
-\r
- }\r
-\r
- // Next are the textureing params, skipping for the moment\r
-\r
- XmlNodeList colors = lad.GetElementsByTagName("global_color");\r
- {\r
- foreach (XmlNode globalcolornode in colors)\r
- {\r
- foreach (XmlNode node in globalcolornode.ChildNodes)\r
- {\r
- if (node.Name == "param")\r
- {\r
- VisualParamEx vp = new VisualParamEx(node, VisualParamEx.ParamType.TYPE_COLOR);\r
- }\r
- }\r
- }\r
- }\r
-\r
- // Get layer paramaters, a bit of a verbose way to do it but we probably want to get access\r
- // to some of the other data not just the <param> tag\r
-\r
- XmlNodeList layer_sets = lad.GetElementsByTagName("layer_set");\r
- {\r
- foreach (XmlNode layer_set in layer_sets)\r
- {\r
- foreach (XmlNode layer in layer_set.ChildNodes)\r
- {\r
- foreach (XmlNode layernode in layer.ChildNodes)\r
- {\r
- if (layernode.Name == "param")\r
- {\r
- VisualParamEx vp = new VisualParamEx(layernode, VisualParamEx.ParamType.TYPE_COLOR);\r
- }\r
- }\r
- }\r
- }\r
- }\r
-\r
- // Next are the driver parameters, these are parameters that change multiple real parameters\r
-\r
- XmlNodeList drivers = lad.GetElementsByTagName("driver_parameters");\r
-\r
- foreach (XmlNode node in drivers[0].ChildNodes) //lazy \r
- {\r
- if (node.Name == "param")\r
- {\r
- VisualParamEx vp = new VisualParamEx(node, VisualParamEx.ParamType.TYPE_DRIVER);\r
- }\r
- }\r
-\r
- lindenMeshesLoaded = true;\r
- }\r
-\r
- public void morphtest(Avatar av, int param, float weight)\r
- {\r
- VisualParamEx vpx;\r
- if (VisualParamEx.allParams.TryGetValue(param, out vpx))\r
- {\r
-\r
- //Logger.Log(string.Format("Applying visual parameter {0} id {1} value {2}", vpx.Name, vpx.ParamID, weight), Helpers.LogLevel.Info);\r
-\r
- //weight = weight * 2.0f;\r
- //weight=weight-1.0f;\r
-\r
- if (weight < 0)\r
- weight = 0;\r
-\r
- if (weight > 1.0)\r
- weight = 1;\r
-\r
- float value = vpx.MinValue + ((vpx.MaxValue - vpx.MinValue) * weight);\r
-\r
- if (vpx.pType == VisualParamEx.ParamType.TYPE_MORPH)\r
- {\r
- // Its a morph\r
- GLMesh mesh;\r
- if (_meshes.TryGetValue(vpx.morphmesh, out mesh))\r
- {\r
- foreach (LindenMesh.Morph morph in mesh.Morphs) //optimise me to a dictionary\r
- {\r
- if (morph.Name == vpx.Name)\r
- {\r
- if (mesh.Name == "skirtMesh" && _showSkirt == false)\r
- return;\r
-\r
- mesh.morphmesh(morph, value);\r
-\r
- return;\r
- }\r
- }\r
- }\r
- else\r
- {\r
- // Not a mesh morph \r
-\r
- // Its a volume deform, these appear to be related to collision volumes\r
- /*\r
- if (vpx.VolumeDeforms == null)\r
- {\r
- Logger.Log(String.Format("paramater {0} has invalid mesh {1}", param, vpx.morphmesh), Helpers.LogLevel.Warning);\r
- }\r
- else\r
- {\r
- foreach (KeyValuePair<string, VisualParamEx.VolumeDeform> kvp in vpx.VolumeDeforms)\r
- {\r
- skel.deformbone(kvp.Key, kvp.Value.pos, kvp.Value.scale);\r
- }\r
- }\r
- * */\r
-\r
- }\r
-\r
- }\r
- else\r
- {\r
- // Its not a morph, it might be a driver though\r
- if (vpx.pType == VisualParamEx.ParamType.TYPE_DRIVER)\r
- {\r
- foreach (VisualParamEx.driven child in vpx.childparams)\r
- {\r
- morphtest(av, child.id, weight); //TO DO use minmax if they are present\r
- }\r
- return;\r
- }\r
-\r
- //Is this a bone deform?\r
- if (vpx.pType == VisualParamEx.ParamType.TYPE_BONEDEFORM)\r
- {\r
- foreach (KeyValuePair<string, Vector3> kvp in vpx.BoneDeforms)\r
- {\r
- skel.deformbone(kvp.Key, new Vector3(0, 0, 0), kvp.Value * value, Quaternion.Identity);\r
- }\r
- return;\r
- }\r
- else\r
- {\r
- //Logger.Log(String.Format("paramater {0} is not a morph and not a driver", param), Helpers.LogLevel.Warning);\r
- }\r
- }\r
-\r
- }\r
- else\r
- {\r
- Logger.Log("Invalid paramater " + param.ToString(), Helpers.LogLevel.Warning);\r
- }\r
- }\r
-\r
- public void morph(Avatar av)\r
- {\r
-\r
- if (av.VisualParameters == null)\r
- return;\r
-\r
- ThreadPool.QueueUserWorkItem(sync =>\r
- {\r
- int x = 0;\r
-\r
- if (av.VisualParameters.Length > 123)\r
- {\r
- if (av.VisualParameters[31] > 127)\r
- {\r
- msex = VisualParamEx.EparamSex.SEX_MALE;\r
- }\r
- else\r
- {\r
- msex = VisualParamEx.EparamSex.SEX_FEMALE;\r
- }\r
- }\r
-\r
- foreach (GLMesh mesh in _meshes.Values)\r
- {\r
- mesh.resetallmorphs();\r
- }\r
-\r
- foreach (byte vpvalue in av.VisualParameters)\r
- {\r
- /*\r
- if (vpsent == true && VisualAppearanceParameters[x] == vpvalue)\r
- {\r
- \r
- x++;\r
- continue;\r
- }\r
- */\r
-\r
- VisualAppearanceParameters[x] = vpvalue;\r
-\r
- if (x >= VisualParamEx.tweakable_params.Count)\r
- {\r
- //Logger.Log("Two many visual paramaters in Avatar appearance", Helpers.LogLevel.Warning);\r
- break;\r
- }\r
-\r
- VisualParamEx vpe = (VisualParamEx)VisualParamEx.tweakable_params.GetByIndex(x);\r
-\r
- if (vpe.sex != VisualParamEx.EparamSex.SEX_BOTH && vpe.sex != msex)\r
- {\r
- x++;\r
- continue;\r
- }\r
-\r
- float value = (vpvalue / 255.0f);\r
- this.morphtest(av, vpe.ParamID, value);\r
-\r
- x++;\r
- // if (x > 100)\r
- // break;\r
- }\r
-\r
- vpsent = true;\r
-\r
- foreach (GLMesh mesh in _meshes.Values)\r
- {\r
- mesh.applyjointweights();\r
- }\r
- });\r
- }\r
- }\r
-\r
- public class RenderAvatar : SceneObject\r
- {\r
- public static readonly BoundingVolume AvatarBoundingVolume;\r
-\r
- // Static constructor\r
- static RenderAvatar()\r
- {\r
- AvatarBoundingVolume = new BoundingVolume();\r
- AvatarBoundingVolume.FromScale(Vector3.One);\r
- }\r
-\r
- // Default constructor\r
- public RenderAvatar()\r
- {\r
- BoundingVolume = AvatarBoundingVolume;\r
- Type = SceneObjectType.Avatar;\r
- }\r
-\r
- public override Primitive BasePrim\r
- {\r
- get { return avatar; }\r
- set\r
- {\r
- if (value is Avatar)\r
- {\r
- avatar = (Avatar)value;\r
- AvatarBoundingVolume.CalcScaled(avatar.Scale);\r
- }\r
- }\r
- }\r
-\r
- public override void Step(float time)\r
- {\r
- glavatar.skel.animate(time);\r
- base.Step(time);\r
- }\r
-\r
- public GLAvatar glavatar = new GLAvatar();\r
- public Avatar avatar;\r
- public FaceData[] data = new FaceData[32];\r
- public Dictionary<UUID, Animation> animlist = new Dictionary<UUID, Animation>();\r
- public Dictionary<WearableType, AppearanceManager.WearableData> Wearables = new Dictionary<WearableType, AppearanceManager.WearableData>();\r
-\r
- }\r
-\r
- public class skeleton\r
- {\r
- public Dictionary<string, Bone> mBones;\r
- public Dictionary<string, int> mPriority = new Dictionary<string, int>();\r
- public static Dictionary<int, string> mUpperMeshMapping = new Dictionary<int, string>();\r
- public static Dictionary<int, string> mLowerMeshMapping = new Dictionary<int, string>();\r
- public static Dictionary<int, string> mHeadMeshMapping = new Dictionary<int, string>();\r
-\r
- public List<BinBVHAnimationReader> mAnimations = new List<BinBVHAnimationReader>();\r
-\r
- public static Dictionary<UUID, RenderAvatar> mAnimationTransactions = new Dictionary<UUID, RenderAvatar>();\r
-\r
- public static Dictionary<UUID, BinBVHAnimationReader> mAnimationCache = new Dictionary<UUID, BinBVHAnimationReader>();\r
-\r
- public bool mNeedsUpdate = false;\r
- public bool mNeedsMeshRebuild = false;\r
-\r
- public Bone mLeftEye = null;\r
- public Bone mRightEye = null;\r
-\r
- public struct binBVHJointState\r
- {\r
- public float currenttime_rot;\r
- public int lastkeyframe_rot;\r
- public int nextkeyframe_rot;\r
-\r
- public float currenttime_pos;\r
- public int lastkeyframe_pos;\r
- public int nextkeyframe_pos;\r
-\r
- public int loopinframe;\r
- public int loopoutframe;\r
- }\r
-\r
-\r
- public skeleton()\r
- {\r
-\r
-\r
-\r
- mBones = new Dictionary<string, Bone>();\r
-\r
- foreach (Bone src in Bone.mBones.Values)\r
- {\r
- Bone newbone = new Bone(src);\r
- mBones.Add(newbone.name, newbone);\r
- }\r
-\r
- //rebuild the skeleton structure on the new copy\r
- foreach (Bone src in mBones.Values)\r
- {\r
- if (src.mParentBone != null)\r
- {\r
- src.parent = mBones[src.mParentBone];\r
- src.parent.children.Add(src);\r
- }\r
- }\r
-\r
- //FUDGE\r
- if (mUpperMeshMapping.Count == 0)\r
- {\r
- mUpperMeshMapping.Add(1, "mPelvis");\r
- mUpperMeshMapping.Add(2, "mTorso");\r
- mUpperMeshMapping.Add(3, "mChest");\r
- mUpperMeshMapping.Add(4, "mNeck");\r
- mUpperMeshMapping.Add(5, "");\r
- mUpperMeshMapping.Add(6, "mCollarLeft");\r
- mUpperMeshMapping.Add(7, "mShoulderLeft");\r
- mUpperMeshMapping.Add(8, "mElbowLeft");\r
- mUpperMeshMapping.Add(9, "mWristLeft");\r
- mUpperMeshMapping.Add(10, "");\r
- mUpperMeshMapping.Add(11, "mCollarRight");\r
- mUpperMeshMapping.Add(12, "mShoulderRight");\r
- mUpperMeshMapping.Add(13, "mElbowRight");\r
- mUpperMeshMapping.Add(14, "mWristRight");\r
- mUpperMeshMapping.Add(15, "");\r
-\r
- mLowerMeshMapping.Add(1, "mPelvis");\r
- mLowerMeshMapping.Add(2, "mHipRight");\r
- mLowerMeshMapping.Add(3, "mKneeRight");\r
- mLowerMeshMapping.Add(4, "mAnkleRight");\r
- mLowerMeshMapping.Add(5, "");\r
- mLowerMeshMapping.Add(6, "mHipLeft");\r
- mLowerMeshMapping.Add(7, "mKneeLeft");\r
- mLowerMeshMapping.Add(8, "mAnkleLeft");\r
- mLowerMeshMapping.Add(9, "");\r
-\r
- mHeadMeshMapping.Add(1, "mNeck");\r
- mHeadMeshMapping.Add(2, "mHead");\r
- mHeadMeshMapping.Add(3, "");\r
-\r
- }\r
-\r
- mLeftEye = mBones["mEyeLeft"];\r
- mRightEye = mBones["mEyeRight"];\r
-\r
- }\r
-\r
- public void deformbone(string name, Vector3 pos, Vector3 scale, Quaternion rotation)\r
- {\r
- Bone bone;\r
- if (mBones.TryGetValue(name, out bone))\r
- {\r
- bone.deformbone(pos, scale, rotation);\r
- }\r
- }\r
-\r
- //TODO check offset and rot calcuations should each offset be multiplied by its parent rotation in\r
- // a standard child/parent rot/offset way?\r
- public Vector3 getOffset(string bonename)\r
- {\r
- Bone b;\r
- if (mBones.TryGetValue(bonename, out b))\r
- {\r
- return (b.getTotalOffset());\r
- }\r
- else\r
- {\r
- return Vector3.Zero;\r
- }\r
- }\r
-\r
- public Quaternion getRotation(string bonename)\r
- {\r
- Bone b;\r
- if (mBones.TryGetValue(bonename, out b))\r
- {\r
- return (b.getTotalRotation());\r
- }\r
- else\r
- {\r
- return Quaternion.Identity;\r
- }\r
- }\r
-\r
-\r
- public void flushanimations()\r
- {\r
- lock (mAnimations)\r
- {\r
- mAnimations.Clear();\r
- }\r
- }\r
-\r
- // Add animations to the global decoded list\r
- // TODO garbage collect unused animations somehow\r
- public static void addanimation(OpenMetaverse.Assets.Asset asset, UUID tid, BinBVHAnimationReader b)\r
- {\r
- RenderAvatar av;\r
- mAnimationTransactions.TryGetValue(tid, out av);\r
- if (av == null)\r
- return;\r
-\r
- mAnimationTransactions.Remove(tid);\r
-\r
- if (asset != null)\r
- {\r
- b = new BinBVHAnimationReader(asset.AssetData);\r
- mAnimationCache[asset.AssetID] = b;\r
- Logger.Log("Adding new decoded animaton known animations " + asset.AssetID.ToString(), Helpers.LogLevel.Info);\r
- }\r
-\r
- int pos = 0;\r
- foreach (binBVHJoint joint in b.joints)\r
- {\r
- binBVHJointState state;\r
-\r
- state.lastkeyframe_rot = 0;\r
- state.nextkeyframe_rot = 1;\r
-\r
- state.lastkeyframe_pos = 0;\r
- state.nextkeyframe_pos = 1;\r
-\r
- state.currenttime_rot = 0;\r
- state.currenttime_pos = 0;\r
-\r
- state.loopinframe = 0;\r
- state.loopoutframe = joint.rotationkeys.Length - 1;\r
-\r
- if (b.Loop == true)\r
- {\r
- int frame = 0;\r
- foreach (binBVHJointKey key in joint.rotationkeys)\r
- {\r
- if (key.time == b.InPoint)\r
- {\r
- state.loopinframe = frame;\r
- }\r
-\r
- if (key.time == b.OutPoint)\r
- {\r
- state.loopoutframe = frame;\r
- }\r
-\r
- frame++;\r
-\r
- }\r
-\r
- }\r
-\r
- b.joints[pos].Tag = state;\r
- pos++;\r
- }\r
-\r
- lock (av.glavatar.skel.mAnimations)\r
- {\r
- av.glavatar.skel.mAnimations.Add(b);\r
- }\r
- }\r
-\r
- public void animate(float lastframetime)\r
- {\r
- mPriority.Clear();\r
-\r
- lock (mAnimations)\r
- foreach (BinBVHAnimationReader b in mAnimations)\r
- {\r
- if (b == null)\r
- continue;\r
-\r
- int jpos = 0;\r
- foreach (binBVHJoint joint in b.joints)\r
- {\r
- int prio = 0;\r
-\r
- //Quick hack to stack animations in the correct order\r
- //TODO we need to do this per joint as they all have their own priorities as well ;-(\r
- if (mPriority.TryGetValue(joint.Name, out prio))\r
- {\r
- if (prio > b.Priority)\r
- continue;\r
- }\r
-\r
- mPriority[joint.Name] = b.Priority;\r
-\r
- binBVHJointState state = (binBVHJointState)b.joints[jpos].Tag;\r
-\r
- state.currenttime_rot += lastframetime;\r
- state.currenttime_pos += lastframetime;\r
-\r
- //fudge\r
- if (b.joints[jpos].rotationkeys.Length == 1)\r
- {\r
- state.nextkeyframe_rot = 0;\r
- }\r
-\r
- Vector3 poslerp = Vector3.Zero;\r
-\r
- if (b.joints[jpos].positionkeys.Length > 2)\r
- {\r
- binBVHJointKey pos2 = b.joints[jpos].positionkeys[state.nextkeyframe_pos];\r
-\r
-\r
- if (state.currenttime_pos > pos2.time)\r
- {\r
- state.lastkeyframe_pos++;\r
- state.nextkeyframe_pos++;\r
-\r
- if (state.nextkeyframe_pos >= b.joints[jpos].positionkeys.Length || (state.nextkeyframe_pos >= state.loopoutframe && b.Loop == true))\r
- {\r
- if (b.Loop == true)\r
- {\r
- state.nextkeyframe_pos = state.loopinframe;\r
- state.currenttime_pos = b.InPoint;\r
-\r
- if (state.lastkeyframe_pos >= b.joints[jpos].positionkeys.Length)\r
- {\r
- state.lastkeyframe_pos = state.loopinframe;\r
- }\r
- }\r
- else\r
- {\r
- state.nextkeyframe_pos = joint.positionkeys.Length - 1;\r
- }\r
- }\r
-\r
-\r
-\r
- if (state.lastkeyframe_pos >= b.joints[jpos].positionkeys.Length)\r
- {\r
- if (b.Loop == true)\r
- {\r
- state.lastkeyframe_pos = 0;\r
- state.currenttime_pos = 0;\r
-\r
- }\r
- else\r
- {\r
- state.lastkeyframe_pos = joint.positionkeys.Length - 1;\r
- if (state.lastkeyframe_pos < 0)//eeww\r
- state.lastkeyframe_pos = 0;\r
- }\r
- }\r
- }\r
-\r
- binBVHJointKey pos = b.joints[jpos].positionkeys[state.lastkeyframe_pos];\r
-\r
-\r
- if (state.currenttime_pos != ((pos.time - b.joints[jpos].positionkeys[0].time)))\r
- {\r
-\r
- float delta = (pos2.time - pos.time) / ((state.currenttime_pos) - (pos.time - b.joints[jpos].positionkeys[0].time));\r
-\r
- if (delta < 0)\r
- delta = 0;\r
-\r
- if (delta > 1)\r
- delta = 1;\r
-\r
- poslerp = Vector3.Lerp(pos.key_element, pos2.key_element, delta);\r
- }\r
-\r
- }\r
-\r
-\r
- Vector3 rotlerp = Vector3.Zero;\r
- if (b.joints[jpos].rotationkeys.Length > 0)\r
- {\r
- binBVHJointKey rot2 = b.joints[jpos].rotationkeys[state.nextkeyframe_rot];\r
-\r
- if (state.currenttime_rot > rot2.time)\r
- {\r
- state.lastkeyframe_rot++;\r
- state.nextkeyframe_rot++;\r
-\r
- if (state.nextkeyframe_rot >= b.joints[jpos].rotationkeys.Length || (state.nextkeyframe_rot >= state.loopoutframe && b.Loop == true))\r
- {\r
- if (b.Loop == true)\r
- {\r
- state.nextkeyframe_rot = state.loopinframe;\r
- state.currenttime_rot = b.InPoint;\r
-\r
- if (state.lastkeyframe_rot >= b.joints[jpos].rotationkeys.Length)\r
- {\r
- state.lastkeyframe_rot = state.loopinframe;\r
-\r
-\r
- }\r
-\r
- }\r
- else\r
- {\r
- state.nextkeyframe_rot = joint.rotationkeys.Length - 1;\r
- }\r
- }\r
-\r
- if (state.lastkeyframe_rot >= b.joints[jpos].rotationkeys.Length)\r
- {\r
- if (b.Loop == true)\r
- {\r
- state.lastkeyframe_rot = 0;\r
- state.currenttime_rot = 0;\r
-\r
- }\r
- else\r
- {\r
- state.lastkeyframe_rot = joint.rotationkeys.Length - 1;\r
- }\r
- }\r
- }\r
-\r
- binBVHJointKey rot = b.joints[jpos].rotationkeys[state.lastkeyframe_rot];\r
- rot2 = b.joints[jpos].rotationkeys[state.nextkeyframe_rot];\r
-\r
- float deltarot = 0;\r
- if (state.currenttime_rot != (rot.time - b.joints[jpos].rotationkeys[0].time))\r
- {\r
- deltarot = (rot2.time - rot.time) / ((state.currenttime_rot) - (rot.time - b.joints[jpos].rotationkeys[0].time));\r
- }\r
- \r
- if (deltarot < 0)\r
- deltarot = 0;\r
-\r
- if (deltarot > 1)\r
- deltarot = 1;\r
-\r
- rotlerp = Vector3.Lerp(rot.key_element, rot2.key_element, deltarot);\r
-\r
- }\r
-\r
- b.joints[jpos].Tag = (object)state;\r
-\r
- deformbone(joint.Name, poslerp, new Vector3(0, 0, 0), new Quaternion(rotlerp.X, rotlerp.Y, rotlerp.Z));\r
-\r
- jpos++;\r
- }\r
-\r
- mNeedsMeshRebuild = true;\r
- }\r
-\r
- mNeedsUpdate = false;\r
- }\r
- }\r
-\r
- public class Bone\r
- {\r
- public string name;\r
- public Vector3 pos;\r
- public Quaternion rot;\r
- public Vector3 scale;\r
- public Vector3 piviot;\r
-\r
- public Vector3 orig_pos;\r
- public Quaternion orig_rot;\r
- public Vector3 orig_scale;\r
- public Vector3 orig_piviot;\r
-\r
- Matrix4 mDeformMatrix = Matrix4.Identity;\r
-\r
- public Bone parent;\r
-\r
- public List<Bone> children = new List<Bone>();\r
-\r
- public static Dictionary<string, Bone> mBones = new Dictionary<string, Bone>();\r
- public static Dictionary<int, Bone> mIndexedBones = new Dictionary<int, Bone>();\r
- static int boneaddindex = 0;\r
-\r
- private bool rotdirty = true;\r
- private bool posdirty = true;\r
-\r
- private Vector3 mTotalPos;\r
- private Quaternion mTotalRot;\r
-\r
- private Vector3 mDeltaPos;\r
- private Quaternion mDeltaRot;\r
-\r
- public string mParentBone = null;\r
-\r
- public Bone()\r
- {\r
- }\r
-\r
- public Bone(Bone source)\r
- {\r
- name = String.Copy(source.name);\r
- pos = new Vector3(source.pos);\r
- rot = new Quaternion(source.rot);\r
- scale = new Vector3(source.scale);\r
- piviot = new Vector3(source.piviot);\r
-\r
- orig_piviot = source.orig_piviot;\r
- orig_pos = source.orig_pos;\r
- orig_rot = source.orig_rot;\r
- orig_scale = source.orig_scale;\r
-\r
- mParentBone = source.mParentBone;\r
-\r
- mDeformMatrix = new Matrix4(source.mDeformMatrix);\r
- }\r
-\r
- public static void loadbones(string skeletonfilename)\r
- {\r
- mBones.Clear();\r
- string basedir = Directory.GetCurrentDirectory() + System.IO.Path.DirectorySeparatorChar + "character" + System.IO.Path.DirectorySeparatorChar;\r
- XmlDocument skeleton = new XmlDocument();\r
- skeleton.Load(basedir + skeletonfilename);\r
- XmlNode boneslist = skeleton.GetElementsByTagName("linden_skeleton")[0];\r
- addbone(boneslist.ChildNodes[0], null);\r
- }\r
-\r
- public static void addbone(XmlNode bone, Bone parent)\r
- {\r
-\r
- if (bone.Name != "bone")\r
- return;\r
-\r
- Bone b = new Bone();\r
- b.name = bone.Attributes.GetNamedItem("name").Value;\r
-\r
- string pos = bone.Attributes.GetNamedItem("pos").Value;\r
- string[] posparts = pos.Split(' ');\r
- b.pos = new Vector3(float.Parse(posparts[0]), float.Parse(posparts[1]), float.Parse(posparts[2]));\r
- b.orig_pos = new Vector3(b.pos);\r
-\r
- string rot = bone.Attributes.GetNamedItem("rot").Value;\r
- string[] rotparts = rot.Split(' ');\r
- b.rot = Quaternion.CreateFromEulers((float)(float.Parse(rotparts[0]) * Math.PI / 180f), (float)(float.Parse(rotparts[1]) * Math.PI / 180f), (float)(float.Parse(rotparts[2]) * Math.PI / 180f));\r
- b.orig_rot = new Quaternion(b.rot);\r
-\r
- string scale = bone.Attributes.GetNamedItem("scale").Value;\r
- string[] scaleparts = scale.Split(' ');\r
- b.scale = new Vector3(float.Parse(scaleparts[0]), float.Parse(scaleparts[1]), float.Parse(scaleparts[2]));\r
- b.orig_scale = new Vector3(b.scale);\r
-\r
- float[] deform = Math3D.CreateSRTMatrix(new Vector3(1, 1, 1), b.rot, b.orig_pos);\r
- b.mDeformMatrix = new Matrix4(deform[0], deform[1], deform[2], deform[3], deform[4], deform[5], deform[6], deform[7], deform[8], deform[9], deform[10], deform[11], deform[12], deform[13], deform[14], deform[15]);\r
-\r
- //TODO piviot\r
-\r
- b.parent = parent;\r
- if (parent != null)\r
- {\r
- b.mParentBone = parent.name;\r
- parent.children.Add(b);\r
- }\r
-\r
- mBones.Add(b.name, b);\r
- mIndexedBones.Add(boneaddindex++, b);\r
-\r
- Logger.Log("Found bone " + b.name, Helpers.LogLevel.Info);\r
-\r
- foreach (XmlNode childbone in bone.ChildNodes)\r
- {\r
- addbone(childbone, b);\r
- }\r
-\r
- }\r
-\r
- public void deformbone(Vector3 pos, Vector3 scale, Quaternion rot)\r
- {\r
- //float[] deform = Math3D.CreateSRTMatrix(scale, rot, this.orig_pos);\r
- //mDeformMatrix = new Matrix4(deform[0], deform[1], deform[2], deform[3], deform[4], deform[5], deform[6], deform[7], deform[8], deform[9], deform[10], deform[11], deform[12], deform[13], deform[14], deform[15]);\r
- this.pos = Bone.mBones[name].orig_pos + pos;\r
- this.scale = Bone.mBones[name].orig_scale + scale;\r
- this.rot = Bone.mBones[name].orig_rot * rot;\r
-\r
- markdirty();\r
- }\r
-\r
- // If we deform a bone mark this bone and all its children as dirty. \r
- public void markdirty()\r
- {\r
- rotdirty = true;\r
- posdirty = true;\r
- foreach (Bone childbone in children)\r
- {\r
- childbone.markdirty();\r
- }\r
- }\r
-\r
- public Matrix4 getdeform()\r
- {\r
- if (this.parent != null)\r
- {\r
- return mDeformMatrix * parent.getdeform();\r
- }\r
- else\r
- {\r
- return mDeformMatrix;\r
- }\r
- }\r
-\r
- private Vector3 getOffset()\r
- {\r
- if (parent != null)\r
- {\r
- Quaternion totalrot = getParentRot(); // we don't want this joints rotation included\r
- Vector3 parento = parent.getOffset();\r
- Vector3 mepre = pos * scale;\r
- mepre = mepre * totalrot;\r
- mTotalPos = parento + mepre;\r
-\r
- Vector3 orig = getOrigOffset();\r
- mDeltaPos = mTotalPos - orig;\r
-\r
- posdirty = false;\r
-\r
- return mTotalPos;\r
- }\r
- else\r
- {\r
- Vector3 orig = getOrigOffset();\r
- mTotalPos = (pos * scale);\r
- mDeltaPos = mTotalPos - orig;\r
- posdirty = false;\r
- return mTotalPos;\r
-\r
- }\r
- }\r
-\r
- public Vector3 getMyOffset()\r
- {\r
- return pos * scale;\r
- }\r
-\r
- // Try to save some cycles by not recalculating positions and rotations every time\r
- public Vector3 getTotalOffset()\r
- {\r
- if (posdirty == false)\r
- {\r
- return mTotalPos;\r
- }\r
- else\r
- {\r
- return getOffset();\r
- }\r
- }\r
-\r
- public Vector3 getDeltaOffset()\r
- {\r
- if (posdirty == false)\r
- {\r
- return mDeltaPos;\r
- }\r
- else\r
- {\r
- getOffset();\r
- return mDeltaPos;\r
- }\r
- }\r
-\r
- private Vector3 getOrigOffset()\r
- {\r
- if (parent != null)\r
- {\r
- return (parent.getOrigOffset() + orig_pos);\r
- }\r
- else\r
- {\r
- return orig_pos;\r
- }\r
- }\r
-\r
- private static Quaternion getRotation(string bonename)\r
- {\r
- Bone b;\r
- if (mBones.TryGetValue(bonename, out b))\r
- {\r
- return (b.getRotation());\r
- }\r
- else\r
- {\r
- return Quaternion.Identity;\r
- }\r
- }\r
-\r
-\r
- private Quaternion getParentRot()\r
- {\r
- Quaternion totalrot = Quaternion.Identity;\r
-\r
- if (parent != null)\r
- {\r
- totalrot = parent.getRotation();\r
- }\r
-\r
- return totalrot;\r
-\r
- }\r
-\r
- private Quaternion getRotation()\r
- {\r
- Quaternion totalrot = rot;\r
-\r
- if (parent != null)\r
- {\r
- totalrot = parent.getRotation() * rot;\r
- }\r
-\r
- mTotalRot = totalrot;\r
- rotdirty = false;\r
-\r
- return totalrot;\r
- }\r
-\r
- public Quaternion getTotalRotation()\r
- {\r
- if (rotdirty == false)\r
- {\r
- return mTotalRot;\r
- }\r
- else\r
- {\r
- return getRotation();\r
- }\r
- }\r
- }\r
-\r
- public class VisualParamEx\r
- {\r
-\r
- static public Dictionary<int, VisualParamEx> allParams = new Dictionary<int, VisualParamEx>();\r
- static public Dictionary<int, VisualParamEx> deformParams = new Dictionary<int, VisualParamEx>();\r
- static public Dictionary<int, VisualParamEx> morphParams = new Dictionary<int, VisualParamEx>();\r
- static public Dictionary<int, VisualParamEx> drivenParams = new Dictionary<int, VisualParamEx>();\r
- static public SortedList tweakable_params = new SortedList();\r
-\r
- public Dictionary<string, Vector3> BoneDeforms = null;\r
- public Dictionary<string, VolumeDeform> VolumeDeforms = null;\r
- public List<driven> childparams = null;\r
-\r
- public string morphmesh = null;\r
-\r
- enum GroupType\r
- {\r
- VISUAL_PARAM_GROUP_TWEAKABLE = 0,\r
- VISUAL_PARAM_GROUP_ANIMATABLE,\r
- VISUAL_PARAM_GROUP_TWEAKABLE_NO_TRANSMIT,\r
- }\r
-\r
- public struct VolumeDeform\r
- {\r
- public string name;\r
- public Vector3 scale;\r
- public Vector3 pos;\r
- }\r
-\r
- public enum EparamSex\r
- {\r
- SEX_BOTH = 0,\r
- SEX_FEMALE = 1,\r
- SEX_MALE = 2\r
- }\r
-\r
- public enum ParamType\r
- {\r
- TYPE_BONEDEFORM,\r
- TYPE_MORPH,\r
- TYPE_DRIVER,\r
- TYPE_COLOR,\r
- TYPE_LAYER\r
- }\r
-\r
- public struct driven\r
- {\r
- public int id;\r
- public float max1;\r
- public float max2;\r
- public float min1;\r
- public float min2;\r
- public bool hasMinMax;\r
- }\r
-\r
- public string meshname;\r
-\r
- /// <summary>Index of this visual param</summary>\r
- public int ParamID;\r
- /// <summary>Internal name</summary>\r
- public string Name;\r
- /// <summary>Group ID this parameter belongs to</summary>\r
- public int Group;\r
- /// <summary>Name of the wearable this parameter belongs to</summary>\r
- public string Wearable;\r
- /// <summary>Displayable label of this characteristic</summary>\r
- public string Label;\r
- /// <summary>Displayable label for the minimum value of this characteristic</summary>\r
- public string LabelMin;\r
- /// <summary>Displayable label for the maximum value of this characteristic</summary>\r
- public string LabelMax;\r
- /// <summary>Default value</summary>\r
- public float DefaultValue;\r
- /// <summary>Minimum value</summary>\r
- public float MinValue;\r
- /// <summary>Maximum value</summary>\r
- public float MaxValue;\r
- /// <summary>Is this param used for creation of bump layer?</summary>\r
- public bool IsBumpAttribute;\r
- /// <summary>Alpha blending/bump info</summary>\r
- public VisualAlphaParam? AlphaParams;\r
- /// <summary>Color information</summary>\r
- public VisualColorParam? ColorParams;\r
- /// <summary>Array of param IDs that are drivers for this parameter</summary>\r
- public int[] Drivers;\r
- /// <summary>The Avatar Sex that this parameter applies to</summary>\r
- public EparamSex sex;\r
-\r
- public ParamType pType;\r
-\r
- public static int count = 0;\r
-\r
- /// <summary>\r
- /// Set all the values through the constructor\r
- /// </summary>\r
- /// <param name="paramID">Index of this visual param</param>\r
- /// <param name="name">Internal name</param>\r
- /// <param name="group"></param>\r
- /// <param name="wearable"></param>\r
- /// <param name="label">Displayable label of this characteristic</param>\r
- /// <param name="labelMin">Displayable label for the minimum value of this characteristic</param>\r
- /// <param name="labelMax">Displayable label for the maximum value of this characteristic</param>\r
- /// <param name="def">Default value</param>\r
- /// <param name="min">Minimum value</param>\r
- /// <param name="max">Maximum value</param>\r
- /// <param name="isBumpAttribute">Is this param used for creation of bump layer?</param>\r
- /// <param name="drivers">Array of param IDs that are drivers for this parameter</param>\r
- /// <param name="alpha">Alpha blending/bump info</param>\r
- /// <param name="colorParams">Color information</param>\r
- public VisualParamEx(int paramID, string name, int group, string wearable, string label, string labelMin, string labelMax, float def, float min, float max, bool isBumpAttribute, int[] drivers, VisualAlphaParam? alpha, VisualColorParam? colorParams)\r
- {\r
- ParamID = paramID;\r
- Name = name;\r
- Group = group;\r
- Wearable = wearable;\r
- Label = label;\r
- LabelMin = labelMin;\r
- LabelMax = labelMax;\r
- DefaultValue = def;\r
- MaxValue = max;\r
- MinValue = min;\r
- IsBumpAttribute = isBumpAttribute;\r
- Drivers = drivers;\r
- AlphaParams = alpha;\r
- ColorParams = colorParams;\r
- sex = EparamSex.SEX_BOTH;\r
- }\r
-\r
- public VisualParamEx(XmlNode node, ParamType pt)\r
- {\r
- pType = pt;\r
-\r
- ParamID = Int32.Parse(node.Attributes.GetNamedItem("id").Value);\r
- Name = node.Attributes.GetNamedItem("name").Value;\r
- Group = Int32.Parse(node.Attributes.GetNamedItem("group").Value);\r
-\r
- //These dont exist for facal expresion morphs\r
- if (node.Attributes.GetNamedItem("wearable") != null)\r
- Wearable = node.Attributes.GetNamedItem("wearable").Value;\r
-\r
- MinValue = float.Parse(node.Attributes.GetNamedItem("value_min").Value);\r
- MaxValue = float.Parse(node.Attributes.GetNamedItem("value_max").Value);\r
-\r
- // These do not exists for driven parameters\r
- if (node.Attributes.GetNamedItem("label_min") != null)\r
- {\r
- LabelMin = node.Attributes.GetNamedItem("label_min").Value;\r
- }\r
-\r
- if (node.Attributes.GetNamedItem("label_max") != null)\r
- {\r
- LabelMax = node.Attributes.GetNamedItem("label_max").Value;\r
- }\r
-\r
- XmlNode sexnode = node.Attributes.GetNamedItem("sex");\r
-\r
- if (sexnode != null)\r
- {\r
- if (sexnode.Value == "male")\r
- {\r
- sex = EparamSex.SEX_MALE;\r
- }\r
- else\r
- {\r
- sex = EparamSex.SEX_FEMALE;\r
- }\r
-\r
- }\r
-\r
- Group = int.Parse(node.Attributes.GetNamedItem("group").Value);\r
-\r
- if (Group == (int)GroupType.VISUAL_PARAM_GROUP_TWEAKABLE)\r
- {\r
- if (!tweakable_params.ContainsKey(ParamID)) //stupid duplicate shared params\r
- {\r
- tweakable_params.Add(this.ParamID, this);\r
- }\r
- //Logger.Log(String.Format("Adding tweakable paramater ID {0} {1}", count, this.Name), Helpers.LogLevel.Info);\r
- count++;\r
- }\r
-\r
- //TODO other paramaters but these arew concerned with editing the GUI display so not too fussed at the moment\r
-\r
- try\r
- {\r
- allParams.Add(ParamID, this);\r
- }\r
- catch\r
- {\r
- Logger.Log("Duplicate VisualParam in allParams id " + ParamID.ToString(), Helpers.LogLevel.Info);\r
- }\r
-\r
- if (pt == ParamType.TYPE_BONEDEFORM)\r
- {\r
- // If we are in the skeleton section then we also have bone deforms to parse\r
- BoneDeforms = new Dictionary<string, Vector3>();\r
- if (node.HasChildNodes && node.ChildNodes[0].HasChildNodes)\r
- {\r
- ParseBoneDeforms(node.ChildNodes[0].ChildNodes);\r
- }\r
- deformParams.Add(ParamID, this);\r
- }\r
-\r
- if (pt == ParamType.TYPE_MORPH)\r
- {\r
- VolumeDeforms = new Dictionary<string, VolumeDeform>();\r
- if (node.HasChildNodes && node.ChildNodes[0].HasChildNodes)\r
- {\r
- ParseVolumeDeforms(node.ChildNodes[0].ChildNodes);\r
- }\r
-\r
- try\r
- {\r
- morphParams.Add(ParamID, this);\r
- }\r
- catch\r
- {\r
- Logger.Log("Duplicate VisualParam in morphParams id " + ParamID.ToString(), Helpers.LogLevel.Info);\r
- }\r
-\r
- }\r
-\r
- if (pt == ParamType.TYPE_DRIVER)\r
- {\r
- childparams = new List<driven>();\r
- if (node.HasChildNodes && node.ChildNodes[0].HasChildNodes) //LAZY\r
- {\r
- ParseDrivers(node.ChildNodes[0].ChildNodes);\r
- }\r
-\r
- drivenParams.Add(ParamID, this);\r
-\r
- }\r
-\r
- if (pt == ParamType.TYPE_COLOR)\r
- {\r
- if (node.HasChildNodes)\r
- {\r
- foreach (XmlNode colorchild in node.ChildNodes)\r
- {\r
- if (colorchild.Name == "param_color")\r
- {\r
- //TODO extract <value color="50, 25, 5, 255" />\r
- }\r
- }\r
-\r
- }\r
- }\r
-\r
- }\r
-\r
- void ParseBoneDeforms(XmlNodeList deforms)\r
- {\r
- foreach (XmlNode node in deforms)\r
- {\r
- if (node.Name == "bone")\r
- {\r
- string name = node.Attributes.GetNamedItem("name").Value;\r
- Vector3 scale = XmlParseVector(node.Attributes.GetNamedItem("scale").Value);\r
- BoneDeforms.Add(name, scale);\r
- }\r
- }\r
- }\r
-\r
- void ParseVolumeDeforms(XmlNodeList deforms)\r
- {\r
- foreach (XmlNode node in deforms)\r
- {\r
- if (node.Name == "volume_morph")\r
- {\r
- VolumeDeform vd = new VolumeDeform();\r
- vd.name = node.Attributes.GetNamedItem("name").Value;\r
- vd.name = vd.name.ToLower();\r
-\r
- if (node.Attributes.GetNamedItem("scale") != null)\r
- {\r
- vd.scale = XmlParseVector(node.Attributes.GetNamedItem("scale").Value);\r
- }\r
- else\r
- {\r
- vd.scale = new Vector3(0, 0, 0);\r
- }\r
-\r
- if (node.Attributes.GetNamedItem("pos") != null)\r
- {\r
- vd.pos = XmlParseVector(node.Attributes.GetNamedItem("pos").Value);\r
- }\r
- else\r
- {\r
- vd.pos = new Vector3(0f, 0f, 0f);\r
- }\r
-\r
- VolumeDeforms.Add(vd.name, vd);\r
- }\r
- }\r
- }\r
-\r
- void ParseDrivers(XmlNodeList drivennodes)\r
- {\r
- foreach (XmlNode node in drivennodes)\r
- {\r
- if (node.Name == "driven")\r
- {\r
- driven d = new driven();\r
-\r
- d.id = Int32.Parse(node.Attributes.GetNamedItem("id").Value);\r
- XmlNode param = node.Attributes.GetNamedItem("max1");\r
- if (param != null)\r
- {\r
- d.max1 = float.Parse(param.Value);\r
- d.max2 = float.Parse(node.Attributes.GetNamedItem("max2").Value);\r
- d.min1 = float.Parse(node.Attributes.GetNamedItem("min1").Value);\r
- d.max2 = float.Parse(node.Attributes.GetNamedItem("min2").Value);\r
- d.hasMinMax = true;\r
- }\r
- else\r
- {\r
- d.hasMinMax = false;\r
- }\r
-\r
- childparams.Add(d);\r
-\r
- }\r
- }\r
- }\r
-\r
- public static Vector3 XmlParseVector(string data)\r
- {\r
- string[] posparts = data.Split(' ');\r
- return new Vector3(float.Parse(posparts[0]), float.Parse(posparts[1]), float.Parse(posparts[2]));\r
- }\r
-\r
- public static Quaternion XmlParseRotation(string data)\r
- {\r
- string[] rotparts = data.Split(' ');\r
- return Quaternion.CreateFromEulers((float)(float.Parse(rotparts[0]) * Math.PI / 180f), (float)(float.Parse(rotparts[1]) * Math.PI / 180f), (float)(float.Parse(rotparts[2]) * Math.PI / 180f));\r
- }\r
- }\r
-\r
- /*\r
- * Helper classs for reading the static VFS file, call \r
- * staticVFS.readVFSheaders() with the path to the static_data.db2 and static_index.db2 files\r
- * and it will pass and dump in to openmetaverse_data for you\r
- * This should only be needed to be used if LL update the static VFS in order to refresh our data\r
- */\r
-\r
- class VFSblock\r
- {\r
- public int mLocation;\r
- public int mLength;\r
- public int mAccessTime;\r
- public UUID mFileID;\r
- public int mSize;\r
- public AssetType mAssetType;\r
-\r
- public int readblock(byte[] blockdata, int offset)\r
- {\r
-\r
- BitPack input = new BitPack(blockdata, offset);\r
- mLocation = input.UnpackInt();\r
- mLength = input.UnpackInt();\r
- mAccessTime = input.UnpackInt();\r
- mFileID = input.UnpackUUID();\r
- int filetype = input.UnpackShort();\r
- mAssetType = (AssetType)filetype;\r
- mSize = input.UnpackInt();\r
- offset += 34;\r
-\r
- Logger.Log(String.Format("Found header for {0} type {1} length {2} at {3}", mFileID, mAssetType, mSize, mLocation), Helpers.LogLevel.Info);\r
-\r
- return offset;\r
- }\r
-\r
- }\r
-\r
- public class staticVFS\r
- {\r
- public static void readVFSheaders(string datafile, string indexfile)\r
- {\r
- FileStream datastream;\r
- FileStream indexstream;\r
-\r
- datastream = File.Open(datafile, FileMode.Open);\r
- indexstream = File.Open(indexfile, FileMode.Open);\r
-\r
- int offset = 0;\r
-\r
- byte[] blockdata = new byte[indexstream.Length];\r
- indexstream.Read(blockdata, 0, (int)indexstream.Length);\r
-\r
- while (offset < indexstream.Length)\r
- {\r
- VFSblock block = new VFSblock();\r
- offset = block.readblock(blockdata, offset);\r
-\r
- FileStream writer = File.Open(OpenMetaverse.Settings.RESOURCE_DIR + System.IO.Path.DirectorySeparatorChar + block.mFileID.ToString(), FileMode.Create);\r
- byte[] data = new byte[block.mSize];\r
- datastream.Seek(block.mLocation, SeekOrigin.Begin);\r
- datastream.Read(data, 0, block.mSize);\r
- writer.Write(data, 0, block.mSize);\r
- writer.Close();\r
- }\r
-\r
- }\r
- }\r
+//
+// Radegast Metaverse Client
+// Copyright (c) 2009-2014, Radegast Development Team
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are met:
+//
+// * Redistributions of source code must retain the above copyright notice,
+// this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above copyright
+// notice, this list of conditions and the following disclaimer in the
+// documentation and/or other materials provided with the distribution.
+// * Neither the name of the application "Radegast", nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior CreateReflectionTexture permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+//
+// $Id: RenderingHelpers.cs 1136 2011-09-05 22:45:11Z latifer $
+//
+
+using System;
+using System.Collections.Generic;
+using System.Collections;
+using System.Linq;
+using System.Text;
+using System.IO;
+using System.IO.Compression;
+using System.Xml;
+using System.Threading;
+using OpenTK.Graphics.OpenGL;
+using System.Runtime.InteropServices;
+using System.Drawing;
+using System.Drawing.Imaging;
+using OpenMetaverse;
+using OpenMetaverse.Rendering;
+
+namespace Radegast.Rendering
+{
+ [StructLayout(LayoutKind.Sequential)]
+ public struct Color4b
+ {
+ public byte R;
+ public byte G;
+ public byte B;
+ public byte A;
+ }
+
+ [StructLayout(LayoutKind.Explicit)]
+ public struct ColorVertex
+ {
+ [FieldOffset(0)]
+ public Vertex Vertex;
+ [FieldOffset(32)]
+ public Color4b Color;
+ public static int Size = 36;
+ }
+
+ public class TextureInfo
+ {
+ public System.Drawing.Image Texture;
+ public int TexturePointer;
+ public bool HasAlpha;
+ public bool FullAlpha;
+ public bool IsMask;
+ public bool IsInvisible;
+ public UUID TextureID;
+ public bool FetchFailed;
+ }
+
+ public class TextureLoadItem
+ {
+ public FaceData Data;
+ public Primitive Prim;
+ public Primitive.TextureEntryFace TeFace;
+ public byte[] TextureData = null;
+ public byte[] TGAData = null;
+ public bool LoadAssetFromCache = false;
+ public OpenMetaverse.ImageType ImageType = OpenMetaverse.ImageType.Normal;
+ public string BakeName = string.Empty;
+ public UUID AvatarID = UUID.Zero;
+ }
+
+ public enum RenderPass
+ {
+ Picking,
+ Simple,
+ Alpha,
+ Invisible
+ }
+
+ public enum SceneObjectType
+ {
+ None,
+ Primitive,
+ Avatar,
+ }
+
+ /// <summary>
+ /// Base class for all scene objects
+ /// </summary>
+ public abstract class SceneObject : IComparable, IDisposable
+ {
+ #region Public fields
+ /// <summary>Interpolated local position of the object</summary>
+ public Vector3 InterpolatedPosition;
+ /// <summary>Interpolated local rotation of the object/summary>
+ public Quaternion InterpolatedRotation;
+ /// <summary>Rendered position of the object in the region</summary>
+ public Vector3 RenderPosition;
+ /// <summary>Rendered rotationm of the object in the region</summary>
+ public Quaternion RenderRotation;
+ /// <summary>Per frame calculated square of the distance from camera</summary>
+ public float DistanceSquared;
+ /// <summary>Bounding volume of the object</summary>
+ public BoundingVolume BoundingVolume;
+ /// <summary>Was the sim position and distance from camera calculated during this frame</summary>
+ public bool PositionCalculated;
+ /// <summary>Scene object type</summary>
+ public SceneObjectType Type = SceneObjectType.None;
+ /// <summary>Libomv primitive</summary>
+ public virtual Primitive BasePrim { get; set; }
+ /// <summary>Were initial initialization tasks done</summary>
+ public bool Initialized;
+ /// <summary>Is this object disposed</summary>
+ public bool IsDisposed = false;
+ public int AlphaQueryID = -1;
+ public int SimpleQueryID = -1;
+ public bool HasAlphaFaces;
+ public bool HasSimpleFaces;
+ public bool HasInvisibleFaces;
+
+ #endregion Public fields
+
+ uint previousParent = uint.MaxValue;
+
+ /// <summary>
+ /// Cleanup resources used
+ /// </summary>
+ public virtual void Dispose()
+ {
+ IsDisposed = true;
+ }
+
+ /// <summary>
+ /// Task performed the fist time object is set for rendering
+ /// </summary>
+ public virtual void Initialize()
+ {
+ RenderPosition = InterpolatedPosition = BasePrim.Position;
+ RenderRotation = InterpolatedRotation = BasePrim.Rotation;
+ Initialized = true;
+ }
+
+ /// <summary>
+ /// Perform per frame tasks
+ /// </summary>
+ /// <param name="time">Time since the last call (last frame time in seconds)</param>
+ public virtual void Step(float time)
+ {
+ if (BasePrim == null) return;
+
+ // Don't interpolate when parent changes (sit/stand link/unlink)
+ if (previousParent != BasePrim.ParentID)
+ {
+ previousParent = BasePrim.ParentID;
+ InterpolatedPosition = BasePrim.Position;
+ InterpolatedRotation = BasePrim.Rotation;
+ return;
+ }
+
+ // Linear velocity and acceleration
+ if (BasePrim.Velocity != Vector3.Zero)
+ {
+ BasePrim.Position = InterpolatedPosition = BasePrim.Position + BasePrim.Velocity * time
+ * 0.98f * RadegastInstance.GlobalInstance.Client.Network.CurrentSim.Stats.Dilation;
+ BasePrim.Velocity += BasePrim.Acceleration * time;
+ }
+ else if (InterpolatedPosition != BasePrim.Position)
+ {
+ InterpolatedPosition = RHelp.Smoothed1stOrder(InterpolatedPosition, BasePrim.Position, time);
+ }
+
+ // Angular velocity (target omega)
+ if (BasePrim.AngularVelocity != Vector3.Zero)
+ {
+ Vector3 angVel = BasePrim.AngularVelocity;
+ float angle = time * angVel.Length();
+ Quaternion dQ = Quaternion.CreateFromAxisAngle(angVel, angle);
+ InterpolatedRotation = dQ * InterpolatedRotation;
+ }
+ else if (InterpolatedRotation != BasePrim.Rotation && !(this is RenderAvatar))
+ {
+ InterpolatedRotation = Quaternion.Slerp(InterpolatedRotation, BasePrim.Rotation, time * 10f);
+ if (1f - Math.Abs(Quaternion.Dot(InterpolatedRotation, BasePrim.Rotation)) < 0.0001)
+ InterpolatedRotation = BasePrim.Rotation;
+ }
+ else
+ {
+ InterpolatedRotation = BasePrim.Rotation;
+ }
+ }
+
+ /// <summary>
+ /// Render scene object
+ /// </summary>
+ /// <param name="pass">Which pass are we currently in</param>
+ /// <param name="pickingID">ID used to identify which object was picked</param>
+ /// <param name="scene">Main scene renderer</param>
+ /// <param name="time">Time it took to render the last frame</param>
+ public virtual void Render(RenderPass pass, int pickingID, SceneWindow scene, float time)
+ {
+ }
+
+ /// <summary>
+ /// Implementation of the IComparable interface
+ /// used for sorting by distance
+ /// </summary>
+ /// <param name="other">Object we are comparing to</param>
+ /// <returns>Result of the comparison</returns>
+ public virtual int CompareTo(object other)
+ {
+ SceneObject o = (SceneObject)other;
+ if (this.DistanceSquared < o.DistanceSquared)
+ return -1;
+ else if (this.DistanceSquared > o.DistanceSquared)
+ return 1;
+ else
+ return 0;
+ }
+
+ #region Occlusion queries
+ public void StartQuery(RenderPass pass)
+ {
+ if (!RenderSettings.OcclusionCullingEnabled) return;
+
+ if (pass == RenderPass.Simple)
+ {
+ StartSimpleQuery();
+ }
+ else if (pass == RenderPass.Alpha)
+ {
+ StartAlphaQuery();
+ }
+ }
+
+ public void EndQuery(RenderPass pass)
+ {
+ if (!RenderSettings.OcclusionCullingEnabled) return;
+
+ if (pass == RenderPass.Simple)
+ {
+ EndSimpleQuery();
+ }
+ else if (pass == RenderPass.Alpha)
+ {
+ EndAlphaQuery();
+ }
+ }
+
+ public void StartAlphaQuery()
+ {
+ if (!RenderSettings.OcclusionCullingEnabled) return;
+
+ if (AlphaQueryID == -1)
+ {
+ Compat.GenQueries(out AlphaQueryID);
+ }
+ if (AlphaQueryID > 0)
+ {
+ Compat.BeginQuery(QueryTarget.SamplesPassed, AlphaQueryID);
+ }
+ }
+
+ public void EndAlphaQuery()
+ {
+ if (!RenderSettings.OcclusionCullingEnabled) return;
+
+ if (AlphaQueryID > 0)
+ {
+ Compat.EndQuery(QueryTarget.SamplesPassed);
+ }
+ }
+
+ public void StartSimpleQuery()
+ {
+ if (!RenderSettings.OcclusionCullingEnabled) return;
+
+ if (SimpleQueryID == -1)
+ {
+ Compat.GenQueries(out SimpleQueryID);
+ }
+ if (SimpleQueryID > 0)
+ {
+ Compat.BeginQuery(QueryTarget.SamplesPassed, SimpleQueryID);
+ }
+ }
+
+ public void EndSimpleQuery()
+ {
+ if (!RenderSettings.OcclusionCullingEnabled) return;
+
+ if (SimpleQueryID > 0)
+ {
+ Compat.EndQuery(QueryTarget.SamplesPassed);
+ }
+ }
+
+ public bool Occluded()
+ {
+ if (!RenderSettings.OcclusionCullingEnabled) return false;
+
+ if (HasInvisibleFaces) return false;
+
+ if ((SimpleQueryID == -1 && AlphaQueryID == -1))
+ {
+ return false;
+ }
+
+ if ((!HasAlphaFaces && !HasSimpleFaces)) return true;
+
+ int samples = 1;
+ if (HasSimpleFaces && SimpleQueryID > 0)
+ {
+ Compat.GetQueryObject(SimpleQueryID, GetQueryObjectParam.QueryResult, out samples);
+ }
+ if (HasSimpleFaces && samples > 0)
+ {
+ return false;
+ }
+
+ samples = 1;
+ if (HasAlphaFaces && AlphaQueryID > 0)
+ {
+ Compat.GetQueryObject(AlphaQueryID, GetQueryObjectParam.QueryResult, out samples);
+ }
+ if (HasAlphaFaces && samples > 0)
+ {
+ return false;
+ }
+
+ return true;
+ }
+ #endregion Occlusion queries
+ }
+
+ public static class RHelp
+ {
+ public static readonly Vector3 InvalidPosition = new Vector3(99999f, 99999f, 99999f);
+ static float t1 = 0.075f;
+ static float t2 = t1 / 5.7f;
+
+ public static Vector3 Smoothed1stOrder(Vector3 curPos, Vector3 targetPos, float lastFrameTime)
+ {
+ int numIterations = (int)(lastFrameTime * 100);
+ do
+ {
+ curPos += (targetPos - curPos) * t1;
+ numIterations--;
+ }
+ while (numIterations > 0);
+ if (Vector3.DistanceSquared(curPos, targetPos) < 0.00001f)
+ {
+ curPos = targetPos;
+ }
+ return curPos;
+ }
+
+ public static Vector3 Smoothed2ndOrder(Vector3 curPos, Vector3 targetPos, ref Vector3 accel, float lastFrameTime)
+ {
+ int numIterations = (int)(lastFrameTime * 100);
+ do
+ {
+ accel += (targetPos - accel - curPos) * t1;
+ curPos += accel * t2;
+ numIterations--;
+ }
+ while (numIterations > 0);
+ if (Vector3.DistanceSquared(curPos, targetPos) < 0.00001f)
+ {
+ curPos = targetPos;
+ }
+ return curPos;
+ }
+
+ public static OpenTK.Vector2 TKVector3(Vector2 v)
+ {
+ return new OpenTK.Vector2(v.X, v.Y);
+ }
+
+ public static OpenTK.Vector3 TKVector3(Vector3 v)
+ {
+ return new OpenTK.Vector3(v.X, v.Y, v.Z);
+ }
+
+ public static OpenTK.Vector4 TKVector3(Vector4 v)
+ {
+ return new OpenTK.Vector4(v.X, v.Y, v.Z, v.W);
+ }
+
+ public static Vector2 OMVVector2(OpenTK.Vector2 v)
+ {
+ return new Vector2(v.X, v.Y);
+ }
+
+ public static Vector3 OMVVector3(OpenTK.Vector3 v)
+ {
+ return new Vector3(v.X, v.Y, v.Z);
+ }
+
+ public static Vector4 OMVVector4(OpenTK.Vector4 v)
+ {
+ return new Vector4(v.X, v.Y, v.Z, v.W);
+ }
+
+ public static Color WinColor(OpenTK.Graphics.Color4 color)
+ {
+ return Color.FromArgb((int)(color.A * 255), (int)(color.R * 255), (int)(color.G * 255), (int)(color.B * 255));
+ }
+
+ public static Color WinColor(Color4 color)
+ {
+ return Color.FromArgb((int)(color.A * 255), (int)(color.R * 255), (int)(color.G * 255), (int)(color.B * 255));
+ }
+
+ public static int NextPow2(int start)
+ {
+ int pow = 1;
+ while (pow < start) pow *= 2;
+ return pow;
+ }
+
+ #region Cached image save and load
+ public static readonly string RAD_IMG_MAGIC = "radegast_img";
+
+ public static bool LoadCachedImage(UUID textureID, out byte[] tgaData, out bool hasAlpha, out bool fullAlpha, out bool isMask)
+ {
+ tgaData = null;
+ hasAlpha = fullAlpha = isMask = false;
+
+ try
+ {
+ string fname = RadegastInstance.GlobalInstance.ComputeCacheName(RadegastInstance.GlobalInstance.Client.Settings.ASSET_CACHE_DIR, textureID) + ".rzi";
+
+ using (var f = File.Open(fname, FileMode.Open, FileAccess.Read, FileShare.Read))
+ {
+ byte[] header = new byte[36];
+ int i = 0;
+ f.Read(header, 0, header.Length);
+
+ // check if the file is starting with magic string
+ if (RAD_IMG_MAGIC != Utils.BytesToString(header, 0, RAD_IMG_MAGIC.Length))
+ return false;
+ i += RAD_IMG_MAGIC.Length;
+
+ if (header[i++] != 1) // check version
+ return false;
+
+ hasAlpha = header[i++] == 1;
+ fullAlpha = header[i++] == 1;
+ isMask = header[i++] == 1;
+
+ int uncompressedSize = Utils.BytesToInt(header, i);
+ i += 4;
+
+ textureID = new UUID(header, i);
+ i += 16;
+
+ tgaData = new byte[uncompressedSize];
+ using (var compressed = new DeflateStream(f, CompressionMode.Decompress))
+ {
+ int read = 0;
+ while ((read = compressed.Read(tgaData, read, uncompressedSize - read)) > 0) ;
+ }
+ }
+
+ return true;
+ }
+ catch (FileNotFoundException) { }
+ catch (Exception ex)
+ {
+ Logger.DebugLog(string.Format("Failed to load radegast cache file {0}: {1}", textureID, ex.Message));
+ }
+ return false;
+ }
+
+ public static bool SaveCachedImage(byte[] tgaData, UUID textureID, bool hasAlpha, bool fullAlpha, bool isMask)
+ {
+ try
+ {
+ string fname = RadegastInstance.GlobalInstance.ComputeCacheName(RadegastInstance.GlobalInstance.Client.Settings.ASSET_CACHE_DIR, textureID) + ".rzi";
+
+ using (var f = File.Open(fname, FileMode.Create, FileAccess.Write, FileShare.None))
+ {
+ int i = 0;
+ // magic header
+ f.Write(Utils.StringToBytes(RAD_IMG_MAGIC), 0, RAD_IMG_MAGIC.Length);
+ i += RAD_IMG_MAGIC.Length;
+
+ // version
+ f.WriteByte((byte)1);
+ i++;
+
+ // texture info
+ f.WriteByte(hasAlpha ? (byte)1 : (byte)0);
+ f.WriteByte(fullAlpha ? (byte)1 : (byte)0);
+ f.WriteByte(isMask ? (byte)1 : (byte)0);
+ i += 3;
+
+ // texture size
+ byte[] uncompressedSize = Utils.IntToBytes(tgaData.Length);
+ f.Write(uncompressedSize, 0, uncompressedSize.Length);
+ i += uncompressedSize.Length;
+
+ // texture id
+ byte[] id = new byte[16];
+ textureID.ToBytes(id, 0);
+ f.Write(id, 0, 16);
+ i += 16;
+
+ // compressed texture data
+ using (var compressed = new DeflateStream(f, CompressionMode.Compress))
+ {
+ compressed.Write(tgaData, 0, tgaData.Length);
+ }
+ }
+ return true;
+ }
+ catch (Exception ex)
+ {
+ Logger.DebugLog(string.Format("Failed to save radegast cache file {0}: {1}", textureID, ex.Message));
+ return false;
+ }
+ }
+ #endregion Cached image save and load
+
+ #region Static vertices and indices for a cube (used for bounding box drawing)
+ /**********************************************
+ 5 --- 4
+ /| /|
+ 1 --- 0 |
+ | 6 --| 7
+ |/ |/
+ 2 --- 3
+ ***********************************************/
+ public static readonly float[] CubeVertices = new float[]
+ {
+ 0.5f, 0.5f, 0.5f, // 0
+ -0.5f, 0.5f, 0.5f, // 1
+ -0.5f, -0.5f, 0.5f, // 2
+ 0.5f, -0.5f, 0.5f, // 3
+ 0.5f, 0.5f, -0.5f, // 4
+ -0.5f, 0.5f, -0.5f, // 5
+ -0.5f, -0.5f, -0.5f, // 6
+ 0.5f, -0.5f, -0.5f // 7
+ };
+
+ public static readonly ushort[] CubeIndices = new ushort[]
+ {
+ 0, 1, 2, 3, // Front Face
+ 4, 5, 6, 7, // Back Face
+ 1, 2, 6, 5, // Left Face
+ 0, 3, 7, 4, // Right Face
+ 0, 1, 5, 4, // Top Face
+ 2, 3, 7, 6 // Bottom Face
+ };
+ #endregion Static vertices and indices for a cube (used for bounding box drawing)
+
+ public static int GLLoadImage(Bitmap bitmap, bool hasAlpha)
+ {
+ return GLLoadImage(bitmap, hasAlpha, true);
+ }
+
+ public static int GLLoadImage(Bitmap bitmap, bool hasAlpha, bool useMipmap)
+ {
+ useMipmap = useMipmap && RenderSettings.HasMipmap;
+ int ret = -1;
+ GL.GenTextures(1, out ret);
+ GL.BindTexture(TextureTarget.Texture2D, ret);
+
+ Rectangle rectangle = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
+
+ BitmapData bitmapData =
+ bitmap.LockBits(
+ rectangle,
+ ImageLockMode.ReadOnly,
+ hasAlpha ? System.Drawing.Imaging.PixelFormat.Format32bppArgb : System.Drawing.Imaging.PixelFormat.Format24bppRgb);
+
+ GL.TexImage2D(
+ TextureTarget.Texture2D,
+ 0,
+ hasAlpha ? PixelInternalFormat.Rgba : PixelInternalFormat.Rgb8,
+ bitmap.Width,
+ bitmap.Height,
+ 0,
+ hasAlpha ? OpenTK.Graphics.OpenGL.PixelFormat.Bgra : OpenTK.Graphics.OpenGL.PixelFormat.Bgr,
+ PixelType.UnsignedByte,
+ bitmapData.Scan0);
+
+ GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);
+ GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.Repeat);
+ GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.Repeat);
+ if (useMipmap)
+ {
+ GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.LinearMipmapLinear);
+ GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.GenerateMipmap, 1);
+ GL.GenerateMipmap(GenerateMipmapTarget.Texture2D);
+ }
+ else
+ {
+ GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear);
+ }
+
+ bitmap.UnlockBits(bitmapData);
+ return ret;
+ }
+
+ public static void Draw2DBox(float x, float y, float width, float height, float depth)
+ {
+ GL.Begin(BeginMode.Quads);
+ {
+ GL.TexCoord2(0, 1);
+ GL.Vertex3(x, y, depth);
+ GL.TexCoord2(1, 1);
+ GL.Vertex3(x + width, y, depth);
+ GL.TexCoord2(1, 0);
+ GL.Vertex3(x + width, y + height, depth);
+ GL.TexCoord2(0, 0);
+ GL.Vertex3(x, y + height, depth);
+ }
+ GL.End();
+ }
+
+ public static void ResetMaterial()
+ {
+ GL.Material(MaterialFace.FrontAndBack, MaterialParameter.Ambient, new float[] { 0.2f, 0.2f, 0.2f, 1.0f });
+ GL.Material(MaterialFace.FrontAndBack, MaterialParameter.Diffuse, new float[] { 0.8f, 0.8f, 0.8f, 1.0f });
+ GL.Material(MaterialFace.FrontAndBack, MaterialParameter.Specular, new float[] { 0f, 0f, 0f, 1.0f });
+ GL.Material(MaterialFace.FrontAndBack, MaterialParameter.Emission, new float[] { 0f, 0f, 0f, 1.0f });
+ GL.Material(MaterialFace.FrontAndBack, MaterialParameter.Shininess, 0f);
+ ShaderProgram.Stop();
+ }
+ }
+
+ /// <summary>
+ /// Represents camera object
+ /// </summary>
+ public class Camera
+ {
+ /// <summary>
+ /// Indicates that there was manual camera movement, stop tracking objects
+ /// </summary>
+ public bool Manual;
+ Vector3 mPosition;
+ Vector3 mFocalPoint;
+ bool mModified;
+
+ /// <summary>Camera position</summary>
+ public Vector3 Position
+ {
+ get
+ {
+ return mPosition;
+ }
+
+ set
+ {
+ if (mPosition != value)
+ {
+ mPosition = value;
+ Modify();
+ }
+ }
+ }
+
+ /// <summary>Camera target</summary>
+ public Vector3 FocalPoint
+ {
+ get
+ {
+ return mFocalPoint;
+ }
+
+ set
+ {
+ if (mFocalPoint != value)
+ {
+ mFocalPoint = value;
+ Modify();
+ }
+ }
+ }
+
+ /// <summary>Zoom level</summary>
+ public float Zoom;
+ /// <summary>Draw distance</summary>
+ public float Far;
+ /// <summary>Has camera been modified</summary>
+ public bool Modified { get { return mModified; } set { mModified = value; } }
+
+ public float TimeToTarget = 0f;
+
+ public Vector3 RenderPosition;
+ public Vector3 RenderFocalPoint;
+
+ void Modify()
+ {
+ mModified = true;
+ }
+
+ public void Step(float time)
+ {
+ if (RenderPosition != Position)
+ {
+ RenderPosition = RHelp.Smoothed1stOrder(RenderPosition, Position, time);
+ Modified = true;
+ }
+ if (RenderFocalPoint != FocalPoint)
+ {
+ RenderFocalPoint = RHelp.Smoothed1stOrder(RenderFocalPoint, FocalPoint, time);
+ Modified = true;
+ }
+ }
+
+#if OBSOLETE_CODE
+ [Obsolete("Use Step(), left in here for reference")]
+ public void Step2(float time)
+ {
+ TimeToTarget -= time;
+ if (TimeToTarget <= time)
+ {
+ EndMove();
+ return;
+ }
+
+ mModified = true;
+
+ float pctElapsed = time / TimeToTarget;
+
+ if (RenderPosition != Position)
+ {
+ float distance = Vector3.Distance(RenderPosition, Position);
+ RenderPosition = Vector3.Lerp(RenderPosition, Position, distance * pctElapsed);
+ }
+
+ if (RenderFocalPoint != FocalPoint)
+ {
+ RenderFocalPoint = Interpolate(RenderFocalPoint, FocalPoint, pctElapsed);
+ }
+ }
+
+ Vector3 Interpolate(Vector3 start, Vector3 end, float fraction)
+ {
+ float distance = Vector3.Distance(start, end);
+ Vector3 direction = end - start;
+ return start + direction * fraction;
+ }
+
+ public void EndMove()
+ {
+ mModified = true;
+ TimeToTarget = 0;
+ RenderPosition = Position;
+ RenderFocalPoint = FocalPoint;
+ }
+#endif
+
+ public void Pan(float deltaX, float deltaY)
+ {
+ Manual = true;
+ Vector3 direction = Position - FocalPoint;
+ direction.Normalize();
+ Vector3 vy = direction % Vector3.UnitZ;
+ Vector3 vx = vy % direction;
+ Vector3 vxy = vx * deltaY + vy * deltaX;
+ Position += vxy;
+ FocalPoint += vxy;
+ }
+
+ public void Rotate(float delta, bool horizontal)
+ {
+ Manual = true;
+ Vector3 direction = Position - FocalPoint;
+ if (horizontal)
+ {
+ Position = FocalPoint + direction * new Quaternion(0f, 0f, (float)Math.Sin(delta), (float)Math.Cos(delta));
+ }
+ else
+ {
+ Position = FocalPoint + direction * Quaternion.CreateFromAxisAngle(direction % Vector3.UnitZ, delta);
+ }
+ }
+
+ public void MoveToTarget(float delta)
+ {
+ Manual = true;
+ Position += (Position - FocalPoint) * delta;
+ }
+
+ /// <summary>
+ /// Sets the world in perspective of the camera
+ /// </summary>
+ public void LookAt()
+ {
+ OpenTK.Matrix4 lookAt = OpenTK.Matrix4.LookAt(
+ RenderPosition.X, RenderPosition.Y, RenderPosition.Z,
+ RenderFocalPoint.X, RenderFocalPoint.Y, RenderFocalPoint.Z,
+ 0f, 0f, 1f);
+ GL.MultMatrix(ref lookAt);
+ }
+ }
+
+ public static class MeshToOBJ
+ {
+ public static bool MeshesToOBJ(Dictionary<uint, FacetedMesh> meshes, string filename)
+ {
+ StringBuilder obj = new StringBuilder();
+ StringBuilder mtl = new StringBuilder();
+
+ FileInfo objFileInfo = new FileInfo(filename);
+
+ string mtlFilename = objFileInfo.FullName.Substring(objFileInfo.DirectoryName.Length + 1,
+ objFileInfo.FullName.Length - (objFileInfo.DirectoryName.Length + 1) - 4) + ".mtl";
+
+ obj.AppendLine("# Created by libprimrender");
+ obj.AppendLine("mtllib ./" + mtlFilename);
+ obj.AppendLine();
+
+ mtl.AppendLine("# Created by libprimrender");
+ mtl.AppendLine();
+
+ int primNr = 0;
+ foreach (FacetedMesh mesh in meshes.Values)
+ {
+ for (int j = 0; j < mesh.Faces.Count; j++)
+ {
+ Face face = mesh.Faces[j];
+
+ if (face.Vertices.Count > 2)
+ {
+ string mtlName = String.Format("material{0}-{1}", primNr, face.ID);
+ Primitive.TextureEntryFace tex = face.TextureFace;
+ string texName = tex.TextureID.ToString() + ".tga";
+
+ // FIXME: Convert the source to TGA (if needed) and copy to the destination
+
+ float shiny = 0.00f;
+ switch (tex.Shiny)
+ {
+ case Shininess.High:
+ shiny = 1.00f;
+ break;
+ case Shininess.Medium:
+ shiny = 0.66f;
+ break;
+ case Shininess.Low:
+ shiny = 0.33f;
+ break;
+ }
+
+ obj.AppendFormat("g face{0}-{1}{2}", primNr, face.ID, Environment.NewLine);
+
+ mtl.AppendLine("newmtl " + mtlName);
+ mtl.AppendFormat("Ka {0} {1} {2}{3}", tex.RGBA.R, tex.RGBA.G, tex.RGBA.B, Environment.NewLine);
+ mtl.AppendFormat("Kd {0} {1} {2}{3}", tex.RGBA.R, tex.RGBA.G, tex.RGBA.B, Environment.NewLine);
+ //mtl.AppendFormat("Ks {0} {1} {2}{3}");
+ mtl.AppendLine("Tr " + tex.RGBA.A);
+ mtl.AppendLine("Ns " + shiny);
+ mtl.AppendLine("illum 1");
+ if (tex.TextureID != UUID.Zero && tex.TextureID != Primitive.TextureEntry.WHITE_TEXTURE)
+ mtl.AppendLine("map_Kd ./" + texName);
+ mtl.AppendLine();
+
+ // Write the vertices, texture coordinates, and vertex normals for this side
+ for (int k = 0; k < face.Vertices.Count; k++)
+ {
+ Vertex vertex = face.Vertices[k];
+
+ #region Vertex
+
+ Vector3 pos = vertex.Position;
+
+ // Apply scaling
+ pos *= mesh.Prim.Scale;
+
+ // Apply rotation
+ pos *= mesh.Prim.Rotation;
+
+ // The root prim position is sim-relative, while child prim positions are
+ // parent-relative. We want to apply parent-relative translations but not
+ // sim-relative ones
+ if (mesh.Prim.ParentID != 0)
+ pos += mesh.Prim.Position;
+
+ obj.AppendFormat("v {0} {1} {2}{3}", pos.X, pos.Y, pos.Z, Environment.NewLine);
+
+ #endregion Vertex
+
+ #region Texture Coord
+
+ obj.AppendFormat("vt {0} {1}{2}", vertex.TexCoord.X, vertex.TexCoord.Y,
+ Environment.NewLine);
+
+ #endregion Texture Coord
+
+ #region Vertex Normal
+
+ // HACK: Sometimes normals are getting set to <NaN,NaN,NaN>
+ if (!Single.IsNaN(vertex.Normal.X) && !Single.IsNaN(vertex.Normal.Y) && !Single.IsNaN(vertex.Normal.Z))
+ obj.AppendFormat("vn {0} {1} {2}{3}", vertex.Normal.X, vertex.Normal.Y, vertex.Normal.Z,
+ Environment.NewLine);
+ else
+ obj.AppendLine("vn 0.0 1.0 0.0");
+
+ #endregion Vertex Normal
+ }
+
+ obj.AppendFormat("# {0} vertices{1}", face.Vertices.Count, Environment.NewLine);
+ obj.AppendLine();
+ obj.AppendLine("usemtl " + mtlName);
+
+ #region Elements
+
+ // Write all of the faces (triangles) for this side
+ for (int k = 0; k < face.Indices.Count / 3; k++)
+ {
+ obj.AppendFormat("f -{0}/-{0}/-{0} -{1}/-{1}/-{1} -{2}/-{2}/-{2}{3}",
+ face.Vertices.Count - face.Indices[k * 3 + 0],
+ face.Vertices.Count - face.Indices[k * 3 + 1],
+ face.Vertices.Count - face.Indices[k * 3 + 2],
+ Environment.NewLine);
+ }
+
+ obj.AppendFormat("# {0} elements{1}", face.Indices.Count / 3, Environment.NewLine);
+ obj.AppendLine();
+
+ #endregion Elements
+ }
+ }
+ primNr++;
+ }
+
+ try
+ {
+ File.WriteAllText(filename, obj.ToString());
+ File.WriteAllText(mtlFilename, mtl.ToString());
+ }
+ catch (Exception)
+ {
+ return false;
+ }
+
+ return true;
+ }
+ }
+
+ public static class Math3D
+ {
+ // Column-major:
+ // | 0 4 8 12 |
+ // | 1 5 9 13 |
+ // | 2 6 10 14 |
+ // | 3 7 11 15 |
+
+ public static float[] CreateTranslationMatrix(Vector3 v)
+ {
+ float[] mat = new float[16];
+
+ mat[12] = v.X;
+ mat[13] = v.Y;
+ mat[14] = v.Z;
+ mat[0] = mat[5] = mat[10] = mat[15] = 1;
+
+ return mat;
+ }
+
+ public static float[] CreateRotationMatrix(Quaternion q)
+ {
+ float[] mat = new float[16];
+
+ // Transpose the quaternion (don't ask me why)
+ q.X = q.X * -1f;
+ q.Y = q.Y * -1f;
+ q.Z = q.Z * -1f;
+
+ float x2 = q.X + q.X;
+ float y2 = q.Y + q.Y;
+ float z2 = q.Z + q.Z;
+ float xx = q.X * x2;
+ float xy = q.X * y2;
+ float xz = q.X * z2;
+ float yy = q.Y * y2;
+ float yz = q.Y * z2;
+ float zz = q.Z * z2;
+ float wx = q.W * x2;
+ float wy = q.W * y2;
+ float wz = q.W * z2;
+
+ mat[0] = 1.0f - (yy + zz);
+ mat[1] = xy - wz;
+ mat[2] = xz + wy;
+ mat[3] = 0.0f;
+
+ mat[4] = xy + wz;
+ mat[5] = 1.0f - (xx + zz);
+ mat[6] = yz - wx;
+ mat[7] = 0.0f;
+
+ mat[8] = xz - wy;
+ mat[9] = yz + wx;
+ mat[10] = 1.0f - (xx + yy);
+ mat[11] = 0.0f;
+
+ mat[12] = 0.0f;
+ mat[13] = 0.0f;
+ mat[14] = 0.0f;
+ mat[15] = 1.0f;
+
+ return mat;
+ }
+
+ public static float[] CreateSRTMatrix(Vector3 scale, Quaternion q, Vector3 pos)
+ {
+ float[] mat = new float[16];
+
+ // Transpose the quaternion (don't ask me why)
+ q.X = q.X * -1f;
+ q.Y = q.Y * -1f;
+ q.Z = q.Z * -1f;
+
+ float x2 = q.X + q.X;
+ float y2 = q.Y + q.Y;
+ float z2 = q.Z + q.Z;
+ float xx = q.X * x2;
+ float xy = q.X * y2;
+ float xz = q.X * z2;
+ float yy = q.Y * y2;
+ float yz = q.Y * z2;
+ float zz = q.Z * z2;
+ float wx = q.W * x2;
+ float wy = q.W * y2;
+ float wz = q.W * z2;
+
+ mat[0] = (1.0f - (yy + zz)) * scale.X;
+ mat[1] = (xy - wz) * scale.X;
+ mat[2] = (xz + wy) * scale.X;
+ mat[3] = 0.0f;
+
+ mat[4] = (xy + wz) * scale.Y;
+ mat[5] = (1.0f - (xx + zz)) * scale.Y;
+ mat[6] = (yz - wx) * scale.Y;
+ mat[7] = 0.0f;
+
+ mat[8] = (xz - wy) * scale.Z;
+ mat[9] = (yz + wx) * scale.Z;
+ mat[10] = (1.0f - (xx + yy)) * scale.Z;
+ mat[11] = 0.0f;
+
+ //Positional parts
+ mat[12] = pos.X;
+ mat[13] = pos.Y;
+ mat[14] = pos.Z;
+ mat[15] = 1.0f;
+
+ return mat;
+ }
+
+
+ public static float[] CreateScaleMatrix(Vector3 v)
+ {
+ float[] mat = new float[16];
+
+ mat[0] = v.X;
+ mat[5] = v.Y;
+ mat[10] = v.Z;
+ mat[15] = 1;
+
+ return mat;
+ }
+
+ public static float[] Lerp(float[] matrix1, float[] matrix2, float amount)
+ {
+
+ float[] lerp = new float[16];
+ //Probably not doing this as a loop is cheaper(unrolling)
+ //also for performance we probably should not create new objects
+ // but meh.
+ for (int x = 0; x < 16; x++)
+ {
+ lerp[x] = matrix1[x] + ((matrix2[x] - matrix1[x]) * amount);
+ }
+
+ return lerp;
+ }
+
+
+ public static bool GluProject(OpenTK.Vector3 objPos, OpenTK.Matrix4 modelMatrix, OpenTK.Matrix4 projMatrix, int[] viewport, out OpenTK.Vector3 screenPos)
+ {
+ OpenTK.Vector4 _in;
+ OpenTK.Vector4 _out;
+
+ _in.X = objPos.X;
+ _in.Y = objPos.Y;
+ _in.Z = objPos.Z;
+ _in.W = 1.0f;
+
+ _out = OpenTK.Vector4.Transform(_in, modelMatrix);
+ _in = OpenTK.Vector4.Transform(_out, projMatrix);
+
+ if (_in.W <= 0.0)
+ {
+ screenPos = OpenTK.Vector3.Zero;
+ return false;
+ }
+
+ _in.X /= _in.W;
+ _in.Y /= _in.W;
+ _in.Z /= _in.W;
+ /* Map x, y and z to range 0-1 */
+ _in.X = _in.X * 0.5f + 0.5f;
+ _in.Y = _in.Y * 0.5f + 0.5f;
+ _in.Z = _in.Z * 0.5f + 0.5f;
+
+ /* Map x,y to viewport */
+ _in.X = _in.X * viewport[2] + viewport[0];
+ _in.Y = _in.Y * viewport[3] + viewport[1];
+
+ screenPos.X = _in.X;
+ screenPos.Y = _in.Y;
+ screenPos.Z = _in.Z;
+
+ return true;
+ }
+
+ public static bool GluUnProject(float winx, float winy, float winz, OpenTK.Matrix4 modelMatrix, OpenTK.Matrix4 projMatrix, int[] viewport, out OpenTK.Vector3 pos)
+ {
+ OpenTK.Matrix4 finalMatrix;
+ OpenTK.Vector4 _in;
+ OpenTK.Vector4 _out;
+
+ finalMatrix = OpenTK.Matrix4.Mult(modelMatrix, projMatrix);
+
+ finalMatrix.Invert();
+
+ _in.X = winx;
+ _in.Y = winy;
+ _in.Z = winz;
+ _in.W = 1.0f;
+
+ /* Map x and y from window coordinates */
+ _in.X = (_in.X - viewport[0]) / viewport[2];
+ _in.Y = (_in.Y - viewport[1]) / viewport[3];
+
+ pos = OpenTK.Vector3.Zero;
+
+ /* Map to range -1 to 1 */
+ _in.X = _in.X * 2 - 1;
+ _in.Y = _in.Y * 2 - 1;
+ _in.Z = _in.Z * 2 - 1;
+
+ //__gluMultMatrixVecd(finalMatrix, _in, _out);
+ // check if this works:
+ _out = OpenTK.Vector4.Transform(_in, finalMatrix);
+
+ if (_out.W == 0.0f)
+ return false;
+ _out.X /= _out.W;
+ _out.Y /= _out.W;
+ _out.Z /= _out.W;
+ pos.X = _out.X;
+ pos.Y = _out.Y;
+ pos.Z = _out.Z;
+ return true;
+ }
+
+ public static double[] AbovePlane(double height)
+ {
+ return new double[] { 0, 0, 1, -height };
+ }
+
+ public static double[] BelowPlane(double height)
+ {
+ return new double[] { 0, 0, -1, height };
+ }
+ }
+
+ /*
+ * Helper classs for reading the static VFS file, call
+ * staticVFS.readVFSheaders() with the path to the static_data.db2 and static_index.db2 files
+ * and it will pass and dump in to openmetaverse_data for you
+ * This should only be needed to be used if LL update the static VFS in order to refresh our data
+ */
+
+ class VFSblock
+ {
+ public int mLocation;
+ public int mLength;
+ public int mAccessTime;
+ public UUID mFileID;
+ public int mSize;
+ public AssetType mAssetType;
+
+ public int readblock(byte[] blockdata, int offset)
+ {
+
+ BitPack input = new BitPack(blockdata, offset);
+ mLocation = input.UnpackInt();
+ mLength = input.UnpackInt();
+ mAccessTime = input.UnpackInt();
+ mFileID = input.UnpackUUID();
+ int filetype = input.UnpackShort();
+ mAssetType = (AssetType)filetype;
+ mSize = input.UnpackInt();
+ offset += 34;
+
+ Logger.Log(String.Format("Found header for {0} type {1} length {2} at {3}", mFileID, mAssetType, mSize, mLocation), Helpers.LogLevel.Info);
+
+ return offset;
+ }
+
+ }
+
+ public class staticVFS
+ {
+ public static void readVFSheaders(string datafile, string indexfile)
+ {
+ FileStream datastream;
+ FileStream indexstream;
+
+ datastream = File.Open(datafile, FileMode.Open);
+ indexstream = File.Open(indexfile, FileMode.Open);
+
+ int offset = 0;
+
+ byte[] blockdata = new byte[indexstream.Length];
+ indexstream.Read(blockdata, 0, (int)indexstream.Length);
+
+ while (offset < indexstream.Length)
+ {
+ VFSblock block = new VFSblock();
+ offset = block.readblock(blockdata, offset);
+
+ FileStream writer = File.Open(OpenMetaverse.Settings.RESOURCE_DIR + System.IO.Path.DirectorySeparatorChar + block.mFileID.ToString(), FileMode.Create);
+ byte[] data = new byte[block.mSize];
+ datastream.Seek(block.mLocation, SeekOrigin.Begin);
+ datastream.Read(data, 0, block.mSize);
+ writer.Write(data, 0, block.mSize);
+ writer.Close();
+ }
+
+ }
+ }
}
\ No newline at end of file