Esempio n. 1
0
        public ulong GetMaterialFaceHash(Primitive.TextureEntryFace teFace)
        {
            ulong hash = 5381;

            return(GetMaterialFaceHash(hash, teFace));
        }
Esempio n. 2
0
        private int GetFaceColor(Primitive.TextureEntryFace face)
        {
            int    color;
            Color4 ctmp = Color4.White;

            if (face.TextureID == UUID.Zero)
            {
                return(warp_Color.White);
            }

            if (!m_colors.TryGetValue(face.TextureID, out color))
            {
                bool fetched = false;

                // Attempt to fetch the texture metadata
                string    cacheName = "MAPCLR" + face.TextureID.ToString();
                AssetBase metadata  = m_scene.AssetService.GetCached(cacheName);
                if (metadata != null)
                {
                    OSDMap map = null;
                    try { map = OSDParser.Deserialize(metadata.Data) as OSDMap; } catch { }

                    if (map != null)
                    {
                        ctmp    = map["X-RGBA"].AsColor4();
                        fetched = true;
                    }
                }

                if (!fetched)
                {
                    // Fetch the texture, decode and get the average color,
                    // then save it to a temporary metadata asset
                    AssetBase textureAsset = m_scene.AssetService.Get(face.TextureID.ToString());
                    if (textureAsset != null)
                    {
                        int width, height;
                        ctmp = GetAverageColor(textureAsset.FullID, textureAsset.Data, out width, out height);

                        OSDMap data = new OSDMap {
                            { "X-RGBA", OSD.FromColor4(ctmp) }
                        };
                        metadata = new AssetBase
                        {
                            Data        = System.Text.Encoding.UTF8.GetBytes(OSDParser.SerializeJsonString(data)),
                            Description = "Metadata for texture color" + face.TextureID.ToString(),
                            Flags       = AssetFlags.Collectable,
                            FullID      = UUID.Zero,
                            ID          = cacheName,
                            Local       = true,
                            Temporary   = true,
                            Name        = String.Empty,
                            Type        = (sbyte)AssetType.Unknown
                        };
                        m_scene.AssetService.Store(metadata);
                    }
                    else
                    {
                        ctmp = new Color4(0.5f, 0.5f, 0.5f, 1.0f);
                    }
                }
                color = ConvertColor(ctmp);
                m_colors[face.TextureID] = color;
            }

            return(color);
        }
        ///<summary>
        ///</summary>
        ///<param name = "assetID"></param>
        ///<param name = "inventoryItem"></param>
        ///<param name = "data"></param>
        public UUID UploadCompleteHandler(string assetName, string assetDescription, UUID assetID,
                                          UUID inventoryItem, UUID parentFolder, byte[] data, string inventoryType,
                                          string assetType, uint everyone_mask, uint group_mask, uint next_owner_mask)
        {
            sbyte assType = 0;
            sbyte inType  = 0;

            if (inventoryType == "sound")
            {
                inType  = 1;
                assType = 1;
            }
            else if (inventoryType == "animation")
            {
                inType  = 19;
                assType = 20;
            }
            else if (inventoryType == "snapshot")
            {
                inType  = 15;
                assType = 0;
            }
            else if (inventoryType == "wearable")
            {
                inType = 18;
                switch (assetType)
                {
                case "bodypart":
                    assType = 13;
                    break;

                case "clothing":
                    assType = 5;
                    break;
                }
            }
            else if (inventoryType == "object")
            {
                inType  = (sbyte)InventoryType.Object;
                assType = (sbyte)AssetType.Object;

                List <Vector3>    positions     = new List <Vector3>();
                List <Quaternion> rotations     = new List <Quaternion>();
                OSDMap            request       = (OSDMap)OSDParser.DeserializeLLSDXml(data);
                OSDArray          instance_list = (OSDArray)request["instance_list"];
                OSDArray          mesh_list     = (OSDArray)request["mesh_list"];
                OSDArray          texture_list  = (OSDArray)request["texture_list"];
                SceneObjectGroup  grp           = null;

                List <UUID> textures = new List <UUID>();
#if (!ISWIN)
                for (int i = 0; i < texture_list.Count; i++)
                {
                    AssetBase textureAsset = new AssetBase(UUID.Random(), assetName, AssetType.Texture, m_service.AgentID);
                    textureAsset.Data = texture_list[i].AsBinary();
                    textureAsset.ID   = m_assetService.Store(textureAsset);
                    textures.Add(textureAsset.ID);
                }
#else
                foreach (AssetBase textureAsset in texture_list.Select(t => new AssetBase(UUID.Random(), assetName, AssetType.Texture,
                                                                                          m_service.AgentID)
                {
                    Data = t.AsBinary()
                }))
                {
                    textureAsset.ID = m_assetService.Store(textureAsset);
                    textures.Add(textureAsset.ID);
                }
#endif
                InventoryFolderBase meshFolder = m_inventoryService.GetFolderForType(m_service.AgentID,
                                                                                     InventoryType.Mesh, AssetType.Mesh);
                for (int i = 0; i < mesh_list.Count; i++)
                {
                    PrimitiveBaseShape pbs = PrimitiveBaseShape.CreateBox();

                    Primitive.TextureEntry textureEntry =
                        new Primitive.TextureEntry(Primitive.TextureEntry.WHITE_TEXTURE);
                    OSDMap inner_instance_list = (OSDMap)instance_list[i];

                    OSDArray face_list = (OSDArray)inner_instance_list["face_list"];
                    for (uint face = 0; face < face_list.Count; face++)
                    {
                        OSDMap faceMap = (OSDMap)face_list[(int)face];
                        Primitive.TextureEntryFace f = pbs.Textures.CreateFace(face);
                        if (faceMap.ContainsKey("fullbright"))
                        {
                            f.Fullbright = faceMap["fullbright"].AsBoolean();
                        }
                        if (faceMap.ContainsKey("diffuse_color"))
                        {
                            f.RGBA = faceMap["diffuse_color"].AsColor4();
                        }

                        int   textureNum = faceMap["image"].AsInteger();
                        float imagerot   = faceMap["imagerot"].AsInteger();
                        float offsets    = (float)faceMap["offsets"].AsReal();
                        float offsett    = (float)faceMap["offsett"].AsReal();
                        float scales     = (float)faceMap["scales"].AsReal();
                        float scalet     = (float)faceMap["scalet"].AsReal();

                        if (imagerot != 0)
                        {
                            f.Rotation = imagerot;
                        }
                        if (offsets != 0)
                        {
                            f.OffsetU = offsets;
                        }
                        if (offsett != 0)
                        {
                            f.OffsetV = offsett;
                        }
                        if (scales != 0)
                        {
                            f.RepeatU = scales;
                        }
                        if (scalet != 0)
                        {
                            f.RepeatV = scalet;
                        }
                        f.TextureID = textures.Count > textureNum ? textures[textureNum] : Primitive.TextureEntry.WHITE_TEXTURE;
                        textureEntry.FaceTextures[face] = f;
                    }
                    pbs.TextureEntry = textureEntry.GetBytes();

                    AssetBase meshAsset = new AssetBase(UUID.Random(), assetName, AssetType.Mesh, m_service.AgentID)
                    {
                        Data = mesh_list[i].AsBinary()
                    };
                    meshAsset.ID = m_assetService.Store(meshAsset);

                    if (meshFolder == null)
                    {
                        m_inventoryService.CreateUserInventory(m_service.AgentID, false);
                        meshFolder = m_inventoryService.GetFolderForType(m_service.AgentID, InventoryType.Mesh,
                                                                         AssetType.Mesh);
                    }

                    InventoryItemBase itemBase = new InventoryItemBase(UUID.Random(), m_service.AgentID)
                    {
                        AssetType           = (sbyte)AssetType.Mesh,
                        AssetID             = meshAsset.ID,
                        CreatorId           = m_service.AgentID.ToString(),
                        Folder              = meshFolder.ID,
                        InvType             = (int)InventoryType.Texture,
                        Name                = "(Mesh) - " + assetName,
                        CurrentPermissions  = (uint)PermissionMask.All,
                        BasePermissions     = (uint)PermissionMask.All,
                        EveryOnePermissions = everyone_mask,
                        GroupPermissions    = group_mask,
                        NextPermissions     = next_owner_mask
                    };
                    //Bad... but whatever
                    m_inventoryService.AddItem(itemBase);

                    pbs.SculptEntry   = true;
                    pbs.SculptTexture = meshAsset.ID;
                    pbs.SculptType    = (byte)SculptType.Mesh;
                    pbs.SculptData    = meshAsset.Data;

                    Vector3    position = inner_instance_list["position"].AsVector3();
                    Vector3    scale    = inner_instance_list["scale"].AsVector3();
                    Quaternion rotation = inner_instance_list["rotation"].AsQuaternion();

                    int physicsShapeType = inner_instance_list["physics_shape_type"].AsInteger();
                    int material         = inner_instance_list["material"].AsInteger();
                    int mesh             = inner_instance_list["mesh"].AsInteger();

                    UUID owner_id = m_service.AgentID;

                    IScene fakeScene = new Scene();
                    fakeScene.AddModuleInterfaces(m_service.Registry.GetInterfaces());

                    SceneObjectPart prim = new SceneObjectPart(owner_id, pbs, position, Quaternion.Identity,
                                                               Vector3.Zero, assetName, fakeScene)
                    {
                        Scale = scale, AbsolutePosition = position
                    };

                    rotations.Add(rotation);
                    positions.Add(position);
                    prim.UUID         = UUID.Random();
                    prim.CreatorID    = owner_id;
                    prim.OwnerID      = owner_id;
                    prim.GroupID      = UUID.Zero;
                    prim.LastOwnerID  = prim.OwnerID;
                    prim.CreationDate = Util.UnixTimeSinceEpoch();
                    prim.Name         = assetName;
                    prim.Description  = "";
                    prim.PhysicsType  = (byte)physicsShapeType;

                    prim.BaseMask      = (uint)PermissionMask.All;
                    prim.EveryoneMask  = everyone_mask;
                    prim.NextOwnerMask = next_owner_mask;
                    prim.GroupMask     = group_mask;
                    prim.OwnerMask     = (uint)PermissionMask.All;

                    if (grp == null)
                    {
                        grp = new SceneObjectGroup(prim, fakeScene);
                    }
                    else
                    {
                        grp.AddChild(prim, i + 1);
                    }
                    grp.RootPart.IsAttachment = false;
                }
                if (grp.ChildrenList.Count > 1) //Fix first link #
                {
                    grp.RootPart.LinkNum++;
                }

                Vector3 rootPos = positions[0];
                grp.SetAbsolutePosition(false, rootPos);
                for (int i = 0; i < positions.Count; i++)
                {
                    Vector3 offset = positions[i] - rootPos;
                    grp.ChildrenList[i].SetOffsetPosition(offset);
                    Vector3 abs        = grp.ChildrenList[i].AbsolutePosition;
                    Vector3 currentPos = positions[i];
                }
                //grp.Rotation = rotations[0];
                for (int i = 0; i < rotations.Count; i++)
                {
                    if (i != 0)
                    {
                        grp.ChildrenList[i].SetRotationOffset(false, rotations[i], false);
                    }
                }
                grp.UpdateGroupRotationR(rotations[0]);
                data = Encoding.ASCII.GetBytes(grp.ToXml2());
            }
            AssetBase asset = new AssetBase(assetID, assetName, (AssetType)assType, m_service.AgentID)
            {
                Data = data
            };
            asset.ID = m_assetService.Store(asset);
            assetID  = asset.ID;

            InventoryItemBase item = new InventoryItemBase
            {
                Owner               = m_service.AgentID,
                CreatorId           = m_service.AgentID.ToString(),
                ID                  = inventoryItem,
                AssetID             = asset.ID,
                Description         = assetDescription,
                Name                = assetName,
                AssetType           = assType,
                InvType             = inType,
                Folder              = parentFolder,
                CurrentPermissions  = (uint)PermissionMask.All,
                BasePermissions     = (uint)PermissionMask.All,
                EveryOnePermissions = everyone_mask,
                NextPermissions     = next_owner_mask,
                GroupPermissions    = group_mask,
                CreationDate        = Util.UnixTimeSinceEpoch()
            };

            m_inventoryService.AddItem(item);

            return(assetID);
        }
