Ejemplo n.º 1
0
        /// <summary>
        /// Convert raw uploaded data into the appropriate asset and item.
        /// </summary>
        /// <param name="assetID"></param>
        /// <param name="inventoryItem"></param>
        /// <param name="data"></param>
        public void UploadCompleteHandler(string assetName, string assetDescription, UUID assetID,
                                          UUID inventoryItem, UUID parentFolder, byte[] data, string inventoryType,
                                          string assetType)
        {
            m_log.DebugFormat(
                "Uploaded asset {0} for inventory item {1}, inv type {2}, asset type {3}",
                assetID, inventoryItem, inventoryType, assetType);

            sbyte assType = 0;
            sbyte inType = 0;

            if (inventoryType == "sound")
            {
                inType = 1;
                assType = 1;
            }
            else if (inventoryType == "animation")
            {
                inType = 19;
                assType = 20;
            }
            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>();
                for (int i = 0; i < texture_list.Count; i++)
                {
                    AssetBase textureAsset = new AssetBase(UUID.Random(), assetName, (sbyte)AssetType.Texture, "");
                    textureAsset.Data = texture_list[i].AsBinary();
                    m_assetService.Store(textureAsset);
                    textures.Add(textureAsset.FullID);
                }

                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;

                        if (textures.Count > textureNum)
                            f.TextureID = textures[textureNum];
                        else
                            f.TextureID = Primitive.TextureEntry.WHITE_TEXTURE;

                        textureEntry.FaceTextures[face] = f;
                    }

                    pbs.TextureEntry = textureEntry.GetBytes();

                    AssetBase meshAsset = new AssetBase(UUID.Random(), assetName, (sbyte)AssetType.Mesh, "");
                    meshAsset.Data = mesh_list[i].AsBinary();
                    m_assetService.Store(meshAsset);

                    pbs.SculptEntry = true;
                    pbs.SculptTexture = meshAsset.FullID;
                    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();

                    OSDMap permissions = (OSDMap)inner_instance_list["permissions"];
                    int base_mask = permissions["base_mask"].AsInteger();
                    int everyone_mask = permissions["everyone_mask"].AsInteger();
                    UUID creator_id = permissions["creator_id"].AsUUID();
                    UUID group_id = permissions["group_id"].AsUUID();
                    int group_mask = permissions["group_mask"].AsInteger();
//                    bool is_owner_group = permissions["is_owner_group"].AsBoolean();
//                    UUID last_owner_id = permissions["last_owner_id"].AsUUID();
                    int next_owner_mask = permissions["next_owner_mask"].AsInteger();
                    UUID owner_id = permissions["owner_id"].AsUUID();
                    int owner_mask = permissions["owner_mask"].AsInteger();

                    SceneObjectPart prim
                        = new SceneObjectPart(owner_id, pbs, position, Quaternion.Identity, Vector3.Zero);

                    prim.Scale = scale;
                    prim.OffsetPosition = position;
                    rotations.Add(rotation);
                    positions.Add(position);
                    prim.UUID = UUID.Random();
                    prim.CreatorID = creator_id;
                    prim.OwnerID = owner_id;
                    prim.GroupID = group_id;
                    prim.LastOwnerID = prim.OwnerID;
                    prim.CreationDate = Util.UnixTimeSinceEpoch();
                    prim.Name = assetName;
                    prim.Description = "";

                    prim.BaseMask = (uint)base_mask;
                    prim.EveryoneMask = (uint)everyone_mask;
                    prim.GroupMask = (uint)group_mask;
                    prim.NextOwnerMask = (uint)next_owner_mask;
                    prim.OwnerMask = (uint)owner_mask;

                    if (grp == null)
                        grp = new SceneObjectGroup(prim);
                    else
                        grp.AddPart(prim);
                }

                // Fix first link number
                if (grp.Parts.Length > 1)
                    grp.RootPart.LinkNum++;

                Vector3 rootPos = positions[0];
                grp.AbsolutePosition = rootPos;
                for (int i = 0; i < positions.Count; i++)
                {
                    Vector3 offset = positions[i] - rootPos;
                    grp.Parts[i].OffsetPosition = offset;
                }

                for (int i = 0; i < rotations.Count; i++)
                {
                    if (i != 0)
                        grp.Parts[i].RotationOffset = rotations[i];
                }

                grp.UpdateGroupRotationR(rotations[0]);
                data = ASCIIEncoding.ASCII.GetBytes(SceneObjectSerializer.ToOriginalXmlFormat(grp));
            }

            AssetBase asset;
            asset = new AssetBase(assetID, assetName, assType, m_HostCapsObj.AgentID.ToString());
            asset.Data = data;
            if (AddNewAsset != null)
                AddNewAsset(asset);
            else if (m_assetService != null)
                m_assetService.Store(asset);

            InventoryItemBase item = new InventoryItemBase();
            item.Owner = m_HostCapsObj.AgentID;
            item.CreatorId = m_HostCapsObj.AgentID.ToString();
            item.CreatorData = String.Empty;
            item.ID = inventoryItem;
            item.AssetID = asset.FullID;
            item.Description = assetDescription;
            item.Name = assetName;
            item.AssetType = assType;
            item.InvType = inType;
            item.Folder = parentFolder;
            item.CurrentPermissions = (uint)PermissionMask.All;
            item.BasePermissions = (uint)PermissionMask.All;
            item.EveryOnePermissions = 0;
            item.NextPermissions = (uint)(PermissionMask.Move | PermissionMask.Modify | PermissionMask.Transfer);
            item.CreationDate = Util.UnixTimeSinceEpoch();

            if (AddNewInventoryItem != null)
            {
                AddNewInventoryItem(m_HostCapsObj.AgentID, item);
            }
        }
        /// <summary>
        /// Parses add 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;
                pbs.LastAttachPoint = (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;
                
                // Required for linking
                grp.RootPart.ClearUpdateSchedule();
                
                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++)
            {
                // Required for linking
                rootGroup.RootPart.ClearUpdateSchedule();
                allparts[j].RootPart.ClearUpdateSchedule();
                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;
        }
Ejemplo n.º 3
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;
        }
