clockwerk-opensim – Blame information for rev 1

Subversion Repositories:
Rev:
Rev Author Line No. Line
1 vero 1 /*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27  
28 using System;
29 using System.Collections.Generic;
30 using System.Drawing;
31 using System.Drawing.Imaging;
32 using System.IO;
33 using System.Reflection;
34  
35 using CSJ2K;
36 using Nini.Config;
37 using log4net;
38 using Rednettle.Warp3D;
39 using Mono.Addins;
40  
41 using OpenSim.Framework;
42 using OpenSim.Region.Framework.Interfaces;
43 using OpenSim.Region.Framework.Scenes;
44 using OpenSim.Region.Physics.Manager;
45 using OpenSim.Services.Interfaces;
46  
47 using OpenMetaverse;
48 using OpenMetaverse.Assets;
49 using OpenMetaverse.Imaging;
50 using OpenMetaverse.Rendering;
51 using OpenMetaverse.StructuredData;
52  
53 using WarpRenderer = global::Warp3D.Warp3D;
54  
55 namespace OpenSim.Region.CoreModules.World.Warp3DMap
56 {
57 [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "Warp3DImageModule")]
58 public class Warp3DImageModule : IMapImageGenerator, INonSharedRegionModule
59 {
60 private static readonly UUID TEXTURE_METADATA_MAGIC = new UUID("802dc0e0-f080-4931-8b57-d1be8611c4f3");
61 private static readonly Color4 WATER_COLOR = new Color4(29, 72, 96, 216);
62  
63 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
64  
65 #pragma warning disable 414
66 private static string LogHeader = "[WARP 3D IMAGE MODULE]";
67 #pragma warning restore 414
68  
69 private Scene m_scene;
70 private IRendering m_primMesher;
71 private Dictionary<UUID, Color4> m_colors = new Dictionary<UUID, Color4>();
72  
73 private IConfigSource m_config;
74 private bool m_drawPrimVolume = true; // true if should render the prims on the tile
75 private bool m_textureTerrain = true; // true if to create terrain splatting texture
76 private bool m_texturePrims = true; // true if should texture the rendered prims
77 private float m_texturePrimSize = 48f; // size of prim before we consider texturing it
78 private bool m_renderMeshes = false; // true if to render meshes rather than just bounding boxes
79 private bool m_useAntiAliasing = false; // true if to anti-alias the rendered image
80  
81 private bool m_Enabled = false;
82  
83 #region Region Module interface
84  
85 public void Initialise(IConfigSource source)
86 {
87 m_config = source;
88  
89 string[] configSections = new string[] { "Map", "Startup" };
90  
91 if (Util.GetConfigVarFromSections<string>(
92 m_config, "MapImageModule", configSections, "MapImageModule") != "Warp3DImageModule")
93 return;
94  
95 m_Enabled = true;
96  
97 m_drawPrimVolume
98 = Util.GetConfigVarFromSections<bool>(m_config, "DrawPrimOnMapTile", configSections, m_drawPrimVolume);
99 m_textureTerrain
100 = Util.GetConfigVarFromSections<bool>(m_config, "TextureOnMapTile", configSections, m_textureTerrain);
101 m_texturePrims
102 = Util.GetConfigVarFromSections<bool>(m_config, "TexturePrims", configSections, m_texturePrims);
103 m_texturePrimSize
104 = Util.GetConfigVarFromSections<float>(m_config, "TexturePrimSize", configSections, m_texturePrimSize);
105 m_renderMeshes
106 = Util.GetConfigVarFromSections<bool>(m_config, "RenderMeshes", configSections, m_renderMeshes);
107 m_useAntiAliasing
108 = Util.GetConfigVarFromSections<bool>(m_config, "UseAntiAliasing", configSections, m_useAntiAliasing);
109  
110 }
111  
112 public void AddRegion(Scene scene)
113 {
114 if (!m_Enabled)
115 return;
116  
117 m_scene = scene;
118  
119 List<string> renderers = RenderingLoader.ListRenderers(Util.ExecutingDirectory());
120 if (renderers.Count > 0)
121 {
122 m_primMesher = RenderingLoader.LoadRenderer(renderers[0]);
123 m_log.DebugFormat("[WARP 3D IMAGE MODULE]: Loaded prim mesher {0}", m_primMesher);
124 }
125 else
126 {
127 m_log.Debug("[WARP 3D IMAGE MODULE]: No prim mesher loaded, prim rendering will be disabled");
128 }
129  
130 m_scene.RegisterModuleInterface<IMapImageGenerator>(this);
131 }
132  
133 public void RegionLoaded(Scene scene)
134 {
135 }
136  
137 public void RemoveRegion(Scene scene)
138 {
139 }
140  
141 public void Close()
142 {
143 }
144  
145 public string Name
146 {
147 get { return "Warp3DImageModule"; }
148 }
149  
150 public Type ReplaceableInterface
151 {
152 get { return null; }
153 }
154  
155 #endregion
156  
157 #region IMapImageGenerator Members
158  
159 public Bitmap CreateMapTile()
160 {
161 // Vector3 camPos = new Vector3(127.5f, 127.5f, 221.7025033688163f);
162 // Camera above the middle of the region
163 Vector3 camPos = new Vector3(
164 m_scene.RegionInfo.RegionSizeX/2 - 0.5f,
165 m_scene.RegionInfo.RegionSizeY/2 - 0.5f,
166 221.7025033688163f);
167 // Viewport viewing down onto the region
168 Viewport viewport = new Viewport(camPos, -Vector3.UnitZ, 1024f, 0.1f,
169 (int)m_scene.RegionInfo.RegionSizeX, (int)m_scene.RegionInfo.RegionSizeY,
170 (float)m_scene.RegionInfo.RegionSizeX, (float)m_scene.RegionInfo.RegionSizeY );
171 // Fill the viewport and return the image
172 return CreateMapTile(viewport, false);
173 }
174  
175 public Bitmap CreateViewImage(Vector3 camPos, Vector3 camDir, float fov, int width, int height, bool useTextures)
176 {
177 Viewport viewport = new Viewport(camPos, camDir, fov, Constants.RegionSize, 0.1f, width, height);
178 return CreateMapTile(viewport, useTextures);
179 }
180  
181 public Bitmap CreateMapTile(Viewport viewport, bool useTextures)
182 {
183 m_colors.Clear();
184  
185 int width = viewport.Width;
186 int height = viewport.Height;
187  
188 if (m_useAntiAliasing)
189 {
190 width *= 2;
191 height *= 2;
192 }
193  
194 WarpRenderer renderer = new WarpRenderer();
195  
196 renderer.CreateScene(width, height);
197 renderer.Scene.autoCalcNormals = false;
198  
199 #region Camera
200  
201 warp_Vector pos = ConvertVector(viewport.Position);
202 pos.z -= 0.001f; // Works around an issue with the Warp3D camera
203 warp_Vector lookat = warp_Vector.add(ConvertVector(viewport.Position), ConvertVector(viewport.LookDirection));
204  
205 renderer.Scene.defaultCamera.setPos(pos);
206 renderer.Scene.defaultCamera.lookAt(lookat);
207  
208 if (viewport.Orthographic)
209 {
210 renderer.Scene.defaultCamera.isOrthographic = true;
211 renderer.Scene.defaultCamera.orthoViewWidth = viewport.OrthoWindowWidth;
212 renderer.Scene.defaultCamera.orthoViewHeight = viewport.OrthoWindowHeight;
213 }
214 else
215 {
216 float fov = viewport.FieldOfView;
217 fov *= 1.75f; // FIXME: ???
218 renderer.Scene.defaultCamera.setFov(fov);
219 }
220  
221 #endregion Camera
222  
223 renderer.Scene.addLight("Light1", new warp_Light(new warp_Vector(1.0f, 0.5f, 1f), 0xffffff, 0, 320, 40));
224 renderer.Scene.addLight("Light2", new warp_Light(new warp_Vector(-1f, -1f, 1f), 0xffffff, 0, 100, 40));
225  
226 CreateWater(renderer);
227 CreateTerrain(renderer, m_textureTerrain);
228 if (m_drawPrimVolume)
229 CreateAllPrims(renderer, useTextures);
230  
231 renderer.Render();
232 Bitmap bitmap = renderer.Scene.getImage();
233  
234 if (m_useAntiAliasing)
235 {
236 using (Bitmap origBitmap = bitmap)
237 bitmap = ImageUtils.ResizeImage(origBitmap, viewport.Width, viewport.Height);
238 }
239  
240 // XXX: It shouldn't really be necesary to force a GC here as one should occur anyway pretty shortly
241 // afterwards. It's generally regarded as a bad idea to manually GC. If Warp3D is using lots of memory
242 // then this may be some issue with the Warp3D code itself, though it's also quite possible that generating
243 // this map tile simply takes a lot of memory.
244 foreach (var o in renderer.Scene.objectData.Values)
245 {
246 warp_Object obj = (warp_Object)o;
247 obj.vertexData = null;
248 obj.triangleData = null;
249 }
250  
251 renderer.Scene.removeAllObjects();
252 renderer = null;
253 viewport = null;
254  
255 m_colors.Clear();
256 GC.Collect();
257 m_log.Debug("[WARP 3D IMAGE MODULE]: GC.Collect()");
258  
259 return bitmap;
260 }
261  
262 public byte[] WriteJpeg2000Image()
263 {
264 try
265 {
266 using (Bitmap mapbmp = CreateMapTile())
267 return OpenJPEG.EncodeFromImage(mapbmp, true);
268 }
269 catch (Exception e)
270 {
271 // JPEG2000 encoder failed
272 m_log.Error("[WARP 3D IMAGE MODULE]: Failed generating terrain map: ", e);
273 }
274  
275 return null;
276 }
277  
278 #endregion
279  
280 #region Rendering Methods
281  
282 // Add a water plane to the renderer.
283 private void CreateWater(WarpRenderer renderer)
284 {
285 float waterHeight = (float)m_scene.RegionInfo.RegionSettings.WaterHeight;
286  
287 renderer.AddPlane("Water", m_scene.RegionInfo.RegionSizeX * 0.5f);
288 renderer.Scene.sceneobject("Water").setPos(m_scene.RegionInfo.RegionSizeX/2 - 0.5f,
289 waterHeight,
290 m_scene.RegionInfo.RegionSizeY/2 - 0.5f );
291  
292 warp_Material waterColorMaterial = new warp_Material(ConvertColor(WATER_COLOR));
293 waterColorMaterial.setReflectivity(0); // match water color with standard map module thanks lkalif
294 waterColorMaterial.setTransparency((byte)((1f - WATER_COLOR.A) * 255f));
295 renderer.Scene.addMaterial("WaterColor", waterColorMaterial);
296 renderer.SetObjectMaterial("Water", "WaterColor");
297 }
298  
299 // Add a terrain to the renderer.
300 // Note that we create a 'low resolution' 256x256 vertex terrain rather than trying for
301 // full resolution. This saves a lot of memory especially for very large regions.
302 private void CreateTerrain(WarpRenderer renderer, bool textureTerrain)
303 {
304 ITerrainChannel terrain = m_scene.Heightmap;
305  
306 // 'diff' is the difference in scale between the real region size and the size of terrain we're buiding
307 float diff = (float)m_scene.RegionInfo.RegionSizeX / 256f;
308  
309 warp_Object obj = new warp_Object(256 * 256, 255 * 255 * 2);
310  
311 // Create all the vertices for the terrain
312 for (float y = 0; y < m_scene.RegionInfo.RegionSizeY; y += diff)
313 {
314 for (float x = 0; x < m_scene.RegionInfo.RegionSizeX; x += diff)
315 {
316 warp_Vector pos = ConvertVector(x, y, (float)terrain[(int)x, (int)y]);
317 obj.addVertex(new warp_Vertex(pos,
318 x / (float)m_scene.RegionInfo.RegionSizeX,
319 (((float)m_scene.RegionInfo.RegionSizeY) - y) / m_scene.RegionInfo.RegionSizeY) );
320 }
321 }
322  
323 // Now that we have all the vertices, make another pass and create
324 // the normals for each of the surface triangles and
325 // create the list of triangle indices.
326 for (float y = 0; y < m_scene.RegionInfo.RegionSizeY; y += diff)
327 {
328 for (float x = 0; x < m_scene.RegionInfo.RegionSizeX; x += diff)
329 {
330 float newX = x / diff;
331 float newY = y / diff;
332 if (newX < 255 && newY < 255)
333 {
334 int v = (int)newY * 256 + (int)newX;
335  
336 // Normal for a triangle made up of three adjacent vertices
337 Vector3 v1 = new Vector3(newX, newY, (float)terrain[(int)x, (int)y]);
338 Vector3 v2 = new Vector3(newX + 1, newY, (float)terrain[(int)(x + 1), (int)y]);
339 Vector3 v3 = new Vector3(newX, newY + 1, (float)terrain[(int)x, ((int)(y + 1))]);
340 warp_Vector norm = ConvertVector(SurfaceNormal(v1, v2, v3));
341 norm = norm.reverse();
342 obj.vertex(v).n = norm;
343  
344 // Make two triangles for each of the squares in the grid of vertices
345 obj.addTriangle(
346 v,
347 v + 1,
348 v + 256);
349  
350 obj.addTriangle(
351 v + 256 + 1,
352 v + 256,
353 v + 1);
354 }
355 }
356 }
357  
358 renderer.Scene.addObject("Terrain", obj);
359  
360 UUID[] textureIDs = new UUID[4];
361 float[] startHeights = new float[4];
362 float[] heightRanges = new float[4];
363  
364 OpenSim.Framework.RegionSettings regionInfo = m_scene.RegionInfo.RegionSettings;
365  
366 textureIDs[0] = regionInfo.TerrainTexture1;
367 textureIDs[1] = regionInfo.TerrainTexture2;
368 textureIDs[2] = regionInfo.TerrainTexture3;
369 textureIDs[3] = regionInfo.TerrainTexture4;
370  
371 startHeights[0] = (float)regionInfo.Elevation1SW;
372 startHeights[1] = (float)regionInfo.Elevation1NW;
373 startHeights[2] = (float)regionInfo.Elevation1SE;
374 startHeights[3] = (float)regionInfo.Elevation1NE;
375  
376 heightRanges[0] = (float)regionInfo.Elevation2SW;
377 heightRanges[1] = (float)regionInfo.Elevation2NW;
378 heightRanges[2] = (float)regionInfo.Elevation2SE;
379 heightRanges[3] = (float)regionInfo.Elevation2NE;
380  
381 uint globalX, globalY;
382 Util.RegionHandleToWorldLoc(m_scene.RegionInfo.RegionHandle, out globalX, out globalY);
383  
384 warp_Texture texture;
385 using (
386 Bitmap image
387 = TerrainSplat.Splat(terrain, textureIDs, startHeights, heightRanges,
388 new Vector3d(globalX, globalY, 0.0), m_scene.AssetService, textureTerrain))
389 {
390 texture = new warp_Texture(image);
391 }
392  
393 warp_Material material = new warp_Material(texture);
394 material.setReflectivity(50);
395 renderer.Scene.addMaterial("TerrainColor", material);
396 renderer.Scene.material("TerrainColor").setReflectivity(0); // reduces tile seams a bit thanks lkalif
397 renderer.SetObjectMaterial("Terrain", "TerrainColor");
398 }
399  
400 private void CreateAllPrims(WarpRenderer renderer, bool useTextures)
401 {
402 if (m_primMesher == null)
403 return;
404  
405 m_scene.ForEachSOG(
406 delegate(SceneObjectGroup group)
407 {
408 CreatePrim(renderer, group.RootPart, useTextures);
409 foreach (SceneObjectPart child in group.Parts)
410 CreatePrim(renderer, child, useTextures);
411 }
412 );
413 }
414  
415 private void CreatePrim(WarpRenderer renderer, SceneObjectPart prim,
416 bool useTextures)
417 {
418 const float MIN_SIZE = 2f;
419  
420 if ((PCode)prim.Shape.PCode != PCode.Prim)
421 return;
422 if (prim.Scale.LengthSquared() < MIN_SIZE * MIN_SIZE)
423 return;
424  
425 FacetedMesh renderMesh = null;
426 Primitive omvPrim = prim.Shape.ToOmvPrimitive(prim.OffsetPosition, prim.RotationOffset);
427  
428 if (m_renderMeshes)
429 {
430 if (omvPrim.Sculpt != null && omvPrim.Sculpt.SculptTexture != UUID.Zero)
431 {
432 // Try fetchinng the asset
433 byte[] sculptAsset = m_scene.AssetService.GetData(omvPrim.Sculpt.SculptTexture.ToString());
434 if (sculptAsset != null)
435 {
436 // Is it a mesh?
437 if (omvPrim.Sculpt.Type == SculptType.Mesh)
438 {
439 AssetMesh meshAsset = new AssetMesh(omvPrim.Sculpt.SculptTexture, sculptAsset);
440 FacetedMesh.TryDecodeFromAsset(omvPrim, meshAsset, DetailLevel.Highest, out renderMesh);
441 meshAsset = null;
442 }
443 else // It's sculptie
444 {
445 IJ2KDecoder imgDecoder = m_scene.RequestModuleInterface<IJ2KDecoder>();
446 if (imgDecoder != null)
447 {
448 Image sculpt = imgDecoder.DecodeToImage(sculptAsset);
449 if (sculpt != null)
450 {
451 renderMesh = m_primMesher.GenerateFacetedSculptMesh(omvPrim, (Bitmap)sculpt,
452 DetailLevel.Medium);
453 sculpt.Dispose();
454 }
455 }
456 }
457 }
458 }
459 }
460  
461 // If not a mesh or sculptie, try the regular mesher
462 if (renderMesh == null)
463 {
464 renderMesh = m_primMesher.GenerateFacetedMesh(omvPrim, DetailLevel.Medium);
465 }
466  
467 if (renderMesh == null)
468 return;
469  
470 warp_Vector primPos = ConvertVector(prim.GetWorldPosition());
471 warp_Quaternion primRot = ConvertQuaternion(prim.RotationOffset);
472  
473 warp_Matrix m = warp_Matrix.quaternionMatrix(primRot);
474  
475 if (prim.ParentID != 0)
476 {
477 SceneObjectGroup group = m_scene.SceneGraph.GetGroupByPrim(prim.LocalId);
478 if (group != null)
479 m.transform(warp_Matrix.quaternionMatrix(ConvertQuaternion(group.RootPart.RotationOffset)));
480 }
481  
482 warp_Vector primScale = ConvertVector(prim.Scale);
483  
484 string primID = prim.UUID.ToString();
485  
486 // Create the prim faces
487 // TODO: Implement the useTextures flag behavior
488 for (int i = 0; i < renderMesh.Faces.Count; i++)
489 {
490 Face face = renderMesh.Faces[i];
491 string meshName = primID + "-Face-" + i.ToString();
492  
493 // Avoid adding duplicate meshes to the scene
494 if (renderer.Scene.objectData.ContainsKey(meshName))
495 {
496 continue;
497 }
498  
499 warp_Object faceObj = new warp_Object(face.Vertices.Count, face.Indices.Count / 3);
500  
501 for (int j = 0; j < face.Vertices.Count; j++)
502 {
503 Vertex v = face.Vertices[j];
504  
505 warp_Vector pos = ConvertVector(v.Position);
506 warp_Vector norm = ConvertVector(v.Normal);
507  
508 if (prim.Shape.SculptTexture == UUID.Zero)
509 norm = norm.reverse();
510 warp_Vertex vert = new warp_Vertex(pos, norm, v.TexCoord.X, v.TexCoord.Y);
511  
512 faceObj.addVertex(vert);
513 }
514  
515 for (int j = 0; j < face.Indices.Count; j += 3)
516 {
517 faceObj.addTriangle(
518 face.Indices[j + 0],
519 face.Indices[j + 1],
520 face.Indices[j + 2]);
521 }
522  
523 Primitive.TextureEntryFace teFace = prim.Shape.Textures.GetFace((uint)i);
524 Color4 faceColor = GetFaceColor(teFace);
525 string materialName = String.Empty;
526 if (m_texturePrims && prim.Scale.LengthSquared() > m_texturePrimSize*m_texturePrimSize)
527 materialName = GetOrCreateMaterial(renderer, faceColor, teFace.TextureID);
528 else
529 materialName = GetOrCreateMaterial(renderer, faceColor);
530  
531 faceObj.transform(m);
532 faceObj.setPos(primPos);
533 faceObj.scaleSelf(primScale.x, primScale.y, primScale.z);
534  
535 renderer.Scene.addObject(meshName, faceObj);
536  
537 renderer.SetObjectMaterial(meshName, materialName);
538 }
539 }
540  
541 private Color4 GetFaceColor(Primitive.TextureEntryFace face)
542 {
543 Color4 color;
544  
545 if (face.TextureID == UUID.Zero)
546 return face.RGBA;
547  
548 if (!m_colors.TryGetValue(face.TextureID, out color))
549 {
550 bool fetched = false;
551  
552 // Attempt to fetch the texture metadata
553 UUID metadataID = UUID.Combine(face.TextureID, TEXTURE_METADATA_MAGIC);
554 AssetBase metadata = m_scene.AssetService.GetCached(metadataID.ToString());
555 if (metadata != null)
556 {
557 OSDMap map = null;
558 try { map = OSDParser.Deserialize(metadata.Data) as OSDMap; } catch { }
559  
560 if (map != null)
561 {
562 color = map["X-JPEG2000-RGBA"].AsColor4();
563 fetched = true;
564 }
565 }
566  
567 if (!fetched)
568 {
569 // Fetch the texture, decode and get the average color,
570 // then save it to a temporary metadata asset
571 AssetBase textureAsset = m_scene.AssetService.Get(face.TextureID.ToString());
572 if (textureAsset != null)
573 {
574 int width, height;
575 color = GetAverageColor(textureAsset.FullID, textureAsset.Data, out width, out height);
576  
577 OSDMap data = new OSDMap { { "X-JPEG2000-RGBA", OSD.FromColor4(color) } };
578 metadata = new AssetBase
579 {
580 Data = System.Text.Encoding.UTF8.GetBytes(OSDParser.SerializeJsonString(data)),
581 Description = "Metadata for JPEG2000 texture " + face.TextureID.ToString(),
582 Flags = AssetFlags.Collectable,
583 FullID = metadataID,
584 ID = metadataID.ToString(),
585 Local = true,
586 Temporary = true,
587 Name = String.Empty,
588 Type = (sbyte)AssetType.Unknown
589 };
590 m_scene.AssetService.Store(metadata);
591 }
592 else
593 {
594 color = new Color4(0.5f, 0.5f, 0.5f, 1.0f);
595 }
596 }
597  
598 m_colors[face.TextureID] = color;
599 }
600  
601 return color * face.RGBA;
602 }
603  
604 private string GetOrCreateMaterial(WarpRenderer renderer, Color4 color)
605 {
606 string name = color.ToString();
607  
608 warp_Material material = renderer.Scene.material(name);
609 if (material != null)
610 return name;
611  
612 renderer.AddMaterial(name, ConvertColor(color));
613 if (color.A < 1f)
614 renderer.Scene.material(name).setTransparency((byte)((1f - color.A) * 255f));
615 return name;
616 }
617  
618 public string GetOrCreateMaterial(WarpRenderer renderer, Color4 faceColor, UUID textureID)
619 {
620 string materialName = "Color-" + faceColor.ToString() + "-Texture-" + textureID.ToString();
621  
622 if (renderer.Scene.material(materialName) == null)
623 {
624 renderer.AddMaterial(materialName, ConvertColor(faceColor));
625 if (faceColor.A < 1f)
626 {
627 renderer.Scene.material(materialName).setTransparency((byte) ((1f - faceColor.A)*255f));
628 }
629 warp_Texture texture = GetTexture(textureID);
630 if (texture != null)
631 renderer.Scene.material(materialName).setTexture(texture);
632 }
633  
634 return materialName;
635 }
636  
637 private warp_Texture GetTexture(UUID id)
638 {
639 warp_Texture ret = null;
640  
641 byte[] asset = m_scene.AssetService.GetData(id.ToString());
642  
643 if (asset != null)
644 {
645 IJ2KDecoder imgDecoder = m_scene.RequestModuleInterface<IJ2KDecoder>();
646  
647 try
648 {
649 using (Bitmap img = (Bitmap)imgDecoder.DecodeToImage(asset))
650 ret = new warp_Texture(img);
651 }
652 catch (Exception e)
653 {
654 m_log.Warn(string.Format("[WARP 3D IMAGE MODULE]: Failed to decode asset {0}, exception ", id), e);
655 }
656 }
657  
658 return ret;
659 }
660  
661 #endregion Rendering Methods
662  
663 #region Static Helpers
664  
665 // Note: axis change.
666 private static warp_Vector ConvertVector(float x, float y, float z)
667 {
668 return new warp_Vector(x, z, y);
669 }
670  
671 private static warp_Vector ConvertVector(Vector3 vector)
672 {
673 return new warp_Vector(vector.X, vector.Z, vector.Y);
674 }
675  
676 private static warp_Quaternion ConvertQuaternion(Quaternion quat)
677 {
678 return new warp_Quaternion(quat.X, quat.Z, quat.Y, -quat.W);
679 }
680  
681 private static int ConvertColor(Color4 color)
682 {
683 int c = warp_Color.getColor((byte)(color.R * 255f), (byte)(color.G * 255f), (byte)(color.B * 255f));
684 if (color.A < 1f)
685 c |= (byte)(color.A * 255f) << 24;
686  
687 return c;
688 }
689  
690 private static Vector3 SurfaceNormal(Vector3 c1, Vector3 c2, Vector3 c3)
691 {
692 Vector3 edge1 = new Vector3(c2.X - c1.X, c2.Y - c1.Y, c2.Z - c1.Z);
693 Vector3 edge2 = new Vector3(c3.X - c1.X, c3.Y - c1.Y, c3.Z - c1.Z);
694  
695 Vector3 normal = Vector3.Cross(edge1, edge2);
696 normal.Normalize();
697  
698 return normal;
699 }
700  
701 public static Color4 GetAverageColor(UUID textureID, byte[] j2kData, out int width, out int height)
702 {
703 ulong r = 0;
704 ulong g = 0;
705 ulong b = 0;
706 ulong a = 0;
707  
708 using (MemoryStream stream = new MemoryStream(j2kData))
709 {
710 try
711 {
712 int pixelBytes;
713  
714 using (Bitmap bitmap = (Bitmap)J2kImage.FromStream(stream))
715 {
716 width = bitmap.Width;
717 height = bitmap.Height;
718  
719 BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, bitmap.PixelFormat);
720 pixelBytes = (bitmap.PixelFormat == PixelFormat.Format24bppRgb) ? 3 : 4;
721  
722 // Sum up the individual channels
723 unsafe
724 {
725 if (pixelBytes == 4)
726 {
727 for (int y = 0; y < height; y++)
728 {
729 byte* row = (byte*)bitmapData.Scan0 + (y * bitmapData.Stride);
730  
731 for (int x = 0; x < width; x++)
732 {
733 b += row[x * pixelBytes + 0];
734 g += row[x * pixelBytes + 1];
735 r += row[x * pixelBytes + 2];
736 a += row[x * pixelBytes + 3];
737 }
738 }
739 }
740 else
741 {
742 for (int y = 0; y < height; y++)
743 {
744 byte* row = (byte*)bitmapData.Scan0 + (y * bitmapData.Stride);
745  
746 for (int x = 0; x < width; x++)
747 {
748 b += row[x * pixelBytes + 0];
749 g += row[x * pixelBytes + 1];
750 r += row[x * pixelBytes + 2];
751 }
752 }
753 }
754 }
755 }
756  
757 // Get the averages for each channel
758 const decimal OO_255 = 1m / 255m;
759 decimal totalPixels = (decimal)(width * height);
760  
761 decimal rm = ((decimal)r / totalPixels) * OO_255;
762 decimal gm = ((decimal)g / totalPixels) * OO_255;
763 decimal bm = ((decimal)b / totalPixels) * OO_255;
764 decimal am = ((decimal)a / totalPixels) * OO_255;
765  
766 if (pixelBytes == 3)
767 am = 1m;
768  
769 return new Color4((float)rm, (float)gm, (float)bm, (float)am);
770 }
771 catch (Exception ex)
772 {
773 m_log.WarnFormat(
774 "[WARP 3D IMAGE MODULE]: Error decoding JPEG2000 texture {0} ({1} bytes): {2}",
775 textureID, j2kData.Length, ex.Message);
776  
777 width = 0;
778 height = 0;
779 return new Color4(0.5f, 0.5f, 0.5f, 1.0f);
780 }
781 }
782 }
783  
784 #endregion Static Helpers
785 }
786  
787 public static class ImageUtils
788 {
789 /// <summary>
790 /// Performs bilinear interpolation between four values
791 /// </summary>
792 /// <param name="v00">First, or top left value</param>
793 /// <param name="v01">Second, or top right value</param>
794 /// <param name="v10">Third, or bottom left value</param>
795 /// <param name="v11">Fourth, or bottom right value</param>
796 /// <param name="xPercent">Interpolation value on the X axis, between 0.0 and 1.0</param>
797 /// <param name="yPercent">Interpolation value on fht Y axis, between 0.0 and 1.0</param>
798 /// <returns>The bilinearly interpolated result</returns>
799 public static float Bilinear(float v00, float v01, float v10, float v11, float xPercent, float yPercent)
800 {
801 return Utils.Lerp(Utils.Lerp(v00, v01, xPercent), Utils.Lerp(v10, v11, xPercent), yPercent);
802 }
803  
804 /// <summary>
805 /// Performs a high quality image resize
806 /// </summary>
807 /// <param name="image">Image to resize</param>
808 /// <param name="width">New width</param>
809 /// <param name="height">New height</param>
810 /// <returns>Resized image</returns>
811 public static Bitmap ResizeImage(Image image, int width, int height)
812 {
813 Bitmap result = new Bitmap(width, height);
814  
815 using (Graphics graphics = Graphics.FromImage(result))
816 {
817 graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
818 graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
819 graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
820 graphics.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
821  
822 graphics.DrawImage(image, 0, 0, result.Width, result.Height);
823 }
824  
825 return result;
826 }
827 }
828 }