Esempio n. 4
0
        private Bitmap DrawObjectVolume(Scene whichScene, Bitmap mapbmp)
        {
            ITerrainChannel heightmap = whichScene.RequestModuleInterface <ITerrainChannel>();

            //m_log.Info("[MAPTILE]: Generating Maptile Step 2: Object Volume Profile");
            ISceneEntity[] objs = whichScene.Entities.GetEntities();
            Dictionary <uint, DrawStruct> z_sort = new Dictionary <uint, DrawStruct>();
            //SortedList<float, RectangleDrawStruct> z_sort = new SortedList<float, RectangleDrawStruct>();
            List <float> z_sortheights = new List <float>();
            List <uint>  z_localIDs    = new List <uint>();

            lock (objs)
            {
                foreach (ISceneEntity obj in objs)
                {
                    // Only draw the contents of SceneObjectGroup
                    if (obj is SceneObjectGroup)
                    {
                        SceneObjectGroup mapdot     = (SceneObjectGroup)obj;
                        Color            mapdotspot = Color.Gray; // Default color when prim color is white

                        // Loop over prim in group
                        foreach (SceneObjectPart part in mapdot.ChildrenList)
                        {
                            if (part == null || part.Shape == null)
                            {
                                continue;
                            }

                            // Draw if the object is at least .5 meter wide in any direction
                            if (part.Scale.X > .5f || part.Scale.Y > .5f || part.Scale.Z > .5f)
                            {
                                Vector3 pos = part.GetWorldPosition();

                                // skip prim outside of retion
                                if (pos.X < 0f || pos.X > 256f || pos.Y < 0f || pos.Y > 256f)
                                {
                                    continue;
                                }

                                // skip prim in non-finite position
                                if (Single.IsNaN(pos.X) || Single.IsNaN(pos.Y) ||
                                    Single.IsInfinity(pos.X) || Single.IsInfinity(pos.Y))
                                {
                                    continue;
                                }

                                // Figure out if object is under 256m above the height of the terrain
                                bool isBelow256AboveTerrain = false;

                                try
                                {
                                    if ((int)pos.X == m_scene.RegionInfo.RegionSizeX)
                                    {
                                        pos.X = m_scene.RegionInfo.RegionSizeX - 1;
                                    }
                                    if ((int)pos.Y == m_scene.RegionInfo.RegionSizeY)
                                    {
                                        pos.Y = m_scene.RegionInfo.RegionSizeY - 1;
                                    }
                                    isBelow256AboveTerrain = (pos.Z < (heightmap[(int)pos.X, (int)pos.Y] + 256f));
                                }
                                catch (Exception)
                                {
                                }

                                if (isBelow256AboveTerrain)
                                {
                                    // Try to get the RGBA of the default texture entry..
                                    //
                                    try
                                    {
                                        // get the null checks out of the way
                                        // skip the ones that break
                                        if (part == null)
                                        {
                                            continue;
                                        }

                                        if (part.Shape == null)
                                        {
                                            continue;
                                        }

                                        if (part.Shape.PCode == (byte)PCode.Tree || part.Shape.PCode == (byte)PCode.NewTree || part.Shape.PCode == (byte)PCode.Grass)
                                        {
                                            continue; // eliminates trees from this since we don't really have a good tree representation
                                        }
                                        // if you want tree blocks on the map comment the above line and uncomment the below line
                                        //mapdotspot = Color.PaleGreen;

                                        Primitive.TextureEntry textureEntry = part.Shape.Textures;

                                        if (textureEntry == null || textureEntry.DefaultTexture == null)
                                        {
                                            continue;
                                        }
                                        Color texcolor = Color.Black;
                                        try
                                        {
                                            Primitive.TextureEntryFace tx = part.Shape.Textures.CreateFace(6);
                                            texcolor = computeAverageColor(tx.TextureID, Color.Black);
                                        }
                                        catch (Exception)
                                        {
                                            texcolor = Color.FromArgb((int)textureEntry.DefaultTexture.RGBA.A, (int)textureEntry.DefaultTexture.RGBA.R, (int)textureEntry.DefaultTexture.RGBA.G, (int)textureEntry.DefaultTexture.RGBA.B);
                                        }

                                        if (!(texcolor.R == 255 && texcolor.G == 255 && texcolor.B == 255))
                                        {
                                            // Try to set the map spot color
                                            // If the color gets goofy somehow, skip it *shakes fist at Color4
                                            mapdotspot = texcolor;
                                        }
                                    }
                                    catch (IndexOutOfRangeException)
                                    {
                                        // Windows Array
                                    }
                                    catch (ArgumentOutOfRangeException)
                                    {
                                        // Mono Array
                                    }
                                    // Translate scale by rotation so scale is represented properly when object is rotated
                                    Vector3 lscale = new Vector3(part.Shape.Scale.X, part.Shape.Scale.Y, part.Shape.Scale.Z);
                                    Vector3 scale  = new Vector3();
                                    Vector3 tScale = new Vector3();
                                    Vector3 axPos  = new Vector3(pos.X, pos.Y, pos.Z);

                                    scale = lscale * part.GetWorldRotation();

                                    // negative scales don't work in this situation
                                    scale.X = Math.Abs(scale.X);
                                    scale.Y = Math.Abs(scale.Y);
                                    scale.Z = Math.Abs(scale.Z);

                                    // This scaling isn't very accurate and doesn't take into account the face rotation :P
                                    int mapdrawstartX = (int)(pos.X - scale.X);
                                    int mapdrawstartY = (int)(pos.Y - scale.Y);
                                    int mapdrawendX   = (int)(pos.X + scale.X);
                                    int mapdrawendY   = (int)(pos.Y + scale.Y);

                                    // If object is beyond the edge of the map, don't draw it to avoid errors
                                    if (mapdrawstartX < 0 || mapdrawstartX > (m_scene.RegionInfo.RegionSizeX - 1) || mapdrawendX < 0 || mapdrawendX > (m_scene.RegionInfo.RegionSizeX - 1) ||
                                        mapdrawstartY < 0 || mapdrawstartY > (m_scene.RegionInfo.RegionSizeY - 1) || mapdrawendY < 0 ||
                                        mapdrawendY > (m_scene.RegionInfo.RegionSizeY - 1))
                                    {
                                        continue;
                                    }

                                    #region obb face reconstruction part duex
                                    Vector3[] vertexes = new Vector3[8];

                                    // float[] distance = new float[6];
                                    Vector3[] FaceA = new Vector3[6]; // vertex A for Facei
                                    Vector3[] FaceB = new Vector3[6]; // vertex B for Facei
                                    Vector3[] FaceC = new Vector3[6]; // vertex C for Facei
                                    Vector3[] FaceD = new Vector3[6]; // vertex D for Facei

                                    tScale      = new Vector3(lscale.X, -lscale.Y, lscale.Z);
                                    scale       = ((tScale * part.GetWorldRotation()));
                                    vertexes[0] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z)));
                                    // vertexes[0].x = pos.X + vertexes[0].x;
                                    //vertexes[0].y = pos.Y + vertexes[0].y;
                                    //vertexes[0].z = pos.Z + vertexes[0].z;

                                    FaceA[0] = vertexes[0];
                                    FaceB[3] = vertexes[0];
                                    FaceA[4] = vertexes[0];

                                    tScale      = lscale;
                                    scale       = ((tScale * part.GetWorldRotation()));
                                    vertexes[1] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z)));

                                    // vertexes[1].x = pos.X + vertexes[1].x;
                                    // vertexes[1].y = pos.Y + vertexes[1].y;
                                    //vertexes[1].z = pos.Z + vertexes[1].z;

                                    FaceB[0] = vertexes[1];
                                    FaceA[1] = vertexes[1];
                                    FaceC[4] = vertexes[1];

                                    tScale = new Vector3(lscale.X, -lscale.Y, -lscale.Z);
                                    scale  = ((tScale * part.GetWorldRotation()));

                                    vertexes[2] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z)));

                                    //vertexes[2].x = pos.X + vertexes[2].x;
                                    //vertexes[2].y = pos.Y + vertexes[2].y;
                                    //vertexes[2].z = pos.Z + vertexes[2].z;

                                    FaceC[0] = vertexes[2];
                                    FaceD[3] = vertexes[2];
                                    FaceC[5] = vertexes[2];

                                    tScale      = new Vector3(lscale.X, lscale.Y, -lscale.Z);
                                    scale       = ((tScale * part.GetWorldRotation()));
                                    vertexes[3] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z)));

                                    //vertexes[3].x = pos.X + vertexes[3].x;
                                    // vertexes[3].y = pos.Y + vertexes[3].y;
                                    // vertexes[3].z = pos.Z + vertexes[3].z;

                                    FaceD[0] = vertexes[3];
                                    FaceC[1] = vertexes[3];
                                    FaceA[5] = vertexes[3];

                                    tScale      = new Vector3(-lscale.X, lscale.Y, lscale.Z);
                                    scale       = ((tScale * part.GetWorldRotation()));
                                    vertexes[4] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z)));

                                    // vertexes[4].x = pos.X + vertexes[4].x;
                                    // vertexes[4].y = pos.Y + vertexes[4].y;
                                    // vertexes[4].z = pos.Z + vertexes[4].z;

                                    FaceB[1] = vertexes[4];
                                    FaceA[2] = vertexes[4];
                                    FaceD[4] = vertexes[4];

                                    tScale      = new Vector3(-lscale.X, lscale.Y, -lscale.Z);
                                    scale       = ((tScale * part.GetWorldRotation()));
                                    vertexes[5] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z)));

                                    // vertexes[5].x = pos.X + vertexes[5].x;
                                    // vertexes[5].y = pos.Y + vertexes[5].y;
                                    // vertexes[5].z = pos.Z + vertexes[5].z;

                                    FaceD[1] = vertexes[5];
                                    FaceC[2] = vertexes[5];
                                    FaceB[5] = vertexes[5];

                                    tScale      = new Vector3(-lscale.X, -lscale.Y, lscale.Z);
                                    scale       = ((tScale * part.GetWorldRotation()));
                                    vertexes[6] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z)));

                                    // vertexes[6].x = pos.X + vertexes[6].x;
                                    // vertexes[6].y = pos.Y + vertexes[6].y;
                                    // vertexes[6].z = pos.Z + vertexes[6].z;

                                    FaceB[2] = vertexes[6];
                                    FaceA[3] = vertexes[6];
                                    FaceB[4] = vertexes[6];

                                    tScale      = new Vector3(-lscale.X, -lscale.Y, -lscale.Z);
                                    scale       = ((tScale * part.GetWorldRotation()));
                                    vertexes[7] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z)));

                                    // vertexes[7].x = pos.X + vertexes[7].x;
                                    // vertexes[7].y = pos.Y + vertexes[7].y;
                                    // vertexes[7].z = pos.Z + vertexes[7].z;

                                    FaceD[2] = vertexes[7];
                                    FaceC[3] = vertexes[7];
                                    FaceD[5] = vertexes[7];
                                    #endregion

                                    //int wy = 0;

                                    //bool breakYN = false; // If we run into an error drawing, break out of the
                                    // loop so we don't lag to death on error handling
                                    DrawStruct ds = new DrawStruct();
                                    ds.brush = new SolidBrush(mapdotspot);
                                    if (mapdot.RootPart.Shape.ProfileShape == ProfileShape.Circle)
                                    {
                                        ds.dr = DrawRoutine.Ellipse;
                                        Vector3 Location = new Vector3(part.AbsolutePosition.X - (part.Scale.X / 2),
                                                                       (256 - (part.AbsolutePosition.Y + (part.Scale.Y / 2))),
                                                                       0);
                                        Location.X /= m_scene.RegionInfo.RegionSizeX / Constants.RegionSize;
                                        Location.Y /= m_scene.RegionInfo.RegionSizeY / Constants.RegionSize;
                                        Location    = Location * part.GetWorldRotation();
                                        ds.rect     = new Rectangle((int)Location.X, (int)Location.Y, (int)Math.Abs(part.Shape.Scale.X), (int)Math.Abs(part.Shape.Scale.Y));
                                    }
                                    else //if (mapdot.RootPart.Shape.ProfileShape == ProfileShape.Square)
                                    {
                                        ds.dr = DrawRoutine.Rectangle;
                                        //ds.rect = new Rectangle(mapdrawstartX, (255 - mapdrawstartY), mapdrawendX - mapdrawstartX, mapdrawendY - mapdrawstartY);

                                        ds.trns = new face[FaceA.Length];

                                        for (int i = 0; i < FaceA.Length; i++)
                                        {
                                            Point[] working = new Point[5];
                                            working[0] = project(FaceA[i], axPos);
                                            working[1] = project(FaceB[i], axPos);
                                            working[2] = project(FaceD[i], axPos);
                                            working[3] = project(FaceC[i], axPos);
                                            working[4] = project(FaceA[i], axPos);

                                            face workingface = new face();
                                            workingface.pts = working;

                                            ds.trns[i] = workingface;
                                        }
                                    }

                                    if (!z_localIDs.Contains(part.LocalId))
                                    {
                                        z_sort[part.LocalId] = ds;
                                        z_localIDs.Add(part.LocalId);
                                        z_sortheights.Add(pos.Z);
                                    }
                                } // Object is within 256m Z of terrain
                            }     // object is at least a meter wide
                        }         // loop over group children
                    }             // entitybase is sceneobject group
                }                 // foreach loop over entities

                float[] sortedZHeights = z_sortheights.ToArray();
                uint[]  sortedlocalIds = z_localIDs.ToArray();

                // Sort prim by Z position
                Array.Sort(sortedZHeights, sortedlocalIds);

                Graphics g = Graphics.FromImage(mapbmp);

                for (int s = 0; s < sortedZHeights.Length; s++)
                {
                    if (z_sort.ContainsKey(sortedlocalIds[s]))
                    {
                        DrawStruct rectDrawStruct = z_sort[sortedlocalIds[s]];
                        if (rectDrawStruct.dr == DrawRoutine.Rectangle)
                        {
                            for (int r = 0; r < rectDrawStruct.trns.Length; r++)
                            {
                                g.FillPolygon(rectDrawStruct.brush, rectDrawStruct.trns[r].pts);
                            }
                        }
                        else if (rectDrawStruct.dr == DrawRoutine.Ellipse)
                        {
                            g.FillEllipse(rectDrawStruct.brush, rectDrawStruct.rect);
                        }
                        //g.FillRectangle(rectDrawStruct.brush , rectDrawStruct.rect);
                    }
                }
            } // lock entities objs

            //m_log.Info("[MAPTILE]: Generating Maptile Step 2: Done in " + (Environment.TickCount - tc) + " ms");
            return(mapbmp);
        }
Esempio n. 5
0
        /// <summary>
        /// Handle a fetch request for media textures
        /// </summary>
        /// <param name="omr"></param>
        /// <returns></returns>
        protected string HandleObjectMediaRequest(ObjectMediaRequest omr)
        {
            UUID primId = omr.PrimID;

            SceneObjectPart part = m_scene.GetSceneObjectPart(primId);

            if (null == part)
            {
                m_log.WarnFormat(
                    "[MOAP]: Received a GET ObjectMediaRequest for prim {0} but this doesn't exist in region {1}",
                    primId, m_scene.RegionInfo.RegionName);
                return(string.Empty);
            }

            if (part.Shape.Media == null)
            {
                return(string.Empty);
            }

            MediaEntry[] currentML = part.Shape.Media.ToArray();

            int nentries = currentML.Length;
            int nsides   = part.GetNumberOfSides();

            if (nentries > nsides)
            {
                nentries = nsides;
            }

            Primitive.TextureEntry te = part.Shape.Textures;
            bool isnull = true;

            for (int face = 0; face < nentries; ++face)
            {
                Primitive.TextureEntryFace teFace = te.GetFace((uint)face);
                if (!teFace.MediaFlags)
                {
                    currentML[face] = null;
                }
                else
                {
                    isnull = false;
                }
            }

            if (isnull)
            {
                //remove the damm thing
                part.Shape.Media = null;
                part.MediaUrl    = null;
                return(string.Empty);
            }

            ObjectMediaResponse resp = new ObjectMediaResponse();

            resp.PrimID = primId;

            resp.FaceMedia = currentML;

            resp.Version = part.MediaUrl;

            string rawResp = OSDParser.SerializeLLSDXmlString(resp.Serialize());

//            m_log.DebugFormat("[MOAP]: Got HandleObjectMediaRequestGet raw response is [{0}]", rawResp);

            return(rawResp);
        }
Esempio n. 6
0
        private Color4 GetFaceColor(Primitive.TextureEntryFace face)
        {
            Color4 color;

            if (face.TextureID == UUID.Zero)
            {
                return(face.RGBA);
            }

            if (!m_colors.TryGetValue(face.TextureID, out color))
            {
                bool fetched = false;

                // Attempt to fetch the texture metadata
                UUID      metadataID = UUID.Combine(face.TextureID, TEXTURE_METADATA_MAGIC);
                AssetBase metadata   = m_scene.AssetService.GetCached(metadataID.ToString());
                if (metadata != null)
                {
                    OSDMap map = null;
                    try { map = OSDParser.Deserialize(metadata.Data) as OSDMap; } catch { }

                    if (map != null)
                    {
                        color   = map["X-JPEG2000-RGBA"].AsColor4();
                        fetched = true;
                    }
                }

                if (!fetched)
                {
                    // Fetch the texture, decode and get the average color,
                    // then save it to a temporary metadata asset
                    AssetBase textureAsset = m_scene.AssetService.Get(face.TextureID.ToString());
                    if (textureAsset != null)
                    {
                        int width, height;
                        color = GetAverageColor(textureAsset.FullID, textureAsset.Data, out width, out height);

                        OSDMap data = new OSDMap {
                            { "X-JPEG2000-RGBA", OSD.FromColor4(color) }
                        };
                        metadata = new AssetBase
                        {
                            Data        = System.Text.Encoding.UTF8.GetBytes(OSDParser.SerializeJsonString(data)),
                            Description = "Metadata for JPEG2000 texture " + face.TextureID.ToString(),
                            Flags       = AssetFlags.Collectable,
                            FullID      = metadataID,
                            ID          = metadataID.ToString(),
                            Local       = true,
                            Temporary   = true,
                            Name        = String.Empty,
                            Type        = (sbyte)AssetType.Unknown
                        };
                        m_scene.AssetService.Store(metadata);
                    }
                    else
                    {
                        color = new Color4(0.5f, 0.5f, 0.5f, 1.0f);
                    }
                }

                m_colors[face.TextureID] = color;
            }

            return(color * face.RGBA);
        }
Esempio n. 7
0
        private void openPrimXMLToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            Prims = null;
            OpenFileDialog dialog = new OpenFileDialog();

            dialog.Filter = "Prim Package (*.zip)|*.zip";

            if (dialog.ShowDialog() == DialogResult.OK)
            {
                string tempPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(),
                                                         System.IO.Path.GetRandomFileName());

                try
                {
                    // Create a temporary directory
                    Directory.CreateDirectory(tempPath);

                    FastZip fastzip = new FastZip();
                    fastzip.ExtractZip(dialog.FileName, tempPath, String.Empty);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    return;
                }

                // Check for the prims.xml file
                string primsFile = System.IO.Path.Combine(tempPath, "prims.xml");
                if (!File.Exists(primsFile))
                {
                    MessageBox.Show("prims.xml not found in the archive");
                    return;
                }

                LLSD llsd = null;

                try { llsd = LLSDParser.DeserializeXml(File.ReadAllText(primsFile)); }
                catch (Exception ex) { MessageBox.Show(ex.Message); }

                if (llsd != null && llsd.Type == LLSDType.Map)
                {
                    List <Primitive> primList = Helpers.LLSDToPrimList(llsd);
                    Prims = new List <FacetedMesh>(primList.Count);

                    for (int i = 0; i < primList.Count; i++)
                    {
                        // TODO: Can't render sculpted prims without the textures
                        if (primList[i].Sculpt.SculptTexture != UUID.Zero)
                        {
                            continue;
                        }

                        Primitive   prim = primList[i];
                        FacetedMesh mesh = Render.Plugin.GenerateFacetedMesh(prim, DetailLevel.Highest);

                        // Create a FaceData struct for each face that stores the 3D data
                        // in a Tao.OpenGL friendly format
                        for (int j = 0; j < mesh.Faces.Count; j++)
                        {
                            Face     face = mesh.Faces[j];
                            FaceData data = new FaceData();

                            // Vertices for this face
                            data.Vertices = new float[face.Vertices.Count * 3];
                            for (int k = 0; k < face.Vertices.Count; k++)
                            {
                                data.Vertices[k * 3 + 0] = face.Vertices[k].Position.X;
                                data.Vertices[k * 3 + 1] = face.Vertices[k].Position.Y;
                                data.Vertices[k * 3 + 2] = face.Vertices[k].Position.Z;
                            }

                            // Indices for this face
                            data.Indices = face.Indices.ToArray();

                            // Texture transform for this face
                            Primitive.TextureEntryFace teFace = prim.Textures.GetFace((uint)j);
                            Render.Plugin.TransformTexCoords(face.Vertices, face.Center, teFace);

                            // Texcoords for this face
                            data.TexCoords = new float[face.Vertices.Count * 2];
                            for (int k = 0; k < face.Vertices.Count; k++)
                            {
                                data.TexCoords[k * 2 + 0] = face.Vertices[k].TexCoord.X;
                                data.TexCoords[k * 2 + 1] = face.Vertices[k].TexCoord.Y;
                            }

                            // Texture for this face
                            if (LoadTexture(tempPath, teFace.TextureID, ref data.Texture))
                            {
                                Bitmap bitmap = new Bitmap(data.Texture);
                                bitmap.RotateFlip(RotateFlipType.RotateNoneFlipY);
                                Rectangle  rectangle  = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
                                BitmapData bitmapData = bitmap.LockBits(rectangle, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);

                                Gl.glGenTextures(1, out data.TexturePointer);
                                Gl.glBindTexture(Gl.GL_TEXTURE_2D, data.TexturePointer);

                                Gl.glTexParameteri(Gl.GL_TEXTURE_2D, Gl.GL_TEXTURE_MIN_FILTER, Gl.GL_LINEAR_MIPMAP_LINEAR);
                                Gl.glTexParameteri(Gl.GL_TEXTURE_2D, Gl.GL_TEXTURE_MAG_FILTER, Gl.GL_LINEAR);
                                Gl.glTexParameteri(Gl.GL_TEXTURE_2D, Gl.GL_TEXTURE_WRAP_S, Gl.GL_REPEAT);
                                Gl.glTexParameteri(Gl.GL_TEXTURE_2D, Gl.GL_TEXTURE_WRAP_T, Gl.GL_REPEAT);
                                Gl.glTexParameteri(Gl.GL_TEXTURE_2D, Gl.GL_GENERATE_MIPMAP, Gl.GL_TRUE);

                                Glu.gluBuild2DMipmaps(Gl.GL_TEXTURE_2D, Gl.GL_RGB8, bitmap.Width, bitmap.Height, Gl.GL_BGR, Gl.GL_UNSIGNED_BYTE, bitmapData.Scan0);

                                bitmap.UnlockBits(bitmapData);
                                bitmap.Dispose();
                            }

                            // Set the UserData for this face to our FaceData struct
                            face.UserData = data;
                            mesh.Faces[j] = face;
                        }

                        Prims.Add(mesh);
                    }

                    // Setup the dropdown list of prims
                    PopulatePrimCombobox();

                    glControl.Invalidate();
                }
                else
                {
                    MessageBox.Show("Failed to load LLSD formatted primitive data from " + dialog.FileName);
                }

                Directory.Delete(tempPath);
            }
        }