Ejemplo n.º 4
0
        public void TextureEntry()
        {
            Primitive.TextureEntry te = new Primitive.TextureEntry(UUID.Random());
            Primitive.TextureEntryFace face = te.CreateFace(0);
            face.Bump = Bumpiness.Concrete;
            face.Fullbright = true;
            face.MediaFlags = true;
            face.OffsetU = 0.5f;
            face.OffsetV = -0.5f;
            face.RepeatU = 3.0f;
            face.RepeatV = 4.0f;
            face.RGBA = new Color4(0f, 0.25f, 0.75f, 1f);
            face.Rotation = 1.5f;
            face.Shiny = Shininess.Medium;
            face.TexMapType = MappingType.Planar;
            face.TextureID = UUID.Random();

            byte[] teBytes = te.GetBytes();

            Primitive.TextureEntry te2 = new Primitive.TextureEntry(teBytes, 0, teBytes.Length);

            byte[] teBytes2 = te2.GetBytes();

            Assert.IsTrue(teBytes.Length == teBytes2.Length);

            for (int i = 0; i < teBytes.Length; i++)
            {
                Assert.IsTrue(teBytes[i] == teBytes2[i], "Byte " + i + " is not equal");
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Convert raw uploaded data into the appropriate asset and item.
        /// </summary>
        /// <param name="assetID"></param>
        /// <param name="inventoryItem"></param>
        /// <param name="data"></param>
        public void UploadCompleteHandler(string assetName, string assetDescription, UUID assetID,
                                          UUID inventoryItem, UUID parentFolder, byte[] data, string inventoryType,
                                          string assetType, int cost,
                                          UUID texturesFolder, int nreqtextures, int nreqmeshs, int nreqinstances,
                                          bool IsAtestUpload, ref string error,
                                          ref int nextOwnerMask, ref int groupMask, ref int everyoneMask)
        {
            lock (m_ModelCost)
                m_FileAgentInventoryState = FileAgentInventoryState.processUpload;

            m_log.DebugFormat(
                "[BUNCH OF CAPS]: Uploaded asset {0} for inventory item {1}, inv type {2}, asset type {3}",
                assetID, inventoryItem, inventoryType, assetType);

            sbyte assType = 0;
            sbyte inType = 0;

            IClientAPI client = null;

            UUID owner_id = m_HostCapsObj.AgentID;
            UUID creatorID;

            bool istest = IsAtestUpload && m_enableFreeTestUpload && (cost > 0);

            bool restrictPerms = m_RestrictFreeTestUploadPerms && istest;

            if (istest && m_testAssetsCreatorID != UUID.Zero)
                creatorID = m_testAssetsCreatorID;
            else
                creatorID = owner_id;

            string creatorIDstr = creatorID.ToString();

            IMoneyModule mm = m_Scene.RequestModuleInterface<IMoneyModule>();
            if (mm != null)
            {
                // make sure client still has enougth credit
                if (!mm.UploadCovered(m_HostCapsObj.AgentID, (int)cost))
                {
                    error = "Insufficient funds.";
                    return;
                }
            }

            // strings to types
            if (inventoryType == "sound")
            {
                inType = (sbyte)InventoryType.Sound;
                assType = (sbyte)AssetType.Sound;
            }
            else if (inventoryType == "snapshot")
            {
                inType = (sbyte)InventoryType.Snapshot;
            }
            else if (inventoryType == "animation")
            {
                inType = (sbyte)InventoryType.Animation;
                assType = (sbyte)AssetType.Animation;
            }
            else if (inventoryType == "animset")
            {
                inType = (sbyte)CustomInventoryType.AnimationSet;
                assType = (sbyte)CustomAssetType.AnimationSet;
                m_log.Debug("got animset upload request");
            }
            else if (inventoryType == "wearable")
            {
                inType = (sbyte)InventoryType.Wearable;
                switch (assetType)
                {
                    case "bodypart":
                        assType = (sbyte)AssetType.Bodypart;
                        break;
                    case "clothing":
                        assType = (sbyte)AssetType.Clothing;
                        break;
                }
            }
            else if (inventoryType == "object")
            {
                if (assetType == "mesh") // this code for now is for mesh models uploads only
                {
                    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);

                    // compare and get updated information
/* does nothing still we do need something to avoid special viewer to upload something diferent from the cost estimation
                    bool mismatchError = true;

                    while (mismatchError)
                    {
                        mismatchError = false;
                    }

                    if (mismatchError)
                    {
                        error = "Upload and fee estimation information don't match";
                        lock (m_ModelCost)
                            m_FileAgentInventoryState = FileAgentInventoryState.idle;

                        return;
                    }
*/
                    OSDArray instance_list = (OSDArray)request["instance_list"];
                    OSDArray mesh_list = (OSDArray)request["mesh_list"];
                    OSDArray texture_list = (OSDArray)request["texture_list"];
                    SceneObjectGroup grp = null;

                    // create and store texture assets
                    bool doTextInv = (!istest && m_enableModelUploadTextureToInventory &&
                                    texturesFolder != UUID.Zero);


                    List<UUID> textures = new List<UUID>();

                   
//                    if (doTextInv)
                        m_Scene.TryGetClient(m_HostCapsObj.AgentID, out client);

                    if(client == null) // don't put textures in inventory if there is no client
                        doTextInv = false;

                    for (int i = 0; i < texture_list.Count; i++)
                    {
                        AssetBase textureAsset = new AssetBase(UUID.Random(), assetName, (sbyte)AssetType.Texture, creatorIDstr);
                        textureAsset.Data = texture_list[i].AsBinary();
                        if (istest)
                            textureAsset.Local = true;
                        m_assetService.Store(textureAsset);
                        textures.Add(textureAsset.FullID);

                        if (doTextInv)
                        {
                            string name = assetName;
                            if (name.Length > 25)
                                name = name.Substring(0, 24);
                            name += "_Texture#" + i.ToString();
                            InventoryItemBase texitem = new InventoryItemBase();
                            texitem.Owner = m_HostCapsObj.AgentID;
                            texitem.CreatorId = creatorIDstr;
                            texitem.CreatorData = String.Empty;
                            texitem.ID = UUID.Random();
                            texitem.AssetID = textureAsset.FullID;
                            texitem.Description = "mesh model texture";
                            texitem.Name = name;
                            texitem.AssetType = (int)AssetType.Texture;
                            texitem.InvType = (int)InventoryType.Texture;
                            texitem.Folder = texturesFolder;

                            texitem.CurrentPermissions
                                = (uint)(PermissionMask.Move | PermissionMask.Copy | PermissionMask.Modify | PermissionMask.Transfer | PermissionMask.Export);

                            texitem.BasePermissions = (uint)PermissionMask.All | (uint)PermissionMask.Export;
                            texitem.EveryOnePermissions = 0;
                            texitem.NextPermissions = (uint)PermissionMask.All;
                            texitem.CreationDate = Util.UnixTimeSinceEpoch();

                            m_Scene.AddInventoryItem(client, texitem);
                            texitem = null;
                        }
                    }

                    // create and store meshs assets
                    List<UUID> meshAssets = new List<UUID>();
                    List<bool> meshAvatarSkeletons = new List<bool>();
                    List<bool> meshAvatarColliders = new List<bool>();

                    bool curAvSkeleton;
                    bool curAvCollider;
                    for (int i = 0; i < mesh_list.Count; i++)
                    {
                        curAvSkeleton = false;
                        curAvCollider = false;

                        // we do need to parse the mesh now
                        OSD osd = OSDParser.DeserializeLLSDBinary(mesh_list[i]);
                        if (osd is OSDMap)
                        {
                            OSDMap mosd = (OSDMap)osd;
                            if (mosd.ContainsKey("skeleton"))
                            {
                                OSDMap skeleton = (OSDMap)mosd["skeleton"];
                                int sksize = skeleton["size"].AsInteger();
                                if (sksize > 0)
                                    curAvSkeleton = true;
                            }
                        }

                        AssetBase meshAsset = new AssetBase(UUID.Random(), assetName, (sbyte)AssetType.Mesh, creatorIDstr);
                        meshAsset.Data = mesh_list[i].AsBinary();
                        if (istest)
                            meshAsset.Local = true;
                        m_assetService.Store(meshAsset);
                        meshAssets.Add(meshAsset.FullID);
                        meshAvatarSkeletons.Add(curAvSkeleton);
                        meshAvatarColliders.Add(curAvCollider);

                        // test code 
                        if (curAvSkeleton && client != null)
                        {
                            string name = assetName;
                            if (name.Length > 25)
                                name = name.Substring(0, 24);
                            name += "_Mesh#" + i.ToString();
                            InventoryItemBase meshitem = new InventoryItemBase();
                            meshitem.Owner = m_HostCapsObj.AgentID;
                            meshitem.CreatorId = creatorIDstr;
                            meshitem.CreatorData = String.Empty;
                            meshitem.ID = UUID.Random();
                            meshitem.AssetID = meshAsset.FullID;
                            meshitem.Description = "mesh ";
                            meshitem.Name = name;
                            meshitem.AssetType = (int)AssetType.Mesh;
                            meshitem.InvType = (int)InventoryType.Mesh;
                            //                            meshitem.Folder = UUID.Zero; // send to default

                            meshitem.Folder = parentFolder; // dont let it go to folder Meshes that viewers dont show

                            // If we set PermissionMask.All then when we rez the item the next permissions will replace the current
                            // (owner) permissions.  This becomes a problem if next permissions are changed.
                            meshitem.CurrentPermissions
                                = (uint)(PermissionMask.Move | PermissionMask.Copy | PermissionMask.Modify | PermissionMask.Transfer);

                            meshitem.BasePermissions = (uint)PermissionMask.All;
                            meshitem.EveryOnePermissions = 0;
                            meshitem.NextPermissions = (uint)PermissionMask.All;
                            meshitem.CreationDate = Util.UnixTimeSinceEpoch();

                            m_Scene.AddInventoryItem(client, meshitem);
                            meshitem = null;
                        }
                    }

                    int skipedMeshs = 0;
                    // build prims from instances
                    for (int i = 0; i < instance_list.Count; i++)
                    {
                        OSDMap inner_instance_list = (OSDMap)instance_list[i];

                        // skip prims that are 2 small
                        Vector3 scale = inner_instance_list["scale"].AsVector3();

                        if (scale.X < m_PrimScaleMin || scale.Y < m_PrimScaleMin || scale.Z < m_PrimScaleMin)
                        {
                            skipedMeshs++;
                            continue;
                        }

                        PrimitiveBaseShape pbs = PrimitiveBaseShape.CreateBox();

                        Primitive.TextureEntry textureEntry
                            = new Primitive.TextureEntry(Primitive.TextureEntry.WHITE_TEXTURE);


                        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;

                            if (textures.Count > textureNum)
                                f.TextureID = textures[textureNum];
                            else
                                f.TextureID = Primitive.TextureEntry.WHITE_TEXTURE;

                            textureEntry.FaceTextures[face] = f;
                        }

                        pbs.TextureEntry = textureEntry.GetBytes();

                        bool hasmesh = false;
                        if (inner_instance_list.ContainsKey("mesh")) // seems to happen always but ...
                        {
                            int meshindx = inner_instance_list["mesh"].AsInteger();
                            if (meshAssets.Count > meshindx)
                            {
                                pbs.SculptEntry = true;
                                pbs.SculptType = (byte)SculptType.Mesh;
                                pbs.SculptTexture = meshAssets[meshindx]; // actual asset UUID after meshs suport introduction
                                // data will be requested from asset on rez (i hope)
                                hasmesh = true;
                            }
                        }

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

                        // for now viwers do send fixed defaults
                        // but this may change
//                        int physicsShapeType = inner_instance_list["physics_shape_type"].AsInteger();
                        byte physicsShapeType = (byte)PhysShapeType.convex; // default is simple convex
//                        int material = inner_instance_list["material"].AsInteger();
                        byte material = (byte)Material.Wood;

// no longer used - begin ------------------------
//                    int mesh = inner_instance_list["mesh"].AsInteger();

//                    OSDMap permissions = (OSDMap)inner_instance_list["permissions"];
//                    int base_mask = permissions["base_mask"].AsInteger();
//                    int everyone_mask = permissions["everyone_mask"].AsInteger();
//                    UUID creator_id = permissions["creator_id"].AsUUID();
//                    UUID group_id = permissions["group_id"].AsUUID();
//                    int group_mask = permissions["group_mask"].AsInteger();
//                    bool is_owner_group = permissions["is_owner_group"].AsBoolean();
//                    UUID last_owner_id = permissions["last_owner_id"].AsUUID();
//                    int next_owner_mask = permissions["next_owner_mask"].AsInteger();
//                    UUID owner_id = permissions["owner_id"].AsUUID();
//                    int owner_mask = permissions["owner_mask"].AsInteger();
// no longer used - end ------------------------
                       

                        SceneObjectPart prim
                            = new SceneObjectPart(owner_id, pbs, position, Quaternion.Identity, Vector3.Zero);

                        prim.Scale = scale;
                        rotations.Add(rotation);
                        positions.Add(position);
                        prim.UUID = UUID.Random();
                        prim.CreatorID = creatorID;
                        prim.OwnerID = owner_id;
                        prim.GroupID = UUID.Zero;
                        prim.LastOwnerID = creatorID;
                        prim.CreationDate = Util.UnixTimeSinceEpoch();
                        
                        if (grp == null)
                            prim.Name = assetName;
                        else
                            prim.Name = assetName + "#" + i.ToString();

                        prim.EveryoneMask = 0;
                        prim.GroupMask = 0;

                        if (restrictPerms)
                        {
                            prim.BaseMask = (uint)(PermissionMask.Move | PermissionMask.Modify);
                            prim.OwnerMask = (uint)(PermissionMask.Move | PermissionMask.Modify);
                            prim.NextOwnerMask = 0;
                        }
                        else
                        {
                            prim.BaseMask = (uint)PermissionMask.All | (uint)PermissionMask.Export;
                            prim.OwnerMask = (uint)PermissionMask.All | (uint)PermissionMask.Export;
                            prim.GroupMask = prim.BaseMask & (uint)groupMask;
                            prim.EveryoneMask = prim.BaseMask & (uint)everyoneMask;
                            prim.NextOwnerMask = prim.BaseMask & (uint)nextOwnerMask;
                            // If the viewer gives us bogus permissions, revert to the SL
                            // default of transfer only.
                            if ((prim.NextOwnerMask & (uint)PermissionMask.All) == 0)
                                prim.NextOwnerMask = (uint)PermissionMask.Transfer;
                        }

                        if(istest)
                            prim.Description = "For testing only. Other uses are prohibited";
                        else
                            prim.Description = "";

                        prim.Material = material;
                        prim.PhysicsShapeType = physicsShapeType;

//                    prim.BaseMask = (uint)base_mask;
//                    prim.EveryoneMask = (uint)everyone_mask;
//                    prim.GroupMask = (uint)group_mask;
//                    prim.NextOwnerMask = (uint)next_owner_mask;
//                    prim.OwnerMask = (uint)owner_mask;

                        if (grp == null)
                        {
                            grp = new SceneObjectGroup(prim);
                            grp.LastOwnerID = creatorID;
                        }
                        else
                            grp.AddPart(prim);
                    }

                    Vector3 rootPos = positions[0];

                    if (grp.Parts.Length > 1)
                    {
                        // Fix first link number
                        grp.RootPart.LinkNum++;

                        Quaternion rootRotConj = Quaternion.Conjugate(rotations[0]);
                        Quaternion tmprot;
                        Vector3 offset;

                        // fix children rotations and positions
                        for (int i = 1; i < rotations.Count; i++)
                        {
                            tmprot = rotations[i];
                            tmprot = rootRotConj * tmprot;

                            grp.Parts[i].RotationOffset = tmprot;

                            offset = positions[i] - rootPos;

                            offset *= rootRotConj;
                            grp.Parts[i].OffsetPosition = offset;
                        }

                        grp.AbsolutePosition = rootPos;
                        grp.UpdateGroupRotationR(rotations[0]);
                    }
                    else
                    {
                        grp.AbsolutePosition = rootPos;
                        grp.UpdateGroupRotationR(rotations[0]);
                    }

                    data = ASCIIEncoding.ASCII.GetBytes(SceneObjectSerializer.ToOriginalXmlFormat(grp));
                }

                else // not a mesh model
                {
                    m_log.ErrorFormat("[CAPS Asset Upload] got unsuported assetType for object upload");
                    return;
                }
            }

            AssetBase asset;
            asset = new AssetBase(assetID, assetName, assType, creatorIDstr);
            asset.Data = data;
            if (istest)
                asset.Local = true;
            if (AddNewAsset != null)
                AddNewAsset(asset);
            else if (m_assetService != null)
                m_assetService.Store(asset);

            InventoryItemBase item = new InventoryItemBase();
            item.Owner = m_HostCapsObj.AgentID;
            item.CreatorId = creatorIDstr;
            item.CreatorData = String.Empty;
            item.ID = inventoryItem;
            item.AssetID = asset.FullID;
            if (istest)
            {
                item.Description = "For testing only. Other uses are prohibited";
                item.Flags = (uint) (InventoryItemFlags.SharedSingleReference);
            }
            else
                item.Description = assetDescription;
            item.Name = assetName;
            item.AssetType = assType;
            item.InvType = inType;
            item.Folder = parentFolder;

            // If we set PermissionMask.All then when we rez the item the next permissions will replace the current
            // (owner) permissions.  This becomes a problem if next permissions are changed.

            if (inType == (sbyte)CustomInventoryType.AnimationSet)
            {
                AnimationSet.setCreateItemPermitions(item);
            }

            else if (restrictPerms)
            {
                item.BasePermissions = (uint)(PermissionMask.Move | PermissionMask.Modify);
                item.CurrentPermissions = (uint)(PermissionMask.Move | PermissionMask.Modify);
                item.GroupPermissions = 0;
                item.EveryOnePermissions = 0;
                item.NextPermissions = 0;
            }
            else
            {
                item.BasePermissions = (uint)PermissionMask.All | (uint)PermissionMask.Export;
                item.CurrentPermissions = (uint)PermissionMask.All | (uint)PermissionMask.Export;
                item.GroupPermissions = item.BasePermissions & (uint)groupMask;
                item.EveryOnePermissions = item.BasePermissions & (uint)everyoneMask;
                item.NextPermissions = item.BasePermissions & (uint)nextOwnerMask;
                if ((item.NextPermissions & (uint)PermissionMask.All) == 0)
                    item.NextPermissions = (uint)PermissionMask.Transfer;
            }

            item.CreationDate = Util.UnixTimeSinceEpoch();

            everyoneMask = (int)item.EveryOnePermissions;
            groupMask = (int)item.GroupPermissions;
            nextOwnerMask = (int)item.NextPermissions;

            m_Scene.TryGetClient(m_HostCapsObj.AgentID, out client);

            if (AddNewInventoryItem != null)
            {
                if (istest)
                {
                    m_Scene.AddInventoryItem(client, item);
/*
                    AddNewInventoryItem(m_HostCapsObj.AgentID, item, 0);
                    if (client != null)
                        client.SendAgentAlertMessage("Upload will have no cost, for personal test purposes only. Other uses are forbiden. Items may not work on a another region" , true);
 */
                }
                else
                {
                    AddNewInventoryItem(m_HostCapsObj.AgentID, item, (uint)cost);
//                    if (client != null)
//                    {
//                        // let users see anything..  i don't so far
//                        string str;
//                        if (cost > 0)
//                            // dont remember where is money unit name to put here
//                            str = "Upload complete. charged " + cost.ToString() + "$";
//                        else
//                            str = "Upload complete";
//                        client.SendAgentAlertMessage(str, true);
//                    }
                }
            }

            lock (m_ModelCost)
                m_FileAgentInventoryState = FileAgentInventoryState.idle;
        }
