OSDN Git Service

* Modified camera control to mimic inferior model found in other viewers
[radegast/radegast.git] / Radegast / GUI / Rendering / RenderingHelpers.cs
1 // \r
2 // Radegast Metaverse Client\r
3 // Copyright (c) 2009-2011, Radegast Development Team\r
4 // All rights reserved.\r
5 // \r
6 // Redistribution and use in source and binary forms, with or without\r
7 // modification, are permitted provided that the following conditions are met:\r
8 // \r
9 //     * Redistributions of source code must retain the above copyright notice,\r
10 //       this list of conditions and the following disclaimer.\r
11 //     * Redistributions in binary form must reproduce the above copyright\r
12 //       notice, this list of conditions and the following disclaimer in the\r
13 //       documentation and/or other materials provided with the distribution.\r
14 //     * Neither the name of the application "Radegast", nor the names of its\r
15 //       contributors may be used to endorse or promote products derived from\r
16 //       this software without specific prior CreateReflectionTexture permission.\r
17 // \r
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"\r
19 // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r
20 // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\r
21 // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\r
22 // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\r
23 // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\r
24 // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\r
25 // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\r
26 // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\r
27 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r
28 //\r
29 // $Id$\r
30 //\r
31 \r
32 using System;\r
33 using System.Collections.Generic;\r
34 using System.Collections;\r
35 using System.Linq;\r
36 using System.Text;\r
37 using System.IO;\r
38 using System.IO.Compression;\r
39 using System.Xml;\r
40 using System.Threading;\r
41 using OpenTK.Graphics.OpenGL;\r
42 using System.Runtime.InteropServices;\r
43 using System.Drawing;\r
44 using System.Drawing.Imaging;\r
45 using OpenMetaverse;\r
46 using OpenMetaverse.Rendering;\r
47 \r
48 namespace Radegast.Rendering\r
49 {\r
50     [StructLayout(LayoutKind.Sequential)]\r
51     public struct Color4b\r
52     {\r
53         public byte R;\r
54         public byte G;\r
55         public byte B;\r
56         public byte A;\r
57     }\r
58 \r
59     [StructLayout(LayoutKind.Explicit)]\r
60     public struct ColorVertex\r
61     {\r
62         [FieldOffset(0)]\r
63         public Vertex Vertex;\r
64         [FieldOffset(32)]\r
65         public Color4b Color;\r
66         public static int Size = 36;\r
67     }\r
68 \r
69     public class TextureInfo\r
70     {\r
71         public System.Drawing.Image Texture;\r
72         public int TexturePointer;\r
73         public bool HasAlpha;\r
74         public bool FullAlpha;\r
75         public bool IsMask;\r
76         public UUID TextureID;\r
77         public bool FetchFailed;\r
78     }\r
79 \r
80     public class TextureLoadItem\r
81     {\r
82         public FaceData Data;\r
83         public Primitive Prim;\r
84         public Primitive.TextureEntryFace TeFace;\r
85         public byte[] TextureData = null;\r
86         public byte[] TGAData = null;\r
87         public bool LoadAssetFromCache = false;\r
88     }\r
89 \r
90     public enum RenderPass\r
91     {\r
92         Picking,\r
93         Simple,\r
94         Alpha\r
95     }\r
96 \r
97     public enum SceneObjectType\r
98     {\r
99         None,\r
100         Primitive,\r
101         Avatar,\r
102     }\r
103 \r
104     /// <summary>\r
105     /// Base class for all scene objects\r
106     /// </summary>\r
107     public abstract class SceneObject : IComparable, IDisposable\r
108     {\r
109         #region Public fields\r
110         /// <summary>Interpolated local position of the object</summary>\r
111         public Vector3 InterpolatedPosition;\r
112         /// <summary>Interpolated local rotation of the object/summary>\r
113         public Quaternion InterpolatedRotation;\r
114         /// <summary>Rendered position of the object in the region</summary>\r
115         public Vector3 RenderPosition;\r
116         /// <summary>Rendered rotationm of the object in the region</summary>\r
117         public Quaternion RenderRotation;\r
118         /// <summary>Per frame calculated square of the distance from camera</summary>\r
119         public float DistanceSquared;\r
120         /// <summary>Bounding volume of the object</summary>\r
121         public BoundingVolume BoundingVolume;\r
122         /// <summary>Was the sim position and distance from camera calculated during this frame</summary>\r
123         public bool PositionCalculated;\r
124         /// <summary>Scene object type</summary>\r
125         public SceneObjectType Type = SceneObjectType.None;\r
126         /// <summary>Libomv primitive</summary>\r
127         public virtual Primitive BasePrim { get; set; }\r
128         /// <summary>Were initial initialization tasks done</summary>\r
129         public bool Initialized;\r
130         /// <summary>Is this object disposed</summary>\r
131         public bool IsDisposed = false;\r
132         public int AlphaQueryID = -1;\r
133         public int SimpleQueryID = -1;\r
134         public bool HasAlphaFaces;\r
135         public bool HasSimpleFaces;\r
136 \r
137         #endregion Public fields\r
138 \r
139         uint previousParent = uint.MaxValue;\r
140 \r
141         /// <summary>\r
142         /// Cleanup resources used\r
143         /// </summary>\r
144         public virtual void Dispose()\r
145         {\r
146             IsDisposed = true;\r
147         }\r
148 \r
149         /// <summary>\r
150         /// Task performed the fist time object is set for rendering\r
151         /// </summary>\r
152         public virtual void Initialize()\r
153         {\r
154             RenderPosition = InterpolatedPosition = BasePrim.Position;\r
155             RenderRotation = InterpolatedRotation = BasePrim.Rotation;\r
156             Initialized = true;\r
157         }\r
158 \r
159         /// <summary>\r
160         /// Perform per frame tasks\r
161         /// </summary>\r
162         /// <param name="time">Time since the last call (last frame time in seconds)</param>\r
163         public virtual void Step(float time)\r
164         {\r
165             // Don't interpolate when parent changes (sit/stand link/unlink)\r
166             if (previousParent != BasePrim.ParentID)\r
167             {\r
168                 previousParent = BasePrim.ParentID;\r
169                 InterpolatedPosition = BasePrim.Position;\r
170                 InterpolatedRotation = BasePrim.Rotation;\r
171                 return;\r
172             }\r
173 \r
174             // Linear velocity and acceleration\r
175             if (BasePrim.Velocity != Vector3.Zero)\r
176             {\r
177                 BasePrim.Position = InterpolatedPosition = BasePrim.Position + BasePrim.Velocity * time\r
178                     * 0.98f * RadegastInstance.GlobalInstance.Client.Network.CurrentSim.Stats.Dilation;\r
179                 BasePrim.Velocity += BasePrim.Acceleration * time;\r
180             }\r
181             else if (InterpolatedPosition != BasePrim.Position)\r
182             {\r
183                 InterpolatedPosition = RHelp.Smoothed1stOrder(InterpolatedPosition, BasePrim.Position, time);\r
184             }\r
185 \r
186             // Angular velocity (target omega)\r
187             if (BasePrim.AngularVelocity != Vector3.Zero)\r
188             {\r
189                 Vector3 angVel = BasePrim.AngularVelocity;\r
190                 float angle = time * angVel.Length();\r
191                 Quaternion dQ = Quaternion.CreateFromAxisAngle(angVel, angle);\r
192                 InterpolatedRotation = dQ * InterpolatedRotation;\r
193             }\r
194             else if (InterpolatedRotation != BasePrim.Rotation && !(this is RenderAvatar))\r
195             {\r
196                 InterpolatedRotation = Quaternion.Slerp(InterpolatedRotation, BasePrim.Rotation, time * 10f);\r
197                 if (1f - Math.Abs(Quaternion.Dot(InterpolatedRotation, BasePrim.Rotation)) < 0.0001)\r
198                     InterpolatedRotation = BasePrim.Rotation;\r
199             }\r
200             else\r
201             {\r
202                 InterpolatedRotation = BasePrim.Rotation;\r
203             }\r
204         }\r
205 \r
206         /// <summary>\r
207         /// Render scene object\r
208         /// </summary>\r
209         /// <param name="pass">Which pass are we currently in</param>\r
210         /// <param name="pickingID">ID used to identify which object was picked</param>\r
211         /// <param name="scene">Main scene renderer</param>\r
212         /// <param name="time">Time it took to render the last frame</param>\r
213         public virtual void Render(RenderPass pass, int pickingID, SceneWindow scene, float time)\r
214         {\r
215         }\r
216 \r
217         /// <summary>\r
218         /// Implementation of the IComparable interface\r
219         /// used for sorting by distance\r
220         /// </summary>\r
221         /// <param name="other">Object we are comparing to</param>\r
222         /// <returns>Result of the comparison</returns>\r
223         public virtual int CompareTo(object other)\r
224         {\r
225             SceneObject o = (SceneObject)other;\r
226             if (this.DistanceSquared < o.DistanceSquared)\r
227                 return -1;\r
228             else if (this.DistanceSquared > o.DistanceSquared)\r
229                 return 1;\r
230             else\r
231                 return 0;\r
232         }\r
233 \r
234         #region Occlusion queries\r
235         public void StartQuery(RenderPass pass)\r
236         {\r
237             if (!RenderSettings.OcclusionCullingEnabled) return;\r
238 \r
239             if (pass == RenderPass.Simple)\r
240             {\r
241                 StartSimpleQuery();\r
242             }\r
243             else if (pass == RenderPass.Alpha)\r
244             {\r
245                 StartAlphaQuery();\r
246             }\r
247         }\r
248 \r
249         public void EndQuery(RenderPass pass)\r
250         {\r
251             if (!RenderSettings.OcclusionCullingEnabled) return;\r
252 \r
253             if (pass == RenderPass.Simple)\r
254             {\r
255                 EndSimpleQuery();\r
256             }\r
257             else if (pass == RenderPass.Alpha)\r
258             {\r
259                 EndAlphaQuery();\r
260             }\r
261         }\r
262 \r
263         public void StartAlphaQuery()\r
264         {\r
265             if (!RenderSettings.OcclusionCullingEnabled) return;\r
266 \r
267             if (AlphaQueryID == -1)\r
268             {\r
269                 Compat.GenQueries(out AlphaQueryID);\r
270             }\r
271             if (AlphaQueryID > 0)\r
272             {\r
273                 Compat.BeginQuery(QueryTarget.SamplesPassed, AlphaQueryID);\r
274             }\r
275         }\r
276 \r
277         public void EndAlphaQuery()\r
278         {\r
279             if (!RenderSettings.OcclusionCullingEnabled) return;\r
280 \r
281             if (AlphaQueryID > 0)\r
282             {\r
283                 Compat.EndQuery(QueryTarget.SamplesPassed);\r
284             }\r
285         }\r
286 \r
287         public void StartSimpleQuery()\r
288         {\r
289             if (!RenderSettings.OcclusionCullingEnabled) return;\r
290 \r
291             if (SimpleQueryID == -1)\r
292             {\r
293                 Compat.GenQueries(out SimpleQueryID);\r
294             }\r
295             if (SimpleQueryID > 0)\r
296             {\r
297                 Compat.BeginQuery(QueryTarget.SamplesPassed, SimpleQueryID);\r
298             }\r
299         }\r
300 \r
301         public void EndSimpleQuery()\r
302         {\r
303             if (!RenderSettings.OcclusionCullingEnabled) return;\r
304 \r
305             if (SimpleQueryID > 0)\r
306             {\r
307                 Compat.EndQuery(QueryTarget.SamplesPassed);\r
308             }\r
309         }\r
310 \r
311         public bool Occluded()\r
312         {\r
313             if (!RenderSettings.OcclusionCullingEnabled) return false;\r
314 \r
315             if ((SimpleQueryID == -1 && AlphaQueryID == -1))\r
316             {\r
317                 return false;\r
318             }\r
319 \r
320             if ((!HasAlphaFaces && !HasSimpleFaces)) return true;\r
321 \r
322             int samples = 1;\r
323             if (HasSimpleFaces && SimpleQueryID > 0)\r
324             {\r
325                 Compat.GetQueryObject(SimpleQueryID, GetQueryObjectParam.QueryResult, out samples);\r
326             }\r
327             if (HasSimpleFaces && samples > 0)\r
328             {\r
329                 return false;\r
330             }\r
331 \r
332             samples = 1;\r
333             if (HasAlphaFaces && AlphaQueryID > 0)\r
334             {\r
335                 Compat.GetQueryObject(AlphaQueryID, GetQueryObjectParam.QueryResult, out samples);\r
336             }\r
337             if (HasAlphaFaces && samples > 0)\r
338             {\r
339                 return false;\r
340             }\r
341 \r
342             return true;\r
343         }\r
344         #endregion Occlusion queries\r
345     }\r
346 \r
347     public static class RHelp\r
348     {\r
349         public static readonly Vector3 InvalidPosition = new Vector3(99999f, 99999f, 99999f);\r
350         static float t1 = 0.075f;\r
351         static float t2 = t1 / 5.7f;\r
352 \r
353         public static Vector3 Smoothed1stOrder(Vector3 curPos, Vector3 targetPos, float lastFrameTime)\r
354         {\r
355             int numIterations = (int)(lastFrameTime * 100);\r
356             do\r
357             {\r
358                 curPos += (targetPos - curPos) * t1;\r
359                 numIterations--;\r
360             }\r
361             while (numIterations > 0);\r
362             if (Vector3.DistanceSquared(curPos, targetPos) < 0.00001f)\r
363             {\r
364                 curPos = targetPos;\r
365             }\r
366             return curPos;\r
367         }\r
368 \r
369         public static Vector3 Smoothed2ndOrder(Vector3 curPos, Vector3 targetPos, ref Vector3 accel, float lastFrameTime)\r
370         {\r
371             int numIterations = (int)(lastFrameTime * 100);\r
372             do\r
373             {\r
374                 accel += (targetPos - accel - curPos) * t1;\r
375                 curPos += accel * t2;\r
376                 numIterations--;\r
377             }\r
378             while (numIterations > 0);\r
379             if (Vector3.DistanceSquared(curPos, targetPos) < 0.00001f)\r
380             {\r
381                 curPos = targetPos;\r
382             }\r
383             return curPos;\r
384         }\r
385 \r
386         public static OpenTK.Vector2 TKVector3(Vector2 v)\r
387         {\r
388             return new OpenTK.Vector2(v.X, v.Y);\r
389         }\r
390 \r
391         public static OpenTK.Vector3 TKVector3(Vector3 v)\r
392         {\r
393             return new OpenTK.Vector3(v.X, v.Y, v.Z);\r
394         }\r
395 \r
396         public static OpenTK.Vector4 TKVector3(Vector4 v)\r
397         {\r
398             return new OpenTK.Vector4(v.X, v.Y, v.Z, v.W);\r
399         }\r
400 \r
401         public static Vector2 OMVVector2(OpenTK.Vector2 v)\r
402         {\r
403             return new Vector2(v.X, v.Y);\r
404         }\r
405 \r
406         public static Vector3 OMVVector3(OpenTK.Vector3 v)\r
407         {\r
408             return new Vector3(v.X, v.Y, v.Z);\r
409         }\r
410 \r
411         public static Vector4 OMVVector4(OpenTK.Vector4 v)\r
412         {\r
413             return new Vector4(v.X, v.Y, v.Z, v.W);\r
414         }\r
415 \r
416         public static Color WinColor(OpenTK.Graphics.Color4 color)\r
417         {\r
418             return Color.FromArgb((int)(color.A * 255), (int)(color.R * 255), (int)(color.G * 255), (int)(color.B * 255));\r
419         }\r
420 \r
421         public static Color WinColor(Color4 color)\r
422         {\r
423             return Color.FromArgb((int)(color.A * 255), (int)(color.R * 255), (int)(color.G * 255), (int)(color.B * 255));\r
424         }\r
425 \r
426         public static int NextPow2(int start)\r
427         {\r
428             int pow = 1;\r
429             while (pow < start) pow *= 2;\r
430             return pow;\r
431         }\r
432 \r
433         #region Cached image save and load\r
434         public static readonly string RAD_IMG_MAGIC = "radegast_img";\r
435 \r
436         public static bool LoadCachedImage(UUID textureID, out byte[] tgaData, out bool hasAlpha, out bool fullAlpha, out bool isMask)\r
437         {\r
438             tgaData = null;\r
439             hasAlpha = fullAlpha = isMask = false;\r
440 \r
441             try\r
442             {\r
443                 string fname = System.IO.Path.Combine(RadegastInstance.GlobalInstance.Client.Settings.ASSET_CACHE_DIR, string.Format("{0}.rzi", textureID));\r
444                 //string fname = System.IO.Path.Combine(".", string.Format("{0}.rzi", textureID));\r
445 \r
446                 using (var f = File.Open(fname, FileMode.Open, FileAccess.Read, FileShare.Read))\r
447                 {\r
448                     byte[] header = new byte[36];\r
449                     int i = 0;\r
450                     f.Read(header, 0, header.Length);\r
451 \r
452                     // check if the file is starting with magic string\r
453                     if (RAD_IMG_MAGIC != Utils.BytesToString(header, 0, RAD_IMG_MAGIC.Length))\r
454                         return false;\r
455                     i += RAD_IMG_MAGIC.Length;\r
456 \r
457                     if (header[i++] != 1) // check version\r
458                         return false;\r
459 \r
460                     hasAlpha = header[i++] == 1;\r
461                     fullAlpha = header[i++] == 1;\r
462                     isMask = header[i++] == 1;\r
463 \r
464                     int uncompressedSize = Utils.BytesToInt(header, i);\r
465                     i += 4;\r
466 \r
467                     textureID = new UUID(header, i);\r
468                     i += 16;\r
469 \r
470                     tgaData = new byte[uncompressedSize];\r
471                     using (var compressed = new DeflateStream(f, CompressionMode.Decompress))\r
472                     {\r
473                         int read = 0;\r
474                         while ((read = compressed.Read(tgaData, read, uncompressedSize - read)) > 0) ;\r
475                     }\r
476                 }\r
477 \r
478                 return true;\r
479             }\r
480             catch (FileNotFoundException) { }\r
481             catch (Exception ex)\r
482             {\r
483                 Logger.DebugLog(string.Format("Failed to load radegast cache file {0}: {1}", textureID, ex.Message));\r
484             }\r
485             return false;\r
486         }\r
487 \r
488         public static bool SaveCachedImage(byte[] tgaData, UUID textureID, bool hasAlpha, bool fullAlpha, bool isMask)\r
489         {\r
490             try\r
491             {\r
492                 string fname = System.IO.Path.Combine(RadegastInstance.GlobalInstance.Client.Settings.ASSET_CACHE_DIR, string.Format("{0}.rzi", textureID));\r
493                 //string fname = System.IO.Path.Combine(".", string.Format("{0}.rzi", textureID));\r
494 \r
495                 using (var f = File.Open(fname, FileMode.Create, FileAccess.Write, FileShare.None))\r
496                 {\r
497                     int i = 0;\r
498                     // magic header\r
499                     f.Write(Utils.StringToBytes(RAD_IMG_MAGIC), 0, RAD_IMG_MAGIC.Length);\r
500                     i += RAD_IMG_MAGIC.Length;\r
501 \r
502                     // version\r
503                     f.WriteByte((byte)1);\r
504                     i++;\r
505 \r
506                     // texture info\r
507                     f.WriteByte(hasAlpha ? (byte)1 : (byte)0);\r
508                     f.WriteByte(fullAlpha ? (byte)1 : (byte)0);\r
509                     f.WriteByte(isMask ? (byte)1 : (byte)0);\r
510                     i += 3;\r
511 \r
512                     // texture size\r
513                     byte[] uncompressedSize = Utils.IntToBytes(tgaData.Length);\r
514                     f.Write(uncompressedSize, 0, uncompressedSize.Length);\r
515                     i += uncompressedSize.Length;\r
516 \r
517                     // texture id\r
518                     byte[] id = new byte[16];\r
519                     textureID.ToBytes(id, 0);\r
520                     f.Write(id, 0, 16);\r
521                     i += 16;\r
522 \r
523                     // compressed texture data\r
524                     using (var compressed = new DeflateStream(f, CompressionMode.Compress))\r
525                     {\r
526                         compressed.Write(tgaData, 0, tgaData.Length);\r
527                     }\r
528                 }\r
529                 return true;\r
530             }\r
531             catch (Exception ex)\r
532             {\r
533                 Logger.DebugLog(string.Format("Failed to save radegast cache file {0}: {1}", textureID, ex.Message));\r
534                 return false;\r
535             }\r
536         }\r
537         #endregion Cached image save and load\r
538 \r
539         #region Static vertices and indices for a cube (used for bounding box drawing)\r
540         /**********************************************\r
541           5 --- 4\r
542          /|    /|\r
543         1 --- 0 |\r
544         | 6 --| 7\r
545         |/    |/\r
546         2 --- 3\r
547         ***********************************************/\r
548         public static readonly float[] CubeVertices = new float[]\r
549         {\r
550              0.5f,  0.5f,  0.5f, // 0\r
551                 -0.5f,  0.5f,  0.5f, // 1\r
552                 -0.5f, -0.5f,  0.5f, // 2\r
553                  0.5f, -0.5f,  0.5f, // 3\r
554                  0.5f,  0.5f, -0.5f, // 4\r
555                 -0.5f,  0.5f, -0.5f, // 5\r
556                 -0.5f, -0.5f, -0.5f, // 6\r
557                  0.5f, -0.5f, -0.5f  // 7\r
558         };\r
559 \r
560         public static readonly ushort[] CubeIndices = new ushort[]\r
561         {\r
562             0, 1, 2, 3,     // Front Face\r
563                 4, 5, 6, 7,     // Back Face\r
564                 1, 2, 6, 5,     // Left Face\r
565                 0, 3, 7, 4,     // Right Face\r
566                 0, 1, 5, 4,     // Top Face\r
567                 2, 3, 7, 6      // Bottom Face\r
568         };\r
569         #endregion Static vertices and indices for a cube (used for bounding box drawing)\r
570 \r
571         public static int GLLoadImage(Bitmap bitmap, bool hasAlpha)\r
572         {\r
573             return GLLoadImage(bitmap, hasAlpha, true);\r
574         }\r
575 \r
576         public static int GLLoadImage(Bitmap bitmap, bool hasAlpha, bool useMipmap)\r
577         {\r
578             useMipmap = useMipmap && RenderSettings.HasMipmap;\r
579             int ret = -1;\r
580             GL.GenTextures(1, out ret);\r
581             GL.BindTexture(TextureTarget.Texture2D, ret);\r
582 \r
583             Rectangle rectangle = new Rectangle(0, 0, bitmap.Width, bitmap.Height);\r
584 \r
585             BitmapData bitmapData =\r
586                 bitmap.LockBits(\r
587                 rectangle,\r
588                 ImageLockMode.ReadOnly,\r
589                 hasAlpha ? System.Drawing.Imaging.PixelFormat.Format32bppArgb : System.Drawing.Imaging.PixelFormat.Format24bppRgb);\r
590 \r
591             GL.TexImage2D(\r
592                 TextureTarget.Texture2D,\r
593                 0,\r
594                 hasAlpha ? PixelInternalFormat.Rgba : PixelInternalFormat.Rgb8,\r
595                 bitmap.Width,\r
596                 bitmap.Height,\r
597                 0,\r
598                 hasAlpha ? OpenTK.Graphics.OpenGL.PixelFormat.Bgra : OpenTK.Graphics.OpenGL.PixelFormat.Bgr,\r
599                 PixelType.UnsignedByte,\r
600                 bitmapData.Scan0);\r
601 \r
602             GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);\r
603             GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.Repeat);\r
604             GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.Repeat);\r
605             if (useMipmap)\r
606             {\r
607                 GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.LinearMipmapLinear);\r
608                 GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.GenerateMipmap, 1);\r
609                 GL.GenerateMipmap(GenerateMipmapTarget.Texture2D);\r
610             }\r
611             else\r
612             {\r
613                 GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear);\r
614             }\r
615 \r
616             bitmap.UnlockBits(bitmapData);\r
617             return ret;\r
618         }\r
619 \r
620         public static void Draw2DBox(float x, float y, float width, float height, float depth)\r
621         {\r
622             GL.Begin(BeginMode.Quads);\r
623             {\r
624                 GL.TexCoord2(0, 1);\r
625                 GL.Vertex3(x, y, depth);\r
626                 GL.TexCoord2(1, 1);\r
627                 GL.Vertex3(x + width, y, depth);\r
628                 GL.TexCoord2(1, 0);\r
629                 GL.Vertex3(x + width, y + height, depth);\r
630                 GL.TexCoord2(0, 0);\r
631                 GL.Vertex3(x, y + height, depth);\r
632             }\r
633             GL.End();\r
634         }\r
635 \r
636         public static void ResetMaterial()\r
637         {\r
638             GL.Material(MaterialFace.FrontAndBack, MaterialParameter.Ambient, new float[] { 0.2f, 0.2f, 0.2f, 1.0f });\r
639             GL.Material(MaterialFace.FrontAndBack, MaterialParameter.Diffuse, new float[] { 0.8f, 0.8f, 0.8f, 1.0f });\r
640             GL.Material(MaterialFace.FrontAndBack, MaterialParameter.Specular, new float[] { 0f, 0f, 0f, 1.0f });\r
641             GL.Material(MaterialFace.FrontAndBack, MaterialParameter.Emission, new float[] { 0f, 0f, 0f, 1.0f });\r
642             GL.Material(MaterialFace.FrontAndBack, MaterialParameter.Shininess, 0f);\r
643             ShaderProgram.Stop();\r
644         }\r
645     }\r
646 \r
647     /// <summary>\r
648     /// Represents camera object\r
649     /// </summary>\r
650     public class Camera\r
651     {\r
652         /// <summary>\r
653         /// Indicates that there was manual camera movement, stop tracking objects\r
654         /// </summary>\r
655         public bool Manual;\r
656         Vector3 mPosition;\r
657         Vector3 mFocalPoint;\r
658         bool mModified;\r
659 \r
660         /// <summary>Camera position</summary>\r
661         public Vector3 Position { get { return mPosition; } set { mPosition = value; Modify(); } }\r
662         /// <summary>Camera target</summary>\r
663         public Vector3 FocalPoint { get { return mFocalPoint; } set { mFocalPoint = value; Modify(); } }\r
664         /// <summary>Zoom level</summary>\r
665         public float Zoom;\r
666         /// <summary>Draw distance</summary>\r
667         public float Far;\r
668         /// <summary>Has camera been modified</summary>\r
669         public bool Modified { get { return mModified; } set { mModified = value; } }\r
670 \r
671         public float TimeToTarget = 0f;\r
672 \r
673         public Vector3 RenderPosition;\r
674         public Vector3 RenderFocalPoint;\r
675 \r
676         void Modify()\r
677         {\r
678             mModified = true;\r
679         }\r
680 \r
681         public void Step(float time)\r
682         {\r
683             if (RenderPosition != Position)\r
684             {\r
685                 RenderPosition = RHelp.Smoothed1stOrder(RenderPosition, Position, time);\r
686                 Modified = true;\r
687             }\r
688             if (RenderFocalPoint != FocalPoint)\r
689             {\r
690                 RenderFocalPoint = RHelp.Smoothed1stOrder(RenderFocalPoint, FocalPoint, time);\r
691                 Modified = true;\r
692             }\r
693         }\r
694 \r
695         [Obsolete("Use Step(), left in here for reference")]\r
696         public void Step2(float time)\r
697         {\r
698             TimeToTarget -= time;\r
699             if (TimeToTarget <= time)\r
700             {\r
701                 EndMove();\r
702                 return;\r
703             }\r
704 \r
705             mModified = true;\r
706 \r
707             float pctElapsed = time / TimeToTarget;\r
708 \r
709             if (RenderPosition != Position)\r
710             {\r
711                 float distance = Vector3.Distance(RenderPosition, Position);\r
712                 RenderPosition = Vector3.Lerp(RenderPosition, Position, distance * pctElapsed);\r
713             }\r
714 \r
715             if (RenderFocalPoint != FocalPoint)\r
716             {\r
717                 RenderFocalPoint = Interpolate(RenderFocalPoint, FocalPoint, pctElapsed);\r
718             }\r
719         }\r
720 \r
721         Vector3 Interpolate(Vector3 start, Vector3 end, float fraction)\r
722         {\r
723             float distance = Vector3.Distance(start, end);\r
724             Vector3 direction = end - start;\r
725             return start + direction * fraction;\r
726         }\r
727 \r
728         public void EndMove()\r
729         {\r
730             mModified = true;\r
731             TimeToTarget = 0;\r
732             RenderPosition = Position;\r
733             RenderFocalPoint = FocalPoint;\r
734         }\r
735 \r
736         public void Pan(float deltaX, float deltaY)\r
737         {\r
738             Manual = true;\r
739             Vector3 direction = Position - FocalPoint;\r
740             direction.Normalize();\r
741             Vector3 vy = direction % Vector3.UnitZ;\r
742             Vector3 vx = vy % direction;\r
743             Vector3 vxy = vx * deltaY + vy * deltaX;\r
744             Position += vxy;\r
745             FocalPoint += vxy;\r
746         }\r
747 \r
748         public void Rotate(float delta, bool horizontal)\r
749         {\r
750             Manual = true;\r
751             Vector3 direction = Position - FocalPoint;\r
752             if (horizontal)\r
753             {\r
754                 Position = FocalPoint + direction * new Quaternion(0f, 0f, (float)Math.Sin(delta), (float)Math.Cos(delta));\r
755             }\r
756             else\r
757             {\r
758                 Position = FocalPoint + direction * Quaternion.CreateFromAxisAngle(direction % Vector3.UnitZ, delta);\r
759             }\r
760         }\r
761 \r
762         public void MoveToTarget(float delta)\r
763         {\r
764             Manual = true;\r
765             Position += (Position - FocalPoint) * delta;\r
766         }\r
767 \r
768         /// <summary>\r
769         /// Sets the world in perspective of the camera\r
770         /// </summary>\r
771         public void LookAt()\r
772         {\r
773             OpenTK.Matrix4 lookAt = OpenTK.Matrix4.LookAt(\r
774                 RenderPosition.X, RenderPosition.Y, RenderPosition.Z,\r
775                 RenderFocalPoint.X, RenderFocalPoint.Y, RenderFocalPoint.Z,\r
776                 0f, 0f, 1f);\r
777             GL.MultMatrix(ref lookAt);\r
778         }\r
779     }\r
780 \r
781     public static class MeshToOBJ\r
782     {\r
783         public static bool MeshesToOBJ(Dictionary<uint, FacetedMesh> meshes, string filename)\r
784         {\r
785             StringBuilder obj = new StringBuilder();\r
786             StringBuilder mtl = new StringBuilder();\r
787 \r
788             FileInfo objFileInfo = new FileInfo(filename);\r
789 \r
790             string mtlFilename = objFileInfo.FullName.Substring(objFileInfo.DirectoryName.Length + 1,\r
791                 objFileInfo.FullName.Length - (objFileInfo.DirectoryName.Length + 1) - 4) + ".mtl";\r
792 \r
793             obj.AppendLine("# Created by libprimrender");\r
794             obj.AppendLine("mtllib ./" + mtlFilename);\r
795             obj.AppendLine();\r
796 \r
797             mtl.AppendLine("# Created by libprimrender");\r
798             mtl.AppendLine();\r
799 \r
800             int primNr = 0;\r
801             foreach (FacetedMesh mesh in meshes.Values)\r
802             {\r
803                 for (int j = 0; j < mesh.Faces.Count; j++)\r
804                 {\r
805                     Face face = mesh.Faces[j];\r
806 \r
807                     if (face.Vertices.Count > 2)\r
808                     {\r
809                         string mtlName = String.Format("material{0}-{1}", primNr, face.ID);\r
810                         Primitive.TextureEntryFace tex = face.TextureFace;\r
811                         string texName = tex.TextureID.ToString() + ".tga";\r
812 \r
813                         // FIXME: Convert the source to TGA (if needed) and copy to the destination\r
814 \r
815                         float shiny = 0.00f;\r
816                         switch (tex.Shiny)\r
817                         {\r
818                             case Shininess.High:\r
819                                 shiny = 1.00f;\r
820                                 break;\r
821                             case Shininess.Medium:\r
822                                 shiny = 0.66f;\r
823                                 break;\r
824                             case Shininess.Low:\r
825                                 shiny = 0.33f;\r
826                                 break;\r
827                         }\r
828 \r
829                         obj.AppendFormat("g face{0}-{1}{2}", primNr, face.ID, Environment.NewLine);\r
830 \r
831                         mtl.AppendLine("newmtl " + mtlName);\r
832                         mtl.AppendFormat("Ka {0} {1} {2}{3}", tex.RGBA.R, tex.RGBA.G, tex.RGBA.B, Environment.NewLine);\r
833                         mtl.AppendFormat("Kd {0} {1} {2}{3}", tex.RGBA.R, tex.RGBA.G, tex.RGBA.B, Environment.NewLine);\r
834                         //mtl.AppendFormat("Ks {0} {1} {2}{3}");\r
835                         mtl.AppendLine("Tr " + tex.RGBA.A);\r
836                         mtl.AppendLine("Ns " + shiny);\r
837                         mtl.AppendLine("illum 1");\r
838                         if (tex.TextureID != UUID.Zero && tex.TextureID != Primitive.TextureEntry.WHITE_TEXTURE)\r
839                             mtl.AppendLine("map_Kd ./" + texName);\r
840                         mtl.AppendLine();\r
841 \r
842                         // Write the vertices, texture coordinates, and vertex normals for this side\r
843                         for (int k = 0; k < face.Vertices.Count; k++)\r
844                         {\r
845                             Vertex vertex = face.Vertices[k];\r
846 \r
847                             #region Vertex\r
848 \r
849                             Vector3 pos = vertex.Position;\r
850 \r
851                             // Apply scaling\r
852                             pos *= mesh.Prim.Scale;\r
853 \r
854                             // Apply rotation\r
855                             pos *= mesh.Prim.Rotation;\r
856 \r
857                             // The root prim position is sim-relative, while child prim positions are\r
858                             // parent-relative. We want to apply parent-relative translations but not\r
859                             // sim-relative ones\r
860                             if (mesh.Prim.ParentID != 0)\r
861                                 pos += mesh.Prim.Position;\r
862 \r
863                             obj.AppendFormat("v {0} {1} {2}{3}", pos.X, pos.Y, pos.Z, Environment.NewLine);\r
864 \r
865                             #endregion Vertex\r
866 \r
867                             #region Texture Coord\r
868 \r
869                             obj.AppendFormat("vt {0} {1}{2}", vertex.TexCoord.X, vertex.TexCoord.Y,\r
870                                 Environment.NewLine);\r
871 \r
872                             #endregion Texture Coord\r
873 \r
874                             #region Vertex Normal\r
875 \r
876                             // HACK: Sometimes normals are getting set to <NaN,NaN,NaN>\r
877                             if (!Single.IsNaN(vertex.Normal.X) && !Single.IsNaN(vertex.Normal.Y) && !Single.IsNaN(vertex.Normal.Z))\r
878                                 obj.AppendFormat("vn {0} {1} {2}{3}", vertex.Normal.X, vertex.Normal.Y, vertex.Normal.Z,\r
879                                     Environment.NewLine);\r
880                             else\r
881                                 obj.AppendLine("vn 0.0 1.0 0.0");\r
882 \r
883                             #endregion Vertex Normal\r
884                         }\r
885 \r
886                         obj.AppendFormat("# {0} vertices{1}", face.Vertices.Count, Environment.NewLine);\r
887                         obj.AppendLine();\r
888                         obj.AppendLine("usemtl " + mtlName);\r
889 \r
890                         #region Elements\r
891 \r
892                         // Write all of the faces (triangles) for this side\r
893                         for (int k = 0; k < face.Indices.Count / 3; k++)\r
894                         {\r
895                             obj.AppendFormat("f -{0}/-{0}/-{0} -{1}/-{1}/-{1} -{2}/-{2}/-{2}{3}",\r
896                                 face.Vertices.Count - face.Indices[k * 3 + 0],\r
897                                 face.Vertices.Count - face.Indices[k * 3 + 1],\r
898                                 face.Vertices.Count - face.Indices[k * 3 + 2],\r
899                                 Environment.NewLine);\r
900                         }\r
901 \r
902                         obj.AppendFormat("# {0} elements{1}", face.Indices.Count / 3, Environment.NewLine);\r
903                         obj.AppendLine();\r
904 \r
905                         #endregion Elements\r
906                     }\r
907                 }\r
908                 primNr++;\r
909             }\r
910 \r
911             try\r
912             {\r
913                 File.WriteAllText(filename, obj.ToString());\r
914                 File.WriteAllText(mtlFilename, mtl.ToString());\r
915             }\r
916             catch (Exception)\r
917             {\r
918                 return false;\r
919             }\r
920 \r
921             return true;\r
922         }\r
923     }\r
924 \r
925     public static class Math3D\r
926     {\r
927         // Column-major:\r
928         // |  0  4  8 12 |\r
929         // |  1  5  9 13 |\r
930         // |  2  6 10 14 |\r
931         // |  3  7 11 15 |\r
932 \r
933         public static float[] CreateTranslationMatrix(Vector3 v)\r
934         {\r
935             float[] mat = new float[16];\r
936 \r
937             mat[12] = v.X;\r
938             mat[13] = v.Y;\r
939             mat[14] = v.Z;\r
940             mat[0] = mat[5] = mat[10] = mat[15] = 1;\r
941 \r
942             return mat;\r
943         }\r
944 \r
945         public static float[] CreateRotationMatrix(Quaternion q)\r
946         {\r
947             float[] mat = new float[16];\r
948 \r
949             // Transpose the quaternion (don't ask me why)\r
950             q.X = q.X * -1f;\r
951             q.Y = q.Y * -1f;\r
952             q.Z = q.Z * -1f;\r
953 \r
954             float x2 = q.X + q.X;\r
955             float y2 = q.Y + q.Y;\r
956             float z2 = q.Z + q.Z;\r
957             float xx = q.X * x2;\r
958             float xy = q.X * y2;\r
959             float xz = q.X * z2;\r
960             float yy = q.Y * y2;\r
961             float yz = q.Y * z2;\r
962             float zz = q.Z * z2;\r
963             float wx = q.W * x2;\r
964             float wy = q.W * y2;\r
965             float wz = q.W * z2;\r
966 \r
967             mat[0] = 1.0f - (yy + zz);\r
968             mat[1] = xy - wz;\r
969             mat[2] = xz + wy;\r
970             mat[3] = 0.0f;\r
971 \r
972             mat[4] = xy + wz;\r
973             mat[5] = 1.0f - (xx + zz);\r
974             mat[6] = yz - wx;\r
975             mat[7] = 0.0f;\r
976 \r
977             mat[8] = xz - wy;\r
978             mat[9] = yz + wx;\r
979             mat[10] = 1.0f - (xx + yy);\r
980             mat[11] = 0.0f;\r
981 \r
982             mat[12] = 0.0f;\r
983             mat[13] = 0.0f;\r
984             mat[14] = 0.0f;\r
985             mat[15] = 1.0f;\r
986 \r
987             return mat;\r
988         }\r
989 \r
990         public static float[] CreateSRTMatrix(Vector3 scale, Quaternion q, Vector3 pos)\r
991         {\r
992             float[] mat = new float[16];\r
993 \r
994             // Transpose the quaternion (don't ask me why)\r
995             q.X = q.X * -1f;\r
996             q.Y = q.Y * -1f;\r
997             q.Z = q.Z * -1f;\r
998 \r
999             float x2 = q.X + q.X;\r
1000             float y2 = q.Y + q.Y;\r
1001             float z2 = q.Z + q.Z;\r
1002             float xx = q.X * x2;\r
1003             float xy = q.X * y2;\r
1004             float xz = q.X * z2;\r
1005             float yy = q.Y * y2;\r
1006             float yz = q.Y * z2;\r
1007             float zz = q.Z * z2;\r
1008             float wx = q.W * x2;\r
1009             float wy = q.W * y2;\r
1010             float wz = q.W * z2;\r
1011 \r
1012             mat[0] = (1.0f - (yy + zz)) * scale.X;\r
1013             mat[1] = (xy - wz) * scale.X;\r
1014             mat[2] = (xz + wy) * scale.X;\r
1015             mat[3] = 0.0f;\r
1016 \r
1017             mat[4] = (xy + wz) * scale.Y;\r
1018             mat[5] = (1.0f - (xx + zz)) * scale.Y;\r
1019             mat[6] = (yz - wx) * scale.Y;\r
1020             mat[7] = 0.0f;\r
1021 \r
1022             mat[8] = (xz - wy) * scale.Z;\r
1023             mat[9] = (yz + wx) * scale.Z;\r
1024             mat[10] = (1.0f - (xx + yy)) * scale.Z;\r
1025             mat[11] = 0.0f;\r
1026 \r
1027             //Positional parts\r
1028             mat[12] = pos.X;\r
1029             mat[13] = pos.Y;\r
1030             mat[14] = pos.Z;\r
1031             mat[15] = 1.0f;\r
1032 \r
1033             return mat;\r
1034         }\r
1035 \r
1036 \r
1037         public static float[] CreateScaleMatrix(Vector3 v)\r
1038         {\r
1039             float[] mat = new float[16];\r
1040 \r
1041             mat[0] = v.X;\r
1042             mat[5] = v.Y;\r
1043             mat[10] = v.Z;\r
1044             mat[15] = 1;\r
1045 \r
1046             return mat;\r
1047         }\r
1048 \r
1049         public static float[] Lerp(float[] matrix1, float[] matrix2, float amount)\r
1050         {\r
1051 \r
1052             float[] lerp = new float[16];\r
1053             //Probably not doing this as a loop is cheaper(unrolling)\r
1054             //also for performance we probably should not create new objects\r
1055             // but meh.\r
1056             for (int x = 0; x < 16; x++)\r
1057             {\r
1058                 lerp[x] = matrix1[x] + ((matrix2[x] - matrix1[x]) * amount);\r
1059             }\r
1060 \r
1061             return lerp;\r
1062         }\r
1063 \r
1064 \r
1065         public static bool GluProject(OpenTK.Vector3 objPos, OpenTK.Matrix4 modelMatrix, OpenTK.Matrix4 projMatrix, int[] viewport, out OpenTK.Vector3 screenPos)\r
1066         {\r
1067             OpenTK.Vector4 _in;\r
1068             OpenTK.Vector4 _out;\r
1069 \r
1070             _in.X = objPos.X;\r
1071             _in.Y = objPos.Y;\r
1072             _in.Z = objPos.Z;\r
1073             _in.W = 1.0f;\r
1074 \r
1075             _out = OpenTK.Vector4.Transform(_in, modelMatrix);\r
1076             _in = OpenTK.Vector4.Transform(_out, projMatrix);\r
1077 \r
1078             if (_in.W <= 0.0)\r
1079             {\r
1080                 screenPos = OpenTK.Vector3.Zero;\r
1081                 return false;\r
1082             }\r
1083 \r
1084             _in.X /= _in.W;\r
1085             _in.Y /= _in.W;\r
1086             _in.Z /= _in.W;\r
1087             /* Map x, y and z to range 0-1 */\r
1088             _in.X = _in.X * 0.5f + 0.5f;\r
1089             _in.Y = _in.Y * 0.5f + 0.5f;\r
1090             _in.Z = _in.Z * 0.5f + 0.5f;\r
1091 \r
1092             /* Map x,y to viewport */\r
1093             _in.X = _in.X * viewport[2] + viewport[0];\r
1094             _in.Y = _in.Y * viewport[3] + viewport[1];\r
1095 \r
1096             screenPos.X = _in.X;\r
1097             screenPos.Y = _in.Y;\r
1098             screenPos.Z = _in.Z;\r
1099 \r
1100             return true;\r
1101         }\r
1102 \r
1103         public static bool GluUnProject(float winx, float winy, float winz, OpenTK.Matrix4 modelMatrix, OpenTK.Matrix4 projMatrix, int[] viewport, out OpenTK.Vector3 pos)\r
1104         {\r
1105             OpenTK.Matrix4 finalMatrix;\r
1106             OpenTK.Vector4 _in;\r
1107             OpenTK.Vector4 _out;\r
1108 \r
1109             finalMatrix = OpenTK.Matrix4.Mult(modelMatrix, projMatrix);\r
1110 \r
1111             finalMatrix.Invert();\r
1112 \r
1113             _in.X = winx;\r
1114             _in.Y = winy;\r
1115             _in.Z = winz;\r
1116             _in.W = 1.0f;\r
1117 \r
1118             /* Map x and y from window coordinates */\r
1119             _in.X = (_in.X - viewport[0]) / viewport[2];\r
1120             _in.Y = (_in.Y - viewport[1]) / viewport[3];\r
1121 \r
1122             pos = OpenTK.Vector3.Zero;\r
1123 \r
1124             /* Map to range -1 to 1 */\r
1125             _in.X = _in.X * 2 - 1;\r
1126             _in.Y = _in.Y * 2 - 1;\r
1127             _in.Z = _in.Z * 2 - 1;\r
1128 \r
1129             //__gluMultMatrixVecd(finalMatrix, _in, _out);\r
1130             // check if this works:\r
1131             _out = OpenTK.Vector4.Transform(_in, finalMatrix);\r
1132 \r
1133             if (_out.W == 0.0f)\r
1134                 return false;\r
1135             _out.X /= _out.W;\r
1136             _out.Y /= _out.W;\r
1137             _out.Z /= _out.W;\r
1138             pos.X = _out.X;\r
1139             pos.Y = _out.Y;\r
1140             pos.Z = _out.Z;\r
1141             return true;\r
1142         }\r
1143 \r
1144         public static double[] AbovePlane(double height)\r
1145         {\r
1146             return new double[] { 0, 0, 1, -height };\r
1147         }\r
1148 \r
1149         public static double[] BelowPlane(double height)\r
1150         {\r
1151             return new double[] { 0, 0, -1, height };\r
1152         }\r
1153     }\r
1154 \r
1155     /*\r
1156      *  Helper classs for reading the static VFS file, call \r
1157      *  staticVFS.readVFSheaders() with the path to the static_data.db2 and static_index.db2 files\r
1158      *  and it will pass and dump in to openmetaverse_data for you\r
1159      *  This should only be needed to be used if LL update the static VFS in order to refresh our data\r
1160      */\r
1161 \r
1162     class VFSblock\r
1163     {\r
1164         public int mLocation;\r
1165         public int mLength;\r
1166         public int mAccessTime;\r
1167         public UUID mFileID;\r
1168         public int mSize;\r
1169         public AssetType mAssetType;\r
1170 \r
1171         public int readblock(byte[] blockdata, int offset)\r
1172         {\r
1173 \r
1174             BitPack input = new BitPack(blockdata, offset);\r
1175             mLocation = input.UnpackInt();\r
1176             mLength = input.UnpackInt();\r
1177             mAccessTime = input.UnpackInt();\r
1178             mFileID = input.UnpackUUID();\r
1179             int filetype = input.UnpackShort();\r
1180             mAssetType = (AssetType)filetype;\r
1181             mSize = input.UnpackInt();\r
1182             offset += 34;\r
1183 \r
1184             Logger.Log(String.Format("Found header for {0} type {1} length {2} at {3}", mFileID, mAssetType, mSize, mLocation), Helpers.LogLevel.Info);\r
1185 \r
1186             return offset;\r
1187         }\r
1188 \r
1189     }\r
1190 \r
1191     public class staticVFS\r
1192     {\r
1193         public static void readVFSheaders(string datafile, string indexfile)\r
1194         {\r
1195             FileStream datastream;\r
1196             FileStream indexstream;\r
1197 \r
1198             datastream = File.Open(datafile, FileMode.Open);\r
1199             indexstream = File.Open(indexfile, FileMode.Open);\r
1200 \r
1201             int offset = 0;\r
1202 \r
1203             byte[] blockdata = new byte[indexstream.Length];\r
1204             indexstream.Read(blockdata, 0, (int)indexstream.Length);\r
1205 \r
1206             while (offset < indexstream.Length)\r
1207             {\r
1208                 VFSblock block = new VFSblock();\r
1209                 offset = block.readblock(blockdata, offset);\r
1210 \r
1211                 FileStream writer = File.Open(OpenMetaverse.Settings.RESOURCE_DIR + System.IO.Path.DirectorySeparatorChar + block.mFileID.ToString(), FileMode.Create);\r
1212                 byte[] data = new byte[block.mSize];\r
1213                 datastream.Seek(block.mLocation, SeekOrigin.Begin);\r
1214                 datastream.Read(data, 0, block.mSize);\r
1215                 writer.Write(data, 0, block.mSize);\r
1216                 writer.Close();\r
1217             }\r
1218 \r
1219         }\r
1220     }\r
1221 }