Esempio n. 8
0
        private void UpdatePrimBlocking(Primitive prim)
        {
            FacetedMesh mesh         = null;
            FacetedMesh existingMesh = null;

            lock (Prims)
            {
                if (Prims.ContainsKey(prim.LocalID))
                {
                    existingMesh = Prims[prim.LocalID];
                }
            }

            if (prim.Textures == null)
            {
                return;
            }

            try
            {
                if (prim.Sculpt != null && prim.Sculpt.SculptTexture != UUID.Zero)
                {
                    if (prim.Sculpt.Type != SculptType.Mesh)
                    { // Regular sculptie
                        Image img = null;
                        if (!LoadTexture(prim.Sculpt.SculptTexture, ref img, true))
                        {
                            return;
                        }
                        mesh = renderer.GenerateFacetedSculptMesh(prim, (Bitmap)img, DetailLevel.Highest);
                    }
                    else
                    { // Mesh
                        AutoResetEvent gotMesh     = new AutoResetEvent(false);
                        bool           meshSuccess = false;

                        Client.Assets.RequestMesh(prim.Sculpt.SculptTexture, (success, meshAsset) =>
                        {
                            if (!success || !FacetedMesh.TryDecodeFromAsset(prim, meshAsset, DetailLevel.Highest, out mesh))
                            {
                                Logger.Log("Failed to fetch or decode the mesh asset", Helpers.LogLevel.Warning, Client);
                            }
                            else
                            {
                                meshSuccess = true;
                            }
                            gotMesh.Set();
                        });

                        if (!gotMesh.WaitOne(20 * 1000, false))
                        {
                            return;
                        }
                        if (!meshSuccess)
                        {
                            return;
                        }
                    }
                }
                else
                {
                    mesh = renderer.GenerateFacetedMesh(prim, DetailLevel.Highest);
                }
            }
            catch
            {
                return;
            }

            // Create a FaceData struct for each face that stores the 3D data
            // in a OpenGL friendly format
            for (int j = 0; j < mesh.Faces.Count; j++)
            {
                Face     face = mesh.Faces[j];
                FaceData data = new FaceData
                {
                    Vertices = new float[face.Vertices.Count * 3],
                    Normals  = new float[face.Vertices.Count * 3]
                };

                // Vertices for this face
                for (int k = 0; k < face.Vertices.Count; k++)
                {
                    data.Vertices[k * 3 + 0] = face.Vertices[k].Position.X;
                    data.Vertices[k * 3 + 1] = face.Vertices[k].Position.Y;
                    data.Vertices[k * 3 + 2] = face.Vertices[k].Position.Z;

                    data.Normals[k * 3 + 0] = face.Vertices[k].Normal.X;
                    data.Normals[k * 3 + 1] = face.Vertices[k].Normal.Y;
                    data.Normals[k * 3 + 2] = face.Vertices[k].Normal.Z;
                }

                // Indices for this face
                data.Indices = face.Indices.ToArray();

                // Texture transform for this face
                Primitive.TextureEntryFace teFace = prim.Textures.GetFace((uint)j);
                renderer.TransformTexCoords(face.Vertices, face.Center, teFace, prim.Scale);

                // Texcoords for this face
                data.TexCoords = new float[face.Vertices.Count * 2];
                for (int k = 0; k < face.Vertices.Count; k++)
                {
                    data.TexCoords[k * 2 + 0] = face.Vertices[k].TexCoord.X;
                    data.TexCoords[k * 2 + 1] = face.Vertices[k].TexCoord.Y;
                }

                // Set the UserData for this face to our FaceData struct
                face.UserData = data;
                mesh.Faces[j] = face;


                if (existingMesh != null &&
                    j < existingMesh.Faces.Count &&
                    existingMesh.Faces[j].TextureFace.TextureID == teFace.TextureID &&
                    ((FaceData)existingMesh.Faces[j].UserData).TextureInfo.TexturePointer != 0
                    )
                {
                    FaceData existingData = (FaceData)existingMesh.Faces[j].UserData;
                    data.TextureInfo.TexturePointer = existingData.TextureInfo.TexturePointer;
                }
                else
                {
                    var textureItem = new TextureLoadItem()
                    {
                        Data   = data,
                        Prim   = prim,
                        TeFace = teFace
                    };

                    PendingTextures.Enqueue(textureItem);
                }
            }

            lock (Prims)
            {
                Prims[prim.LocalID] = mesh;
            }
            SafeInvalidate();
        }
Esempio n. 9
0
 public bool Matches(Primitive.TextureEntryFace TextureEntry)
 {
     return(TextureID.Equals(TextureEntry.TextureID) && Color.Equals(TextureEntry.RGBA));
 }
        void CreatePrim(WarpRenderer renderer, ISceneChildEntity prim, bool texturePrims)
        {
            try {
                if ((PCode)prim.Shape.PCode != PCode.Prim)
                {
                    return;
                }
                if (prim.Scale.LengthSquared() < MIN_PRIM_SIZE * MIN_PRIM_SIZE)
                {
                    return;
                }

                Primitive   omvPrim    = prim.Shape.ToOmvPrimitive(prim.OffsetPosition, prim.GetRotationOffset());
                FacetedMesh renderMesh = null;

                // Are we dealing with a sculptie or mesh?
                if (omvPrim.Sculpt != null && omvPrim.Sculpt.SculptTexture != UUID.Zero)
                {
                    // Try fetching the asset
                    byte [] sculptAsset = m_scene.AssetService.GetData(omvPrim.Sculpt.SculptTexture.ToString());
                    if (sculptAsset != null)
                    {
                        // Is it a mesh?
                        if (omvPrim.Sculpt.Type == SculptType.Mesh)
                        {
                            AssetMesh meshAsset = new AssetMesh(omvPrim.Sculpt.SculptTexture, sculptAsset);
                            FacetedMesh.TryDecodeFromAsset(omvPrim, meshAsset, DetailLevel.Highest, out renderMesh);
                            meshAsset = null;
                        }
                        else   // It's sculptie
                        {
                            Image sculpt = m_imgDecoder.DecodeToImage(sculptAsset);
                            if (sculpt != null)
                            {
                                renderMesh = m_primMesher.GenerateFacetedSculptMesh(omvPrim, (Bitmap)sculpt,
                                                                                    DetailLevel.Medium);
                                sculpt.Dispose();
                            }
                        }
                        sculptAsset = null;
                    }
                    else
                    {
                        // missing sculpt data... replace with something
                        renderMesh = m_primMesher.GenerateFacetedMesh(omvPrim, DetailLevel.Medium);
                    }
                }
                else   // Prim
                {
                    renderMesh = m_primMesher.GenerateFacetedMesh(omvPrim, DetailLevel.Medium);
                }

                if (renderMesh == null)
                {
                    return;
                }

                warp_Vector     primPos = ConvertVector(prim.GetWorldPosition());
                warp_Quaternion primRot = ConvertQuaternion(prim.GetRotationOffset());

                warp_Matrix m = warp_Matrix.quaternionMatrix(primRot);

                if (prim.ParentID != 0)
                {
                    ISceneEntity group = m_scene.GetGroupByPrim(prim.LocalId);
                    if (group != null)
                    {
                        m.transform(warp_Matrix.quaternionMatrix(ConvertQuaternion(group.RootChild.GetRotationOffset())));
                    }
                }

                warp_Vector primScale = ConvertVector(prim.Scale);

                string primID = prim.UUID.ToString();

                // Create the prim faces
                for (int i = 0; i < renderMesh.Faces.Count; i++)
                {
                    Face   renderFace = renderMesh.Faces [i];
                    string meshName   = primID + "-Face-" + i;

                    warp_Object faceObj = new warp_Object(renderFace.Vertices.Count, renderFace.Indices.Count / 3);

                    foreach (Vertex v in renderFace.Vertices)
                    {
                        warp_Vector pos  = ConvertVector(v.Position);
                        warp_Vector norm = ConvertVector(v.Normal);

                        if (prim.Shape.SculptTexture == UUID.Zero)
                        {
                            norm = norm.reverse();
                        }
                        warp_Vertex vert = new warp_Vertex(pos, norm, v.TexCoord.X, v.TexCoord.Y);

                        faceObj.addVertex(vert);
                    }

                    for (int j = 0; j < renderFace.Indices.Count;)
                    {
                        faceObj.addTriangle(
                            renderFace.Indices [j++],
                            renderFace.Indices [j++],
                            renderFace.Indices [j++]);
                    }

                    Primitive.TextureEntryFace teFace = prim.Shape.Textures.GetFace((uint)i);
                    string materialName;
                    Color4 faceColor = GetFaceColor(teFace);

                    if (texturePrims && (prim.Scale.LengthSquared() > m_texturePrimSize))
                    {
                        materialName = GetOrCreateMaterial(renderer, faceColor, teFace.TextureID);
                    }
                    else
                    {
                        materialName = GetOrCreateMaterial(renderer, faceColor);
                    }

                    faceObj.transform(m);
                    faceObj.setPos(primPos);
                    faceObj.scaleSelf(primScale.x, primScale.y, primScale.z);

                    renderer.Scene.addObject(meshName, faceObj);

                    renderer.SetObjectMaterial(meshName, materialName);

                    faceObj = null;
                }
                renderMesh.Faces.Clear();
                renderMesh = null;
            } catch (Exception ex) {
                MainConsole.Instance.Warn("[WarpTile generator]: Exception creating prim, " + ex);
            }
        }
Esempio n. 11
0
        private void RenderObjects(RenderPass pass)
        {
            lock (Prims)
            {
                int primNr = 0;
                foreach (FacetedMesh mesh in Prims.Values)
                {
                    primNr++;
                    Primitive prim = mesh.Prim;
                    // Individual prim matrix
                    GL.PushMatrix();

                    if (prim.ParentID == RootPrimLocalID)
                    {
                        FacetedMesh parent = null;
                        if (Prims.TryGetValue(prim.ParentID, out parent))
                        {
                            // Apply prim translation and rotation relative to the root prim
                            GL.MultMatrix(Math3D.CreateRotationMatrix(parent.Prim.Rotation));
                            //GL.MultMatrixf(Math3D.CreateTranslationMatrix(parent.Prim.Position));
                        }

                        // Prim roation relative to root
                        GL.MultMatrix(Math3D.CreateTranslationMatrix(prim.Position));
                    }

                    // Prim roation
                    GL.MultMatrix(Math3D.CreateRotationMatrix(prim.Rotation));

                    // Prim scaling
                    GL.Scale(prim.Scale.X, prim.Scale.Y, prim.Scale.Z);

                    // Draw the prim faces
                    for (int j = 0; j < mesh.Faces.Count; j++)
                    {
                        Primitive.TextureEntryFace teFace = mesh.Prim.Textures.FaceTextures[j];
                        Face     face = mesh.Faces[j];
                        FaceData data = (FaceData)face.UserData;

                        if (teFace == null)
                        {
                            teFace = mesh.Prim.Textures.DefaultTexture;
                        }

                        if (pass == RenderPass.Picking)
                        {
                            data.PickingID = primNr;
                            var primNrBytes = Utils.Int16ToBytes((short)primNr);
                            var faceColor   = new byte[] { primNrBytes[0], primNrBytes[1], (byte)j, 255 };

                            GL.Color4(faceColor);
                        }
                        else
                        {
                            bool belongToAlphaPass = (teFace.RGBA.A < 0.99) || data.TextureInfo.HasAlpha;

                            if (belongToAlphaPass && pass != RenderPass.Alpha)
                            {
                                continue;
                            }
                            if (!belongToAlphaPass && pass == RenderPass.Alpha)
                            {
                                continue;
                            }

                            // Don't render transparent faces
                            if (teFace.RGBA.A <= 0.01f)
                            {
                                continue;
                            }

                            switch (teFace.Shiny)
                            {
                            case Shininess.High:
                                GL.Material(MaterialFace.Front, MaterialParameter.Shininess, 94f);
                                break;

                            case Shininess.Medium:
                                GL.Material(MaterialFace.Front, MaterialParameter.Shininess, 64f);
                                break;

                            case Shininess.Low:
                                GL.Material(MaterialFace.Front, MaterialParameter.Shininess, 24f);
                                break;

                            case Shininess.None:
                            default:
                                GL.Material(MaterialFace.Front, MaterialParameter.Shininess, 0f);
                                break;
                            }

                            var faceColor = new float[] { teFace.RGBA.R, teFace.RGBA.G, teFace.RGBA.B, teFace.RGBA.A };

                            GL.Color4(faceColor);
                            GL.Material(MaterialFace.Front, MaterialParameter.AmbientAndDiffuse, faceColor);
                            GL.Material(MaterialFace.Front, MaterialParameter.Specular, faceColor);

                            if (data.TextureInfo.TexturePointer != 0)
                            {
                                GL.Enable(EnableCap.Texture2D);
                            }
                            else
                            {
                                GL.Disable(EnableCap.Texture2D);
                            }

                            // Bind the texture
                            GL.BindTexture(TextureTarget.Texture2D, data.TextureInfo.TexturePointer);
                        }

                        GL.TexCoordPointer(2, TexCoordPointerType.Float, 0, data.TexCoords);
                        GL.VertexPointer(3, VertexPointerType.Float, 0, data.Vertices);
                        GL.NormalPointer(NormalPointerType.Float, 0, data.Normals);
                        GL.DrawElements(PrimitiveType.Triangles, data.Indices.Length, DrawElementsType.UnsignedShort, data.Indices);
                    }

                    // Pop the prim matrix
                    GL.PopMatrix();
                }
            }
        }
Esempio n. 12
0
        public override string Execute(string[] args, UUID fromAgentID)
        {
            if (args.Length != 1)
            {
                return("Usage: dumpoutfit [avatar-uuid]");
            }

            UUID target;

            if (!UUID.TryParse(args[0], out target))
            {
                return("Usage: dumpoutfit [avatar-uuid]");
            }

            lock (Client.Network.Simulators)
            {
                for (int i = 0; i < Client.Network.Simulators.Count; i++)
                {
                    Avatar targetAv = Client.Network.Simulators[i].ObjectsAvatars.Find(
                        avatar => avatar.ID == target
                        );

                    if (targetAv != null)
                    {
                        StringBuilder output = new StringBuilder("Downloading ");

                        lock (OutfitAssets) OutfitAssets.Clear();

                        for (int j = 0; j < targetAv.Textures.FaceTextures.Length; j++)
                        {
                            Primitive.TextureEntryFace face = targetAv.Textures.FaceTextures[j];

                            if (face != null)
                            {
                                ImageType type = ImageType.Normal;

                                switch ((AvatarTextureIndex)j)
                                {
                                case AvatarTextureIndex.HeadBaked:
                                case AvatarTextureIndex.EyesBaked:
                                case AvatarTextureIndex.UpperBaked:
                                case AvatarTextureIndex.LowerBaked:
                                case AvatarTextureIndex.SkirtBaked:
                                    type = ImageType.Baked;
                                    break;
                                }

                                OutfitAssets.Add(face.TextureID);
                                Client.Assets.RequestImage(face.TextureID, type, Assets_OnImageReceived);
                                output.Append(((AvatarTextureIndex)j).ToString());
                                output.Append(" ");
                            }
                        }

                        return(output.ToString());
                    }
                }
            }

            return("Couldn't find avatar " + target.ToString());
        }