Ejemplo n.º 6
0
        ///<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;
        }
Ejemplo n.º 7
0
Archivo: coin.cs Proyecto: zadark/par
        public AgentSetAppearancePacket replacer_lols(AgentSetAppearancePacket packet)
        {
            AgentSetAppearancePacket p = cloneASA(packet);
            if (p.ObjectData != null)
            {
                if (p.ObjectData.TextureEntry != null)
                {
                    Primitive.TextureEntry te = new Primitive.TextureEntry(p.ObjectData.TextureEntry, 0, p.ObjectData.TextureEntry.Length);
                    if (te != null)
                    {
                        if (te.FaceTextures != null)
                        {
                            if (te.FaceTextures.Length > 0)
                            {
                                //Console.WriteLine("Coin is replacing textures...");
                                UUID replace = lols[lolcounter];
                                lolcounter++;
                                if (lolcounter >= lols.Length)
                                    lolcounter = 0;
                                for (int i = 0; i <= 7; i++)
                                {
                                    if (te.FaceTextures[i] != null)
                                        te.FaceTextures[i].TextureID = replace;
                                }
                                for (int i = 12; i <= 18; i++)
                                {
                                    if (te.FaceTextures[i] != null)
                                        te.FaceTextures[i].TextureID = replace;
                                }

                                if (p.ObjectData != null)
                                    p.ObjectData.TextureEntry = te.GetBytes();
                                //Console.WriteLine("OK!");
                            }
                        }
                    }
                }
            }
            return p;
        }
