OpenSim
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Events Macros
Warp3DImageModule.cs
Go to the documentation of this file.
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.PhysicsModules.SharedBase;
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")]
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  private Bitmap lastImage = null;
84  private DateTime lastImageTime = DateTime.MinValue;
85 
86  #region Region Module interface
87 
88  public void Initialise(IConfigSource source)
89  {
90  m_config = source;
91 
92  string[] configSections = new string[] { "Map", "Startup" };
93 
94  if (Util.GetConfigVarFromSections<string>(
95  m_config, "MapImageModule", configSections, "MapImageModule") != "Warp3DImageModule")
96  return;
97 
98  m_Enabled = true;
99 
100  m_drawPrimVolume
101  = Util.GetConfigVarFromSections<bool>(m_config, "DrawPrimOnMapTile", configSections, m_drawPrimVolume);
102  m_textureTerrain
103  = Util.GetConfigVarFromSections<bool>(m_config, "TextureOnMapTile", configSections, m_textureTerrain);
104  m_texturePrims
105  = Util.GetConfigVarFromSections<bool>(m_config, "TexturePrims", configSections, m_texturePrims);
106  m_texturePrimSize
107  = Util.GetConfigVarFromSections<float>(m_config, "TexturePrimSize", configSections, m_texturePrimSize);
108  m_renderMeshes
109  = Util.GetConfigVarFromSections<bool>(m_config, "RenderMeshes", configSections, m_renderMeshes);
110  m_useAntiAliasing
111  = Util.GetConfigVarFromSections<bool>(m_config, "UseAntiAliasing", configSections, m_useAntiAliasing);
112 
113  }
114 
115  public void AddRegion(Scene scene)
116  {
117  if (!m_Enabled)
118  return;
119 
120  m_scene = scene;
121 
122  List<string> renderers = RenderingLoader.ListRenderers(Util.ExecutingDirectory());
123  if (renderers.Count > 0)
124  m_log.Info("[MAPTILE]: Loaded prim mesher " + renderers[0]);
125  else
126  m_log.Info("[MAPTILE]: No prim mesher loaded, prim rendering will be disabled");
127 
128  m_scene.RegisterModuleInterface<IMapImageGenerator>(this);
129  }
130 
131  public void RegionLoaded(Scene scene)
132  {
133  }
134 
135  public void RemoveRegion(Scene scene)
136  {
137  }
138 
139  public void Close()
140  {
141  }
142 
143  public string Name
144  {
145  get { return "Warp3DImageModule"; }
146  }
147 
148  public Type ReplaceableInterface
149  {
150  get { return null; }
151  }
152 
153  #endregion
154 
155  #region IMapImageGenerator Members
156 
157  public Bitmap CreateMapTile()
158  {
159  /* this must be on all map, not just its image
160  if ((DateTime.Now - lastImageTime).TotalSeconds < 3600)
161  {
162  return (Bitmap)lastImage.Clone();
163  }
164  */
165 
166  List<string> renderers = RenderingLoader.ListRenderers(Util.ExecutingDirectory());
167  if (renderers.Count > 0)
168  {
169  m_primMesher = RenderingLoader.LoadRenderer(renderers[0]);
170  }
171 
172  Vector3 camPos = new Vector3(
173  m_scene.RegionInfo.RegionSizeX / 2 - 0.5f,
174  m_scene.RegionInfo.RegionSizeY / 2 - 0.5f,
175  221.7025033688163f);
176  // Viewport viewing down onto the region
177  Viewport viewport = new Viewport(camPos, -Vector3.UnitZ, 1024f, 0.1f,
178  (int)m_scene.RegionInfo.RegionSizeX, (int)m_scene.RegionInfo.RegionSizeY,
179  (float)m_scene.RegionInfo.RegionSizeX, (float)m_scene.RegionInfo.RegionSizeY);
180 
181  Bitmap tile = CreateMapTile(viewport, false);
182  m_primMesher = null;
183  return tile;
184 /*
185  lastImage = tile;
186  lastImageTime = DateTime.Now;
187  return (Bitmap)lastImage.Clone();
188  */
189  }
190 
191  public Bitmap CreateViewImage(Vector3 camPos, Vector3 camDir, float fov, int width, int height, bool useTextures)
192  {
193  Viewport viewport = new Viewport(camPos, camDir, fov, Constants.RegionSize, 0.1f, width, height);
194  return CreateMapTile(viewport, useTextures);
195  }
196 
197  public Bitmap CreateMapTile(Viewport viewport, bool useTextures)
198  {
199  m_colors.Clear();
200 
201  int width = viewport.Width;
202  int height = viewport.Height;
203 
204  if (m_useAntiAliasing)
205  {
206  width *= 2;
207  height *= 2;
208  }
209 
210  WarpRenderer renderer = new WarpRenderer();
211 
212  renderer.CreateScene(width, height);
213  renderer.Scene.autoCalcNormals = false;
214 
215  #region Camera
216 
217  warp_Vector pos = ConvertVector(viewport.Position);
218  pos.z -= 0.001f; // Works around an issue with the Warp3D camera
219  warp_Vector lookat = warp_Vector.add(ConvertVector(viewport.Position), ConvertVector(viewport.LookDirection));
220 
221  renderer.Scene.defaultCamera.setPos(pos);
222  renderer.Scene.defaultCamera.lookAt(lookat);
223 
224  if (viewport.Orthographic)
225  {
226  renderer.Scene.defaultCamera.isOrthographic = true;
227  renderer.Scene.defaultCamera.orthoViewWidth = viewport.OrthoWindowWidth;
228  renderer.Scene.defaultCamera.orthoViewHeight = viewport.OrthoWindowHeight;
229  }
230  else
231  {
232  float fov = viewport.FieldOfView;
233  fov *= 1.75f; // FIXME: ???
234  renderer.Scene.defaultCamera.setFov(fov);
235  }
236 
237  #endregion Camera
238 
239  renderer.Scene.addLight("Light1", new warp_Light(new warp_Vector(1.0f, 0.5f, 1f), 0xffffff, 0, 320, 40));
240  renderer.Scene.addLight("Light2", new warp_Light(new warp_Vector(-1f, -1f, 1f), 0xffffff, 0, 100, 40));
241 
242  CreateWater(renderer);
243  CreateTerrain(renderer, m_textureTerrain);
244  if (m_drawPrimVolume)
245  CreateAllPrims(renderer, useTextures);
246 
247  renderer.Render();
248  Bitmap bitmap = renderer.Scene.getImage();
249 
250  if (m_useAntiAliasing)
251  {
252  using (Bitmap origBitmap = bitmap)
253  bitmap = ImageUtils.ResizeImage(origBitmap, viewport.Width, viewport.Height);
254  }
255 
256  // XXX: It shouldn't really be necesary to force a GC here as one should occur anyway pretty shortly
257  // afterwards. It's generally regarded as a bad idea to manually GC. If Warp3D is using lots of memory
258  // then this may be some issue with the Warp3D code itself, though it's also quite possible that generating
259  // this map tile simply takes a lot of memory.
260  foreach (var o in renderer.Scene.objectData.Values)
261  {
262  warp_Object obj = (warp_Object)o;
263  obj.vertexData = null;
264  obj.triangleData = null;
265  }
266 
267  renderer.Scene.removeAllObjects();
268  renderer = null;
269  viewport = null;
270 
271  m_colors.Clear();
272  GC.Collect();
273  m_log.Debug("[WARP 3D IMAGE MODULE]: GC.Collect()");
274 
275  return bitmap;
276  }
277 
278  public byte[] WriteJpeg2000Image()
279  {
280  try
281  {
282  using (Bitmap mapbmp = CreateMapTile())
283  return OpenJPEG.EncodeFromImage(mapbmp, true);
284  }
285  catch (Exception e)
286  {
287  // JPEG2000 encoder failed
288  m_log.Error("[WARP 3D IMAGE MODULE]: Failed generating terrain map: ", e);
289  }
290 
291  return null;
292  }
293 
294  #endregion
295 
296  #region Rendering Methods
297 
298  // Add a water plane to the renderer.
299  private void CreateWater(WarpRenderer renderer)
300  {
301  float waterHeight = (float)m_scene.RegionInfo.RegionSettings.WaterHeight;
302 
303  renderer.AddPlane("Water", m_scene.RegionInfo.RegionSizeX * 0.5f);
304  renderer.Scene.sceneobject("Water").setPos(m_scene.RegionInfo.RegionSizeX / 2 - 0.5f,
305  waterHeight,
306  m_scene.RegionInfo.RegionSizeY / 2 - 0.5f);
307 
308  warp_Material waterColorMaterial = new warp_Material(ConvertColor(WATER_COLOR));
309  waterColorMaterial.setReflectivity(0); // match water color with standard map module thanks lkalif
310  waterColorMaterial.setTransparency((byte)((1f - WATER_COLOR.A) * 255f));
311  renderer.Scene.addMaterial("WaterColor", waterColorMaterial);
312  renderer.SetObjectMaterial("Water", "WaterColor");
313  }
314 
315  // Add a terrain to the renderer.
316  // Note that we create a 'low resolution' 256x256 vertex terrain rather than trying for
317  // full resolution. This saves a lot of memory especially for very large regions.
318  private void CreateTerrain(WarpRenderer renderer, bool textureTerrain)
319  {
320  ITerrainChannel terrain = m_scene.Heightmap;
321 
322  // 'diff' is the difference in scale between the real region size and the size of terrain we're buiding
323  float diff = (float)m_scene.RegionInfo.RegionSizeX / 256f;
324 
325  warp_Object obj = new warp_Object(256 * 256, 255 * 255 * 2);
326 
327  // Create all the vertices for the terrain
328  for (float y = 0; y < m_scene.RegionInfo.RegionSizeY; y += diff)
329  {
330  for (float x = 0; x < m_scene.RegionInfo.RegionSizeX; x += diff)
331  {
332  warp_Vector pos = ConvertVector(x, y, (float)terrain[(int)x, (int)y]);
333  obj.addVertex(new warp_Vertex(pos,
334  x / (float)m_scene.RegionInfo.RegionSizeX,
335  (((float)m_scene.RegionInfo.RegionSizeY) - y) / m_scene.RegionInfo.RegionSizeY));
336  }
337  }
338 
339  // Now that we have all the vertices, make another pass and create
340  // the normals for each of the surface triangles and
341  // create the list of triangle indices.
342  for (float y = 0; y < m_scene.RegionInfo.RegionSizeY; y += diff)
343  {
344  for (float x = 0; x < m_scene.RegionInfo.RegionSizeX; x += diff)
345  {
346  float newX = x / diff;
347  float newY = y / diff;
348  if (newX < 255 && newY < 255)
349  {
350  int v = (int)newY * 256 + (int)newX;
351 
352  // Normal for a triangle made up of three adjacent vertices
353  Vector3 v1 = new Vector3(newX, newY, (float)terrain[(int)x, (int)y]);
354  Vector3 v2 = new Vector3(newX + 1, newY, (float)terrain[(int)(x + 1), (int)y]);
355  Vector3 v3 = new Vector3(newX, newY + 1, (float)terrain[(int)x, ((int)(y + 1))]);
356  warp_Vector norm = ConvertVector(SurfaceNormal(v1, v2, v3));
357  norm = norm.reverse();
358  obj.vertex(v).n = norm;
359 
360  // Make two triangles for each of the squares in the grid of vertices
361  obj.addTriangle(
362  v,
363  v + 1,
364  v + 256);
365 
366  obj.addTriangle(
367  v + 256 + 1,
368  v + 256,
369  v + 1);
370  }
371  }
372  }
373 
374  renderer.Scene.addObject("Terrain", obj);
375 
376  UUID[] textureIDs = new UUID[4];
377  float[] startHeights = new float[4];
378  float[] heightRanges = new float[4];
379 
381 
382  textureIDs[0] = regionInfo.TerrainTexture1;
383  textureIDs[1] = regionInfo.TerrainTexture2;
384  textureIDs[2] = regionInfo.TerrainTexture3;
385  textureIDs[3] = regionInfo.TerrainTexture4;
386 
387  startHeights[0] = (float)regionInfo.Elevation1SW;
388  startHeights[1] = (float)regionInfo.Elevation1NW;
389  startHeights[2] = (float)regionInfo.Elevation1SE;
390  startHeights[3] = (float)regionInfo.Elevation1NE;
391 
392  heightRanges[0] = (float)regionInfo.Elevation2SW;
393  heightRanges[1] = (float)regionInfo.Elevation2NW;
394  heightRanges[2] = (float)regionInfo.Elevation2SE;
395  heightRanges[3] = (float)regionInfo.Elevation2NE;
396 
397  uint globalX, globalY;
398  Util.RegionHandleToWorldLoc(m_scene.RegionInfo.RegionHandle, out globalX, out globalY);
399 
400  warp_Texture texture;
401  using (
402  Bitmap image
403  = TerrainSplat.Splat(
404  terrain, textureIDs, startHeights, heightRanges,
405  new Vector3d(globalX, globalY, 0.0), m_scene.AssetService, textureTerrain))
406  {
407  texture = new warp_Texture(image);
408  }
409 
410  warp_Material material = new warp_Material(texture);
411  material.setReflectivity(50);
412  renderer.Scene.addMaterial("TerrainColor", material);
413  renderer.Scene.material("TerrainColor").setReflectivity(0); // reduces tile seams a bit thanks lkalif
414  renderer.SetObjectMaterial("Terrain", "TerrainColor");
415  }
416 
417  private void CreateAllPrims(WarpRenderer renderer, bool useTextures)
418  {
419  if (m_primMesher == null)
420  return;
421 
422  m_scene.ForEachSOG(
423  delegate(SceneObjectGroup group)
424  {
425  foreach (SceneObjectPart child in group.Parts)
426  CreatePrim(renderer, child, useTextures);
427  }
428  );
429  }
430 
431  private void CreatePrim(WarpRenderer renderer, SceneObjectPart prim,
432  bool useTextures)
433  {
434  const float MIN_SIZE = 2f;
435 
436  if ((PCode)prim.Shape.PCode != PCode.Prim)
437  return;
438  if (prim.Scale.LengthSquared() < MIN_SIZE * MIN_SIZE)
439  return;
440 
441  FacetedMesh renderMesh = null;
442  Primitive omvPrim = prim.Shape.ToOmvPrimitive(prim.OffsetPosition, prim.RotationOffset);
443 
444  if (m_renderMeshes)
445  {
446  if (omvPrim.Sculpt != null && omvPrim.Sculpt.SculptTexture != UUID.Zero)
447  {
448  // Try fetchinng the asset
449  byte[] sculptAsset = m_scene.AssetService.GetData(omvPrim.Sculpt.SculptTexture.ToString());
450  if (sculptAsset != null)
451  {
452  // Is it a mesh?
453  if (omvPrim.Sculpt.Type == SculptType.Mesh)
454  {
455  AssetMesh meshAsset = new AssetMesh(omvPrim.Sculpt.SculptTexture, sculptAsset);
456  FacetedMesh.TryDecodeFromAsset(omvPrim, meshAsset, DetailLevel.Highest, out renderMesh);
457  meshAsset = null;
458  }
459  else // It's sculptie
460  {
461  IJ2KDecoder imgDecoder = m_scene.RequestModuleInterface<IJ2KDecoder>();
462  if (imgDecoder != null)
463  {
464  Image sculpt = imgDecoder.DecodeToImage(sculptAsset);
465  if (sculpt != null)
466  {
467  renderMesh = m_primMesher.GenerateFacetedSculptMesh(omvPrim, (Bitmap)sculpt,
468  DetailLevel.Medium);
469  sculpt.Dispose();
470  }
471  }
472  }
473  }
474  }
475  }
476 
477  // If not a mesh or sculptie, try the regular mesher
478  if (renderMesh == null)
479  {
480  renderMesh = m_primMesher.GenerateFacetedMesh(omvPrim, DetailLevel.Medium);
481  }
482 
483  if (renderMesh == null)
484  return;
485 
486  warp_Vector primPos = ConvertVector(prim.GetWorldPosition());
487  warp_Quaternion primRot = ConvertQuaternion(prim.RotationOffset);
488 
489  warp_Matrix m = warp_Matrix.quaternionMatrix(primRot);
490 
491  if (prim.ParentID != 0)
492  {
493  SceneObjectGroup group = m_scene.SceneGraph.GetGroupByPrim(prim.LocalId);
494  if (group != null)
495  m.transform(warp_Matrix.quaternionMatrix(ConvertQuaternion(group.RootPart.RotationOffset)));
496  }
497 
498  warp_Vector primScale = ConvertVector(prim.Scale);
499 
500  string primID = prim.UUID.ToString();
501 
502  // Create the prim faces
503  // TODO: Implement the useTextures flag behavior
504  for (int i = 0; i < renderMesh.Faces.Count; i++)
505  {
506  Face face = renderMesh.Faces[i];
507  string meshName = primID + "-Face-" + i.ToString();
508 
509  // Avoid adding duplicate meshes to the scene
510  if (renderer.Scene.objectData.ContainsKey(meshName))
511  {
512  continue;
513  }
514 
515  warp_Object faceObj = new warp_Object(face.Vertices.Count, face.Indices.Count / 3);
516 
517  for (int j = 0; j < face.Vertices.Count; j++)
518  {
519  Vertex v = face.Vertices[j];
520 
521  warp_Vector pos = ConvertVector(v.Position);
522  warp_Vector norm = ConvertVector(v.Normal);
523 
524  if (prim.Shape.SculptTexture == UUID.Zero)
525  norm = norm.reverse();
526  warp_Vertex vert = new warp_Vertex(pos, norm, v.TexCoord.X, v.TexCoord.Y);
527 
528  faceObj.addVertex(vert);
529  }
530 
531  for (int j = 0; j < face.Indices.Count; j += 3)
532  {
533  faceObj.addTriangle(
534  face.Indices[j + 0],
535  face.Indices[j + 1],
536  face.Indices[j + 2]);
537  }
538 
539  Primitive.TextureEntryFace teFace = prim.Shape.Textures.GetFace((uint)i);
540  Color4 faceColor = GetFaceColor(teFace);
541  string materialName = String.Empty;
542  if (m_texturePrims && prim.Scale.LengthSquared() > m_texturePrimSize*m_texturePrimSize)
543  materialName = GetOrCreateMaterial(renderer, faceColor, teFace.TextureID);
544  else
545  materialName = GetOrCreateMaterial(renderer, faceColor);
546 
547  faceObj.transform(m);
548  faceObj.setPos(primPos);
549  faceObj.scaleSelf(primScale.x, primScale.y, primScale.z);
550 
551  renderer.Scene.addObject(meshName, faceObj);
552 
553  renderer.SetObjectMaterial(meshName, materialName);
554  }
555  }
556 
557  private Color4 GetFaceColor(Primitive.TextureEntryFace face)
558  {
559  Color4 color;
560 
561  if (face.TextureID == UUID.Zero)
562  return face.RGBA;
563 
564  if (!m_colors.TryGetValue(face.TextureID, out color))
565  {
566  bool fetched = false;
567 
568  // Attempt to fetch the texture metadata
569  UUID metadataID = UUID.Combine(face.TextureID, TEXTURE_METADATA_MAGIC);
570  AssetBase metadata = m_scene.AssetService.GetCached(metadataID.ToString());
571  if (metadata != null)
572  {
573  OSDMap map = null;
574  try { map = OSDParser.Deserialize(metadata.Data) as OSDMap; } catch { }
575 
576  if (map != null)
577  {
578  color = map["X-JPEG2000-RGBA"].AsColor4();
579  fetched = true;
580  }
581  }
582 
583  if (!fetched)
584  {
585  // Fetch the texture, decode and get the average color,
586  // then save it to a temporary metadata asset
587  AssetBase textureAsset = m_scene.AssetService.Get(face.TextureID.ToString());
588  if (textureAsset != null)
589  {
590  int width, height;
591  color = GetAverageColor(textureAsset.FullID, textureAsset.Data, out width, out height);
592 
593  OSDMap data = new OSDMap { { "X-JPEG2000-RGBA", OSD.FromColor4(color) } };
594  metadata = new AssetBase
595  {
596  Data = System.Text.Encoding.UTF8.GetBytes(OSDParser.SerializeJsonString(data)),
597  Description = "Metadata for JPEG2000 texture " + face.TextureID.ToString(),
598  Flags = AssetFlags.Collectable,
599  FullID = metadataID,
600  ID = metadataID.ToString(),
601  Local = true,
602  Temporary = true,
603  Name = String.Empty,
604  Type = (sbyte)AssetType.Unknown
605  };
606  m_scene.AssetService.Store(metadata);
607  }
608  else
609  {
610  color = new Color4(0.5f, 0.5f, 0.5f, 1.0f);
611  }
612  }
613 
614  m_colors[face.TextureID] = color;
615  }
616 
617  return color * face.RGBA;
618  }
619 
620  private string GetOrCreateMaterial(WarpRenderer renderer, Color4 color)
621  {
622  string name = color.ToString();
623 
624  warp_Material material = renderer.Scene.material(name);
625  if (material != null)
626  return name;
627 
628  renderer.AddMaterial(name, ConvertColor(color));
629  if (color.A < 1f)
630  renderer.Scene.material(name).setTransparency((byte)((1f - color.A) * 255f));
631  return name;
632  }
633 
634  public string GetOrCreateMaterial(WarpRenderer renderer, Color4 faceColor, UUID textureID)
635  {
636  string materialName = "Color-" + faceColor.ToString() + "-Texture-" + textureID.ToString();
637 
638  if (renderer.Scene.material(materialName) == null)
639  {
640  renderer.AddMaterial(materialName, ConvertColor(faceColor));
641  if (faceColor.A < 1f)
642  {
643  renderer.Scene.material(materialName).setTransparency((byte) ((1f - faceColor.A)*255f));
644  }
645  warp_Texture texture = GetTexture(textureID);
646  if (texture != null)
647  renderer.Scene.material(materialName).setTexture(texture);
648  }
649 
650  return materialName;
651  }
652 
653  private warp_Texture GetTexture(UUID id)
654  {
655  warp_Texture ret = null;
656 
657  byte[] asset = m_scene.AssetService.GetData(id.ToString());
658 
659  if (asset != null)
660  {
661  IJ2KDecoder imgDecoder = m_scene.RequestModuleInterface<IJ2KDecoder>();
662 
663  try
664  {
665  using (Bitmap img = (Bitmap)imgDecoder.DecodeToImage(asset))
666  ret = new warp_Texture(img);
667  }
668  catch (Exception e)
669  {
670  m_log.Warn(string.Format("[WARP 3D IMAGE MODULE]: Failed to decode asset {0}, exception ", id), e);
671  }
672  }
673 
674  return ret;
675  }
676 
677  #endregion Rendering Methods
678 
679  #region Static Helpers
680  // Note: axis change.
681  private static warp_Vector ConvertVector(float x, float y, float z)
682  {
683  return new warp_Vector(x, z, y);
684  }
685 
686  private static warp_Vector ConvertVector(Vector3 vector)
687  {
688  return new warp_Vector(vector.X, vector.Z, vector.Y);
689  }
690 
691  private static warp_Quaternion ConvertQuaternion(Quaternion quat)
692  {
693  return new warp_Quaternion(quat.X, quat.Z, quat.Y, -quat.W);
694  }
695 
696  private static int ConvertColor(Color4 color)
697  {
698  int c = warp_Color.getColor((byte)(color.R * 255f), (byte)(color.G * 255f), (byte)(color.B * 255f));
699  if (color.A < 1f)
700  c |= (byte)(color.A * 255f) << 24;
701 
702  return c;
703  }
704 
705  private static Vector3 SurfaceNormal(Vector3 c1, Vector3 c2, Vector3 c3)
706  {
707  Vector3 edge1 = new Vector3(c2.X - c1.X, c2.Y - c1.Y, c2.Z - c1.Z);
708  Vector3 edge2 = new Vector3(c3.X - c1.X, c3.Y - c1.Y, c3.Z - c1.Z);
709 
710  Vector3 normal = Vector3.Cross(edge1, edge2);
711  normal.Normalize();
712 
713  return normal;
714  }
715 
716  public static Color4 GetAverageColor(UUID textureID, byte[] j2kData, out int width, out int height)
717  {
718  ulong r = 0;
719  ulong g = 0;
720  ulong b = 0;
721  ulong a = 0;
722 
723  using (MemoryStream stream = new MemoryStream(j2kData))
724  {
725  try
726  {
727  int pixelBytes;
728 
729  using (Bitmap bitmap = (Bitmap)J2kImage.FromStream(stream))
730  {
731  width = bitmap.Width;
732  height = bitmap.Height;
733 
734  BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, bitmap.PixelFormat);
735  pixelBytes = (bitmap.PixelFormat == PixelFormat.Format24bppRgb) ? 3 : 4;
736 
737  // Sum up the individual channels
738  unsafe
739  {
740  if (pixelBytes == 4)
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  a += row[x * pixelBytes + 3];
752  }
753  }
754  }
755  else
756  {
757  for (int y = 0; y < height; y++)
758  {
759  byte* row = (byte*)bitmapData.Scan0 + (y * bitmapData.Stride);
760 
761  for (int x = 0; x < width; x++)
762  {
763  b += row[x * pixelBytes + 0];
764  g += row[x * pixelBytes + 1];
765  r += row[x * pixelBytes + 2];
766  }
767  }
768  }
769  }
770  }
771 
772  // Get the averages for each channel
773  const decimal OO_255 = 1m / 255m;
774  decimal totalPixels = (decimal)(width * height);
775 
776  decimal rm = ((decimal)r / totalPixels) * OO_255;
777  decimal gm = ((decimal)g / totalPixels) * OO_255;
778  decimal bm = ((decimal)b / totalPixels) * OO_255;
779  decimal am = ((decimal)a / totalPixels) * OO_255;
780 
781  if (pixelBytes == 3)
782  am = 1m;
783 
784  return new Color4((float)rm, (float)gm, (float)bm, (float)am);
785  }
786  catch (Exception ex)
787  {
788  m_log.WarnFormat(
789  "[WARP 3D IMAGE MODULE]: Error decoding JPEG2000 texture {0} ({1} bytes): {2}",
790  textureID, j2kData.Length, ex.Message);
791 
792  width = 0;
793  height = 0;
794  return new Color4(0.5f, 0.5f, 0.5f, 1.0f);
795  }
796  }
797  }
798 
799  #endregion Static Helpers
800  }
801 
802  public static class ImageUtils
803  {
814  public static float Bilinear(float v00, float v01, float v10, float v11, float xPercent, float yPercent)
815  {
816  return Utils.Lerp(Utils.Lerp(v00, v01, xPercent), Utils.Lerp(v10, v11, xPercent), yPercent);
817  }
818 
826  public static Bitmap ResizeImage(Image image, int width, int height)
827  {
828  Bitmap result = new Bitmap(width, height);
829 
830  using (Graphics graphics = Graphics.FromImage(result))
831  {
832  graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
833  graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
834  graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
835  graphics.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
836 
837  graphics.DrawImage(image, 0, 0, result.Width, result.Height);
838  }
839 
840  return result;
841  }
842  }
843 }
void Initialise(IConfigSource source)
This is called to initialize the region module. For shared modules, this is called exactly once...
static Color4 GetAverageColor(UUID textureID, byte[] j2kData, out int width, out int height)
float X
Definition: HelperTypes.cs:41
void RemoveRegion(Scene scene)
This is called whenever a Scene is removed. For shared modules, this can happen several times...
OpenSim.Server.Handlers.Simulation.Utils Utils
Bitmap CreateViewImage(Vector3 camPos, Vector3 camDir, float fov, int width, int height, bool useTextures)
OpenMetaverse.StructuredData.OSDMap OSDMap
OpenSim.Framework.RegionSettings RegionSettings
A scene object group is conceptually an object in the scene. The object is constituted of SceneObject...
void AddRegion(Scene scene)
This is called whenever a Scene is added. For shared modules, this can happen several times...
Asset class. All Assets are reference by this class or a class derived from this class ...
Definition: AssetBase.cs:49
Image DecodeToImage(byte[] j2kData)
Provides a synchronous decode direct to an image object
Vector3 Scale
Change the scale of this part.
Bitmap CreateMapTile(Viewport viewport, bool useTextures)
OpenSim.Region.OptionalModules.Scripting.Minimodule.Object.SculptType SculptType
Definition: SOPObject.cs:39
global::Warp3D.Warp3D WarpRenderer
override string ToString()
Definition: AssetBase.cs:246
string GetOrCreateMaterial(WarpRenderer renderer, Color4 faceColor, UUID textureID)
uint ParentID
The parent ID of this part.
void Close()
This is the inverse to Initialise. After a Close(), this instance won't be usable anymore...
float Y
Definition: HelperTypes.cs:47
void RegionLoaded(Scene scene)
This will be called once for every scene loaded. In a shared module this will be multiple times in on...
OpenSim.Region.ScriptEngine.Shared.LSL_Types.Vector3 vector
Definition: ICM_Api.cs:33
Vector3 GetWorldPosition()
Method for a prim to get it's world position from the group.