Esempio n. 13
0
 public bool Matches(Primitive.TextureEntryFace TextureEntry)
 {
     return(TextureID == TextureEntry.TextureID && Color == TextureEntry.RGBA);
 }
Esempio n. 14
0
        public void Export(string Filename)
        {
            FileName = Filename;

            MeshedPrims.Clear();

            if (string.IsNullOrEmpty(FileName))
            {
                return;
            }

            WorkPool.QueueUserWorkItem(sync =>
            {
                if (ExportTextures)
                {
                    SaveTextures();
                }
                for (int i = 0; i < Prims.Count; i++)
                {
                    if (!CanExport(Prims[i]))
                    {
                        continue;
                    }

                    FacetedMesh mesh = MeshPrim(Prims[i]);
                    if (mesh == null)
                    {
                        continue;
                    }

                    for (int j = 0; j < mesh.Faces.Count; j++)
                    {
                        Face face = mesh.Faces[j];

                        Primitive.TextureEntryFace teFace = mesh.Faces[j].TextureFace;
                        if (teFace == null)
                        {
                            continue;
                        }


                        // Sculpt UV vertically flipped compared to prims. Flip back
                        if (Prims[i].Sculpt != null && Prims[i].Sculpt.SculptTexture != UUID.Zero && Prims[i].Sculpt.Type != SculptType.Mesh)
                        {
                            teFace          = (Primitive.TextureEntryFace)teFace.Clone();
                            teFace.RepeatV *= -1;
                        }

                        // Texture transform for this face
                        Mesher.TransformTexCoords(face.Vertices, face.Center, teFace, Prims[i].Scale);
                    }
                    MeshedPrims.Add(mesh);
                }

                string msg;
                if (MeshedPrims.Count == 0)
                {
                    msg = string.Format("Can export 0 out of {0} prims.{1}{1}Skipping.", Prims.Count, Environment.NewLine);
                }
                else
                {
                    msg = string.Format("Exported {0} out of {1} objects to{2}{2}{3}", MeshedPrims.Count, Prims.Count, Environment.NewLine, FileName);
                }
                GenerateCollada();
                File.WriteAllText(FileName, DocToString(Doc));
                OnProgress(msg);
            });
        }
Esempio n. 15
0
        private void CreatePrim(WarpRenderer renderer, SceneObjectPart prim,
                                bool useTextures)
        {
            const float MIN_SIZE = 2f;

            if ((PCode)prim.Shape.PCode != PCode.Prim)
            {
                return;
            }
            if (prim.Scale.LengthSquared() < MIN_SIZE * MIN_SIZE)
            {
                return;
            }

            Primitive   omvPrim    = prim.Shape.ToOmvPrimitive(prim.OffsetPosition, prim.RotationOffset);
            FacetedMesh renderMesh = m_primMesher.GenerateFacetedMesh(omvPrim, DetailLevel.Medium);

            if (renderMesh == null)
            {
                return;
            }

            warp_Vector     primPos = ConvertVector(prim.GetWorldPosition());
            warp_Quaternion primRot = ConvertQuaternion(prim.RotationOffset);

            warp_Matrix m = warp_Matrix.quaternionMatrix(primRot);

            if (prim.ParentID != 0)
            {
                SceneObjectGroup group = m_scene.SceneGraph.GetGroupByPrim(prim.LocalId);
                if (group != null)
                {
                    m.transform(warp_Matrix.quaternionMatrix(ConvertQuaternion(group.RootPart.RotationOffset)));
                }
            }

            warp_Vector primScale = ConvertVector(prim.Scale);

            string primID = prim.UUID.ToString();

            // Create the prim faces
            // TODO: Implement the useTextures flag behavior
            for (int i = 0; i < renderMesh.Faces.Count; i++)
            {
                Face   face     = renderMesh.Faces[i];
                string meshName = primID + "-Face-" + i.ToString();

                // Avoid adding duplicate meshes to the scene
                if (renderer.Scene.objectData.ContainsKey(meshName))
                {
                    continue;
                }

                warp_Object faceObj = new warp_Object(face.Vertices.Count, face.Indices.Count / 3);

                for (int j = 0; j < face.Vertices.Count; j++)
                {
                    Vertex v = face.Vertices[j];

                    warp_Vector pos  = ConvertVector(v.Position);
                    warp_Vector norm = ConvertVector(v.Normal);

                    if (prim.Shape.SculptTexture == UUID.Zero)
                    {
                        norm = norm.reverse();
                    }
                    warp_Vertex vert = new warp_Vertex(pos, norm, v.TexCoord.X, v.TexCoord.Y);

                    faceObj.addVertex(vert);
                }

                for (int j = 0; j < face.Indices.Count; j += 3)
                {
                    faceObj.addTriangle(
                        face.Indices[j + 0],
                        face.Indices[j + 1],
                        face.Indices[j + 2]);
                }

                Primitive.TextureEntryFace teFace = prim.Shape.Textures.GetFace((uint)i);
                Color4 faceColor    = GetFaceColor(teFace);
                string materialName = GetOrCreateMaterial(renderer, faceColor);

                faceObj.transform(m);
                faceObj.setPos(primPos);
                faceObj.scaleSelf(primScale.x, primScale.y, primScale.z);

                renderer.Scene.addObject(meshName, faceObj);

                renderer.SetObjectMaterial(meshName, materialName);
            }
        }
            /// <summary>
            /// Called once new texture data has been received for this updater.
            /// </summary>
            public void DataReceived(byte[] data, Scene scene)
            {
                SceneObjectPart part = scene.GetSceneObjectPart(PrimID);

                if (part == null || data == null || data.Length <= 1)
                {
                    string msg =
                        String.Format("DynamicTextureModule: Error preparing image using URL {0}", Url);
                    scene.SimChat(Utils.StringToBytes(msg), ChatTypeEnum.Say,
                                  0, part.ParentGroup.RootPart.AbsolutePosition, part.Name, part.UUID, false);
                    return;
                }

                byte[]    assetData = null;
                AssetBase oldAsset  = null;

                if (BlendWithOldTexture)
                {
                    Primitive.TextureEntryFace defaultFace = part.Shape.Textures.DefaultTexture;
                    if (defaultFace != null)
                    {
                        oldAsset = scene.AssetService.Get(defaultFace.TextureID.ToString());

                        if (oldAsset != null)
                        {
                            assetData = BlendTextures(data, oldAsset.Data, SetNewFrontAlpha, FrontAlpha);
                        }
                    }
                }

                if (assetData == null)
                {
                    assetData = new byte[data.Length];
                    Array.Copy(data, assetData, data.Length);
                }

                // Create a new asset for user
                AssetBase asset = new AssetBase(UUID.Random(), "DynamicImage" + Util.RandomClass.Next(1, 10000), (sbyte)AssetType.Texture,
                                                scene.RegionInfo.RegionID.ToString());

                asset.Data        = assetData;
                asset.Description = String.Format("URL image : {0}", Url);
                asset.Local       = false;
                asset.Temporary   = ((Disp & DISP_TEMP) != 0);
                scene.AssetService.Store(asset);
//                scene.CommsManager.AssetCache.AddAsset(asset);

                IJ2KDecoder cacheLayerDecode = scene.RequestModuleInterface <IJ2KDecoder>();

                if (cacheLayerDecode != null)
                {
                    cacheLayerDecode.Decode(asset.FullID, asset.Data);
                    cacheLayerDecode = null;
                    LastAssetID      = asset.FullID;
                }

                UUID oldID = UUID.Zero;

                lock (part)
                {
                    // mostly keep the values from before
                    Primitive.TextureEntry tmptex = part.Shape.Textures;

                    // remove the old asset from the cache
                    oldID = tmptex.DefaultTexture.TextureID;

                    if (Face == ALL_SIDES)
                    {
                        tmptex.DefaultTexture.TextureID = asset.FullID;
                    }
                    else
                    {
                        try
                        {
                            Primitive.TextureEntryFace texface = tmptex.CreateFace((uint)Face);
                            texface.TextureID         = asset.FullID;
                            tmptex.FaceTextures[Face] = texface;
                        }
                        catch (Exception)
                        {
                            tmptex.DefaultTexture.TextureID = asset.FullID;
                        }
                    }

                    // I'm pretty sure we always want to force this to true
                    // I'm pretty sure noone whats to set fullbright true if it wasn't true before.
                    // tmptex.DefaultTexture.Fullbright = true;

                    part.UpdateTexture(tmptex);
                }

                if (oldID != UUID.Zero && ((Disp & DISP_EXPIRE) != 0))
                {
                    if (oldAsset == null)
                    {
                        oldAsset = scene.AssetService.Get(oldID.ToString());
                    }
                    if (oldAsset != null)
                    {
                        if (oldAsset.Temporary == true)
                        {
                            scene.AssetService.Delete(oldID.ToString());
                        }
                    }
                }
            }
Esempio n. 17
0
        private void CreatePrim(WarpRenderer renderer, SceneObjectPart prim,
                                bool useTextures)
        {
            const float MIN_SIZE_SQUARE = 4f;

            if ((PCode)prim.Shape.PCode != PCode.Prim)
            {
                return;
            }
            float primScaleLenSquared = prim.Scale.LengthSquared();

            if (primScaleLenSquared < MIN_SIZE_SQUARE)
            {
                return;
            }

            FacetedMesh renderMesh = null;
            Primitive   omvPrim    = prim.Shape.ToOmvPrimitive(prim.OffsetPosition, prim.RotationOffset);

            if (m_renderMeshes)
            {
                if (omvPrim.Sculpt != null && omvPrim.Sculpt.SculptTexture != UUID.Zero)
                {
                    // Try fetchinng the asset
                    byte[] sculptAsset = m_scene.AssetService.GetData(omvPrim.Sculpt.SculptTexture.ToString());
                    if (sculptAsset != null)
                    {
                        // Is it a mesh?
                        if (omvPrim.Sculpt.Type == SculptType.Mesh)
                        {
                            AssetMesh meshAsset = new AssetMesh(omvPrim.Sculpt.SculptTexture, sculptAsset);
                            FacetedMesh.TryDecodeFromAsset(omvPrim, meshAsset, DetailLevel.Highest, out renderMesh);
                            meshAsset = null;
                        }
                        else // It's sculptie
                        {
                            IJ2KDecoder imgDecoder = m_scene.RequestModuleInterface <IJ2KDecoder>();
                            if (imgDecoder != null)
                            {
                                Image sculpt = imgDecoder.DecodeToImage(sculptAsset);
                                if (sculpt != null)
                                {
                                    renderMesh = m_primMesher.GenerateFacetedSculptMesh(omvPrim, (Bitmap)sculpt,
                                                                                        DetailLevel.Medium);
                                    sculpt.Dispose();
                                }
                            }
                        }
                    }
                }
            }

            // If not a mesh or sculptie, try the regular mesher
            if (renderMesh == null)
            {
                renderMesh = m_primMesher.GenerateFacetedMesh(omvPrim, DetailLevel.Medium);
            }

            if (renderMesh == null)
            {
                return;
            }

            string primID = prim.UUID.ToString();

            // Create the prim faces
            // TODO: Implement the useTextures flag behavior
            for (int i = 0; i < renderMesh.Faces.Count; i++)
            {
                Face   face     = renderMesh.Faces[i];
                string meshName = primID + i.ToString();

                // Avoid adding duplicate meshes to the scene
                if (renderer.Scene.objectData.ContainsKey(meshName))
                {
                    continue;
                }

                warp_Object faceObj = new warp_Object();
                for (int j = 0; j < face.Vertices.Count; j++)
                {
                    Vertex      v    = face.Vertices[j];
                    warp_Vector pos  = ConvertVector(v.Position);
                    warp_Vertex vert = new warp_Vertex(pos, v.TexCoord.X, v.TexCoord.Y);
                    faceObj.addVertex(vert);
                }

                for (int j = 0; j < face.Indices.Count; j += 3)
                {
                    faceObj.addTriangle(
                        face.Indices[j + 0],
                        face.Indices[j + 1],
                        face.Indices[j + 2]);
                }

                Primitive.TextureEntryFace teFace = prim.Shape.Textures.GetFace((uint)i);
                Color4 faceColor    = GetFaceColor(teFace);
                string materialName = String.Empty;
                if (m_texturePrims && primScaleLenSquared > m_texturePrimSize * m_texturePrimSize)
                {
                    materialName = GetOrCreateMaterial(renderer, faceColor, teFace.TextureID);
                }
                else
                {
                    materialName = GetOrCreateMaterial(renderer, faceColor);
                }

                warp_Vector     primPos = ConvertVector(prim.GetWorldPosition());
                warp_Quaternion primRot = ConvertQuaternion(prim.GetWorldRotation());
                warp_Matrix     m       = warp_Matrix.quaternionMatrix(primRot);
                faceObj.transform(m);
                faceObj.setPos(primPos);
                faceObj.scaleSelf(prim.Scale.X, prim.Scale.Z, prim.Scale.Y);

                renderer.Scene.addObject(meshName, faceObj);
                renderer.SetObjectMaterial(meshName, materialName);
            }
        }
        /// <summary>
        /// Parses ad request
        /// </summary>
        /// <param name="request"></param>
        /// <param name="AgentId"></param>
        /// <param name="cap"></param>
        /// <returns></returns>
        public Hashtable ProcessAdd(Hashtable request, UUID AgentId, Caps cap)
        {
            Hashtable responsedata = new Hashtable();

            responsedata["int_response_code"]   = 400; //501; //410; //404;
            responsedata["content_type"]        = "text/plain";
            responsedata["keepalive"]           = false;
            responsedata["str_response_string"] = "Request wasn't what was expected";
            ScenePresence avatar;

            if (!m_scene.TryGetScenePresence(AgentId, out avatar))
            {
                return(responsedata);
            }

            OSDMap r = (OSDMap)OSDParser.Deserialize((string)request["requestbody"]);
            UploadObjectAssetMessage message = new UploadObjectAssetMessage();

            try
            {
                message.Deserialize(r);
            }
            catch (Exception ex)
            {
                m_log.Error("[UPLOAD OBJECT ASSET MODULE]: Error deserializing message " + ex.ToString());
                message = null;
            }

            if (message == null)
            {
                responsedata["int_response_code"]   = 400; //501; //410; //404;
                responsedata["content_type"]        = "text/plain";
                responsedata["keepalive"]           = false;
                responsedata["str_response_string"] =
                    "<llsd><map><key>error</key><string>Error parsing Object</string></map></llsd>";

                return(responsedata);
            }

            Vector3    pos     = avatar.AbsolutePosition + (Vector3.UnitX * avatar.Rotation);
            Quaternion rot     = Quaternion.Identity;
            Vector3    rootpos = Vector3.Zero;
//            Quaternion rootrot = Quaternion.Identity;

            SceneObjectGroup rootGroup = null;

            SceneObjectGroup[] allparts = new SceneObjectGroup[message.Objects.Length];
            for (int i = 0; i < message.Objects.Length; i++)
            {
                UploadObjectAssetMessage.Object obj = message.Objects[i];
                PrimitiveBaseShape pbs = PrimitiveBaseShape.CreateBox();

                if (i == 0)
                {
                    rootpos = obj.Position;
//                    rootrot = obj.Rotation;
                }

                // Combine the extraparams data into it's ugly blob again....
                //int bytelength = 0;
                //for (int extparams = 0; extparams < obj.ExtraParams.Length; extparams++)
                //{
                //    bytelength += obj.ExtraParams[extparams].ExtraParamData.Length;
                //}
                //byte[] extraparams = new byte[bytelength];
                //int position = 0;



                //for (int extparams = 0; extparams < obj.ExtraParams.Length; extparams++)
                //{
                //    Buffer.BlockCopy(obj.ExtraParams[extparams].ExtraParamData, 0, extraparams, position,
                //                     obj.ExtraParams[extparams].ExtraParamData.Length);
                //
                //    position += obj.ExtraParams[extparams].ExtraParamData.Length;
                // }

                //pbs.ExtraParams = extraparams;
                for (int extparams = 0; extparams < obj.ExtraParams.Length; extparams++)
                {
                    UploadObjectAssetMessage.Object.ExtraParam extraParam = obj.ExtraParams[extparams];
                    switch ((ushort)extraParam.Type)
                    {
                    case (ushort)ExtraParamType.Sculpt:
                        Primitive.SculptData sculpt = new Primitive.SculptData(extraParam.ExtraParamData, 0);

                        pbs.SculptEntry = true;

                        pbs.SculptTexture = obj.SculptID;
                        pbs.SculptType    = (byte)sculpt.Type;

                        break;

                    case (ushort)ExtraParamType.Flexible:
                        Primitive.FlexibleData flex = new Primitive.FlexibleData(extraParam.ExtraParamData, 0);
                        pbs.FlexiEntry    = true;
                        pbs.FlexiDrag     = flex.Drag;
                        pbs.FlexiForceX   = flex.Force.X;
                        pbs.FlexiForceY   = flex.Force.Y;
                        pbs.FlexiForceZ   = flex.Force.Z;
                        pbs.FlexiGravity  = flex.Gravity;
                        pbs.FlexiSoftness = flex.Softness;
                        pbs.FlexiTension  = flex.Tension;
                        pbs.FlexiWind     = flex.Wind;
                        break;

                    case (ushort)ExtraParamType.Light:
                        Primitive.LightData light = new Primitive.LightData(extraParam.ExtraParamData, 0);
                        pbs.LightColorA    = light.Color.A;
                        pbs.LightColorB    = light.Color.B;
                        pbs.LightColorG    = light.Color.G;
                        pbs.LightColorR    = light.Color.R;
                        pbs.LightCutoff    = light.Cutoff;
                        pbs.LightEntry     = true;
                        pbs.LightFalloff   = light.Falloff;
                        pbs.LightIntensity = light.Intensity;
                        pbs.LightRadius    = light.Radius;
                        break;

                    case 0x40:
                        pbs.ReadProjectionData(extraParam.ExtraParamData, 0);
                        break;
                    }
                }
                pbs.PathBegin        = (ushort)obj.PathBegin;
                pbs.PathCurve        = (byte)obj.PathCurve;
                pbs.PathEnd          = (ushort)obj.PathEnd;
                pbs.PathRadiusOffset = (sbyte)obj.RadiusOffset;
                pbs.PathRevolutions  = (byte)obj.Revolutions;
                pbs.PathScaleX       = (byte)obj.ScaleX;
                pbs.PathScaleY       = (byte)obj.ScaleY;
                pbs.PathShearX       = (byte)obj.ShearX;
                pbs.PathShearY       = (byte)obj.ShearY;
                pbs.PathSkew         = (sbyte)obj.Skew;
                pbs.PathTaperX       = (sbyte)obj.TaperX;
                pbs.PathTaperY       = (sbyte)obj.TaperY;
                pbs.PathTwist        = (sbyte)obj.Twist;
                pbs.PathTwistBegin   = (sbyte)obj.TwistBegin;
                pbs.HollowShape      = (HollowShape)obj.ProfileHollow;
                pbs.PCode            = (byte)PCode.Prim;
                pbs.ProfileBegin     = (ushort)obj.ProfileBegin;
                pbs.ProfileCurve     = (byte)obj.ProfileCurve;
                pbs.ProfileEnd       = (ushort)obj.ProfileEnd;
                pbs.Scale            = obj.Scale;
                pbs.State            = (byte)0;
                SceneObjectPart prim = new SceneObjectPart();
                prim.UUID         = UUID.Random();
                prim.CreatorID    = AgentId;
                prim.OwnerID      = AgentId;
                prim.GroupID      = obj.GroupID;
                prim.LastOwnerID  = prim.OwnerID;
                prim.CreationDate = Util.UnixTimeSinceEpoch();
                prim.Name         = obj.Name;
                prim.Description  = "";

                prim.PayPrice[0] = -2;
                prim.PayPrice[1] = -2;
                prim.PayPrice[2] = -2;
                prim.PayPrice[3] = -2;
                prim.PayPrice[4] = -2;
                Primitive.TextureEntry tmp =
                    new Primitive.TextureEntry(UUID.Parse("89556747-24cb-43ed-920b-47caed15465f"));

                for (int j = 0; j < obj.Faces.Length; j++)
                {
                    UploadObjectAssetMessage.Object.Face face = obj.Faces[j];

                    Primitive.TextureEntryFace primFace = tmp.CreateFace((uint)j);

                    primFace.Bump       = face.Bump;
                    primFace.RGBA       = face.Color;
                    primFace.Fullbright = face.Fullbright;
                    primFace.Glow       = face.Glow;
                    primFace.TextureID  = face.ImageID;
                    primFace.Rotation   = face.ImageRot;
                    primFace.MediaFlags = ((face.MediaFlags & 1) != 0);

                    primFace.OffsetU    = face.OffsetS;
                    primFace.OffsetV    = face.OffsetT;
                    primFace.RepeatU    = face.ScaleS;
                    primFace.RepeatV    = face.ScaleT;
                    primFace.TexMapType = (MappingType)(face.MediaFlags & 6);
                }
                pbs.TextureEntry = tmp.GetBytes();
                prim.Shape       = pbs;
                prim.Scale       = obj.Scale;


                SceneObjectGroup grp = new SceneObjectGroup();

                grp.SetRootPart(prim);
                prim.ParentID = 0;
                if (i == 0)
                {
                    rootGroup = grp;
                }
                grp.AttachToScene(m_scene);
                grp.AbsolutePosition = obj.Position;
                prim.RotationOffset  = obj.Rotation;

                grp.RootPart.IsAttachment = false;
                // Required for linking
                grp.RootPart.UpdateFlag = 0;

                if (m_scene.Permissions.CanRezObject(1, avatar.UUID, pos))
                {
                    m_scene.AddSceneObject(grp);
                    grp.AbsolutePosition = obj.Position;
                }
                allparts[i] = grp;
            }

            for (int j = 1; j < allparts.Length; j++)
            {
                rootGroup.RootPart.UpdateFlag   = 0;
                allparts[j].RootPart.UpdateFlag = 0;
                rootGroup.LinkToGroup(allparts[j]);
            }

            rootGroup.ScheduleGroupForFullUpdate();
            pos = m_scene.GetNewRezLocation(Vector3.Zero, rootpos, UUID.Zero, rot, (byte)1, 1, true, allparts[0].GroupScale(), false);

            responsedata["int_response_code"]   = 200; //501; //410; //404;
            responsedata["content_type"]        = "text/plain";
            responsedata["keepalive"]           = false;
            responsedata["str_response_string"] = String.Format("<llsd><map><key>local_id</key>{0}</map></llsd>", ConvertUintToBytes(allparts[0].LocalId));

            return(responsedata);
        }