Ejemplo n.º 8
0
 /// <summary>
 /// Set the color of prim faces
 /// </summary>
 /// <param name="color"></param>
 /// <param name="face"></param>
 public void SetFaceColor(Vector3 color, int face)
 {
     // The only way to get a deep copy/ If we don't do this, we can
     // mever detect color changes further down.
     Byte[] buf = Shape.Textures.GetBytes();
     Primitive.TextureEntry tex = new Primitive.TextureEntry(buf, 0, buf.Length);
     Color4 texcolor;
     if (face >= 0 && face < GetNumberOfSides())
     {
         texcolor = tex.CreateFace((uint)face).RGBA;
         texcolor.R = Util.Clip((float)color.X, 0.0f, 1.0f);
         texcolor.G = Util.Clip((float)color.Y, 0.0f, 1.0f);
         texcolor.B = Util.Clip((float)color.Z, 0.0f, 1.0f);
         tex.FaceTextures[face].RGBA = texcolor;
         UpdateTextureEntry(tex.GetBytes());
         return;
     }
     else if (face == ALL_SIDES)
     {
         for (uint i = 0; i < GetNumberOfSides(); i++)
         {
             if (tex.FaceTextures[i] != null)
             {
                 texcolor = tex.FaceTextures[i].RGBA;
                 texcolor.R = Util.Clip((float)color.X, 0.0f, 1.0f);
                 texcolor.G = Util.Clip((float)color.Y, 0.0f, 1.0f);
                 texcolor.B = Util.Clip((float)color.Z, 0.0f, 1.0f);
                 tex.FaceTextures[i].RGBA = texcolor;
             }
             texcolor = tex.DefaultTexture.RGBA;
             texcolor.R = Util.Clip((float)color.X, 0.0f, 1.0f);
             texcolor.G = Util.Clip((float)color.Y, 0.0f, 1.0f);
             texcolor.B = Util.Clip((float)color.Z, 0.0f, 1.0f);
             tex.DefaultTexture.RGBA = texcolor;
         }
         UpdateTextureEntry(tex.GetBytes());
         return;
     }
 }
Ejemplo n.º 9
0
        /// <summary>
        /// Convert raw uploaded data into the appropriate asset and item.
        /// </summary>
        /// <param name="assetID"></param>
        /// <param name="inventoryItem"></param>
        /// <param name="data"></param>
        public void UploadCompleteHandler(string assetName, string assetDescription, UUID assetID,
                                          UUID inventoryItem, UUID parentFolder, byte[] data, string inventoryType,
                                          string assetType)
        {
            m_log.DebugFormat(
                "[BUNCH OF CAPS]: Uploaded asset {0} for inventory item {1}, inv type {2}, asset type {3}",
                assetID, inventoryItem, inventoryType, assetType);

            sbyte assType = 0;
            sbyte inType = 0;

            if (inventoryType == "sound")
            {
                inType = (sbyte)InventoryType.Sound;
                assType = (sbyte)AssetType.Sound;
            }
            else if (inventoryType == "snapshot")
            {
                inType = (sbyte)InventoryType.Snapshot;
            }
            else if (inventoryType == "animation")
            {
                inType = (sbyte)InventoryType.Animation;
                assType = (sbyte)AssetType.Animation;
            }
            else if (inventoryType == "wearable")
            {
                inType = (sbyte)InventoryType.Wearable;
                switch (assetType)
                {
                    case "bodypart":
                        assType = (sbyte)AssetType.Bodypart;
                        break;
                    case "clothing":
                        assType = (sbyte)AssetType.Clothing;
                        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;

                InventoryFolderBase textureUploadFolder = null;

                List<InventoryFolderBase> foldersToUpdate = new List<InventoryFolderBase>();
                List<InventoryItemBase> itemsToUpdate = new List<InventoryItemBase>();
                IClientInventory clientInv = null;
                
                if (texture_list.Count > 0)
                {
                    ScenePresence avatar = null;
                    m_Scene.TryGetScenePresence(m_HostCapsObj.AgentID, out avatar);

                    if (avatar != null)
                    {
                        IClientCore core = (IClientCore)avatar.ControllingClient;

                        if (core.TryGet<IClientInventory>(out clientInv))
                        {
                            var systemTextureFolder = m_Scene.InventoryService.GetFolderForType(m_HostCapsObj.AgentID, AssetType.Texture);
                            textureUploadFolder = new InventoryFolderBase(UUID.Random(), assetName, m_HostCapsObj.AgentID, (short)AssetType.Unknown, systemTextureFolder.ID, 1);
                            if (m_Scene.InventoryService.AddFolder(textureUploadFolder))
                            {
                                foldersToUpdate.Add(textureUploadFolder);

                                m_log.DebugFormat(
                                    "[BUNCH OF CAPS]: Created new folder '{0}' ({1}) for textures uploaded with mesh object {2}", 
                                    textureUploadFolder.Name, textureUploadFolder.ID, assetName);
                            }
                            else
                            {
                                textureUploadFolder = null;
                            }
                        }
                    }
                }

                List<UUID> textures = new List<UUID>();
                for (int i = 0; i < texture_list.Count; i++)
                {
                    AssetBase textureAsset = new AssetBase(UUID.Random(), assetName, (sbyte)AssetType.Texture, "");
                    textureAsset.Data = texture_list[i].AsBinary();
                    m_assetService.Store(textureAsset);
                    textures.Add(textureAsset.FullID);

                    if (textureUploadFolder != null)
                    {
                        InventoryItemBase textureItem = new InventoryItemBase();
                        textureItem.Owner = m_HostCapsObj.AgentID;
                        textureItem.CreatorId = m_HostCapsObj.AgentID.ToString();
                        textureItem.CreatorData = String.Empty;
                        textureItem.ID = UUID.Random();
                        textureItem.AssetID = textureAsset.FullID;
                        textureItem.Description = assetDescription;
                        textureItem.Name = assetName + " - Texture " + (i + 1).ToString();
                        textureItem.AssetType = (int)AssetType.Texture;
                        textureItem.InvType = (int)InventoryType.Texture;
                        textureItem.Folder = textureUploadFolder.ID;
                        textureItem.CurrentPermissions
                            = (uint)(PermissionMask.Move | PermissionMask.Copy | PermissionMask.Modify | PermissionMask.Transfer | PermissionMask.Export);
                        textureItem.BasePermissions = (uint)PermissionMask.All | (uint)PermissionMask.Export;
                        textureItem.EveryOnePermissions = 0;
                        textureItem.NextPermissions = (uint)PermissionMask.All;
                        textureItem.CreationDate = Util.UnixTimeSinceEpoch();
                        m_Scene.InventoryService.AddItem(textureItem);
                        itemsToUpdate.Add(textureItem);

                        m_log.DebugFormat(
                            "[BUNCH OF CAPS]: Created new inventory item '{0}' ({1}) for texture uploaded with mesh object {2}", 
                            textureItem.Name, textureItem.ID, assetName);
                    }
                }

                if (clientInv != null && (foldersToUpdate.Count > 0 || itemsToUpdate.Count > 0))
                {
                    clientInv.SendBulkUpdateInventory(foldersToUpdate.ToArray(), itemsToUpdate.ToArray());
                }

                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;

                        if (textures.Count > textureNum)
                            f.TextureID = textures[textureNum];
                        else
                            f.TextureID = Primitive.TextureEntry.WHITE_TEXTURE;

                        textureEntry.FaceTextures[face] = f;
                    }

                    pbs.TextureEntry = textureEntry.GetBytes();

                    AssetBase meshAsset = new AssetBase(UUID.Random(), assetName, (sbyte)AssetType.Mesh, "");
                    meshAsset.Data = mesh_list[i].AsBinary();
                    m_assetService.Store(meshAsset);

                    pbs.SculptEntry = true;
                    pbs.SculptTexture = meshAsset.FullID;
                    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();

// no longer used - begin ------------------------
//                    int physicsShapeType = inner_instance_list["physics_shape_type"].AsInteger();
//                    int material = inner_instance_list["material"].AsInteger();
//                    int mesh = inner_instance_list["mesh"].AsInteger();

//                    OSDMap permissions = (OSDMap)inner_instance_list["permissions"];
//                    int base_mask = permissions["base_mask"].AsInteger();
//                    int everyone_mask = permissions["everyone_mask"].AsInteger();
//                    UUID creator_id = permissions["creator_id"].AsUUID();
//                    UUID group_id = permissions["group_id"].AsUUID();
//                    int group_mask = permissions["group_mask"].AsInteger();
//                    bool is_owner_group = permissions["is_owner_group"].AsBoolean();
//                    UUID last_owner_id = permissions["last_owner_id"].AsUUID();
//                    int next_owner_mask = permissions["next_owner_mask"].AsInteger();
//                    UUID owner_id = permissions["owner_id"].AsUUID();
//                    int owner_mask = permissions["owner_mask"].AsInteger();
// no longer used - end ------------------------

		      UUID owner_id = m_HostCapsObj.AgentID;

                    SceneObjectPart prim
                        = new SceneObjectPart(owner_id, pbs, position, Quaternion.Identity, Vector3.Zero);

                    prim.Scale = scale;
                    //prim.OffsetPosition = 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.BaseMask = (uint)base_mask;
//                    prim.EveryoneMask = (uint)everyone_mask;
//                    prim.GroupMask = (uint)group_mask;
//                    prim.NextOwnerMask = (uint)next_owner_mask;
//                    prim.OwnerMask = (uint)owner_mask;

                    if (grp == null)
                        grp = new SceneObjectGroup(prim);
                    else
                        grp.AddPart(prim);
                }

                Vector3 rootPos = positions[0];

                if (grp.Parts.Length > 1)
                {
                    // Fix first link number
                    grp.RootPart.LinkNum++;

                    Quaternion rootRotConj = Quaternion.Conjugate(rotations[0]);
                    Quaternion tmprot;
                    Vector3 offset;

                    // fix children rotations and positions
                    for (int i = 1; i < rotations.Count; i++)
                    {
                        tmprot = rotations[i];
                        tmprot = rootRotConj * tmprot;

                        grp.Parts[i].RotationOffset = tmprot;

                        offset = positions[i] - rootPos;

                        offset *= rootRotConj;
                        grp.Parts[i].OffsetPosition = offset;
                    }

                    grp.AbsolutePosition = rootPos;
                    grp.UpdateGroupRotationR(rotations[0]);
                }
                else
                {
                    grp.AbsolutePosition = rootPos;
                    grp.UpdateGroupRotationR(rotations[0]);
                }

                data = ASCIIEncoding.ASCII.GetBytes(SceneObjectSerializer.ToOriginalXmlFormat(grp));
            }

            AssetBase asset;
            asset = new AssetBase(assetID, assetName, assType, m_HostCapsObj.AgentID.ToString());
            asset.Data = data;
            if (AddNewAsset != null)
                AddNewAsset(asset);
            else if (m_assetService != null)
                m_assetService.Store(asset);

            InventoryItemBase item = new InventoryItemBase();
            item.Owner = m_HostCapsObj.AgentID;
            item.CreatorId = m_HostCapsObj.AgentID.ToString();
            item.CreatorData = String.Empty;
            item.ID = inventoryItem;
            item.AssetID = asset.FullID;
            item.Description = assetDescription;
            item.Name = assetName;
            item.AssetType = assType;
            item.InvType = inType;
            item.Folder = parentFolder;

            // If we set PermissionMask.All then when we rez the item the next permissions will replace the current
            // (owner) permissions.  This becomes a problem if next permissions are changed.
            item.CurrentPermissions
                = (uint)(PermissionMask.Move | PermissionMask.Copy | PermissionMask.Modify | PermissionMask.Transfer | PermissionMask.Export);

            item.BasePermissions = (uint)PermissionMask.All | (uint)PermissionMask.Export;
            item.EveryOnePermissions = 0;
            item.NextPermissions = (uint)PermissionMask.All;
            item.CreationDate = Util.UnixTimeSinceEpoch();

            if (AddNewInventoryItem != null)
            {
                AddNewInventoryItem(m_HostCapsObj.AgentID, item);
            }
        }
Ejemplo n.º 10
0
Archivo: Penny.cs Proyecto: zadark/par
 public Packet ApHand(Packet packet, IPEndPoint sim)
 {
     if (form.getChecked()==false)
         {
             return packet;
         }
         AgentSetAppearancePacket packet2 = (AgentSetAppearancePacket) packet;
         if ((packet2.ObjectData == null) || (packet2.ObjectData.TextureEntry == null))
         {
             return packet;
         }
         Primitive.TextureEntry entry = new Primitive.TextureEntry(packet2.ObjectData.TextureEntry, 0, packet2.ObjectData.TextureEntry.Length);
         if (((entry == null) || (entry.FaceTextures == null)) || (entry.FaceTextures.Length <= 0))
         {
             return packet;
         }
         Console.WriteLine("Penny is replacing textures...");
         UUID uuid =  new UUID("5aa5c70d-d787-571b-0495-4fc1bdef1500");
         for (int i = 0; i <= 7; i++)
         {
             if (entry.FaceTextures[i] != null)
             {
                 entry.FaceTextures[i].TextureID = uuid;
             }
         }
         for (int j = 12; j <= 0x12; j++)
         {
             if (entry.FaceTextures[j] != null)
             {
                 entry.FaceTextures[j].TextureID = uuid;
             }
         }
         if (packet2.ObjectData != null)
         {
             packet2.ObjectData.TextureEntry = entry.GetBytes();
         }
         Console.WriteLine("OK! Thanks Day!");
         return packet2;
 }
Ejemplo n.º 11
0
        /// <summary>
        /// Assign a single material value.  Based on the values passed we'll either set (or clear) the materials for a SOP.
        /// </summary>
        /// <param name="sop">The SOP being affected.</param>
        /// <param name="face">The face to assign, or -1 if the default texture is being set.</param>
        /// <param name="id">The ID assigned to this material.  Setting a Zero UUID clears it.</param>
        /// <param name="material">If not null, the material to set.  Otherwise we are clearing.</param>
        private void AssignSingleMaterial(SceneObjectPart sop, int face, OSDMap matData)
        {
            /// Get a copy of the texture entry so we can make changes.
            var te = new Primitive.TextureEntry(sop.Shape.TextureEntry, 0, sop.Shape.TextureEntry.Length);
            if (te == null)
            {
                m_log.Warn("[RenderMaterials]: null TextureEntry for localId: " + sop.LocalId.ToString());
                return;
            }

            lock (m_knownMaterials)
            {
                UUID id = UUID.Zero;

                // Record what we currently have
                var currentMaterialIDs = getMaterialIDsFromTextureEntry(te);

                // If there is a material being set see if we've seen it before.
                // If not we'll add it to the region cache
                if (matData != null)
                {
                    RenderMaterial material = RenderMaterial.FromOSD(matData);
                    id = sop.Shape.RenderMaterials.AddMaterial(material);

                    if (m_knownMaterials.ContainsKey(id))
                    {
                        material = m_knownMaterials[id].material;
                        var entry = m_knownMaterials[id];
                        if (entry.partIds.Contains(sop.LocalId) == false)
                            entry.partIds.Add(sop.LocalId);
                    }
                    else
                    {
                        m_knownMaterials[id] = new RenderMaterialEntry(material, sop.LocalId);
                    }

                    m_log.DebugFormat("[RenderMaterials]: SOP {0}, Face {1}, Adding RenderMaterial {2}", 
                        sop.LocalId, face, material.ToString());
                }

                // Set the Material ID in the sop texture entry. If there's a face defined
                // use that else use the Default entry.  ID can either be a material ID
                // we set from the lookup above or Zero when we are clearing a material.
                if (face < 0)
                {
                    te.DefaultTexture.MaterialID = id;
                }
                else
                {
                    var faceEntry = te.CreateFace((uint)face);
                    faceEntry.MaterialID = id;
                }

                // Get the updated list of Materials from the TextureEntry.  We will
                // Use that to rebuild the RenderMaterials for the part. We'll also get a list
                // of entries that have been removed based on what we fetched initially so we
                // can clean that up in our cache.
                var newMaterialIDs = getMaterialIDsFromTextureEntry(te);

                // If there was an update and the material id has changed, clean up the old value.  
                // Have to be careful here. It might still be in use in another slot.  So we build 
                // a list of keys and walk the texture entries subtracting keys in use.  Whatever
                // is left are candidates to clean up.
                foreach (var entry in newMaterialIDs)
                {
                    if (currentMaterialIDs.Contains(entry))
                    {
                        currentMaterialIDs.Remove(entry);
                    }

                    if (sop.Shape.RenderMaterials.ContainsMaterial(entry) == false)
                    {
                        m_log.WarnFormat("[RenderMaterials]: SOP {0}, Face {1}, RenderMaterials {2} should be present but isn't!",
                            sop.LocalId, face, entry.ToString());
                    }
                }

                // currentMaterialsIDs contains orphans if any.  Remove them from the sop.Shape and the cache (if needed)
                foreach (var entry in currentMaterialIDs)
                {
                    if (sop.Shape.RenderMaterials.ContainsMaterial(entry) == true)
                    {
                        m_log.DebugFormat("[RenderMaterials]: SOP {0}, Face {1}, Removing unused RenderMaterials {2} from shape.",
                            sop.LocalId, face, entry.ToString());
                        sop.Shape.RenderMaterials.RemoveMaterial(entry);
                    }
                    else
                    {
                        m_log.WarnFormat("[RenderMaterials]: SOP {0}, Face {1}, ORPHANED RenderMaterials {2} should be present but isn't!",
                            sop.LocalId, face, entry.ToString());
                    }

                    if (m_knownMaterials.ContainsKey(entry))
                    {
                        m_knownMaterials[entry].partIds.Remove(sop.LocalId);
                        if (m_knownMaterials[entry].partIds.Count <= 0)
                        { 
                            m_log.DebugFormat("[RenderMaterials]: Removing unused RenderMaterials {0} from region cache.", entry.ToString());
                            m_knownMaterials.Remove(entry);
                        }
                    }
                }
            }

            // Update the texture entry which will force an update to connected clients
            sop.UpdateTextureEntry(te.GetBytes());
        }