Esempio n. 19
0
        /// <summary>
        ///   Parses ad request
        /// </summary>
        /// <param name = "request"></param>
        /// <param name = "AgentId"></param>
        /// <param name = "cap"></param>
        /// <returns></returns>
        public byte[] ProcessAdd(Stream request, OSHttpResponse response, UUID AgentId)
        {
            IScenePresence avatar;

            if (!m_scene.TryGetScenePresence(AgentId, out avatar))
            {
                return(MainServer.NoResponse);
            }

            OSDMap r = (OSDMap)OSDParser.Deserialize(request);
            UploadObjectAssetMessage message = new UploadObjectAssetMessage();

            try
            {
                message.Deserialize(r);
            }
            catch (Exception ex)
            {
                MainConsole.Instance.Error("[UploadObjectAssetModule]: Error deserializing message " + ex);
                message = null;
            }

            if (message == null)
            {
                response.StatusCode = 400; //501; //410; //404;
                return(Encoding.UTF8.GetBytes("<llsd><map><key>error</key><string>Error parsing Object</string></map></llsd>"));
            }

            Vector3    pos     = avatar.AbsolutePosition + (Vector3.UnitX * avatar.Rotation);
            Quaternion rot     = Quaternion.Identity;
            Vector3    rootpos = Vector3.Zero;

            SceneObjectGroup rootGroup = null;

            SceneObjectGroup[] allparts = new SceneObjectGroup[message.Objects.Length];
            for (int i = 0; i < message.Objects.Length; i++)
            {
                UploadObjectAssetMessage.Object obj = message.Objects[i];
                PrimitiveBaseShape pbs = PrimitiveBaseShape.CreateBox();

                if (i == 0)
                {
                    rootpos = obj.Position;
                }


                // Combine the extraparams data into it's ugly blob again....
                //int bytelength = 0;
                //for (int extparams = 0; extparams < obj.ExtraParams.Length; extparams++)
                //{
                //    bytelength += obj.ExtraParams[extparams].ExtraParamData.Length;
                //}
                //byte[] extraparams = new byte[bytelength];
                //int position = 0;


                //for (int extparams = 0; extparams < obj.ExtraParams.Length; extparams++)
                //{
                //    Buffer.BlockCopy(obj.ExtraParams[extparams].ExtraParamData, 0, extraparams, position,
                //                     obj.ExtraParams[extparams].ExtraParamData.Length);
                //
                //    position += obj.ExtraParams[extparams].ExtraParamData.Length;
                // }

                //pbs.ExtraParams = extraparams;
                foreach (UploadObjectAssetMessage.Object.ExtraParam extraParam in obj.ExtraParams)
                {
                    switch ((ushort)extraParam.Type)
                    {
                    case (ushort)ExtraParamType.Sculpt:
                        Primitive.SculptData sculpt = new Primitive.SculptData(extraParam.ExtraParamData, 0);

                        pbs.SculptEntry = true;

                        pbs.SculptTexture = obj.SculptID;
                        pbs.SculptType    = (byte)sculpt.Type;

                        break;

                    case (ushort)ExtraParamType.Flexible:
                        Primitive.FlexibleData flex = new Primitive.FlexibleData(extraParam.ExtraParamData, 0);
                        pbs.FlexiEntry    = true;
                        pbs.FlexiDrag     = flex.Drag;
                        pbs.FlexiForceX   = flex.Force.X;
                        pbs.FlexiForceY   = flex.Force.Y;
                        pbs.FlexiForceZ   = flex.Force.Z;
                        pbs.FlexiGravity  = flex.Gravity;
                        pbs.FlexiSoftness = flex.Softness;
                        pbs.FlexiTension  = flex.Tension;
                        pbs.FlexiWind     = flex.Wind;
                        break;

                    case (ushort)ExtraParamType.Light:
                        Primitive.LightData light = new Primitive.LightData(extraParam.ExtraParamData, 0);
                        pbs.LightColorA    = light.Color.A;
                        pbs.LightColorB    = light.Color.B;
                        pbs.LightColorG    = light.Color.G;
                        pbs.LightColorR    = light.Color.R;
                        pbs.LightCutoff    = light.Cutoff;
                        pbs.LightEntry     = true;
                        pbs.LightFalloff   = light.Falloff;
                        pbs.LightIntensity = light.Intensity;
                        pbs.LightRadius    = light.Radius;
                        break;

                    case 0x40:
                        pbs.ReadProjectionData(extraParam.ExtraParamData, 0);
                        break;
                    }
                }
                pbs.PathBegin        = (ushort)obj.PathBegin;
                pbs.PathCurve        = (byte)obj.PathCurve;
                pbs.PathEnd          = (ushort)obj.PathEnd;
                pbs.PathRadiusOffset = (sbyte)obj.RadiusOffset;
                pbs.PathRevolutions  = (byte)obj.Revolutions;
                pbs.PathScaleX       = (byte)obj.ScaleX;
                pbs.PathScaleY       = (byte)obj.ScaleY;
                pbs.PathShearX       = (byte)obj.ShearX;
                pbs.PathShearY       = (byte)obj.ShearY;
                pbs.PathSkew         = (sbyte)obj.Skew;
                pbs.PathTaperX       = (sbyte)obj.TaperX;
                pbs.PathTaperY       = (sbyte)obj.TaperY;
                pbs.PathTwist        = (sbyte)obj.Twist;
                pbs.PathTwistBegin   = (sbyte)obj.TwistBegin;
                pbs.HollowShape      = (HollowShape)obj.ProfileHollow;
                pbs.PCode            = (byte)PCode.Prim;
                pbs.ProfileBegin     = (ushort)obj.ProfileBegin;
                pbs.ProfileCurve     = (byte)obj.ProfileCurve;
                pbs.ProfileEnd       = (ushort)obj.ProfileEnd;
                pbs.Scale            = obj.Scale;
                pbs.State            = 0;
                SceneObjectPart prim = new SceneObjectPart(AgentId, pbs, obj.Position, obj.Rotation,
                                                           Vector3.Zero, obj.Name, m_scene)
                {
                    UUID      = UUID.Random(),
                    CreatorID = AgentId,
                    OwnerID   = AgentId,
                    GroupID   = obj.GroupID
                };
                prim.LastOwnerID  = prim.OwnerID;
                prim.CreationDate = Util.UnixTimeSinceEpoch();
                prim.Name         = obj.Name;
                prim.Description  = "";

                prim.PayPrice[0] = -2;
                prim.PayPrice[1] = -2;
                prim.PayPrice[2] = -2;
                prim.PayPrice[3] = -2;
                prim.PayPrice[4] = -2;
                Primitive.TextureEntry tmp =
                    new Primitive.TextureEntry(UUID.Parse("89556747-24cb-43ed-920b-47caed15465f"));

                for (int j = 0; j < obj.Faces.Length; j++)
                {
                    UploadObjectAssetMessage.Object.Face face = obj.Faces[j];

                    Primitive.TextureEntryFace primFace = tmp.CreateFace((uint)j);

                    primFace.Bump       = face.Bump;
                    primFace.RGBA       = face.Color;
                    primFace.Fullbright = face.Fullbright;
                    primFace.Glow       = face.Glow;
                    primFace.TextureID  = face.ImageID;
                    primFace.Rotation   = face.ImageRot;
                    primFace.MediaFlags = ((face.MediaFlags & 1) != 0);

                    primFace.OffsetU    = face.OffsetS;
                    primFace.OffsetV    = face.OffsetT;
                    primFace.RepeatU    = face.ScaleS;
                    primFace.RepeatV    = face.ScaleT;
                    primFace.TexMapType = (MappingType)(face.MediaFlags & 6);
                }
                pbs.TextureEntry = tmp.GetBytes();
                prim.Shape       = pbs;
                prim.Scale       = obj.Scale;

                SceneObjectGroup grp = new SceneObjectGroup(prim, m_scene);

                prim.ParentID = 0;
                if (i == 0)
                {
                    rootGroup = grp;
                }

                grp.AbsolutePosition = obj.Position;
                prim.RotationOffset  = obj.Rotation;

                grp.RootPart.IsAttachment = false;

                string reason;
                if (m_scene.Permissions.CanRezObject(1, avatar.UUID, pos, out reason))
                {
                    m_scene.SceneGraph.AddPrimToScene(grp);
                    grp.AbsolutePosition = obj.Position;
                }
                else
                {
                    //Stop now then
                    avatar.ControllingClient.SendAlertMessage("You do not have permission to rez objects here: " +
                                                              reason);
                    return(MainServer.NoResponse);
                }
                allparts[i] = grp;
            }

            for (int j = 1; j < allparts.Length; j++)
            {
                rootGroup.LinkToGroup(allparts[j]);
            }

            rootGroup.ScheduleGroupUpdate(PrimUpdateFlags.ForcedFullUpdate);
            pos = m_scene.SceneGraph.GetNewRezLocation(Vector3.Zero, rootpos, UUID.Zero, rot, 1, 1, true,
                                                       allparts[0].GroupScale(), false);

            OSDMap map = new OSDMap();

            map["local_id"] = allparts[0].LocalId;
            return(OSDParser.SerializeLLSDXmlBytes(map));
        }