Ejemplo n.º 12
0
        private static PrimitiveBaseShape GetShape(int vShape)
        {
            PrimitiveBaseShape shape = new PrimitiveBaseShape();

            shape.PCode = 9;
            shape.PathBegin = 0;
            shape.PathEnd = 0;
            shape.PathScaleX = 100;
            shape.PathScaleY = 100;
            shape.PathShearX = 0;
            shape.PathShearY = 0;
            shape.PathSkew = 0;
            shape.ProfileBegin = 0;
            shape.ProfileEnd = 0;
            shape.Scale = new Vector3(0.5f, 0.5f, 0.5f);
            //shape.Scale.X = shape.Scale.Y = shape.Scale.Z = 0.5f;
            shape.PathCurve = 16;
            shape.ProfileCurve = 1;
            shape.ProfileHollow = 0;
            shape.PathRadiusOffset = 0;
            shape.PathRevolutions = 0;
            shape.PathTaperX = 0;
            shape.PathTaperY = 0;
            shape.PathTwist = 0;
            shape.PathTwistBegin = 0;
            Primitive.TextureEntry ntex = new Primitive.TextureEntry(new UUID("00000000-0000-1111-9999-000000000005"));
            shape.TextureEntry = ntex.GetBytes();//ntex.ToBytes();
            return shape;
        }
Ejemplo n.º 13
0
Archivo: coin.cs Proyecto: zadark/par
        public AgentSetAppearancePacket replacer_tails(AgentSetAppearancePacket packet)
        {
            AgentSetAppearancePacket p = cloneASA(packet);
            if (p.ObjectData != null)
            {
                if (p.ObjectData.TextureEntry != null)
                {
                    Primitive.TextureEntry te = new Primitive.TextureEntry(p.ObjectData.TextureEntry, 0, p.ObjectData.TextureEntry.Length);
                    if (te != null)
                    {
                        if (te.FaceTextures != null)
                        {
                            if (te.FaceTextures.Length > 0)
                            {
                                //Console.WriteLine("Coin is replacing textures...");
                                UUID replace = new UUID("8183e823-c443-2142-6eb6-2ab763d4f81c");
                                for (int i = 0; i <= 7; i++)
                                {
                                    if (te.FaceTextures[i] != null)
                                        te.FaceTextures[i].TextureID = replace;
                                }
                                for (int i = 12; i <= 18; i++)
                                {
                                    if (te.FaceTextures[i] != null)
                                        te.FaceTextures[i].TextureID = replace;
                                }

                                if (p.ObjectData != null)
                                    p.ObjectData.TextureEntry = te.GetBytes();
                                //Console.WriteLine("OK!");
                            }
                        }
                    }
                }
            }
            return p;
        }
Ejemplo n.º 14
0
        public AgentSetAppearancePacket MakeAppearancePacket()
        {
            AgentSetAppearancePacket set = new AgentSetAppearancePacket();
            set.AgentData.AgentID = Client.Self.AgentID;
            set.AgentData.SessionID = Client.Self.SessionID;
            set.AgentData.SerialNum = (uint)Interlocked.Increment(ref SetAppearanceSerialNum);

            // Visual params used in the agent height calculation
            float agentSizeVPHeight = 0.0f;
            float agentSizeVPHeelHeight = 0.0f;
            float agentSizeVPPlatformHeight = 0.0f;
            float agentSizeVPHeadSize = 0.5f;
            float agentSizeVPLegLength = 0.0f;
            float agentSizeVPNeckLength = 0.0f;
            float agentSizeVPHipLength = 0.0f;

            lock (Wearables)
            {
                #region VisualParam

                int vpIndex = 0;
                int nrParams;
                bool wearingPhysics = false;

                foreach (WearableData wearable in Wearables.Values)
                {
                    if (wearable.WearableType == WearableType.Physics)
                    {
                        wearingPhysics = true;
                        break;
                    }
                }

                if (wearingPhysics)
                {
                    nrParams = 251;
                }
                else
                {
                    nrParams = 218;
                }

                set.VisualParam = new AgentSetAppearancePacket.VisualParamBlock[nrParams];

                foreach (KeyValuePair<int, VisualParam> kvp in VisualParams.Params)
                {
                    VisualParam vp = kvp.Value;
                    float paramValue = 0f;
                    bool found = false;

                    // Try and find this value in our collection of downloaded wearables
                    foreach (WearableData data in Wearables.Values)
                    {
                        if (data.Asset != null && data.Asset.Params.TryGetValue(vp.ParamID, out paramValue))
                        {
                            found = true;
                            break;
                        }
                    }

                    // Use a default value if we don't have one set for it
                    if (!found)
                        paramValue = vp.DefaultValue;

                    // Only Group-0 parameters are sent in AgentSetAppearance packets
                    if (kvp.Value.Group == 0)
                    {
                        set.VisualParam[vpIndex] = new AgentSetAppearancePacket.VisualParamBlock();
                        set.VisualParam[vpIndex].ParamValue = Utils.FloatToByte(paramValue, vp.MinValue, vp.MaxValue);
                        ++vpIndex;
                    }

                    // Check if this is one of the visual params used in the agent height calculation
                    switch (vp.ParamID)
                    {
                        case 33:
                            agentSizeVPHeight = paramValue;
                            break;
                        case 198:
                            agentSizeVPHeelHeight = paramValue;
                            break;
                        case 503:
                            agentSizeVPPlatformHeight = paramValue;
                            break;
                        case 682:
                            agentSizeVPHeadSize = paramValue;
                            break;
                        case 692:
                            agentSizeVPLegLength = paramValue;
                            break;
                        case 756:
                            agentSizeVPNeckLength = paramValue;
                            break;
                        case 842:
                            agentSizeVPHipLength = paramValue;
                            break;
                    }

                    if (vpIndex == nrParams) break;
                }

                MyVisualParameters = new byte[set.VisualParam.Length];
                for (int i = 0; i < set.VisualParam.Length; i++)
                {
                    MyVisualParameters[i] = set.VisualParam[i].ParamValue;
                }

                #endregion VisualParam

                #region TextureEntry

                Primitive.TextureEntry te = new Primitive.TextureEntry(DEFAULT_AVATAR_TEXTURE);

                for (uint i = 0; i < Textures.Length; i++)
                {
                    if ((i == 0 || i == 5 || i == 6) && Client.Settings.CLIENT_IDENTIFICATION_TAG != UUID.Zero)
                    {
                        Primitive.TextureEntryFace face = te.CreateFace(i);
                        face.TextureID = Client.Settings.CLIENT_IDENTIFICATION_TAG;
                        Logger.DebugLog("Sending client identification tag: " + Client.Settings.CLIENT_IDENTIFICATION_TAG, Client);
                    }
                    else if (Textures[i].TextureID != UUID.Zero)
                    {
                        Primitive.TextureEntryFace face = te.CreateFace(i);
                        face.TextureID = Textures[i].TextureID;
                        Logger.DebugLog("Sending texture entry for " + (AvatarTextureIndex)i + " to " + Textures[i].TextureID, Client);
                    }
                }

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

                #endregion TextureEntry

                #region WearableData

                set.WearableData = new AgentSetAppearancePacket.WearableDataBlock[BAKED_TEXTURE_COUNT];

                // Build hashes for each of the bake layers from the individual components
                for (int bakedIndex = 0; bakedIndex < BAKED_TEXTURE_COUNT; bakedIndex++)
                {
                    UUID hash = UUID.Zero;

                    for (int wearableIndex = 0; wearableIndex < WEARABLES_PER_LAYER; wearableIndex++)
                    {
                        WearableType type = WEARABLE_BAKE_MAP[bakedIndex][wearableIndex];

                        WearableData wearable;
                        if (type != WearableType.Invalid && Wearables.TryGetValue(type, out wearable))
                            hash ^= wearable.AssetID;
                    }

                    if (hash != UUID.Zero)
                    {
                        // Hash with our magic value for this baked layer
                        hash ^= BAKED_TEXTURE_HASH[bakedIndex];
                    }

                    // Tell the server what cached texture assetID to use for each bake layer
                    set.WearableData[bakedIndex] = new AgentSetAppearancePacket.WearableDataBlock();
                    set.WearableData[bakedIndex].TextureIndex = BakeIndexToTextureIndex[bakedIndex];
                    set.WearableData[bakedIndex].CacheID = hash;
                    Logger.DebugLog("Sending TextureIndex " + (BakeType)bakedIndex + " with CacheID " + hash, Client);
                }

                #endregion WearableData

                #region Agent Size

                // Takes into account the Shoe Heel/Platform offsets but not the HeadSize offset. Seems to work.
                double agentSizeBase = 1.706;

                // The calculation for the HeadSize scalar may be incorrect, but it seems to work
                double agentHeight = agentSizeBase + (agentSizeVPLegLength * .1918) + (agentSizeVPHipLength * .0375) +
                    (agentSizeVPHeight * .12022) + (agentSizeVPHeadSize * .01117) + (agentSizeVPNeckLength * .038) +
                    (agentSizeVPHeelHeight * .08) + (agentSizeVPPlatformHeight * .07);

                set.AgentData.Size = new Vector3(0.45f, 0.6f, (float)agentHeight);

                #endregion Agent Size

                if (Client.Settings.AVATAR_TRACKING)
                {
                    Avatar me;
                    if (Client.Network.CurrentSim.ObjectsAvatars.TryGetValue(Client.Self.LocalID, out me))
                    {
                        me.Textures = MyTextures;
                        me.VisualParameters = MyVisualParameters;
                    }
                }
            }
            return set;
        }
Ejemplo n.º 15
0
        private void SendAgentSetAppearance()
        {
            AgentSetAppearancePacket set = new AgentSetAppearancePacket();
            set.AgentData.AgentID = Network.AgentID;
            set.AgentData.SessionID = Network.SessionID;
            set.AgentData.SerialNum = SetAppearanceSerialNum++;
            set.VisualParam = new AgentSetAppearancePacket.VisualParamBlock[218];

            float AgentSizeVPHeight = 0.0f;
            float AgentSizeVPHeelHeight = 0.0f;
            float AgentSizeVPPlatformHeight = 0.0f;
            float AgentSizeVPHeadSize = 0.5f;
            float AgentSizeVPLegLength = 0.0f;
            float AgentSizeVPNeckLength = 0.0f;
            float AgentSizeVPHipLength = 0.0f;

            lock (Wearables.Dictionary)
            {
                // Only for debugging output
                int count = 0, vpIndex = 0;

                // Build the visual param array
                foreach (KeyValuePair<int, VisualParam> kvp in VisualParams.Params)
                {
                    VisualParam vp = kvp.Value;

                    // Only Group-0 parameters are sent in AgentSetAppearance packets
                    if (vp.Group == 0)
                    {
                        set.VisualParam[vpIndex] = new AgentSetAppearancePacket.VisualParamBlock();

                        // Try and find this value in our collection of downloaded wearables
                        foreach (WearableData data in Wearables.Dictionary.Values)
                        {
                            if (data.Asset != null && data.Asset.Params.ContainsKey(vp.ParamID))
                            {
                                set.VisualParam[vpIndex].ParamValue = Utils.FloatToByte(data.Asset.Params[vp.ParamID], vp.MinValue, vp.MaxValue);
                                count++;

                                switch (vp.ParamID)
                                {
                                    case 33:
                                        AgentSizeVPHeight = data.Asset.Params[vp.ParamID];
                                        break;
                                    case 198:
                                        AgentSizeVPHeelHeight = data.Asset.Params[vp.ParamID];
                                        break;
                                    case 503:
                                        AgentSizeVPPlatformHeight = data.Asset.Params[vp.ParamID];
                                        break;
                                    case 682:
                                        AgentSizeVPHeadSize = data.Asset.Params[vp.ParamID];
                                        break;
                                    case 692:
                                        AgentSizeVPLegLength = data.Asset.Params[vp.ParamID];
                                        break;
                                    case 756:
                                        AgentSizeVPNeckLength = data.Asset.Params[vp.ParamID];
                                        break;
                                    case 842:
                                        AgentSizeVPHipLength = data.Asset.Params[vp.ParamID];
                                        break;
                                }
                                break;
                            }
                        }

                        ++vpIndex;
                    }
                }

                // Build the texture entry for our agent
                Primitive.TextureEntry te = new Primitive.TextureEntry(DEFAULT_AVATAR_TEXTURE);

                // Put our AgentTextures array in to TextureEntry
                lock (AgentTextures)
                {
                    for (uint i = 0; i < AgentTextures.Length; i++)
                    {
                        if (AgentTextures[i] != UUID.Zero)
                        {
                            Primitive.TextureEntryFace face = te.CreateFace(i);
                            face.TextureID = AgentTextures[i];
                        }
                    }
                }

                foreach (WearableData data in Wearables.Dictionary.Values)
                {
                    if (data.Asset != null)
                    {
                        foreach (KeyValuePair<TextureIndex, UUID> texture in data.Asset.Textures)
                        {
                            Primitive.TextureEntryFace face = te.CreateFace((uint)texture.Key);
                            face.TextureID = texture.Value;

                            Log.DebugLog("Setting agent texture " + ((TextureIndex)texture.Key).ToString() + " to " +
                                texture.Value.ToString());
                        }
                    }
                }

                // Set the packet TextureEntry
                set.ObjectData.TextureEntry = te.GetBytes();
            }

            // FIXME: Our hackish algorithm is making squished avatars. See
            // http://www.OpenMetaverse.org/wiki/Agent_Size for discussion of the correct algorithm
            //float height = Utils.ByteToFloat(set.VisualParam[33].ParamValue, VisualParams.Params[33].MinValue,
            //    VisualParams.Params[33].MaxValue);

            // Takes into account the Shoe Heel/Platform offsets but not the Head Size Offset.  But seems to work.
            double AgentSizeBase = 1.706;

            // The calculation for the Head Size scalar may be incorrect.  But seems to work.
            double AgentHeight = AgentSizeBase + (AgentSizeVPLegLength * .1918) + (AgentSizeVPHipLength * .0375) +
                (AgentSizeVPHeight * .12022) + (AgentSizeVPHeadSize * .01117) + (AgentSizeVPNeckLength * .038) +
                (AgentSizeVPHeelHeight * .08) + (AgentSizeVPPlatformHeight * .07);

            set.AgentData.Size = new Vector3(0.45f, 0.6f, (float)AgentHeight);

            // TODO: Account for not having all the textures baked yet
            set.WearableData = new AgentSetAppearancePacket.WearableDataBlock[BAKED_TEXTURE_COUNT];

            // Build hashes for each of the bake layers from the individual components
            for (int bakedIndex = 0; bakedIndex < BAKED_TEXTURE_COUNT; bakedIndex++)
            {
                UUID hash = new UUID();

                for (int wearableIndex = 0; wearableIndex < WEARABLES_PER_LAYER; wearableIndex++)
                {
                    WearableType type = WEARABLE_BAKE_MAP[bakedIndex][wearableIndex];
                    UUID assetID = GetWearableAsset(type);

                    // Build a hash of all the texture asset IDs in this baking layer
                    if (assetID != UUID.Zero) hash ^= assetID;
                }

                if (hash != UUID.Zero)
                {
                    // Hash with our secret value for this baked layer
                    hash ^= BAKED_TEXTURE_HASH[bakedIndex];
                }

                // Tell the server what cached texture assetID to use for each bake layer
                set.WearableData[bakedIndex] = new AgentSetAppearancePacket.WearableDataBlock();
                set.WearableData[bakedIndex].TextureIndex = (byte)bakedIndex;
                set.WearableData[bakedIndex].CacheID = hash;
                Log.DebugLog("Setting baked agent texture hash " + ((BakeType)bakedIndex).ToString() + " to " + hash);

            }

            // Finally, send the packet
            Network.SendPacket(set);
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Set the color & alpha of prim faces
        /// </summary>
        /// <param name="face"></param>
        /// <param name="color"></param>
        /// <param name="alpha"></param>
        public void SetFaceColorAlpha(int face, Vector3 color, double ?alpha)
        {
            Vector3 clippedColor = Util.Clip(color, 0.0f, 1.0f);
            float clippedAlpha = alpha.HasValue ?
                Util.Clip((float)alpha.Value, 0.0f, 1.0f) : 0;

            // The only way to get a deep copy/ If we don't do this, we can
            // never detect color changes further down.
            Byte[] buf = Shape.Textures.GetBytes();
            Primitive.TextureEntry tex = new Primitive.TextureEntry(buf, 0, buf.Length);
            Color4 texcolor;
            if (face >= 0 && face < GetNumberOfSides())
            {
                texcolor = tex.CreateFace((uint)face).RGBA;
                texcolor.R = clippedColor.X;
                texcolor.G = clippedColor.Y;
                texcolor.B = clippedColor.Z;
                if (alpha.HasValue)
                {
                    texcolor.A = clippedAlpha;
                }
                tex.FaceTextures[face].RGBA = texcolor;
                UpdateTextureEntry(tex.GetBytes());
                return;
            }
            else if (face == ALL_SIDES)
            {
                for (uint i = 0; i < GetNumberOfSides(); i++)
                {
                    if (tex.FaceTextures[i] != null)
                    {
                        texcolor = tex.FaceTextures[i].RGBA;
                        texcolor.R = clippedColor.X;
                        texcolor.G = clippedColor.Y;
                        texcolor.B = clippedColor.Z;
                        if (alpha.HasValue)
                        {
                            texcolor.A = clippedAlpha;
                        }
                        tex.FaceTextures[i].RGBA = texcolor;
                    }
                    texcolor = tex.DefaultTexture.RGBA;
                    texcolor.R = clippedColor.X;
                    texcolor.G = clippedColor.Y;
                    texcolor.B = clippedColor.Z;
                    if (alpha.HasValue)
                    {
                        texcolor.A = clippedAlpha;
                    }
                    tex.DefaultTexture.RGBA = texcolor;
                }
                UpdateTextureEntry(tex.GetBytes());
                return;
            }
        }
        public byte[] RenderMaterialsPostCap(string path, Stream request,
            OSHttpRequest httpRequest, OSHttpResponse httpResponse)
        {
            MainConsole.Instance.Debug("[MaterialsDemoModule]: POST cap handler");

            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);
                                    AssetBase materialAsset = null;
                                    if (m_knownMaterials.ContainsKey(id))
                                    {
                                        MainConsole.Instance.Info("[MaterialsDemoModule]: request for known material ID: " + id.ToString());
                                        OSDMap matMap = new OSDMap();
                                        matMap["ID"] = elem.AsBinary();

                                        matMap["Material"] = m_knownMaterials[id];
                                        respArr.Add(matMap);
                                    }
                                    else if ((materialAsset = m_scene.AssetService.Get(id.ToString())) != null)
                                    {
                                        MainConsole.Instance.Info("[MaterialsDemoModule]: request for stored material ID: " + id.ToString());
                                        OSDMap matMap = new OSDMap();
                                        matMap["ID"] = elem.AsBinary();

                                        matMap["Material"] = (OSDMap)OSDParser.DeserializeJson(
                                            Encoding.UTF8.GetString(materialAsset.Data));
                                        respArr.Add(matMap);
                                    }
                                    else
                                        MainConsole.Instance.Info("[MaterialsDemoModule]: request for UNKNOWN material ID: " + id.ToString());
                                }
                                catch (Exception)
                                {
                                    // report something here?
                                    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)
                                        {
                                            MainConsole.Instance.Debug("[MaterialsDemoModule]: processing matsMap: " + OSDParser.SerializeJsonString(matsMap));

                                            uint matLocalID = 0;
                                            try { matLocalID = matsMap["ID"].AsUInteger(); }
                                            catch (Exception e) { MainConsole.Instance.Warn("[MaterialsDemoModule]: cannot decode \"ID\" from matsMap: " + e.Message); }
                                            MainConsole.Instance.Debug("[MaterialsDemoModule]: matLocalId: " + matLocalID.ToString());

                                            OSDMap mat = null;
                                            try { mat = matsMap["Material"] as OSDMap; }
                                            catch (Exception e) { MainConsole.Instance.Warn("[MaterialsDemoModule]: cannot decode \"Material\" from matsMap: " + e.Message); }
                                            MainConsole.Instance.Debug("[MaterialsDemoModule]: mat: " + OSDParser.SerializeJsonString(mat));

                                            UUID id = HashOsd(mat);
                                            m_knownMaterials[id] = mat;

                                            var sop = m_scene.GetSceneObjectPart(matLocalID);
                                            if (sop == null)
                                                MainConsole.Instance.Debug("[MaterialsDemoModule]: null SOP for localId: " + matLocalID.ToString());
                                            else
                                            {
                                                var te = new Primitive.TextureEntry(sop.Shape.TextureEntry, 0, sop.Shape.TextureEntry.Length);

                                                if (te == null)
                                                {
                                                    MainConsole.Instance.Debug("[MaterialsDemoModule]: null TextureEntry for localId: " + matLocalID.ToString());
                                                }
                                                else
                                                {
                                                    int face = -1;

                                                    if (matsMap.ContainsKey("Face"))
                                                    {
                                                        face = matsMap["Face"].AsInteger();
                                                        if (te.FaceTextures == null) // && face == 0)
                                                        {
                                                            if (te.DefaultTexture == null)
                                                                MainConsole.Instance.Debug("[MaterialsDemoModule]: te.DefaultTexture is null");
                                                            else
                                                            {
                                                                    te.DefaultTexture.MaterialID = id;
                                                            }
                                                        }
                                                        else
                                                        {
                                                            if (te.FaceTextures.Length >= face - 1)
                                                            {
                                                                if (te.FaceTextures[face] == null)
                                                                    te.DefaultTexture.MaterialID = id;
                                                                else
                                                                    te.FaceTextures[face].MaterialID = id;
                                                            }
                                                        }
                                                    }
                                                    else
                                                    {
                                                        if (te.DefaultTexture != null)
                                                            te.DefaultTexture.MaterialID = id;
                                                    }

                                                    MainConsole.Instance.Debug("[MaterialsDemoModule]: setting material ID for face " + face.ToString() + " to " + id.ToString());

                                                    //we cant use sop.UpdateTextureEntry(te); because it filters so do it manually

                                                    if (sop.ParentEntity != null)
                                                    {
                                                        sop.Shape.TextureEntry = te.GetBytes();
                                                        sop.TriggerScriptChangedEvent(Changed.TEXTURE);
                                                        sop.ParentEntity.HasGroupChanged = true;

                                                        sop.ScheduleUpdate(PrimUpdateFlags.FullUpdate);

                                                        AssetBase asset = new AssetBase(id, "RenderMaterial",
                                                            AssetType.Texture, sop.OwnerID)
                                                            {
                                                                Data = Encoding.UTF8.GetBytes(
                                                                    OSDParser.SerializeJsonString(mat))
                                                            };
                                                        m_scene.AssetService.Store(asset);

                                                        StoreMaterialsForPart(sop);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    catch (Exception e)
                                    {
                                        MainConsole.Instance.Warn("[MaterialsDemoModule]: exception processing received material: " + e.ToString());
                                    }
                                }
                            }
                        }
                    }

                }
                catch (Exception e)
                {
                    MainConsole.Instance.Warn("[MaterialsDemoModule]: exception decoding zipped CAP payload: " + e.ToString());
                }
                MainConsole.Instance.Debug("[MaterialsDemoModule]: knownMaterials.Count: " + m_knownMaterials.Count.ToString());
            }

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

            //MainConsole.Instance.Debug("[MaterialsDemoModule]: cap request: " + request);
            MainConsole.Instance.Debug("[MaterialsDemoModule]: cap request (zipped portion): " + ZippedOsdBytesToString(req["Zipped"].AsBinary()));
            MainConsole.Instance.Debug("[MaterialsDemoModule]: cap response: " + response);
            return OSDParser.SerializeLLSDBinary(resp);
        }