Esempio n. 20
0
        private void UploadObjectAssetHandler(Capability cap, IHttpClientContext context, IHttpRequest request, IHttpResponse response)
        {
            UploadObjectAssetMessage message;

            if (LLUtil.TryGetMessage <UploadObjectAssetMessage>(request.Body, out message))
            {
                LLPrimitive parent = null;

                // Build the linkset
                for (int i = 0; i < message.Objects.Length; i++)
                {
                    UploadObjectAssetMessage.Object obj = message.Objects[i];

                    #region Primitive Creation

                    Primitive prim = new Primitive();
                    prim.Properties = new Primitive.ObjectProperties();
                    prim.Sculpt     = new Primitive.SculptData();
                    prim.Textures   = new Primitive.TextureEntry(UUID.Zero);

                    prim.Flags     = PrimFlags.CastShadows | PrimFlags.InventoryEmpty | PrimFlags.CreateSelected;
                    prim.ID        = UUID.Random();
                    prim.MediaURL  = String.Empty;
                    prim.OwnerID   = cap.OwnerID;
                    prim.GroupID   = obj.GroupID;
                    prim.TextColor = Color4.Black;

                    prim.Properties.CreationDate = DateTime.UtcNow;
                    prim.Properties.CreatorID    = cap.OwnerID;
                    prim.Properties.Description  = String.Empty;
                    prim.Properties.GroupID      = obj.GroupID;
                    prim.Properties.LastOwnerID  = cap.OwnerID;
                    prim.Properties.Name         = obj.Name;
                    prim.Properties.ObjectID     = prim.ID;
                    prim.Properties.OwnerID      = prim.OwnerID;
                    prim.Properties.Permissions  = (m_permissions != null) ?
                                                   m_permissions.GetDefaultPermissions() :
                                                   Permissions.FullPermissions;
                    prim.Properties.SalePrice = 10;

                    prim.PrimData.PCode            = PCode.Prim;
                    prim.PrimData.Material         = obj.Material;
                    prim.PrimData.PathBegin        = obj.PathBegin;
                    prim.PrimData.PathCurve        = (PathCurve)obj.PathCurve;
                    prim.PrimData.PathEnd          = obj.PathEnd;
                    prim.PrimData.ProfileBegin     = obj.ProfileBegin;
                    prim.PrimData.ProfileCurve     = (ProfileCurve)obj.ProfileCurve;
                    prim.PrimData.ProfileEnd       = obj.ProfileEnd;
                    prim.PrimData.ProfileHollow    = obj.ProfileHollow;
                    prim.PrimData.PathRadiusOffset = obj.RadiusOffset;
                    prim.PrimData.PathRevolutions  = obj.Revolutions;
                    prim.PrimData.PathScaleX       = obj.ScaleX;
                    prim.PrimData.PathScaleY       = obj.ScaleY;
                    prim.PrimData.PathShearX       = obj.ShearX;
                    prim.PrimData.PathShearY       = obj.ShearY;
                    prim.PrimData.PathSkew         = obj.Skew;
                    prim.PrimData.PathTaperX       = obj.TaperX;
                    prim.PrimData.PathTaperY       = obj.TaperY;
                    prim.PrimData.PathTwist        = obj.Twist;
                    prim.PrimData.PathTwistBegin   = obj.TwistBegin;

                    // Extra parameters
                    for (int j = 0; j < obj.ExtraParams.Length; j++)
                    {
                        UploadObjectAssetMessage.Object.ExtraParam extraParam = obj.ExtraParams[j];

                        switch (extraParam.Type)
                        {
                        case ExtraParamType.Flexible:
                            prim.Flexible = new Primitive.FlexibleData(extraParam.ExtraParamData, 0);
                            break;

                        case ExtraParamType.Light:
                            prim.Light = new Primitive.LightData(extraParam.ExtraParamData, 0);
                            break;

                        case ExtraParamType.Sculpt:
                            prim.Sculpt = new Primitive.SculptData(extraParam.ExtraParamData, 0);
                            break;
                        }
                    }

                    // Faces
                    for (int j = 0; j < obj.Faces.Length; j++)
                    {
                        UploadObjectAssetMessage.Object.Face face = obj.Faces[j];

                        Primitive.TextureEntryFace primFace = prim.Textures.GetFace(0);
                        primFace.Bump       = face.Bump;
                        primFace.RGBA       = face.Color;
                        primFace.Fullbright = face.Fullbright;
                        primFace.Glow       = face.Glow;
                        primFace.TextureID  = face.ImageID;
                        primFace.Rotation   = face.ImageRot;
                        primFace.MediaFlags = ((face.MediaFlags & MEDIA_MASK) != 0);

                        primFace.OffsetU    = face.OffsetS;
                        primFace.OffsetV    = face.OffsetT;
                        primFace.RepeatU    = face.ScaleS;
                        primFace.RepeatV    = face.ScaleT;
                        primFace.TexMapType = (MappingType)(face.MediaFlags & TEX_MAP_MASK);
                    }

                    prim.Sculpt.SculptTexture = obj.SculptID;
                    prim.Sculpt.Type          = obj.SculptType;

                    #endregion Primitive Creation

                    LLPrimitive llprim = new LLPrimitive(prim, m_scene, m_primMesher);
                    llprim.Scale = obj.Scale;

                    // Link children prims to the parent
                    if (i == 0)
                    {
                        llprim.RelativePosition = obj.Position;
                        llprim.RelativeRotation = obj.Rotation;
                        m_scene.EntityAddOrUpdate(this, llprim, UpdateFlags.FullUpdate, 0);

                        parent = llprim;
                    }
                    else
                    {
                        llprim.RelativePosition = obj.Position;
                        llprim.RelativeRotation = obj.Rotation;
                        llprim.SetParent(parent, true, false);
                        m_scene.EntityAddOrUpdate(this, llprim, UpdateFlags.FullUpdate, 0);
                    }
                }
            }
            else
            {
                m_log.Warn("Received invalid data for UploadObjectAsset");
                response.Status = System.Net.HttpStatusCode.BadRequest;
            }
        }
            /// <summary>
            ///     Called once new texture data has been received for this updater.
            /// </summary>
            public void DataReceived(byte [] data, IScene scene)
            {
                ISceneChildEntity part = scene.GetSceneObjectPart(PrimID);

                if (part == null || data == null || data.Length <= 1)
                {
                    IChatModule chatModule = scene.RequestModuleInterface <IChatModule> ();
                    if (chatModule != null)
                    {
                        string msg =
                            string.Format("DynamicTextureModule: Error preparing image using URL {0}", Url);
                        if (part != null)
                        {
                            chatModule.SimChat(msg, ChatTypeEnum.Say, 0,
                                               part.ParentEntity.AbsolutePosition, part.Name, part.UUID, false, scene);
                        }
                        else
                        {
                            chatModule.SimChat(msg, ChatTypeEnum.Say, 0,
                                               new Vector3(), "Unknown", UUID.Zero, false, scene);
                        }
                    }
                    return;
                }

                byte []   assetData = null;
                AssetBase oldAsset  = null;

                if (BlendWithOldTexture)
                {
                    Primitive.TextureEntryFace defaultFace = part.Shape.Textures.DefaultTexture;
                    if (defaultFace != null)
                    {
                        oldAsset = scene.AssetService.Get(defaultFace.TextureID.ToString());

                        if (oldAsset != null)
                        {
                            assetData = BlendTextures(data, oldAsset.Data, SetNewFrontAlpha, FrontAlpha, scene);
                        }
                    }
                }

                if (assetData == null)
                {
                    assetData = new byte [data.Length];
                    Array.Copy(data, assetData, data.Length);
                }

                AssetBase asset = null;

                if (LastAssetID != UUID.Zero)
                {
                    asset = scene.AssetService.Get(LastAssetID.ToString());
                    if (asset != null)
                    {
                        asset.Description = string.Format("URL image : {0}", Url);
                        asset.Data        = assetData;
                        if ((asset.Flags & AssetFlags.Local) == AssetFlags.Local)
                        {
                            asset.Flags = asset.Flags & ~AssetFlags.Local;
                        }
                        if (((asset.Flags & AssetFlags.Temporary) == AssetFlags.Temporary) != ((Disp & DISP_TEMP) != 0))
                        {
                            if ((Disp & DISP_TEMP) != 0)
                            {
                                asset.Flags |= AssetFlags.Temporary;
                            }
                            else
                            {
                                asset.Flags = asset.Flags & ~AssetFlags.Temporary;
                            }
                        }
                        asset.ID = scene.AssetService.Store(asset);
                    }
                }

                // either we have no LastAssetID or the above failed to retrieve the asset...so...
                if (asset == null)
                {
                    // Create a new asset for user
                    asset = new AssetBase(UUID.Random(), "DynamicImage" + Util.RandomClass.Next(1, 10000),
                                          AssetType.Texture,
                                          scene.RegionInfo.RegionID)
                    {
                        Data = assetData, Description = string.Format("URL image : {0}", Url)
                    };
                    if ((Disp & DISP_TEMP) != 0)
                    {
                        asset.Flags = AssetFlags.Temporary;
                    }
                    asset.ID = scene.AssetService.Store(asset);
                }

                IJ2KDecoder cacheLayerDecode = scene.RequestModuleInterface <IJ2KDecoder> ();

                if (cacheLayerDecode != null)
                {
                    cacheLayerDecode.Decode(asset.ID, asset.Data);
                    cacheLayerDecode = null;
                    LastAssetID      = asset.ID;
                }

                UUID oldID = UUID.Zero;

                lock (part) {
                    // mostly keep the values from before
                    Primitive.TextureEntry tmptex = part.Shape.Textures;

                    // remove the old asset from the cache
                    oldID = tmptex.DefaultTexture.TextureID;

                    if (Face == ALL_SIDES)
                    {
                        tmptex.DefaultTexture.TextureID = asset.ID;
                    }
                    else
                    {
                        try {
                            Primitive.TextureEntryFace texface = tmptex.CreateFace((uint)Face);
                            texface.TextureID          = asset.ID;
                            tmptex.FaceTextures [Face] = texface;
                        } catch (Exception) {
                            tmptex.DefaultTexture.TextureID = asset.ID;
                        }
                    }

                    // I'm pretty sure we always want to force this to true
                    // I'm pretty sure no one wants to set fullbright true if it wasn't true before.
                    // tmptex.DefaultTexture.Fullbright = true;

                    part.UpdateTexture(tmptex, true);
                }

                if (oldID != UUID.Zero && ((Disp & DISP_EXPIRE) != 0))
                {
                    if (oldAsset == null)
                    {
                        oldAsset = scene.AssetService.Get(oldID.ToString());
                    }
                    if (oldAsset != null)
                    {
                        if ((oldAsset.Flags & AssetFlags.Temporary) == AssetFlags.Temporary)
                        {
                            scene.AssetService.Delete(oldID);
                        }
                    }
                }

                if (oldAsset != null)
                {
                    oldAsset.Dispose();
                }
                asset.Dispose();
            }
Esempio n. 22
0
        /// <summary>
        /// Find the materials used in one Face, and add them to 'm_regionMaterials'.
        /// </summary>
        private bool GetStoredMaterialInFace(SceneObjectPart part, Primitive.TextureEntryFace face)
        {
            UUID id = face.MaterialID;

            if (id == UUID.Zero)
            {
                return(false);
            }

            OSDMap mat;

            lock (materialslock)
            {
                if (m_Materials.ContainsKey(id))
                {
                    m_MaterialsRefCount[id]++;
                    return(false);
                }

                AssetBase matAsset = m_scene.AssetService.Get(id.ToString());
                if (matAsset == null || matAsset.Data == null || matAsset.Data.Length == 0)
                {
                    // grid may just be down...
                    return(false);
                }

                byte[] data = matAsset.Data;

                // string txt = System.Text.Encoding.ASCII.GetString(data);
                try
                {
                    mat = (OSDMap)OSDParser.DeserializeLLSDXml(data);
                }
                catch (Exception e)
                {
                    m_log.WarnFormat("[Materials]: cannot decode material asset {0}: {1}", id, e.Message);
                    return(false);
                }

                FaceMaterial fmat = new FaceMaterial(mat);

                if (fmat == null ||
                    (fmat.DiffuseAlphaMode == 1 &&
                     fmat.NormalMapID == UUID.Zero &&
                     fmat.SpecularMapID == UUID.Zero))
                {
                    face.MaterialID = UUID.Zero;
                    return(true);
                }

                fmat.ID = id;

                if (m_Materials.ContainsKey(id))
                {
                    m_MaterialsRefCount[id]++;
                }
                else
                {
                    m_Materials[id]         = fmat;
                    m_MaterialsRefCount[id] = 1;
                }
                return(false);
            }
        }
Esempio n. 23
0
        /// <summary>
        /// Append a scene object part report to an input StringBuilder
        /// </summary>
        /// <returns></returns>
        /// <param name='sb'></param>
        /// <param name='sop'</param>
        /// <param name='showFull'>
        /// If true then information on each inventory item will be shown.
        /// If false then only summary inventory information is shown.
        /// </param>
        private StringBuilder AddScenePartReport(StringBuilder sb, SceneObjectPart sop, bool showFull)
        {
            ConsoleDisplayList cdl = new ConsoleDisplayList();

            cdl.AddRow("Name", sop.Name);
            cdl.AddRow("Description", sop.Description);
            cdl.AddRow("Local ID", sop.LocalId);
            cdl.AddRow("UUID", sop.UUID);
            cdl.AddRow("Location", string.Format("{0} @ {1}", sop.AbsolutePosition, sop.ParentGroup.Scene.Name));
            cdl.AddRow(
                "Parent",
                sop.IsRoot ? "Is Root" : string.Format("{0} {1}", sop.ParentGroup.Name, sop.ParentGroup.UUID));
            cdl.AddRow("Link number", sop.LinkNum);
            cdl.AddRow("Flags", sop.Flags);

            if (showFull)
            {
                PrimitiveBaseShape s = sop.Shape;
                cdl.AddRow("FlexiDrag", s.FlexiDrag);
                cdl.AddRow("FlexiEntry", s.FlexiEntry);
                cdl.AddRow("FlexiForce", string.Format("<{0},{1},{2}>", s.FlexiForceX, s.FlexiForceY, s.FlexiForceZ));
                cdl.AddRow("FlexiGravity", s.FlexiGravity);
                cdl.AddRow("FlexiSoftness", s.FlexiSoftness);
                cdl.AddRow("HollowShape", s.HollowShape);
                cdl.AddRow(
                    "LightColor",
                    string.Format("<{0},{1},{2},{3}>", s.LightColorR, s.LightColorB, s.LightColorG, s.LightColorA));
                cdl.AddRow("LightCutoff", s.LightCutoff);
                cdl.AddRow("LightEntry", s.LightEntry);
                cdl.AddRow("LightFalloff", s.LightFalloff);
                cdl.AddRow("LightIntensity", s.LightIntensity);
                cdl.AddRow("LightRadius", s.LightRadius);
                cdl.AddRow("Location (relative)", sop.RelativePosition);
                cdl.AddRow("Media", string.Format("{0} entries", s.Media != null ? s.Media.Count.ToString() : "n/a"));
                cdl.AddRow("PathBegin", s.PathBegin);
                cdl.AddRow("PathEnd", s.PathEnd);
                cdl.AddRow("PathCurve", s.PathCurve);
                cdl.AddRow("PathRadiusOffset", s.PathRadiusOffset);
                cdl.AddRow("PathRevolutions", s.PathRevolutions);
                cdl.AddRow("PathScale", string.Format("<{0},{1}>", s.PathScaleX, s.PathScaleY));
                cdl.AddRow("PathSkew", string.Format("<{0},{1}>", s.PathShearX, s.PathShearY));
                cdl.AddRow("FlexiDrag", s.PathSkew);
                cdl.AddRow("PathTaper", string.Format("<{0},{1}>", s.PathTaperX, s.PathTaperY));
                cdl.AddRow("PathTwist", s.PathTwist);
                cdl.AddRow("PathTwistBegin", s.PathTwistBegin);
                cdl.AddRow("PCode", s.PCode);
                cdl.AddRow("ProfileBegin", s.ProfileBegin);
                cdl.AddRow("ProfileEnd", s.ProfileEnd);
                cdl.AddRow("ProfileHollow", s.ProfileHollow);
                cdl.AddRow("ProfileShape", s.ProfileShape);
                cdl.AddRow("ProjectionAmbiance", s.ProjectionAmbiance);
                cdl.AddRow("ProjectionEntry", s.ProjectionEntry);
                cdl.AddRow("ProjectionFocus", s.ProjectionFocus);
                cdl.AddRow("ProjectionFOV", s.ProjectionFOV);
                cdl.AddRow("ProjectionTextureUUID", s.ProjectionTextureUUID);
                cdl.AddRow("Rotation (Relative)", sop.RotationOffset);
                cdl.AddRow("Rotation (World)", sop.GetWorldRotation());
                cdl.AddRow("Scale", s.Scale);
                cdl.AddRow(
                    "SculptData",
                    string.Format("{0} bytes", s.SculptData != null ? s.SculptData.Length.ToString() : "n/a"));
                cdl.AddRow("SculptEntry", s.SculptEntry);
                cdl.AddRow("SculptTexture", s.SculptTexture);
                cdl.AddRow("SculptType", s.SculptType);
                cdl.AddRow("State", s.State);

                // TODO, need to display more information about textures but in a compact format
                // to stop output becoming huge.
                for (int i = 0; i < sop.GetNumberOfSides(); i++)
                {
                    Primitive.TextureEntryFace teFace = s.Textures.FaceTextures[i];

                    UUID textureID;

                    if (teFace != null)
                    {
                        textureID = teFace.TextureID;
                    }
                    else
                    {
                        textureID = s.Textures.DefaultTexture.TextureID;
                    }

                    cdl.AddRow(string.Format("Face {0} texture ID", i), textureID);
                }

                //cdl.AddRow("Textures", string.Format("{0} entries", s.Textures.
            }

            object itemsOutput;

            if (showFull)
            {
                StringBuilder itemsSb = new StringBuilder("\n");
                itemsOutput = AddScenePartItemsReport(itemsSb, sop.Inventory).ToString();
            }
            else
            {
                itemsOutput = sop.Inventory.Count;
            }

            cdl.AddRow("Items", itemsOutput);

            return(sb.Append(cdl.ToString()));
        }