Ejemplo n.º 18
0
        /// <summary>
        ///     Parses ad request
        /// </summary>
        /// <param name="request"></param>
        /// <param name="response"></param>
        /// <param name="AgentId"></param>
        /// <returns></returns>
        public byte[] ProcessAdd(Stream request, OSHttpResponse response, UUID AgentId)
        {
            IScenePresence avatar;

            if (!m_scene.TryGetScenePresence(AgentId, out avatar))
                return MainServer.BlankResponse;

            OSDMap r = (OSDMap) OSDParser.Deserialize(HttpServerHandlerHelpers.ReadFully(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)
                                           {
                                               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.SetRotationOffset(true, obj.Rotation, true);

                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.BlankResponse;
                }
                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);
        }
        private Tuple<RenderMaterials, byte[]>  ExtractRenderMaterials(dynamic osPart)
        {
            var te = new Primitive.TextureEntry(osPart.Shape.TextureEntry, 0, osPart.Shape.TextureEntry.Length);
            var materialTextureIds = new List<Guid>();
            var mats = new RenderMaterials();

            if (te.DefaultTexture != null)
            {
                te.DefaultTexture.MaterialID = ExtractMaterial(te.DefaultTexture.MaterialID.Guid, mats);
            }

            foreach (Primitive.TextureEntryFace face in te.FaceTextures)
            {
                if (face != null)
                {
                    face.MaterialID = ExtractMaterial(face.MaterialID.Guid, mats);
                }
            }
            
            return new Tuple<RenderMaterials, byte[]>(mats, te.GetBytes());
        }