Esempio n. 24
0
        public void RenderMaterialsPutCap(IOSHttpRequest request, IOSHttpResponse response, UUID agentID)
        {
            OSDMap req;

            try
            {
                req = (OSDMap)OSDParser.DeserializeLLSDXml(request.InputStream);
            }
            catch
            {
                response.StatusCode = (int)HttpStatusCode.BadRequest;
                return;
            }

            OSDMap   materialsFromViewer = null;
            OSDArray respArr             = new OSDArray();

            OSD tmpOSD;
            HashSet <SceneObjectPart> parts = new HashSet <SceneObjectPart>();

            if (req.TryGetValue("Zipped", out tmpOSD))
            {
                OSD osd = null;

                byte[] inBytes = tmpOSD.AsBinary();

                try
                {
                    osd = ZDecompressBytesToOsd(inBytes);

                    if (osd != null && osd is OSDMap)
                    {
                        materialsFromViewer = osd as OSDMap;

                        if (materialsFromViewer.TryGetValue("FullMaterialsPerFace", out tmpOSD) && (tmpOSD is OSDArray))
                        {
                            OSDArray matsArr = tmpOSD as OSDArray;
                            try
                            {
                                foreach (OSDMap matsMap in matsArr)
                                {
                                    uint primLocalID = 0;
                                    try
                                    {
                                        primLocalID = matsMap["ID"].AsUInteger();
                                    }
                                    catch (Exception e)
                                    {
                                        m_log.Warn("[Materials]: cannot decode \"ID\" from matsMap: " + e.Message);
                                        continue;
                                    }

                                    SceneObjectPart sop = m_scene.GetSceneObjectPart(primLocalID);
                                    if (sop == null)
                                    {
                                        m_log.WarnFormat("[Materials]: SOP not found for localId: {0}", primLocalID.ToString());
                                        continue;
                                    }

                                    if (!m_scene.Permissions.CanEditObject(sop.UUID, agentID))
                                    {
                                        m_log.WarnFormat("User {0} can't edit object {1} {2}", agentID, sop.Name, sop.UUID);
                                        continue;
                                    }

                                    OSDMap mat = null;
                                    try
                                    {
                                        mat = matsMap["Material"] as OSDMap;
                                    }
                                    catch (Exception e)
                                    {
                                        m_log.Warn("[Materials]: cannot decode \"Material\" from matsMap: " + e.Message);
                                        continue;
                                    }

                                    Primitive.TextureEntry te = new Primitive.TextureEntry(sop.Shape.TextureEntry, 0, sop.Shape.TextureEntry.Length);
                                    if (te == null)
                                    {
                                        m_log.WarnFormat("[Materials]: Error in TextureEntry for SOP {0} {1}", sop.Name, sop.UUID);
                                        continue;
                                    }

                                    int  face  = -1;
                                    UUID oldid = UUID.Zero;
                                    Primitive.TextureEntryFace faceEntry = null;
                                    if (matsMap.TryGetValue("Face", out tmpOSD))
                                    {
                                        face      = tmpOSD.AsInteger();
                                        faceEntry = te.CreateFace((uint)face);
                                    }
                                    else
                                    {
                                        faceEntry = te.DefaultTexture;
                                    }

                                    if (faceEntry == null)
                                    {
                                        continue;
                                    }

                                    UUID         id;
                                    FaceMaterial newFaceMat = null;
                                    if (mat == null)
                                    {
                                        // This happens then the user removes a material from a prim
                                        id = UUID.Zero;
                                    }
                                    else
                                    {
                                        newFaceMat = new FaceMaterial(mat);
                                        if (newFaceMat.DiffuseAlphaMode == 1 &&
                                            newFaceMat.NormalMapID == UUID.Zero &&
                                            newFaceMat.SpecularMapID == UUID.Zero
                                            )
                                        {
                                            id = UUID.Zero;
                                        }
                                        else
                                        {
                                            newFaceMat.genID();
                                            id = newFaceMat.ID;
                                        }
                                    }

                                    oldid = faceEntry.MaterialID;

                                    if (oldid == id)
                                    {
                                        continue;
                                    }

                                    if (faceEntry != null)
                                    {
                                        faceEntry.MaterialID = id;
                                        //m_log.DebugFormat("[Materials]: in \"{0}\" {1}, setting material ID for face {2} to {3}", sop.Name, sop.UUID, face, id);
                                        // We can't use sop.UpdateTextureEntry(te) because it filters, so do it manually
                                        sop.Shape.TextureEntry = te.GetBytes(9);
                                    }

                                    if (oldid != UUID.Zero)
                                    {
                                        RemoveMaterial(oldid);
                                    }

                                    lock (materialslock)
                                    {
                                        if (id != UUID.Zero)
                                        {
                                            if (m_Materials.ContainsKey(id))
                                            {
                                                m_MaterialsRefCount[id]++;
                                            }
                                            else
                                            {
                                                m_Materials[id]         = newFaceMat;
                                                m_MaterialsRefCount[id] = 1;
                                                m_changed[newFaceMat]   = Util.GetTimeStamp();
                                            }
                                        }
                                    }

                                    if (!parts.Contains(sop))
                                    {
                                        parts.Add(sop);
                                    }
                                }

                                foreach (SceneObjectPart sop in parts)
                                {
                                    if (sop.ParentGroup != null && !sop.ParentGroup.IsDeleted)
                                    {
                                        sop.TriggerScriptChangedEvent(Changed.TEXTURE);
                                        sop.ScheduleFullUpdate();
                                        sop.ParentGroup.HasGroupChanged = true;
                                    }
                                }
                            }
                            catch (Exception e)
                            {
                                m_log.Warn("[Materials]: exception processing received material ", e);
                                response.StatusCode = (int)HttpStatusCode.BadRequest;
                                return;
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    m_log.Warn("[Materials]: exception decoding zipped CAP payload ", e);
                    response.StatusCode = (int)HttpStatusCode.BadRequest;
                    return;
                }
            }

            OSDMap resp = new OSDMap();

            resp["Zipped"]     = ZCompressOSD(respArr, false);
            response.RawBuffer = Encoding.UTF8.GetBytes(OSDParser.SerializeLLSDXmlString(resp));

            //m_log.Debug("[Materials]: cap request: " + request);
            //m_log.Debug("[Materials]: cap request (zipped portion): " + ZippedOsdBytesToString(req["Zipped"].AsBinary()));
            //m_log.Debug("[Materials]: cap response: " + response);
        }
Esempio n. 25
0
        private void CreatePrim(WarpRenderer renderer, SceneObjectPart prim)
        {
            if ((PCode)prim.Shape.PCode != PCode.Prim)
            {
                return;
            }

            Vector3 ppos = prim.GetWorldPosition();

            if (ppos.Z < m_renderMinHeight || ppos.Z > m_renderMaxHeight)
            {
                return;
            }

            warp_Vector     primPos = ConvertVector(ppos);
            warp_Quaternion primRot = ConvertQuaternion(prim.GetWorldRotation());
            warp_Matrix     m       = warp_Matrix.quaternionMatrix(primRot);

            float screenFactor = renderer.Scene.EstimateBoxProjectedArea(primPos, ConvertVector(prim.Scale), m);

            if (screenFactor < 0)
            {
                return;
            }

            const float log2inv = -1.442695f;
            int         p2      = (int)((float)Math.Log(screenFactor) * log2inv * 0.25 - 1);

            if (p2 < 0)
            {
                p2 = 0;
            }
            else if (p2 > 3)
            {
                p2 = 3;
            }

            DetailLevel lod = (DetailLevel)(3 - p2);

            FacetedMesh renderMesh = null;
            Primitive   omvPrim    = prim.Shape.ToOmvPrimitive(prim.OffsetPosition, prim.RotationOffset);

            if (m_renderMeshes)
            {
                if (omvPrim.Sculpt != null && omvPrim.Sculpt.SculptTexture != UUID.Zero)
                {
                    // Try fetchinng the asset
                    AssetBase sculptAsset = m_scene.AssetService.Get(omvPrim.Sculpt.SculptTexture.ToString());
                    if (sculptAsset != null)
                    {
                        // Is it a mesh?
                        if (omvPrim.Sculpt.Type == SculptType.Mesh)
                        {
                            AssetMesh meshAsset = new AssetMesh(omvPrim.Sculpt.SculptTexture, sculptAsset.Data);
                            FacetedMesh.TryDecodeFromAsset(omvPrim, meshAsset, lod, out renderMesh);
                            meshAsset = null;
                        }
                        else // It's sculptie
                        {
                            if (m_imgDecoder != null)
                            {
                                Image sculpt = m_imgDecoder.DecodeToImage(sculptAsset.Data);
                                if (sculpt != null)
                                {
                                    renderMesh = m_primMesher.GenerateFacetedSculptMesh(omvPrim, (Bitmap)sculpt, lod);
                                    sculpt.Dispose();
                                }
                            }
                        }
                    }
                    else
                    {
                        m_log.WarnFormat("[Warp3D] failed to get mesh or sculpt asset {0} of prim {1} at {2}",
                                         omvPrim.Sculpt.SculptTexture.ToString(), prim.Name, prim.GetWorldPosition().ToString());
                    }
                }
            }

            // If not a mesh or sculptie, try the regular mesher
            if (renderMesh == null)
            {
                renderMesh = m_primMesher.GenerateFacetedMesh(omvPrim, lod);
            }

            if (renderMesh == null)
            {
                return;
            }

            string primID = prim.UUID.ToString();

            // Create the prim faces
            // TODO: Implement the useTextures flag behavior
            for (int i = 0; i < renderMesh.Faces.Count; i++)
            {
                Face   face     = renderMesh.Faces[i];
                string meshName = primID + i.ToString();

                // Avoid adding duplicate meshes to the scene
                if (renderer.Scene.objectData.ContainsKey(meshName))
                {
                    continue;
                }

                warp_Object faceObj = new warp_Object();

                Primitive.TextureEntryFace teFace = prim.Shape.Textures.GetFace((uint)i);
                Color4 faceColor = teFace.RGBA;
                if (faceColor.A == 0)
                {
                    continue;
                }

                string materialName = string.Empty;
                if (m_texturePrims)
                {
                    // if(lod > DetailLevel.Low)
                    {
                        // materialName = GetOrCreateMaterial(renderer, faceColor, teFace.TextureID, lod == DetailLevel.Low);
                        materialName = GetOrCreateMaterial(renderer, faceColor, teFace.TextureID, false, prim);
                        if (String.IsNullOrEmpty(materialName))
                        {
                            continue;
                        }
                        int c = renderer.Scene.material(materialName).getColor();
                        if ((c & warp_Color.MASKALPHA) == 0)
                        {
                            continue;
                        }
                    }
                }
                else
                {
                    materialName = GetOrCreateMaterial(renderer, faceColor);
                }

                if (renderer.Scene.material(materialName).getTexture() == null)
                {
                    // uv map details dont not matter for color;
                    for (int j = 0; j < face.Vertices.Count; j++)
                    {
                        Vertex      v    = face.Vertices[j];
                        warp_Vector pos  = ConvertVector(v.Position);
                        warp_Vertex vert = new warp_Vertex(pos, v.TexCoord.X, v.TexCoord.Y);
                        faceObj.addVertex(vert);
                    }
                }
                else
                {
                    float tu;
                    float tv;
                    float offsetu  = teFace.OffsetU + 0.5f;
                    float offsetv  = teFace.OffsetV + 0.5f;
                    float scaleu   = teFace.RepeatU;
                    float scalev   = teFace.RepeatV;
                    float rotation = teFace.Rotation;
                    float rc       = 0;
                    float rs       = 0;
                    if (rotation != 0)
                    {
                        rc = (float)Math.Cos(rotation);
                        rs = (float)Math.Sin(rotation);
                    }

                    for (int j = 0; j < face.Vertices.Count; j++)
                    {
                        warp_Vertex vert;
                        Vertex      v   = face.Vertices[j];
                        warp_Vector pos = ConvertVector(v.Position);
                        if (teFace.TexMapType == MappingType.Planar)
                        {
                            UVPlanarMap(v, prim.Scale, out tu, out tv);
                        }
                        else
                        {
                            tu = v.TexCoord.X - 0.5f;
                            tv = 0.5f - v.TexCoord.Y;
                        }
                        if (rotation != 0)
                        {
                            float tur = tu * rc - tv * rs;
                            float tvr = tu * rs + tv * rc;
                            tur *= scaleu;
                            tur += offsetu;

                            tvr *= scalev;
                            tvr += offsetv;
                            vert = new warp_Vertex(pos, tur, tvr);
                        }
                        else
                        {
                            tu  *= scaleu;
                            tu  += offsetu;
                            tv  *= scalev;
                            tv  += offsetv;
                            vert = new warp_Vertex(pos, tu, tv);
                        }

                        faceObj.addVertex(vert);
                    }
                }

                for (int j = 0; j < face.Indices.Count; j += 3)
                {
                    faceObj.addTriangle(
                        face.Indices[j + 0],
                        face.Indices[j + 1],
                        face.Indices[j + 2]);
                }

                faceObj.scaleSelf(prim.Scale.X, prim.Scale.Z, prim.Scale.Y);
                faceObj.transform(m);
                faceObj.setPos(primPos);

                renderer.Scene.addObject(meshName, faceObj);
                renderer.SetObjectMaterial(meshName, materialName);
            }
        }
Esempio n. 26
0
        /// <summary>
        /// Render Primitive
        /// </summary>
        /// <param name="pass">Which pass are we currently in</param>
        /// <param name="pickingID">ID used to identify which object was picked</param>
        /// <param name="scene">Main scene renderer</param>
        /// <param name="time">Time it took to render the last frame</param>
        public override void Render(RenderPass pass, int pickingID, SceneWindow scene, float time)
        {
            if (!RenderSettings.AvatarRenderingEnabled && Attached) return;

            // Individual prim matrix
            GL.PushMatrix();

            // Prim roation and position and scale
            GL.MultMatrix(Math3D.CreateSRTMatrix(Prim.Scale, RenderRotation, RenderPosition));

            // Do we have animated texture on this face
            bool animatedTexture = false;

            // Initialise flags tracking what type of faces this prim has
            if (pass == RenderPass.Simple)
            {
                HasSimpleFaces = false;
            }
            else if (pass == RenderPass.Alpha)
            {
                HasAlphaFaces = false;
            }
            else if (pass == RenderPass.Invisible)
            {
                HasInvisibleFaces = false;
            }

            // Draw the prim faces
            for (int j = 0; j < Faces.Count; j++)
            {
                Primitive.TextureEntryFace teFace = Prim.Textures.GetFace((uint)j);
                Face face = Faces[j];
                FaceData data = (FaceData)face.UserData;

                if (data == null)
                    continue;

                if (teFace == null)
                    continue;

                // Don't render transparent faces
                Color4 RGBA = teFace.RGBA;

                if (data.TextureInfo.FullAlpha || RGBA.A <= 0.01f) continue;

                bool switchedLightsOff = false;

                if (pass == RenderPass.Picking)
                {
                    data.PickingID = pickingID;
                    var primNrBytes = Utils.UInt16ToBytes((ushort)pickingID);
                    var faceColor = new byte[] { primNrBytes[0], primNrBytes[1], (byte)j, 255 };
                    GL.Color4(faceColor);
                }
                else if (pass == RenderPass.Invisible)
                {
                    if (!data.TextureInfo.IsInvisible) continue;
                    HasInvisibleFaces = true;
                }
                else
                {
                    if (data.TextureInfo.IsInvisible) continue;
                    bool belongToAlphaPass = (RGBA.A < 0.99f) || (data.TextureInfo.HasAlpha && !data.TextureInfo.IsMask);

                    if (belongToAlphaPass && pass != RenderPass.Alpha) continue;
                    if (!belongToAlphaPass && pass == RenderPass.Alpha) continue;

                    if (pass == RenderPass.Simple)
                    {
                        HasSimpleFaces = true;
                    }
                    else if (pass == RenderPass.Alpha)
                    {
                        HasAlphaFaces = true;
                    }

                    if (teFace.Fullbright)
                    {
                        GL.Disable(EnableCap.Lighting);
                        switchedLightsOff = true;
                    }

                    float shiny = 0f;
                    switch (teFace.Shiny)
                    {
                        case Shininess.High:
                            shiny = 0.96f;
                            break;

                        case Shininess.Medium:
                            shiny = 0.64f;
                            break;

                        case Shininess.Low:
                            shiny = 0.24f;
                            break;
                    }

                    if (shiny > 0f)
                    {
                        scene.StartShiny();
                    }
                    GL.Material(MaterialFace.Front, MaterialParameter.Shininess, shiny);
                    var faceColor = new float[] { RGBA.R, RGBA.G, RGBA.B, RGBA.A };
                    GL.Color4(faceColor);

                    GL.Material(MaterialFace.Front, MaterialParameter.Specular, new float[] { 0.5f, 0.5f, 0.5f, 1f });

                    if (data.TextureInfo.TexturePointer == 0)
                    {
                        TextureInfo teInfo;
                        if (scene.TryGetTextureInfo(teFace.TextureID, out teInfo))
                        {
                            data.TextureInfo = teInfo;
                        }
                    }

                    if (data.TextureInfo.TexturePointer == 0)
                    {
                        GL.Disable(EnableCap.Texture2D);
                        if (!data.TextureInfo.FetchFailed)
                        {
                            scene.DownloadTexture(new TextureLoadItem()
                            {
                                Prim = this.Prim,
                                TeFace = teFace,
                                Data = data
                            }, false);
                        }
                    }
                    else
                    {
                        // Is this face using texture animation
                        if ((Prim.TextureAnim.Flags & Primitive.TextureAnimMode.ANIM_ON) != 0
                            && (Prim.TextureAnim.Face == j || Prim.TextureAnim.Face == 255))
                        {
                            if (data.AnimInfo == null)
                            {
                                data.AnimInfo = new TextureAnimationInfo();
                            }
                            data.AnimInfo.PrimAnimInfo = Prim.TextureAnim;
                            data.AnimInfo.Step(time);
                            animatedTexture = true;
                        }
                        else if (data.AnimInfo != null) // Face texture not animated. Do we have previous anim setting?
                        {
                            data.AnimInfo = null;
                        }

                        GL.Enable(EnableCap.Texture2D);
                        GL.BindTexture(TextureTarget.Texture2D, data.TextureInfo.TexturePointer);
                    }
                }

                if (!RenderSettings.UseVBO || data.VBOFailed)
                {
                    Vertex[] verts = face.Vertices.ToArray();
                    ushort[] indices = face.Indices.ToArray();

                    unsafe
                    {
                        fixed (float* normalPtr = &verts[0].Normal.X)
                        fixed (float* texPtr = &verts[0].TexCoord.X)
                        {
                            GL.NormalPointer(NormalPointerType.Float, FaceData.VertexSize, (IntPtr)normalPtr);
                            GL.TexCoordPointer(2, TexCoordPointerType.Float, FaceData.VertexSize, (IntPtr)texPtr);
                            GL.VertexPointer(3, VertexPointerType.Float, FaceData.VertexSize, verts);
                            GL.DrawElements(BeginMode.Triangles, indices.Length, DrawElementsType.UnsignedShort, indices);
                        }
                    }
                }
                else
                {
                    if (data.CheckVBO(face))
                    {
                        Compat.BindBuffer(BufferTarget.ArrayBuffer, data.VertexVBO);
                        Compat.BindBuffer(BufferTarget.ElementArrayBuffer, data.IndexVBO);
                        GL.NormalPointer(NormalPointerType.Float, FaceData.VertexSize, (IntPtr)12);
                        GL.TexCoordPointer(2, TexCoordPointerType.Float, FaceData.VertexSize, (IntPtr)(24));
                        GL.VertexPointer(3, VertexPointerType.Float, FaceData.VertexSize, (IntPtr)(0));

                        GL.DrawElements(BeginMode.Triangles, face.Indices.Count, DrawElementsType.UnsignedShort, IntPtr.Zero);
                    }
                    Compat.BindBuffer(BufferTarget.ArrayBuffer, 0);
                    Compat.BindBuffer(BufferTarget.ElementArrayBuffer, 0);

                }

                if (switchedLightsOff)
                {
                    GL.Enable(EnableCap.Lighting);
                    switchedLightsOff = false;
                }

            }

            GL.BindTexture(TextureTarget.Texture2D, 0);
            RHelp.ResetMaterial();

            // Reset texture coordinates if we modified them in texture animation
            if (animatedTexture)
            {
                GL.MatrixMode(MatrixMode.Texture);
                GL.LoadIdentity();
                GL.MatrixMode(MatrixMode.Modelview);
            }

            // Pop the prim matrix
            GL.PopMatrix();

            base.Render(pass, pickingID, scene, time);
        }
Esempio n. 27
0
        public string RenderMaterialsPostCap(string request, UUID agentID)
        {
            OSDMap req  = (OSDMap)OSDParser.DeserializeLLSDXml(request);
            OSDMap resp = new OSDMap();

            OSDMap materialsFromViewer = null;

            OSDArray respArr = new OSDArray();

            if (req.ContainsKey("Zipped"))
            {
                OSD osd = null;

                byte[] inBytes = req["Zipped"].AsBinary();

                try
                {
                    osd = ZDecompressBytesToOsd(inBytes);

                    if (osd != null)
                    {
                        if (osd is OSDArray) // assume array of MaterialIDs designating requested material entries
                        {
                            foreach (OSD elem in (OSDArray)osd)
                            {
                                try
                                {
                                    UUID id = new UUID(elem.AsBinary(), 0);

                                    lock (m_regionMaterials)
                                    {
                                        if (m_regionMaterials.ContainsKey(id))
                                        {
                                            OSDMap matMap = new OSDMap();
                                            matMap["ID"]       = OSD.FromBinary(id.GetBytes());
                                            matMap["Material"] = m_regionMaterials[id];
                                            respArr.Add(matMap);
                                        }
                                        else
                                        {
                                            m_log.Warn("[Materials]: request for unknown material ID: " + id.ToString());

                                            // Theoretically we could try to load the material from the assets service,
                                            // but that shouldn't be necessary because the viewer should only request
                                            // materials that exist in a prim on the region, and all of these materials
                                            // are already stored in m_regionMaterials.
                                        }
                                    }
                                }
                                catch (Exception e)
                                {
                                    m_log.Error("Error getting materials in response to viewer request", e);
                                    continue;
                                }
                            }
                        }
                        else if (osd is OSDMap) // request to assign a material
                        {
                            materialsFromViewer = osd as OSDMap;

                            if (materialsFromViewer.ContainsKey("FullMaterialsPerFace"))
                            {
                                OSD matsOsd = materialsFromViewer["FullMaterialsPerFace"];
                                if (matsOsd is OSDArray)
                                {
                                    OSDArray matsArr = matsOsd as OSDArray;

                                    try
                                    {
                                        foreach (OSDMap matsMap in matsArr)
                                        {
                                            uint primLocalID = 0;
                                            try {
                                                primLocalID = matsMap["ID"].AsUInteger();
                                            }
                                            catch (Exception e) {
                                                m_log.Warn("[Materials]: cannot decode \"ID\" from matsMap: " + e.Message);
                                                continue;
                                            }

                                            OSDMap mat = null;
                                            try
                                            {
                                                mat = matsMap["Material"] as OSDMap;
                                            }
                                            catch (Exception e)
                                            {
                                                m_log.Warn("[Materials]: cannot decode \"Material\" from matsMap: " + e.Message);
                                                continue;
                                            }

                                            SceneObjectPart sop = m_scene.GetSceneObjectPart(primLocalID);
                                            if (sop == null)
                                            {
                                                m_log.WarnFormat("[Materials]: SOP not found for localId: {0}", primLocalID.ToString());
                                                continue;
                                            }

                                            if (!m_scene.Permissions.CanEditObject(sop.UUID, agentID))
                                            {
                                                m_log.WarnFormat("User {0} can't edit object {1} {2}", agentID, sop.Name, sop.UUID);
                                                continue;
                                            }

                                            Primitive.TextureEntry te = new Primitive.TextureEntry(sop.Shape.TextureEntry, 0, sop.Shape.TextureEntry.Length);
                                            if (te == null)
                                            {
                                                m_log.WarnFormat("[Materials]: Error in TextureEntry for SOP {0} {1}", sop.Name, sop.UUID);
                                                continue;
                                            }


                                            UUID id;
                                            if (mat == null)
                                            {
                                                // This happens then the user removes a material from a prim
                                                id = UUID.Zero;
                                            }
                                            else
                                            {
                                                id = StoreMaterialAsAsset(agentID, mat, sop);
                                            }


                                            int face = -1;

                                            if (matsMap.ContainsKey("Face"))
                                            {
                                                face = matsMap["Face"].AsInteger();
                                                Primitive.TextureEntryFace faceEntry = te.CreateFace((uint)face);
                                                faceEntry.MaterialID = id;
                                            }
                                            else
                                            {
                                                if (te.DefaultTexture == null)
                                                {
                                                    m_log.WarnFormat("[Materials]: TextureEntry.DefaultTexture is null in {0} {1}", sop.Name, sop.UUID);
                                                }
                                                else
                                                {
                                                    te.DefaultTexture.MaterialID = id;
                                                }
                                            }

                                            //m_log.DebugFormat("[Materials]: in \"{0}\" {1}, setting material ID for face {2} to {3}", sop.Name, sop.UUID, face, id);

                                            // We can't use sop.UpdateTextureEntry(te) because it filters, so do it manually
                                            sop.Shape.TextureEntry = te.GetBytes();

                                            if (sop.ParentGroup != null)
                                            {
                                                sop.TriggerScriptChangedEvent(Changed.TEXTURE);
                                                sop.UpdateFlag = UpdateRequired.FULL;
                                                sop.ParentGroup.HasGroupChanged = true;
                                                sop.ScheduleFullUpdate();
                                            }
                                        }
                                    }
                                    catch (Exception e)
                                    {
                                        m_log.Warn("[Materials]: exception processing received material ", e);
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    m_log.Warn("[Materials]: exception decoding zipped CAP payload ", e);
                    //return "";
                }
            }


            resp["Zipped"] = ZCompressOSD(respArr, false);
            string response = OSDParser.SerializeLLSDXmlString(resp);

            //m_log.Debug("[Materials]: cap request: " + request);
            //m_log.Debug("[Materials]: cap request (zipped portion): " + ZippedOsdBytesToString(req["Zipped"].AsBinary()));
            //m_log.Debug("[Materials]: cap response: " + response);
            return(response);
        }
Esempio n. 28
0
        public static bool MeshesToOBJ(List <FacetedMesh> meshes, string filename)
        {
            StringBuilder obj = new StringBuilder();
            StringBuilder mtl = new StringBuilder();

            FileInfo objFileInfo = new FileInfo(filename);

            string mtlFilename = objFileInfo.FullName.Substring(objFileInfo.DirectoryName.Length + 1,
                                                                objFileInfo.FullName.Length - (objFileInfo.DirectoryName.Length + 1) - 4) + ".mtl";

            obj.AppendLine("# Created by libprimrender");
            obj.AppendLine("mtllib ./" + mtlFilename);
            obj.AppendLine();

            mtl.AppendLine("# Created by libprimrender");
            mtl.AppendLine();

            for (int i = 0; i < meshes.Count; i++)
            {
                FacetedMesh mesh = meshes[i];

                for (int j = 0; j < mesh.Faces.Count; j++)
                {
                    Face face = mesh.Faces[j];

                    if (face.Vertices.Count > 2)
                    {
                        string mtlName = String.Format("material{0}-{1}", i, face.ID);
                        Primitive.TextureEntryFace tex = face.TextureFace;
                        string texName = tex.TextureID.ToString() + ".tga";

                        // FIXME: Convert the source to TGA (if needed) and copy to the destination

                        float shiny = 0.00f;
                        switch (tex.Shiny)
                        {
                        case Shininess.High:
                            shiny = 1.00f;
                            break;

                        case Shininess.Medium:
                            shiny = 0.66f;
                            break;

                        case Shininess.Low:
                            shiny = 0.33f;
                            break;
                        }

                        obj.AppendFormat("g face{0}-{1}{2}", i, face.ID, Environment.NewLine);

                        mtl.AppendLine("newmtl " + mtlName);
                        mtl.AppendFormat("Ka {0} {1} {2}{3}", tex.RGBA.R, tex.RGBA.G, tex.RGBA.B, Environment.NewLine);
                        mtl.AppendFormat("Kd {0} {1} {2}{3}", tex.RGBA.R, tex.RGBA.G, tex.RGBA.B, Environment.NewLine);
                        //mtl.AppendFormat("Ks {0} {1} {2}{3}");
                        mtl.AppendLine("Tr " + tex.RGBA.A);
                        mtl.AppendLine("Ns " + shiny);
                        mtl.AppendLine("illum 1");
                        if (tex.TextureID != UUID.Zero && tex.TextureID != Primitive.TextureEntry.WHITE_TEXTURE)
                        {
                            mtl.AppendLine("map_Kd ./" + texName);
                        }
                        mtl.AppendLine();

                        // Write the vertices, texture coordinates, and vertex normals for this side
                        for (int k = 0; k < face.Vertices.Count; k++)
                        {
                            Vertex vertex = face.Vertices[k];

                            #region Vertex

                            Vector3 pos = vertex.Position;

                            // Apply scaling
                            pos *= mesh.Prim.Scale;

                            // Apply rotation
                            pos *= mesh.Prim.Rotation;

                            // The root prim position is sim-relative, while child prim positions are
                            // parent-relative. We want to apply parent-relative translations but not
                            // sim-relative ones
                            if (mesh.Prim.ParentID != 0)
                            {
                                pos += mesh.Prim.Position;
                            }

                            obj.AppendFormat("v {0} {1} {2}{3}", pos.X, pos.Y, pos.Z, Environment.NewLine);

                            #endregion Vertex

                            #region Texture Coord

                            obj.AppendFormat("vt {0} {1}{2}", vertex.TexCoord.X, vertex.TexCoord.Y,
                                             Environment.NewLine);

                            #endregion Texture Coord

                            #region Vertex Normal

                            // HACK: Sometimes normals are getting set to <NaN,NaN,NaN>
                            if (!Single.IsNaN(vertex.Normal.X) && !Single.IsNaN(vertex.Normal.Y) && !Single.IsNaN(vertex.Normal.Z))
                            {
                                obj.AppendFormat("vn {0} {1} {2}{3}", vertex.Normal.X, vertex.Normal.Y, vertex.Normal.Z,
                                                 Environment.NewLine);
                            }
                            else
                            {
                                obj.AppendLine("vn 0.0 1.0 0.0");
                            }

                            #endregion Vertex Normal
                        }

                        obj.AppendFormat("# {0} vertices{1}", face.Vertices.Count, Environment.NewLine);
                        obj.AppendLine();
                        obj.AppendLine("usemtl " + mtlName);

                        #region Elements

                        // Write all of the faces (triangles) for this side
                        for (int k = 0; k < face.Indices.Count / 3; k++)
                        {
                            obj.AppendFormat("f -{0}/-{0}/-{0} -{1}/-{1}/-{1} -{2}/-{2}/-{2}{3}",
                                             face.Vertices.Count - face.Indices[k * 3 + 0],
                                             face.Vertices.Count - face.Indices[k * 3 + 1],
                                             face.Vertices.Count - face.Indices[k * 3 + 2],
                                             Environment.NewLine);
                        }

                        obj.AppendFormat("# {0} elements{1}", face.Indices.Count / 3, Environment.NewLine);
                        obj.AppendLine();

                        #endregion Elements
                    }
                }
            }

            try
            {
                File.WriteAllText(filename, obj.ToString());
                File.WriteAllText(mtlFilename, mtl.ToString());
            }
            catch (Exception)
            {
                return(false);
            }

            return(true);
        }
Esempio n. 29
0
 public void TransformTexCoords(List <Vertex> vertices, Vector3 center, Primitive.TextureEntryFace teFace, Vector3 primScale)
 {
     // Lalala...
 }
Esempio n. 30
0
        /// <summary>
        /// //settexture 5 8dcd4a48-2d37-4909-9f78-f7a9eb4ef903
        /// </summary>
        /// <param name="args"></param>
        /// <param name="fromAgentID"></param>
        /// <param name="WriteLine"></param>
        /// <returns></returns>
        public override CmdResult ExecuteRequest(CmdRequest args)
        {
            UUID asset = UUID.Zero;
            AvatarTextureIndex index = AvatarTextureIndex.Unknown;

            if (args.Length > 1)
            {
                Object val;
                int    argsUsed;
                if (TryEnumParse(typeof(AvatarTextureIndex), args, 0, out argsUsed, out val))
                {
                    index = (AvatarTextureIndex)val;
                }
                string targetName = args[argsUsed];
                if (!UUID.TryParse(targetName, out asset))
                {
                    asset = WorldSystem.SimAssetSystem.GetAssetUUID(targetName, AssetType.Texture);
                }
            }

            // Get our current appearance
            UUID target = Client.Self.AgentID;

#if COGBOT_LIBOMV
            AgentSetAppearancePacket set = Client.Appearance.MakeAppearancePacket();
            Primitive.TextureEntry   te;
            if (!Client.Appearances.ContainsKey(target))
            {
                te = new Primitive.TextureEntry(set.ObjectData.TextureEntry, 0,
                                                set.ObjectData.TextureEntry.Length);
            }
            else
            {
                #region AvatarAppearance to AgentSetAppearance

                AvatarAppearancePacket appearance = TheBotClient.Appearances[target];

                set.AgentData.AgentID   = Client.Self.AgentID;
                set.AgentData.SessionID = Client.Self.SessionID;
                set.AgentData.SerialNum = SerialNum++;
                set.AgentData.Size      = new Vector3(2f, 2f, 2f); // HACK

                set.WearableData = new AgentSetAppearancePacket.WearableDataBlock[0];
                set.VisualParam  = new AgentSetAppearancePacket.VisualParamBlock[appearance.VisualParam.Length];

                for (int i = 0; i < appearance.VisualParam.Length; i++)
                {
                    set.VisualParam[i]            = new AgentSetAppearancePacket.VisualParamBlock();
                    set.VisualParam[i].ParamValue = appearance.VisualParam[i].ParamValue;
                }
                set.ObjectData.TextureEntry = appearance.ObjectData.TextureEntry;

                te = new Primitive.TextureEntry(appearance.ObjectData.TextureEntry, 0,
                                                appearance.ObjectData.TextureEntry.Length);

                #endregion AvatarAppearance to AgentSetAppearance
            }

            #region TextureEntry

            if (index != AvatarTextureIndex.Unknown)
            {
                Primitive.TextureEntryFace face = te.CreateFace((uint)index);
                face.TextureID = asset;
            }

            set.ObjectData.TextureEntry = te.GetBytes();

            #endregion TextureEntry

            // Send the new appearance packet
            Client.Network.SendPacket(set);
#endif
            return(Success("Setting texture entry for " + (AvatarTextureIndex)index + " to " + asset));
        }