public JSONObject parse(WXMaterial wxbb_material, DependenciesAdder AddDependencies) { dependenciesAdder = AddDependencies; m_material = wxbb_material.GetMaterial(); m_mainJson = new JSONObject(JSONObject.Type.OBJECT); m_textures = new JSONObject(JSONObject.Type.OBJECT); m_shaderParams = new JSONObject(JSONObject.Type.OBJECT); m_renderStates = new JSONObject(JSONObject.Type.OBJECT); m_shaderDefinations = new JSONObject(JSONObject.Type.OBJECT); m_mainJson.AddField("effect", "@system/blinnPhong3d"); m_mainJson.AddField("textures", m_textures); m_mainJson.AddField("shaderParams", m_shaderParams); m_mainJson.AddField("renderStates", m_renderStates); m_mainJson.AddField("renderQueue", m_material.renderQueue); m_mainJson.AddField("shaderDefinations", m_shaderDefinations); // m_material = wxbb_material.material; onParse(wxbb_material); return(m_mainJson); }
protected override JSONObject ToJSON(WXHierarchyContext context) { JSONObject json = new JSONObject(JSONObject.Type.OBJECT); JSONObject data = new JSONObject(JSONObject.Type.OBJECT); json.AddField("type", getTypeName()); json.AddField("data", data); data.AddField("active", true); // if (this.collider != null) { data.AddField("convex", this.convex); data.AddField("isTrigger", this.isTrigger); #if UNITY_2017_1_OR_NEWER data.AddField("cookingOptions", (int)this.cookingOptions); #endif if (material != null) { WXPhysicsMaterial materialConverter = new WXPhysicsMaterial(material); string materialPath = materialConverter.Export(context.preset); if (materialPath != null && materialPath != "") { data.AddField("material", materialPath); context.AddResource(materialPath); } } Mesh mesh = this.sharedMesh; if (mesh != null) { WXMesh meshConverter = new WXMesh(mesh); string meshPath = meshConverter.Export(context.preset); data.AddField("mesh", meshPath); context.AddResource(meshPath); } } return(json); }
private void GetLightConfig(JSONObject propsObj, WXHierarchyContext context) { if (RenderSettings.ambientMode == AmbientMode.Skybox) { propsObj.AddField("ambientMode", 0); } else if (RenderSettings.ambientMode == AmbientMode.Trilight) { propsObj.AddField("ambientMode", 1); } else // if (RenderSettings.ambientMode == AmbientMode.Flat) { propsObj.AddField("ambientMode", 2); } Color ambientLight = RenderSettings.ambientLight; JSONObject ambientLightObj = new JSONObject(JSONObject.Type.ARRAY); ambientLightObj.Add(ambientLight.r); ambientLightObj.Add(ambientLight.g); ambientLightObj.Add(ambientLight.b); propsObj.AddField("ambientColor", ambientLightObj); propsObj.AddField("ambientIntensity", RenderSettings.ambientIntensity); JSONObject ambientSkyColorObj = new JSONObject(JSONObject.Type.ARRAY); ambientSkyColorObj.Add(RenderSettings.ambientSkyColor.r); ambientSkyColorObj.Add(RenderSettings.ambientSkyColor.g); ambientSkyColorObj.Add(RenderSettings.ambientSkyColor.b); ambientSkyColorObj.Add(RenderSettings.ambientSkyColor.a); propsObj.AddField("ambientSkyColor", ambientSkyColorObj); JSONObject ambientEquatorColorObj = new JSONObject(JSONObject.Type.ARRAY); ambientEquatorColorObj.Add(RenderSettings.ambientEquatorColor.r); ambientEquatorColorObj.Add(RenderSettings.ambientEquatorColor.g); ambientEquatorColorObj.Add(RenderSettings.ambientEquatorColor.b); ambientEquatorColorObj.Add(RenderSettings.ambientEquatorColor.a); propsObj.AddField("ambientEquatorColor", ambientEquatorColorObj); JSONObject ambientGroundColorObj = new JSONObject(JSONObject.Type.ARRAY); ambientGroundColorObj.Add(RenderSettings.ambientGroundColor.r); ambientGroundColorObj.Add(RenderSettings.ambientGroundColor.g); ambientGroundColorObj.Add(RenderSettings.ambientGroundColor.b); ambientGroundColorObj.Add(RenderSettings.ambientGroundColor.a); propsObj.AddField("ambientGroundColor", ambientGroundColorObj); object Rs = RenderSettings.defaultReflectionMode; if (RenderSettings.defaultReflectionMode == DefaultReflectionMode.Custom) { //saveCubeMapFile(RenderSettings.customReflection, propsObj, false, null); propsObj.AddField("reflectionIntensity", RenderSettings.reflectionIntensity); } else { propsObj.AddField("reflectionResolution", RenderSettings.defaultReflectionResolution); } // saveLightMapFile(propsObj); propsObj.AddField("fogMode", 0); if (RenderSettings.fog) { JSONObject jSONObject5 = new JSONObject(JSONObject.Type.ARRAY); Color fogColor = RenderSettings.fogColor; jSONObject5.Add(fogColor.r); jSONObject5.Add(fogColor.g); jSONObject5.Add(fogColor.b); propsObj.AddField("fogColor", jSONObject5); propsObj.AddField("fogMode", (int)RenderSettings.fogMode); } if (RenderSettings.fogMode == FogMode.Linear) { propsObj.AddField("fogStart", RenderSettings.fogStartDistance); propsObj.AddField("fogRange", RenderSettings.fogEndDistance - RenderSettings.fogStartDistance); } else { propsObj.AddField("fogDensity", RenderSettings.fogDensity); } if (RenderSettings.skybox != null) { WXMaterial materialConverter = new WXMaterial(RenderSettings.skybox, null); propsObj.AddField("skybox", AddDependencies(materialConverter)); } else { propsObj.AddField("skybox", new JSONObject(JSONObject.Type.NULL)); } // lightMapMode JSONObject subtractiveShadowColorObj = new JSONObject(JSONObject.Type.ARRAY); #if UNITY_5_6_OR_NEWER Color subtractiveShadowColor = RenderSettings.subtractiveShadowColor; #else // before 5.5 use default Color Color subtractiveShadowColor = new Color(0.42f, 0.48f, 0.63f, 1f); #endif subtractiveShadowColorObj.Add(subtractiveShadowColor.r); subtractiveShadowColorObj.Add(subtractiveShadowColor.g); subtractiveShadowColorObj.Add(subtractiveShadowColor.b); subtractiveShadowColorObj.Add(subtractiveShadowColor.a); propsObj.AddField("subtractiveShadowColor", subtractiveShadowColorObj); bool shadowMaskFlag = false; JSONObject lightMapDatasObj = new JSONObject(JSONObject.Type.ARRAY); LightmapData[] lightmaps = LightmapSettings.lightmaps; if (lightmaps != null && lightmaps.Length != 0) { for (int i = 0; i < lightmaps.Length; i++) { LightmapData lightmap = lightmaps[i]; JSONObject lightMapDescObj = new JSONObject(JSONObject.Type.OBJECT); #if UNITY_5_6_OR_NEWER if ( lightmap.lightmapColor == null || "" == AssetDatabase.GetAssetPath(lightmap.lightmapColor.GetInstanceID()) ) { continue; } if (lightmap.shadowMask) { shadowMaskFlag = true; WXLightMap textureConverter = new WXLightMap(lightmap.shadowMask); lightMapDescObj.AddField("shadowMask", AddDependencies(textureConverter)); WXLightMap textureConverter2 = new WXLightMap(lightmap.lightmapColor); lightMapDescObj.AddField("color", AddDependencies(textureConverter2)); } else { WXLightMap textureConverter = new WXLightMap(lightmap.lightmapColor); lightMapDescObj.AddField("color", AddDependencies(textureConverter)); } #else if ( lightmap.lightmapLight == null || "" == AssetDatabase.GetAssetPath(lightmap.lightmapLight.GetInstanceID()) ) { continue; } WXLightMap textureConverter = new WXLightMap(lightmap.lightmapLight); lightMapDescObj.AddField("color", AddDependencies(textureConverter)); #endif lightMapDatasObj.Add(lightMapDescObj); } } propsObj.AddField("lightMapDatas", lightMapDatasObj); // 0:subtractive 1:shadowMask propsObj.AddField("lightMapType", shadowMaskFlag ? (int)LightMapType.ShadowMask : (int)LightMapType.Subtractive); }
protected override JSONObject ToJSON(WXHierarchyContext context) { JSONObject json = new JSONObject(JSONObject.Type.OBJECT); JSONObject data = new JSONObject(JSONObject.Type.OBJECT); json.AddField("type", "SkinnedMeshRenderer"); json.AddField("data", data); // Mesh mesh = (renderer.gameObject.GetComponent (typeof(MeshFilter)) as MeshFilter).sharedMesh; // SkinnedMeshRenderer component = renderer.gameObject.GetComponent<SkinnedMeshRenderer>(); data.AddField("active", renderer.enabled); Mesh mesh = renderer.sharedMesh; if (mesh != null) { WXSkinnedMesh meshConverter = new WXSkinnedMesh(mesh, renderer); string meshPath = meshConverter.Export(context.preset); data.AddField("mesh", meshPath); context.AddResource(meshPath); } else { Debug.LogWarning("mesh is null"); } JSONObject materialArray = new JSONObject(JSONObject.Type.ARRAY); Material[] materials = renderer.sharedMaterials; foreach (Material material in materials) { WXMaterial materialConverter = new WXMaterial(material, renderer); string materialPath = materialConverter.Export(context.preset); materialArray.Add(materialPath); context.AddResource(materialPath); } data.AddField("materials", materialArray); data.AddField("props", GenProps()); int lightmapIndex = renderer.lightmapIndex; JSONObject litmapScaleArr = new JSONObject(JSONObject.Type.ARRAY); data.AddField("lightMapScaleOffset", litmapScaleArr); litmapScaleArr.Add(renderer.lightmapScaleOffset.x); litmapScaleArr.Add(renderer.lightmapScaleOffset.y); litmapScaleArr.Add(renderer.lightmapScaleOffset.z); litmapScaleArr.Add(renderer.lightmapScaleOffset.w); data.AddField("lightMapIndex", lightmapIndex); ShadowCastingMode mode = renderer.shadowCastingMode; if (mode == ShadowCastingMode.Off) { data.AddField("castShadow", false); } else { data.AddField("castShadow", true); } bool receiveShadow = renderer.receiveShadows; data.AddField("receiveShadow", receiveShadow); return(json); }
public JSONObject GetAvatarNodeData(GameObject gameObject, GameObject animatorGameObject, ref int id, string path = "") { bool currentNodeHasNotLegalChild = FindNotLegalChild(gameObject); if ( ( (UnityEngine.Object)SelectParentbyType( gameObject, WXUtility.ComponentType.Animator ) != (UnityEngine.Object)animatorGameObject || WXUtility .componentsOnGameObject(gameObject) .IndexOf(WXUtility.ComponentType.Animator) != -1 ) && (UnityEngine.Object)gameObject != (UnityEngine.Object)animatorGameObject ) { return(null); } if (currentNodeHasNotLegalChild) { JSONObject nodeJSON = new JSONObject(JSONObject.Type.OBJECT); JSONObject nodeProps = new JSONObject(JSONObject.Type.OBJECT); JSONObject translate = new JSONObject(JSONObject.Type.ARRAY); JSONObject rotation = new JSONObject(JSONObject.Type.ARRAY); JSONObject scale = new JSONObject(JSONObject.Type.ARRAY); Vector3 localPosition = gameObject.transform.localPosition; Quaternion localRotation = gameObject.transform.localRotation; Vector3 localScale = gameObject.transform.localScale; nodeProps.AddField("name", gameObject.name); nodeJSON.AddField("props", nodeProps); translate = new JSONObject(JSONObject.Type.ARRAY); nodeProps.AddField("translate", translate); translate.Add(localPosition.x * -1f); translate.Add(localPosition.y); translate.Add(localPosition.z); rotation = new JSONObject(JSONObject.Type.ARRAY); nodeProps.AddField("rotation", rotation); rotation.Add(localRotation.x * -1f); rotation.Add(localRotation.y); rotation.Add(localRotation.z); rotation.Add(localRotation.w * -1f); scale = new JSONObject(JSONObject.Type.ARRAY); nodeProps.AddField("scale", scale); scale.Add(localScale.x); scale.Add(localScale.y); scale.Add(localScale.z); id = id + 1; if (id > -1) { if (path.Length > 0) { path = path + "/" + gameObject.name; } else { path = gameObject.name; } } JSONObject nodeChildrenArray = new JSONObject(JSONObject.Type.ARRAY); if (gameObject.transform.childCount > 0) { for (int i = 0; i < gameObject.transform.childCount; i++) { JSONObject child = GetAvatarNodeData(gameObject.transform.GetChild(i).gameObject, animatorGameObject, ref id, path); if (child != null) { nodeChildrenArray.Add(child); } } } nodeJSON.AddField("child", nodeChildrenArray); return(nodeJSON); } return(null); }
protected override JSONObject ToJSON(WXHierarchyContext context) { JSONObject json = new JSONObject(JSONObject.Type.OBJECT); JSONObject data = new JSONObject(JSONObject.Type.OBJECT); JSONObject lodList = new JSONObject(JSONObject.Type.ARRAY); json.AddField("type", getTypeName()); json.AddField("data", data); data.AddField("active", lodGroup.enabled); data.AddField("lodCount", lodGroup.lodCount); float radius = 0f; JSONObject center = new JSONObject(JSONObject.Type.OBJECT); center.AddField("x", 0); center.AddField("y", 0); center.AddField("z", 0); LOD[] lods = lodGroup.GetLODs(); int lodIndex = 0; int radiusCountIndex = 0; string matchedRenderer = ""; foreach (LOD lod in lods) { JSONObject lodObject = new JSONObject(JSONObject.Type.OBJECT); JSONObject rendererList = new JSONObject(JSONObject.Type.ARRAY); lodObject.AddField("screenRelativeTransitionHeight", lod.screenRelativeTransitionHeight); lodObject.AddField("fadeTransitionWidth", lod.fadeTransitionWidth); Renderer[] renderers = lod.renderers; int renderersCount = renderers.Length; int rendererIndex = 0; foreach (Renderer renderer in renderers) { string targetRenderer = HandleRenderer(rendererList, renderer, context); /* 计算LODGroup包围球面积的逻辑: * 1. 如果当前的半径是0,说明一直未得到合法的Mesh半径信息,(比如当前LOD里就没有添加Renderer),说明需要进行一次计算 * 2. 如果当前半径不是0,需要分两种情况讨论 * 2.1. 如果当前的rendererIndex为0,说明是新的一轮LOD遍历,说明此前已经计算出了radius了,已经不用再进行计算了 * 2.2. 如果当前的rendererIndex不为0,且半径也有值,需要判断一下这个值是否是当前轮次计算出来的,如果是的话,也需要继续计算取最大值;如果是上一轮次计算出来的,那么就不需要继续计算了。 */ if ( radius == 0f || (rendererIndex != 0 && (radiusCountIndex == lodIndex)) ) { JSONObject tempBoundingBall = HandleRendererCapsuleBoundingBall(renderer); float tempRadius = tempBoundingBall.GetField("radius").n; if (tempRadius > radius) { radius = tempRadius; center = tempBoundingBall.GetField("center"); matchedRenderer = targetRenderer; } radiusCountIndex = lodIndex; } rendererIndex++; } lodObject.AddField("renderers", rendererList); lodList.Add(lodObject); lodIndex++; } data.AddField("lodList", lodList); data.AddField("radius", radius); data.AddField("center", center); data.AddField("renderer", matchedRenderer); return(json); }
protected override JSONObject ToJSON(WXHierarchyContext context) { JSONObject json = new JSONObject(JSONObject.Type.OBJECT); JSONObject data = new JSONObject(JSONObject.Type.OBJECT); json.AddField("type", "LineRenderer"); json.AddField("data", data); JSONObject materialArray = new JSONObject(JSONObject.Type.ARRAY); Material[] materials = renderer.sharedMaterials; foreach (Material material in materials) { WXMaterial materialConverter = new WXMaterial(material, renderer); string materialPath = materialConverter.Export(context.preset); materialArray.Add(materialPath); context.AddResource(materialPath); } data.AddField("materials", materialArray); ShadowCastingMode mode = renderer.shadowCastingMode; StaticEditorFlags shadowFlags = GameObjectUtility.GetStaticEditorFlags(renderer.gameObject); if (mode == ShadowCastingMode.Off || (shadowFlags & StaticEditorFlags.LightmapStatic) != 0) { data.AddField("castShadow", false); } else { data.AddField("castShadow", true); } bool receiveShadow = renderer.receiveShadows; data.AddField("receiveShadow", receiveShadow); int alignmentNum = 0; #if UNITY_2017_1_OR_NEWER LineAlignment alignment = renderer.alignment; switch (alignment) { case LineAlignment.View: alignmentNum = 0; break; #if UNITY_2018_2_OR_NEWER case LineAlignment.TransformZ: alignmentNum = 1; break; #else case LineAlignment.Local: alignmentNum = 1; break; #endif } data.AddField("alignment", alignmentNum); #endif Color startColor = renderer.startColor; data.AddField("startColor", parseColor(startColor)); Color endColor = renderer.endColor; data.AddField("endColor", parseColor(endColor)); float startWidth = renderer.startWidth; data.AddField("startWidth", startWidth); float endWidth = renderer.endWidth; data.AddField("endWidth", endWidth); LineTextureMode textureMode = renderer.textureMode; int textureModeNum = 0; switch (textureMode) { case LineTextureMode.Stretch: textureModeNum = 0; break; case LineTextureMode.Tile: textureModeNum = 1; break; } data.AddField("textureMode", textureModeNum); int positionCount = 0; #if UNITY_2017_1_OR_NEWER positionCount = renderer.positionCount; #else positionCount = renderer.numPositions; #endif Vector3[] positionsVec = new Vector3[positionCount]; renderer.GetPositions(positionsVec); JSONObject jSONObject = new JSONObject(JSONObject.Type.ARRAY); for (int i = 0; i < positionCount; i++) { JSONObject vec = new JSONObject(JSONObject.Type.ARRAY); vec.Add(positionsVec[i].x * -1f); vec.Add(positionsVec[i].y); vec.Add(positionsVec[i].z); jSONObject.Add(vec); } data.AddField("positions", jSONObject); data.AddField("numCapVertices", renderer.numCapVertices); data.AddField("numCornerVertices", renderer.numCornerVertices); #if UNITY_2017_1_OR_NEWER data.AddField("loop", renderer.loop); #endif data.AddField("useWorldSpace", renderer.useWorldSpace); data.AddField("gColor", GetGradientColor(renderer.colorGradient)); data.AddField("widthCurve", GetCurveData(renderer.widthCurve)); data.AddField("widthMultiplier", renderer.widthMultiplier); return(json); }
/* Shader defination, allow bool, int, float */ protected void AddShaderDefination(string key, bool isOn) { m_shaderDefinations.AddField(key, isOn); }
private static void RegisterUnityProperties() { AddPropertyHandler(typeof(Vector2), (obj, context) => { Vector2 v = (Vector2)obj; if (v == null) { return(null); } JSONObject vec2 = new JSONObject(JSONObject.Type.ARRAY); vec2.Add(v.x); vec2.Add(v.y); return(vec2); }); AddPropertyHandler(typeof(Vector3), (obj, context) => { Vector3 v = (Vector3)obj; if (v == null) { return(null); } JSONObject vec3 = new JSONObject(JSONObject.Type.ARRAY); vec3.Add(v.x); vec3.Add(v.y); vec3.Add(v.z); return(vec3); }); AddPropertyHandler(typeof(Vector4), (obj, context) => { Vector4 v = (Vector4)obj; if (v == null) { return(null); } JSONObject vec4 = new JSONObject(JSONObject.Type.ARRAY); vec4.Add(v.x); vec4.Add(v.y); vec4.Add(v.z); vec4.Add(v.w); return(vec4); }); AddPropertyHandler(typeof(Quaternion), (obj, context) => { Quaternion v = (Quaternion)obj; if (v == null) { return(null); } JSONObject array4 = new JSONObject(JSONObject.Type.ARRAY); array4.Add(v.x); array4.Add(v.y); array4.Add(v.z); array4.Add(v.w); return(array4); }); AddPropertyHandler(typeof(Matrix4x4), (obj, context) => { Matrix4x4 v = (Matrix4x4)obj; if (v == null) { return(null); } JSONObject array16 = new JSONObject(JSONObject.Type.ARRAY); array16.Add(v.m00); array16.Add(v.m01); array16.Add(v.m02); array16.Add(v.m03); array16.Add(v.m10); array16.Add(v.m11); array16.Add(v.m12); array16.Add(v.m13); array16.Add(v.m20); array16.Add(v.m21); array16.Add(v.m22); array16.Add(v.m23); array16.Add(v.m30); array16.Add(v.m31); array16.Add(v.m32); array16.Add(v.m33); return(array16); }); AddPropertyHandler(typeof(Color), (obj, context) => { Color c = (Color)obj; if (c == null) { return(null); } JSONObject vec4 = new JSONObject(JSONObject.Type.ARRAY); vec4.Add((int)(c.r * 255)); vec4.Add((int)(c.g * 255)); vec4.Add((int)(c.b * 255)); vec4.Add((int)(c.a * 255)); return(vec4); }); AddPropertyHandler(typeof(TextAsset), (obj, context) => { TextAsset t = (TextAsset)obj; if (!t) { return(null); } string path = AssetDatabase.GetAssetPath(t); // string copyToPath = Path.Combine(WXResourceStore.storagePath, path); // Debug.Log("WXResourceStore.storagePath:" + WXResourceStore.storagePath); // Debug.Log("path:" + path); // Debug.Log("copyToPath:" + copyToPath); // Regex regex = new Regex(".txt$"); // copyToPath = regex.Replace(copyToPath, ".json"); // if (!Directory.Exists(WXResourceStore.storagePath + "Assets/")) { // Directory.CreateDirectory(WXResourceStore.storagePath + "Assets/"); // } // FileStream fs = new FileStream(copyToPath, FileMode.Create, FileAccess.Write); // wxFileUtil.WriteData(fs, JsonConvert.SerializeObject(new { text = t.text })); // fs.Close(); JSONObject json = new JSONObject(JSONObject.Type.OBJECT); JSONObject data = new JSONObject(JSONObject.Type.OBJECT); // Debug.Log("JsonConvert.SerializeObject(t.text): " + JsonConvert.SerializeObject(t.text)); string text = JsonConvert.SerializeObject(t.text); // 去掉首尾双引号 text = text.Remove(0, 1); text = text.Substring(0, text.Length - 1); data.AddField("text", text); data.AddField("path", path); json.AddField("type", "UnityEngine.TextAsset".EscapeNamespaceSimple()); json.AddField("value", data); return(json); }); AddPropertyHandler(typeof(Material), (obj, context) => { Material material = (Material)obj; if (material == null) { return(null); } WXMaterial materialConverter = new WXMaterial(material, null); string materialPath = materialConverter.Export(context.preset); context.AddResource(materialPath); JSONObject json = new JSONObject(JSONObject.Type.OBJECT); JSONObject data = new JSONObject(JSONObject.Type.OBJECT); json.AddField("type", "UnityEngine.Material".EscapeNamespaceSimple()); json.AddField("value", data); data.AddField("path", materialPath); return(json); }); AddPropertyHandler(typeof(List <>), (obj, context) => { IEnumerable list = (IEnumerable)obj; if (list == null) { return(null); } JSONObject result = new JSONObject(JSONObject.Type.ARRAY); var enumerator = ((IEnumerable)list).GetEnumerator(); while (enumerator.MoveNext()) { object itemObj = enumerator.Current; if (itemObj == null) { continue; } if (itemObj.GetType() == typeof(List <>)) { throw new Exception("List不支持嵌套"); } else { Type type = itemObj.GetType(); if (type.IsSubclassOf(typeof(UnityEngine.Component)) || type == typeof(UnityEngine.GameObject)) { var o = (UnityEngine.Object)itemObj; GameObject go = null; if (o == null) { continue; } if (type.IsSubclassOf(typeof(UnityEngine.Component))) { go = ((Component)o).gameObject; } else if (type == typeof(UnityEngine.GameObject)) { go = (GameObject)o; } var path = AssetDatabase.GetAssetPath(o); // Prefab? if (go.transform.IsChildOf(context.Root.transform) || path == "") { if (!propertiesHandlerDictionary.ContainsKey(type) && !type.IsArray && (!type.IsGenericType || type.GetGenericTypeDefinition() != typeof(List <>)) && type.IsSerializable) { var sobj = new JSONObject(JSONObject.Type.OBJECT); result.Add(sobj); SerializableHandler(type, sobj, itemObj, context); } else if (type != typeof(System.Object) && propertiesHandlerDictionary.ContainsKey(type)) { var res = propertiesHandlerDictionary[type](itemObj, context); result.Add(res); } continue; } if (!WXMonoBehaviourExportHelper.exportedResourcesSet.Contains(go)) { WXMonoBehaviourExportHelper.exportedResourcesSet.Add(go); WXPrefab converter = new WXPrefab(go, path); string prefabPath = converter.Export(ExportPreset.GetExportPreset("prefab")); context.AddResource(prefabPath); } var prefabInfo = new JSONObject(JSONObject.Type.OBJECT); prefabInfo.AddField("type", type.FullName.EscapeNamespaceSimple()); prefabInfo.AddField("path", path); var innerData = new JSONObject(JSONObject.Type.OBJECT); innerData.AddField("type", "UnityPrefabWrapper"); innerData.AddField("value", prefabInfo); // data.AddField(field.Name, innerData); result.Add(innerData); } else if (!propertiesHandlerDictionary.ContainsKey(type) && !type.IsArray && (!type.IsGenericType || type.GetGenericTypeDefinition() != typeof(List <>)) && type.IsSerializable) { var sobj = new JSONObject(JSONObject.Type.OBJECT); result.Add(sobj); SerializableHandler(type, sobj, itemObj, context); } else if (type != typeof(System.Object) && propertiesHandlerDictionary.ContainsKey(type)) { var res = propertiesHandlerDictionary[type](itemObj, context); result.Add(res); } } } return(result); }); // disgusting code logic :( // refactor should be needed AddPropertyHandler(typeof(MonoBehaviour), (obj, context) => { var m = (MonoBehaviour)obj; if (!m) { return(null); } if (ExportLogger.LOGGING) { ExportLogger.AddLog(new ExportLogger.Log(ExportLogger.Log.Type.Property, "Object: " + obj + "\nType: " + obj.GetType())); } var go = m.gameObject; JSONObject innerData = new JSONObject(JSONObject.Type.OBJECT); var path = AssetDatabase.GetAssetPath(go); // Prefab? if (go.transform.IsChildOf(context.Root.transform) || path == "") { var typeName = m.GetType().FullName; var escapedTypeName = WXMonoBehaviourExportHelper.EscapeNamespace(typeName); innerData.AddField("type", escapedTypeName); innerData.AddField("value", context.AddComponentInProperty(new WXEngineMonoBehaviour(m), (Component)obj)); return(innerData); } if (!WXMonoBehaviourExportHelper.exportedResourcesSet.Contains(go)) { WXMonoBehaviourExportHelper.exportedResourcesSet.Add(go); WXPrefab converter = new WXPrefab(go, path); string prefabPath = converter.Export(ExportPreset.GetExportPreset("prefab")); context.AddResource(prefabPath); } var prefabInfo = new JSONObject(JSONObject.Type.OBJECT); { var typeName = m ? m.GetType().FullName : "UnityEngine.GameObject"; var escapedTypeName = WXMonoBehaviourExportHelper.EscapeNamespace(typeName); prefabInfo.AddField("type", escapedTypeName); } prefabInfo.AddField("path", path); innerData.AddField("type", "UnityPrefabWrapper"); innerData.AddField("value", prefabInfo); return(innerData); }); AddPropertyHandler(typeof(Component), (obj, context) => { Component c = (Component)obj; if (!c) { return(null); } if (ExportLogger.LOGGING) { ExportLogger.AddLog(new ExportLogger.Log(ExportLogger.Log.Type.Property, "Object: " + obj + "\nType: " + obj.GetType())); } JSONObject innerData = new JSONObject(JSONObject.Type.OBJECT); var escapedTypeName = WXMonoBehaviourExportHelper.EscapeNamespace(c.GetType().FullName); innerData.AddField("type", escapedTypeName); if (c is Transform) { innerData = GetPrefabOnSerializedField(context, c.gameObject, innerData, false); } // 下面是adaptor独有的类才需要单独写 // Physics //else if (c is BoxCollider) { // innerData.AddField("value", context.AddComponent(new WXBoxCollider((BoxCollider)c), (BoxCollider)c)); //} else if (c is SphereCollider) { // innerData.AddField("value", context.AddComponent(new WXSphereCollider((SphereCollider)c), (SphereCollider)c)); //} else if (c is CapsuleCollider) { // innerData.AddField("value", context.AddComponent(new WXCapsuleCollider((CapsuleCollider)c), (CapsuleCollider)c)); //} else if (c is MeshCollider) { // innerData.AddField("value", context.AddComponent(new WXMeshCollider((MeshCollider)c), (MeshCollider)c)); //} else if (c is Rigidbody) { // innerData.AddField("value", context.AddComponent(new WXRigidbody((Rigidbody)c), (Rigidbody)c)); //} else if (c is AudioSource) { innerData.AddField("value", context.AddComponentInProperty(new WXEngineAudioSource((AudioSource)c), (AudioSource)c)); } // 有ref的类 else { // if (context.componentDictionary.ContainsKey(c)) { innerData.AddField("value", context.AddComponentInProperty(new WXUnityComponent(c), c)); // } } return(innerData); }); AddPropertyHandler(typeof(GameObject), (obj, context) => { var go = (GameObject)obj; if (!go) { return(null); } if (ExportLogger.LOGGING) { ExportLogger.AddLog(new ExportLogger.Log(ExportLogger.Log.Type.Property, "Object: " + obj + "\nType: " + obj.GetType())); } JSONObject innerData = new JSONObject(JSONObject.Type.OBJECT); return(GetPrefabOnSerializedField(context, go, innerData)); }); }
protected override JSONObject ToJSON(WXHierarchyContext context) { JSONObject json = new JSONObject(JSONObject.Type.OBJECT); JSONObject data = new JSONObject(JSONObject.Type.OBJECT); json.AddField("type", "MeshRenderer"); json.AddField("data", data); Mesh mesh = (renderer.gameObject.GetComponent(typeof(MeshFilter)) as MeshFilter).sharedMesh; if (mesh != null) { WXMesh meshConverter = new WXMesh(mesh); string meshPath = meshConverter.Export(context.preset); data.AddField("mesh", meshPath); context.AddResource(meshPath); } else { Debug.LogError(string.Format("{0} mesh is null", renderer.name)); } JSONObject materialArray = new JSONObject(JSONObject.Type.ARRAY); Material[] materials = renderer.sharedMaterials; foreach (Material material in materials) { if (material != null) { WXMaterial materialConverter = new WXMaterial(material, renderer); string materialPath = materialConverter.Export(context.preset); materialArray.Add(materialPath); context.AddResource(materialPath); } } data.AddField("materials", materialArray); int lightmapIndex = renderer.lightmapIndex; JSONObject litmapScaleArr = new JSONObject(JSONObject.Type.ARRAY); data.AddField("lightMapScaleOffset", litmapScaleArr); litmapScaleArr.Add(renderer.lightmapScaleOffset.x); litmapScaleArr.Add(renderer.lightmapScaleOffset.y); litmapScaleArr.Add(renderer.lightmapScaleOffset.z); litmapScaleArr.Add(renderer.lightmapScaleOffset.w); data.AddField("lightMapIndex", lightmapIndex); ShadowCastingMode mode = renderer.shadowCastingMode; StaticEditorFlags shadowFlags = GameObjectUtility.GetStaticEditorFlags(renderer.gameObject); if (mode == ShadowCastingMode.Off || (shadowFlags & StaticEditorFlags.LightmapStatic) != 0) { data.AddField("castShadow", false); } else { data.AddField("castShadow", true); } bool receiveShadow = renderer.receiveShadows; data.AddField("receiveShadow", receiveShadow); return(json); }
protected override JSONObject ToJSON(WXHierarchyContext context) { JSONObject json = new JSONObject(JSONObject.Type.OBJECT); JSONObject data = new JSONObject(JSONObject.Type.OBJECT); json.AddField("type", "MeshRenderer"); json.AddField("data", data); data.AddField("active", renderer.enabled); JSONObject materialArray = new JSONObject(JSONObject.Type.ARRAY); Material[] materials = renderer.sharedMaterials; int materialCount = 0; foreach (Material material in materials) { if (material != null) { WXMaterial materialConverter = new WXMaterial(material, renderer); string materialPath = materialConverter.Export(context.preset); materialArray.Add(materialPath); context.AddResource(materialPath); materialCount++; } } data.AddField("materials", materialArray); MeshFilter meshFilter = renderer.gameObject.GetComponent <MeshFilter> (); if (meshFilter != null && meshFilter.sharedMesh != null) { Mesh mesh = meshFilter.sharedMesh; WXMesh meshConverter = new WXMesh(mesh, materialCount); string meshPath = meshConverter.Export(context.preset); data.AddField("mesh", meshPath); context.AddResource(meshPath); } else { ErrorUtil.ExportErrorReporter.create() .setGameObject(renderer.gameObject) .setHierarchyContext(context) .error(ErrorUtil.ErrorCode.MeshRenderer_MeshNotFound, "Mesh资源转换失败,没法拿到对应的MeshFilter或者它上面的mesh"); } int lightmapIndex = renderer.lightmapIndex; JSONObject litmapScaleArr = new JSONObject(JSONObject.Type.ARRAY); data.AddField("lightMapScaleOffset", litmapScaleArr); litmapScaleArr.Add(renderer.lightmapScaleOffset.x); litmapScaleArr.Add(renderer.lightmapScaleOffset.y); litmapScaleArr.Add(renderer.lightmapScaleOffset.z); litmapScaleArr.Add(renderer.lightmapScaleOffset.w); data.AddField("lightMapIndex", lightmapIndex); ShadowCastingMode mode = renderer.shadowCastingMode; StaticEditorFlags shadowFlags = GameObjectUtility.GetStaticEditorFlags(renderer.gameObject); #if UNITY_2019_2_OR_NEWER if (mode == ShadowCastingMode.Off || (shadowFlags & StaticEditorFlags.ContributeGI) != 0) #else if (mode == ShadowCastingMode.Off || (shadowFlags & StaticEditorFlags.LightmapStatic) != 0) #endif { data.AddField("castShadow", false); } else { data.AddField("castShadow", true); } bool receiveShadow = renderer.receiveShadows; data.AddField("receiveShadow", receiveShadow); return(json); }
protected override JSONObject ToJSON(WXHierarchyContext context) { JSONObject json = new JSONObject(JSONObject.Type.OBJECT); JSONObject data = new JSONObject(JSONObject.Type.OBJECT); json.AddField("type", getTypeName()); json.AddField("data", data); data.AddField("active", true); JSONObject scriptList = WXUIUCommonScript.AddInteractionScript(go, entity, context, false); data.AddField("scriptList", scriptList); Image targetGraphic = (Image)input.targetGraphic; if (targetGraphic != null) { data.AddField("targetGraphic", context.AddComponent(new WXUIUSpriteScript(targetGraphic, go, entity), targetGraphic)); } JSONObject onValueChangedList = new JSONObject(JSONObject.Type.ARRAY); data.AddField("onValueChanged", onValueChangedList); int onChangeCount = input.onValueChanged.GetPersistentEventCount(); for (int i = 0; i < onChangeCount; i++) { var __onChange = new JSONObject(JSONObject.Type.OBJECT); var target = input.onValueChanged.GetPersistentTarget(i); var targetType = target.GetType().ToString(); __onChange.AddField("targetType", targetType); if (targetType == "UnityEngine.GameObject") { GameObject _go = (GameObject)target; __onChange.AddField("target", WXUIUCommonScript.AddComponent(_go, entity, context)); } else { //todo 其他类型的到时候再考虑 MonoBehaviour _target = (MonoBehaviour)target; __onChange.AddField("target", context.AddComponent(new WXEngineMonoBehaviour(_target), _target)); } __onChange.AddField("method", input.onValueChanged.GetPersistentMethodName(i)); onValueChangedList.Add(__onChange); } JSONObject onEditEndList = new JSONObject(JSONObject.Type.ARRAY); data.AddField("onEditEnd", onEditEndList); int onEidtEndCount = input.onEndEdit.GetPersistentEventCount(); for (int i = 0; i < onEidtEndCount; i++) { var __onEnd = new JSONObject(JSONObject.Type.OBJECT); var target = input.onEndEdit.GetPersistentTarget(i); var targetType = target.GetType().ToString(); __onEnd.AddField("targetType", targetType); if (targetType == "UnityEngine.GameObject") { GameObject _go = (GameObject)target; __onEnd.AddField("target", WXUIUCommonScript.AddComponent(_go, entity, context)); } else { //todo 其他类型的到时候再考虑 MonoBehaviour _target = (MonoBehaviour)target; __onEnd.AddField("target", context.AddComponent(new WXEngineMonoBehaviour(_target), _target)); } __onEnd.AddField("method", input.onEndEdit.GetPersistentMethodName(i)); onEditEndList.Add(__onEnd); } Text placeHolder = (Text)input.placeholder; if (placeHolder != null) { JSONObject color = new JSONObject(JSONObject.Type.ARRAY); color.Add(255f * placeHolder.color.r); color.Add(255f * placeHolder.color.g); color.Add(255f * placeHolder.color.b); color.Add(255f * placeHolder.color.a); data.AddField("promptColor", color); input.placeholder.gameObject.SetActive(false); } data.AddField("ref", context.AddComponent(new WXUIUInputField(input, go, entity), input)); return(json); }
protected override JSONObject ToJSON(WXHierarchyContext context) { JSONObject json = new JSONObject(JSONObject.Type.OBJECT); json.AddField("type", "UISprite"); JSONObject subJSON = new JSONObject(JSONObject.Type.OBJECT); JSONObject color = new JSONObject(JSONObject.Type.ARRAY); color.Add(255f * uiTexture.color.r); color.Add(255f * uiTexture.color.g); color.Add(255f * uiTexture.color.b); color.Add(255f * uiTexture.color.a); subJSON.AddField("color", color); subJSON.AddField("colorBlendType", 0); UI2DSprite.Type type = uiTexture.type; subJSON.AddField("type", (int)type); UI2DSprite.Flip flipType = uiTexture.flip; subJSON.AddField("flip", (int)flipType); subJSON.AddField("fillCenter", uiTexture.centerType == UI2DSprite.AdvancedType.Sliced); subJSON.AddField("fillDir", (int)uiTexture.fillDirection); subJSON.AddField("fillAmount", uiTexture.fillAmount); subJSON.AddField("invertFill", uiTexture.invert); string texturePath = ""; if (uiTexture.mainTexture != null) { Texture2D texture2D = (Texture2D)uiTexture.mainTexture; if (texture2D != null) { string path = AssetDatabase.GetAssetPath(texture2D.GetInstanceID()); texturePath = new WXTexture(texture2D).Export(context.preset);// MaterialUtil.SaveTextureFile(texture2D); context.AddResource(texturePath); UISpriteData data = new UISpriteData(); data.width = uiTexture.mainTexture.width; data.height = uiTexture.mainTexture.height; WXSpriteFrame spriteFrame = new WXSpriteFrame(data, texturePath, path); string key = spriteFrame.Export(context.preset); subJSON.AddField("spriteFrame", key); context.AddResource(key); } } else { JSONObject nullJSON = new JSONObject(JSONObject.Type.NULL); subJSON.AddField("spriteFrame", nullJSON); } subJSON.AddField("active", uiTexture.enabled); json.AddField("data", subJSON); return(json); }
protected override void DoExport() { EditorUtility.ClearProgressBar(); BridgeExport.isProcessing = false; List <string> allRecursiveAssets = new List <string>(); // string choosedPath = GetExportPath(); // string savePath = Path.Combine(choosedPath, "Assets/"); var savePath = Path.Combine(ExportStore.storagePath, "Assets/"); updateRecourcesDir(); int totalCount = 0; string [] arr_dir = dirs.ToArray(); JSONObject jsonConfig = new JSONObject(JSONObject.Type.ARRAY); if (arr_dir.Length > 0) { for (int index = 0; index < supportedTypes.Length; index++) { string filter = "t:" + supportedTypes[index]; string[] guids = AssetDatabase.FindAssets(filter, arr_dir); // Debug.Log(guids.Length); if (guids.Length == 0) { continue; } JSONObject category = new JSONObject(JSONObject.Type.OBJECT); JSONObject data = new JSONObject(JSONObject.Type.ARRAY); category.AddField("type", supportedTypes[index]); category.AddField("files", data); var t = 0; HashSet <string> setFiles = new HashSet <string>(); for (int i = 0; i < guids.Length; i++) { string path = AssetDatabase.GUIDToAssetPath(guids[i]); if (path.StartsWith("Assets")) { path = path.Substring(6); } string absolutePath = Path.Combine(Application.dataPath, path); // #if UNITY_EDITOR_WIN // string absolutePath = Application.dataPath + "\\" + path; // #else // string absolutePath = Application.dataPath + "/" + path; // #endif // string filename = System.IO.Path.GetFileName(absolutePath); string copyToPath = Path.Combine(savePath, path); // #if UNITY_EDITOR_WIN // string copyToPath = savePath + "\\" + path; // #else // string copyToPath = savePath + "/" + path; // #endif string extension = System.IO.Path.GetExtension(path); if (setExclude.Contains(extension)) { continue; } if (supportedTypes[index] != "GameObject") { #if USE_RAW_MODE string projpath = "Assets" + path; WXRawResource rawResource = new WXRawResource(projpath); string ret_path = rawResource.Export(this); allRecursiveAssets.Add(ret_path); #else wxFileUtil.CopyFile(absolutePath, copyToPath); #endif } JSONObject fileInfo = new JSONObject(JSONObject.Type.OBJECT); // fileInfo.AddField("key", Path.GetFileNameWithoutExtension(filename)); string key = getResourcePath(path); if (setFiles.Contains(key)) { continue; } else { setFiles.Add(key); } fileInfo.AddField("key", key); fileInfo.AddField("name", "Assets" + path); data.Add(fileInfo); totalCount++; EditorUtility.DisplayProgressBar("原始资源导出", "", t++ / guids.Length); } jsonConfig.Add(category); } } #if USE_RAW_MODE string tempConfigFile = Path.Combine(Application.dataPath, "Resources.json"); wxFileUtil.SaveJsonFile(jsonConfig, tempConfigFile); string configpath = "Assets/Resources.json"; WXRawResource rawConfig = new WXRawResource(configpath); string ret_cfg_path = rawConfig.Export(this); allRecursiveAssets.Add(ret_cfg_path); File.Delete(tempConfigFile); #endif // string content = jsonConfig.ToString(); // ExportStore.AddTextFile(configpath, content, WXUtility.GetMD5FromString(content)); // List<string> useConfig = new List<string>(); // useConfig.Add(configpath); // ExportStore.AddResource(configpath, "raw", null, useConfig); // allRecursiveAssets.Add(configpath); ExportStore.GenerateResourcePackage( "WXResources", allRecursiveAssets ); EditorUtility.ClearProgressBar(); Debug.Log("导出成功,总共导出文件个数:" + totalCount); }
protected override JSONObject ExportResource(ExportPreset preset) { WXHierarchyContext hierarchyContext = new WXHierarchyContext(preset, prefabPath); hierarchyContext.prefab2dType = typeof(WXNGUITree); // 初始化输出的JSON对象 JSONObject prefabJSONObject = new JSONObject(JSONObject.Type.OBJECT); JSONObject metaJson = new JSONObject(JSONObject.Type.OBJECT); prefabJSONObject.AddField("meta", metaJson); // 填充meta metaJson.AddField("name", exportName); metaJson.AddField("type", "2D"); if (exportAsScene) { JSONObject configJson = new JSONObject(JSONObject.Type.OBJECT); metaJson.AddField("config", configJson); JSONObject resolutionJson = new JSONObject(JSONObject.Type.ARRAY); UIRoot uiRoot = getUIRoot(prefabRoot); if (uiRoot != null) { Debug.Log("uiRoot is"); // var a = JsonUtility.ToJson(uiRoot, true); // Debug.Log(a); // Debug.Log(uiRoot.activeHeight); // Debug.Log(uiRoot.manualWidth); // Debug.Log(uiRoot.manualHeight); UIRoot.Scaling scalingStyle = uiRoot.scalingStyle; configJson.AddField("scalingStyle", (int)scalingStyle); configJson.AddField("manualWidth", uiRoot.manualWidth); configJson.AddField("manualHeight", uiRoot.manualHeight); configJson.AddField("minimumHeight", uiRoot.minimumHeight); configJson.AddField("maximumHeight", uiRoot.maximumHeight); configJson.AddField("fitWidth", uiRoot.fitWidth); configJson.AddField("fitHeight", uiRoot.fitHeight); configJson.AddField("adjustByDPI", uiRoot.adjustByDPI); configJson.AddField("shrinkPortraitUI", uiRoot.shrinkPortraitUI); if (scalingStyle == UIRoot.Scaling.Flexible) { // 目前引擎没有对Flexible这种情况的支持,所以默认先导出一个假定的resolution resolutionJson.Add(uiRoot.activeHeight); resolutionJson.Add(uiRoot.activeHeight); } else { resolutionJson.Add(uiRoot.manualWidth); resolutionJson.Add(uiRoot.manualHeight); } } else { // 无root情况,使用默认大小 resolutionJson.Add(1280); resolutionJson.Add(720); } configJson.AddField("resolution", resolutionJson); } // 开始遍历 WXEntity rootEntity = hierarchyContext.IterateGameObject(prefabRoot); prefabJSONObject.AddField("gameObjectList", hierarchyContext.GetGameObjectListJSON()); prefabJSONObject.AddField("componentList", hierarchyContext.GetComponentListJSON()); JSONObject editorInfo = new JSONObject(JSONObject.Type.OBJECT); editorInfo.AddField("assetVersion", 2); prefabJSONObject.AddField("editorInfo", editorInfo); //Debug.Log("Export Prefab " + prefabPath + " " + hierarchyContext.resourceList.Count); foreach (string resource in hierarchyContext.resourceList) { AddDependencies(resource); } return(prefabJSONObject); }
protected override JSONObject ToJSON(WXHierarchyContext context) { entity.components.Add(context.AddComponent(new WXUGUITouchInputComponent(gameObject, entity), null)); JSONObject json = new JSONObject(JSONObject.Type.OBJECT); json.AddField("type", getTypeName()); JSONObject subJSON = new JSONObject(JSONObject.Type.OBJECT); JSONObject colorPressed = new JSONObject(JSONObject.Type.ARRAY); var pressedColor = button.colors.pressedColor; if (pressedColor != null) { colorPressed.Add(255f * pressedColor.r); colorPressed.Add(255f * pressedColor.g); colorPressed.Add(255f * pressedColor.b); colorPressed.Add(255f * pressedColor.a); subJSON.AddField("pressedColor", colorPressed); } JSONObject colorDisabled = new JSONObject(JSONObject.Type.ARRAY); var disabledColor = button.colors.disabledColor; if (disabledColor != null) { colorDisabled.Add(255f * disabledColor.r); colorDisabled.Add(255f * disabledColor.g); colorDisabled.Add(255f * disabledColor.b); colorDisabled.Add(255f * disabledColor.a); subJSON.AddField("disabledColor", colorDisabled); } JSONObject colorNormal = new JSONObject(JSONObject.Type.ARRAY); var normalColor = button.colors.normalColor; if (normalColor != null) { colorNormal.Add(255f * normalColor.r); colorNormal.Add(255f * normalColor.g); colorNormal.Add(255f * normalColor.b); colorNormal.Add(255f * normalColor.a); subJSON.AddField("normalColor", colorNormal); } SpriteState state = button.spriteState; if (state.pressedSprite != null) { string pressedSpriteKey = this.getStateSprite(context, state.pressedSprite); if (pressedSpriteKey != null) { subJSON.AddField("pressedSprite", pressedSpriteKey); } else { subJSON.AddField("pressedSprite", new JSONObject(JSONObject.Type.NULL)); } } if (state.disabledSprite != null) { string disabledSpriteKey = this.getStateSprite(context, state.disabledSprite); if (disabledSpriteKey != null) { subJSON.AddField("disabledSprite", disabledSpriteKey); } else { subJSON.AddField("disabledSprite", new JSONObject(JSONObject.Type.NULL)); } } Image targetImage = button.targetGraphic.GetComponent <Image>(); if (targetImage != null) { string normalSpriteKey = this.getStateSprite(context, targetImage.sprite); if (normalSpriteKey != null) { subJSON.AddField("normalSprite", normalSpriteKey); } else { subJSON.AddField("normalSprite", new JSONObject(JSONObject.Type.NULL)); } } subJSON.AddField("active", button.IsActive()); json.AddField("data", subJSON); return(json); }
// inner recursion method, thus each if-statement must have @return in the end of the following block. private static void innerHandleProperty(Type type, FieldInfo field, object obj, JSONObject data, WXHierarchyContext context) { if (ExportLogger.LOGGING) { ExportLogger.AddLog(new ExportLogger.Log(ExportLogger.Log.Type.Inner, "Type: " + type + "\nObject: " + obj + "\nJson: " + data)); } if (obj == null || type == null || type == typeof(System.Object) || field.IsDefined(typeof(NonSerializedAttribute)) || field.IsDefined(typeof(HideInInspector))) { return; } if (WXBridge.isNGUIPreset) { Type wxnguiType = WXMonoBehaviourExportHelper.GetWXNGUIComponentType(type); if (wxnguiType != null) { var nativeComp = (Component)field.GetValue(obj); if (nativeComp != null) { var go = nativeComp.gameObject; Debug.Log(nativeComp); var entity = context.MakeEntity(go); // 特殊处理 if (wxnguiType.FullName == "WXEngine.WXTransform2DComponent") { data.AddField(field.Name, context.AddComponentInProperty( (WXComponent)Activator.CreateInstance(wxnguiType, (object)nativeComp.transform), nativeComp.transform )); } else { data.AddField(field.Name, context.AddComponentInProperty( (WXComponent)Activator.CreateInstance(wxnguiType, nativeComp, go, entity), nativeComp )); } } } } if (WXBridge.isUGUIPreset) { Type wxuguiType = WXMonoBehaviourExportHelper.GetWXUGUIComponentType(type); if (wxuguiType != null) { var nativeComp = (Component)field.GetValue(obj); if (nativeComp != null) { var go = nativeComp.gameObject; Debug.Log(nativeComp); var entity = context.MakeEntity(go); // 特殊处理 if (wxuguiType.FullName == "WeChat.WXUGUITransform2DComponent") { data.AddField(field.Name, context.AddComponent( (WXComponent)Activator.CreateInstance(wxuguiType, (object)nativeComp.transform), nativeComp.transform )); } else { data.AddField(field.Name, context.AddComponent( (WXComponent)Activator.CreateInstance(wxuguiType, nativeComp, go, entity), nativeComp )); } } } } if (WXBridge.isUGUIPreset) { Type wxuguiType = WXMonoBehaviourExportHelper.GetWXUGUIComponentType(type); if (wxuguiType != null) { var nativeComp = (Component)field.GetValue(obj); if (nativeComp != null) { var go = nativeComp.gameObject; Debug.Log(nativeComp); var entity = context.MakeEntity(go); // 特殊处理 if (wxuguiType.FullName == "WeChat.WXUGUITransform2DComponent") { data.AddField(field.Name, context.AddComponent( (WXComponent)Activator.CreateInstance(wxuguiType, (object)nativeComp.transform), nativeComp.transform )); } else { data.AddField(field.Name, context.AddComponent( (WXComponent)Activator.CreateInstance(wxuguiType, nativeComp, go, entity), nativeComp )); } } } } if (WXMonoBehaviourExportHelper.IsInBlackList(type)) { return; } if (propertiesHandlerDictionary.ContainsKey(type)) { var res = InvokePropertyHandler(type, field.GetValue(obj), context); if (res) { data.AddField(field.Name, res); } return; } else if (type.IsArray || (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List <>))) { var res = InvokePropertyHandler(typeof(List <>), field.GetValue(obj), context); if (res) { data.AddField(field.Name, res); } return; } else if (type.IsEnum) { var res = JSONObject.Create((int)field.GetValue(obj)); if (res) { data.AddField(field.Name, res); } return; } else if (type.IsSubclassOf(typeof(UnityEngine.Component)) || type == typeof(UnityEngine.GameObject)) { // Prefab or not var o = (UnityEngine.Object)field.GetValue(obj); GameObject go = null; if (o == null) { return; } if (type.IsSubclassOf(typeof(UnityEngine.Component))) { go = ((Component)o).gameObject; } else if (type == typeof(UnityEngine.GameObject)) { go = (GameObject)o; } var path = AssetDatabase.GetAssetPath(o); if (go.transform.IsChildOf(context.Root.transform) || path == "") { if (type.IsSerializable) { var _innerData = new JSONObject(JSONObject.Type.OBJECT); data.AddField(field.Name, _innerData); SerializableHandler(type, _innerData, field.GetValue(obj), context); return; } innerHandleProperty(type.BaseType, field, obj, data, context); return; } if (!WXMonoBehaviourExportHelper.exportedResourcesSet.Contains(go)) { WXMonoBehaviourExportHelper.exportedResourcesSet.Add(go); WXPrefab converter = new WXPrefab(go, path); string prefabPath = converter.Export(ExportPreset.GetExportPreset("prefab")); context.AddResource(prefabPath); } var prefabInfo = new JSONObject(JSONObject.Type.OBJECT); prefabInfo.AddField("type", type.FullName.EscapeNamespaceSimple()); prefabInfo.AddField("path", path); var innerData = new JSONObject(JSONObject.Type.OBJECT); innerData.AddField("type", "UnityPrefabWrapper"); innerData.AddField("value", prefabInfo); data.AddField(field.Name, innerData); return; } else if (type.IsSerializable) { // data of serializable object as a new JSONObject to be added var innerData = new JSONObject(JSONObject.Type.OBJECT); data.AddField(field.Name, innerData); SerializableHandler(type, innerData, field.GetValue(obj), context); return; } innerHandleProperty(type.BaseType, field, obj, data, context); }
protected override JSONObject ToJSON(WXHierarchyContext context) { ParticleSystemRenderer particleSystemRenderer = particleSys.GetComponent <ParticleSystemRenderer>(); JSONObject json = new JSONObject(JSONObject.Type.OBJECT); JSONObject data = new JSONObject(JSONObject.Type.OBJECT); json.AddField("type", getTypeName()); json.AddField("data", data); JSONObject materials = new JSONObject(JSONObject.Type.ARRAY); data.AddField("materials", materials); Material[] mats = particleSystemRenderer.sharedMaterials; foreach (Material material in mats) { if (material != null) { WXMaterial materialConverter = new WXMaterial(material, particleSystemRenderer); string materialPath = materialConverter.Export(context.preset); materials.Add(materialPath); context.AddResource(materialPath); } } JSONObject modCommon = new JSONObject(JSONObject.Type.OBJECT); JSONObject modCommonData = new JSONObject(JSONObject.Type.OBJECT); data.AddField("common", modCommonData); modCommonData.AddField("startSize3D", particleSys.main.startSize3D); if (particleSys.main.startSize3D) { modCommonData.AddField("startSizeX", ParseMinMaxCurve(particleSys.main.startSizeX)); modCommonData.AddField("startSizeY", ParseMinMaxCurve(particleSys.main.startSizeY)); modCommonData.AddField("startSizeZ", ParseMinMaxCurve(particleSys.main.startSizeZ)); } else { modCommonData.AddField("startSize", ParseMinMaxCurve(particleSys.main.startSize)); } modCommonData.AddField("startColor", ParseMinMaxGradient(particleSys.main.startColor)); modCommonData.AddField("startLifetime", ParseMinMaxCurve(particleSys.main.startLifetime)); modCommonData.AddField("startRotation3D", particleSys.main.startRotation3D); if (particleSys.main.startRotation3D) { modCommonData.AddField("startRotationX", ParseMinMaxCurve(particleSys.main.startRotationX, (float)(180 / Math.PI))); modCommonData.AddField("startRotationY", ParseMinMaxCurve(particleSys.main.startRotationY, (float)(180 / Math.PI))); modCommonData.AddField("startRotationZ", ParseMinMaxCurve(particleSys.main.startRotationZ, (float)(180 / Math.PI))); } else { modCommonData.AddField("startRotationZ", ParseMinMaxCurve(particleSys.main.startRotation, (float)(180 / Math.PI))); } modCommonData.AddField("startSpeed", ParseMinMaxCurve(particleSys.main.startSpeed)); modCommonData.AddField("gravityModifier", ParseMinMaxCurve(particleSys.main.gravityModifier)); #if UNITY_2018_1_OR_NEWER modCommonData.AddField("randomizeRotation", particleSys.main.flipRotation); #endif modCommonData.AddField("randomSeed", particleSys.randomSeed); modCommonData.AddField("autoRandomSeed", particleSys.useAutoRandomSeed); ParticleSystemScalingMode pScalingMode = particleSys.main.scalingMode; int pScalingModeNum = 0; switch (pScalingMode) { case ParticleSystemScalingMode.Hierarchy: pScalingModeNum = 0; break; case ParticleSystemScalingMode.Local: pScalingModeNum = 1; break; case ParticleSystemScalingMode.Shape: pScalingModeNum = 2; break; } modCommonData.AddField("scalingMode", pScalingModeNum); ParticleSystemSimulationSpace simulationSpace = particleSys.main.simulationSpace; int simulationSpaceNum = 0; switch (simulationSpace) { case ParticleSystemSimulationSpace.Local: simulationSpaceNum = 0; break; case ParticleSystemSimulationSpace.World: simulationSpaceNum = 1; break; case ParticleSystemSimulationSpace.Custom: simulationSpaceNum = 2; break; } modCommonData.AddField("simulationSpace", simulationSpaceNum); JSONObject emitter = new JSONObject(JSONObject.Type.OBJECT); JSONObject emitterData = new JSONObject(JSONObject.Type.OBJECT); data.AddField("emitter", emitterData); emitterData.AddField("playOnAwake", particleSys.main.playOnAwake); emitterData.AddField("looping", particleSys.main.loop); emitterData.AddField("duration", particleSys.main.duration); emitterData.AddField("startDelay", ParseMinMaxCurve(particleSys.main.startDelay)); if (particleSys.emission.enabled) { JSONObject burst = new JSONObject(JSONObject.Type.ARRAY); emitterData.AddField("bursts", burst); int count = particleSys.emission.burstCount; ParticleSystem.Burst[] bursts = new ParticleSystem.Burst[count]; particleSys.emission.GetBursts(bursts); for (int i = 0; i < count; i++) { //burst.Add(ParseBurst(particleSys.emission.GetBurst(i))); burst.Add(ParseBurst(bursts[i])); } emitterData.AddField("rateOverTime", ParseMinMaxCurve(particleSys.emission.rateOverTime)); } emitterData.AddField("maxParticles", particleSys.main.maxParticles); if (particleSystemRenderer.enabled) { JSONObject renderer = new JSONObject(JSONObject.Type.OBJECT); JSONObject rendererData = new JSONObject(JSONObject.Type.OBJECT); data.AddField("renderer", rendererData); ParticleSystemRenderMode pRenderMode = particleSystemRenderer.renderMode; int pRenderModeNum = 0; switch (pRenderMode) { case ParticleSystemRenderMode.Billboard: pRenderModeNum = 1; break; case ParticleSystemRenderMode.Stretch: pRenderModeNum = 2; rendererData.AddField("cameraScale", particleSystemRenderer.cameraVelocityScale); rendererData.AddField("speedScale", particleSystemRenderer.velocityScale); rendererData.AddField("lengthScale", particleSystemRenderer.lengthScale); break; case ParticleSystemRenderMode.HorizontalBillboard: pRenderModeNum = 3; break; case ParticleSystemRenderMode.VerticalBillboard: pRenderModeNum = 4; break; case ParticleSystemRenderMode.Mesh: Mesh mesh = particleSystemRenderer.mesh; if (mesh != null) { WXMesh meshConverter = new WXMesh(mesh); string meshPath = meshConverter.Export(context.preset); rendererData.AddField("mesh", meshPath); rendererData.AddField("meshCount", particleSystemRenderer.meshCount); context.AddResource(meshPath); } else { Debug.LogError(string.Format("{0} mesh is null", particleSys.name)); } pRenderModeNum = 5; break; case ParticleSystemRenderMode.None: pRenderModeNum = 0; break; default: pRenderModeNum = 1; break; } rendererData.AddField("renderMode", pRenderModeNum); int mode = 1; switch (particleSystemRenderer.alignment) { case ParticleSystemRenderSpace.View: mode = 1; break; case ParticleSystemRenderSpace.World: mode = 2; break; case ParticleSystemRenderSpace.Local: mode = 3; break; case ParticleSystemRenderSpace.Facing: mode = 4; break; #if UNITY_2017_1_OR_NEWER case ParticleSystemRenderSpace.Velocity: mode = 5; break; #endif default: break; } rendererData.AddField("renderAlignment", mode); mode = 0; switch (particleSystemRenderer.sortMode) { case ParticleSystemSortMode.None: mode = 0; break; case ParticleSystemSortMode.Distance: mode = 1; break; case ParticleSystemSortMode.OldestInFront: mode = 2; break; case ParticleSystemSortMode.YoungestInFront: mode = 3; break; default: break; } rendererData.AddField("sortMode", mode); rendererData.AddField("sortingFudge", particleSystemRenderer.sortingFudge); rendererData.AddField("normalDirection", particleSystemRenderer.normalDirection); rendererData.AddField("minParticleSize", particleSystemRenderer.minParticleSize); rendererData.AddField("maxParticleSize", particleSystemRenderer.maxParticleSize); var flipValue = TryGetContainProperty(particleSystemRenderer, "flip"); if (flipValue != null) { rendererData.AddField("flip", GetVect3((Vector3)flipValue)); } else { renderer.AddField("flip", GetVect3(new Vector3(0, 0, 0))); } //rendererData.AddField("flip", GetVect3(particleSystemRenderer.flip)); rendererData.AddField("pivot", GetVect3(particleSystemRenderer.pivot)); var allowRollData = TryGetContainProperty(particleSystemRenderer, "allowRoll"); if (allowRollData != null) { rendererData.AddField("allowRoll", (bool)allowRollData); } else { rendererData.AddField("allowRoll", false); } } else { String info = "entity: " + particleSys.gameObject.name + " 的粒子组件没有renderer模块,不可导出;请加上renderer模块,或删除该粒子组件"; ErrorUtil.ExportErrorReporter.create() .setGameObject(particleSys.gameObject) .setHierarchyContext(context) .error(0, "粒子组件没有renderer模块,不可导出;请加上renderer模块,或删除该粒子组件"); } if (particleSys.rotationOverLifetime.enabled) { JSONObject rotationByLife = new JSONObject(JSONObject.Type.OBJECT); JSONObject rotationByLifeData = new JSONObject(JSONObject.Type.OBJECT); data.AddField("rotationByLife", rotationByLifeData); rotationByLifeData.AddField("separateAxes", particleSys.rotationOverLifetime.separateAxes); if (particleSys.rotationOverLifetime.separateAxes) { rotationByLifeData.AddField("x", ParseMinMaxCurve(particleSys.rotationOverLifetime.x, (float)(180 / Math.PI))); rotationByLifeData.AddField("y", ParseMinMaxCurve(particleSys.rotationOverLifetime.y, (float)(180 / Math.PI))); rotationByLifeData.AddField("z", ParseMinMaxCurve(particleSys.rotationOverLifetime.z, (float)(180 / Math.PI))); } else { rotationByLifeData.AddField("z", ParseMinMaxCurve(particleSys.rotationOverLifetime.z, (float)(180 / Math.PI))); } } if (particleSys.sizeOverLifetime.enabled) { JSONObject sizeOverLifetime = new JSONObject(JSONObject.Type.OBJECT); JSONObject sizeOverLifetimeData = new JSONObject(JSONObject.Type.OBJECT); data.AddField("sizeByLife", sizeOverLifetimeData); sizeOverLifetimeData.AddField("separateAxes", particleSys.sizeOverLifetime.separateAxes); if (particleSys.sizeOverLifetime.separateAxes) { sizeOverLifetimeData.AddField("x", ParseMinMaxCurve(particleSys.sizeOverLifetime.x)); sizeOverLifetimeData.AddField("y", ParseMinMaxCurve(particleSys.sizeOverLifetime.y)); sizeOverLifetimeData.AddField("z", ParseMinMaxCurve(particleSys.sizeOverLifetime.z)); } else { sizeOverLifetimeData.AddField("x", ParseMinMaxCurve(particleSys.sizeOverLifetime.size)); } } if (particleSys.velocityOverLifetime.enabled) { JSONObject speedByLifeData = new JSONObject(JSONObject.Type.OBJECT); data.AddField("speedByLife", speedByLifeData); switch (particleSys.velocityOverLifetime.space) { case ParticleSystemSimulationSpace.Local: speedByLifeData.AddField("space", 1); break; case ParticleSystemSimulationSpace.World: speedByLifeData.AddField("space", 2); break; case ParticleSystemSimulationSpace.Custom: break; default: break; } speedByLifeData.AddField("x", ParseMinMaxCurve(particleSys.velocityOverLifetime.x)); speedByLifeData.AddField("y", ParseMinMaxCurve(particleSys.velocityOverLifetime.y)); speedByLifeData.AddField("z", ParseMinMaxCurve(particleSys.velocityOverLifetime.z)); #if UNITY_2018_1_OR_NEWER speedByLifeData.AddField("orbitalX", ParseMinMaxCurve(particleSys.velocityOverLifetime.orbitalX)); speedByLifeData.AddField("orbitalY", ParseMinMaxCurve(particleSys.velocityOverLifetime.orbitalY)); speedByLifeData.AddField("orbitalZ", ParseMinMaxCurve(particleSys.velocityOverLifetime.orbitalZ)); speedByLifeData.AddField("orbitalOffsetX", ParseMinMaxCurve(particleSys.velocityOverLifetime.orbitalOffsetX)); speedByLifeData.AddField("orbitalOffsetY", ParseMinMaxCurve(particleSys.velocityOverLifetime.orbitalOffsetY)); speedByLifeData.AddField("orbitalOffsetZ", ParseMinMaxCurve(particleSys.velocityOverLifetime.orbitalOffsetZ)); speedByLifeData.AddField("radial", ParseMinMaxCurve(particleSys.velocityOverLifetime.radial)); #endif #if UNITY_2017_1_OR_NEWER speedByLifeData.AddField("speedScale", ParseMinMaxCurve(particleSys.velocityOverLifetime.speedModifier)); #endif } if (particleSys.limitVelocityOverLifetime.enabled) { JSONObject speedLimitByLifeData = new JSONObject(JSONObject.Type.OBJECT); data.AddField("speedLimitByLife", speedLimitByLifeData); speedLimitByLifeData.AddField("separateAxes", particleSys.limitVelocityOverLifetime.separateAxes); if (particleSys.limitVelocityOverLifetime.separateAxes) { speedLimitByLifeData.AddField("x", ParseMinMaxCurve(particleSys.limitVelocityOverLifetime.limitX, particleSys.limitVelocityOverLifetime.limitXMultiplier)); speedLimitByLifeData.AddField("y", ParseMinMaxCurve(particleSys.limitVelocityOverLifetime.limitY, particleSys.limitVelocityOverLifetime.limitYMultiplier)); speedLimitByLifeData.AddField("z", ParseMinMaxCurve(particleSys.limitVelocityOverLifetime.limitZ, particleSys.limitVelocityOverLifetime.limitZMultiplier)); } else { speedLimitByLifeData.AddField("x", ParseMinMaxCurve(particleSys.limitVelocityOverLifetime.limit, particleSys.limitVelocityOverLifetime.limitMultiplier)); } speedLimitByLifeData.AddField("dampen", particleSys.limitVelocityOverLifetime.dampen); switch (particleSys.limitVelocityOverLifetime.space) { case ParticleSystemSimulationSpace.Local: speedLimitByLifeData.AddField("space", 1); break; case ParticleSystemSimulationSpace.World: speedLimitByLifeData.AddField("space", 2); break; case ParticleSystemSimulationSpace.Custom: break; default: break; } #if UNITY_2017_1_OR_NEWER speedLimitByLifeData.AddField("drag", ParseMinMaxCurve(particleSys.limitVelocityOverLifetime.drag)); speedLimitByLifeData.AddField("dragMultiplyBySize", particleSys.limitVelocityOverLifetime.multiplyDragByParticleSize); speedLimitByLifeData.AddField("dragMultiplyBySpeed", particleSys.limitVelocityOverLifetime.multiplyDragByParticleVelocity); #endif } if (particleSys.colorOverLifetime.enabled) { JSONObject colorOverLifetime = new JSONObject(JSONObject.Type.OBJECT); JSONObject colorOverLifetimeData = new JSONObject(JSONObject.Type.OBJECT); data.AddField("colorByLife", colorOverLifetimeData); colorOverLifetimeData.AddField("gColor", ParseMinMaxGradient(particleSys.colorOverLifetime.color)); } if (particleSys.shape.enabled) { JSONObject shapeData = new JSONObject(JSONObject.Type.OBJECT); var haveShape = true; if (particleSys.shape.shapeType == ParticleSystemShapeType.Cone || particleSys.shape.shapeType == ParticleSystemShapeType.ConeVolume || particleSys.shape.shapeType == ParticleSystemShapeType.ConeVolumeShell || particleSys.shape.shapeType == ParticleSystemShapeType.ConeShell) { shapeData.AddField("shape", ParseConeShape(particleSys.shape)); } else if (particleSys.shape.shapeType == ParticleSystemShapeType.Sphere || particleSys.shape.shapeType == ParticleSystemShapeType.SphereShell) { shapeData.AddField("shape", ParseSphereShape(particleSys.shape)); } else if (particleSys.shape.shapeType == ParticleSystemShapeType.Circle || particleSys.shape.shapeType == ParticleSystemShapeType.CircleEdge) { shapeData.AddField("shape", ParseCircleShape(particleSys.shape)); } else if (particleSys.shape.shapeType == ParticleSystemShapeType.Box || particleSys.shape.shapeType == ParticleSystemShapeType.BoxEdge || particleSys.shape.shapeType == ParticleSystemShapeType.BoxShell) { shapeData.AddField("shape", ParseBox(particleSys.shape)); } else if (particleSys.shape.shapeType == ParticleSystemShapeType.Hemisphere || particleSys.shape.shapeType == ParticleSystemShapeType.HemisphereShell) { shapeData.AddField("shape", ParseHemisphere(particleSys.shape)); } // else if (particleSys.shape.shapeType == ParticleSystemShapeType.SingleSidedEdge) { // shapeData.AddField("shape", ParseSingleSidedEdge(particleSys.shape)); // } else { var parentChain = go.name; var parent = go.transform.parent; while (parent) { parentChain += " -> " + parent.gameObject.name; parent = parent.parent; } Debug.LogError("unSupport shape (" + particleSys.shape.shapeType.ToString() + ") at: " + parentChain); haveShape = false; } if (haveShape) { data.AddField("emitterShape", shapeData); } } if (particleSys.textureSheetAnimation.enabled) { JSONObject textureSheetAnimationData = new JSONObject(JSONObject.Type.OBJECT); data.AddField("textureSheetAnimation", textureSheetAnimationData); int mode = 1; #if UNITY_2017_1_OR_NEWER mode = 1; switch (particleSys.textureSheetAnimation.mode) { case ParticleSystemAnimationMode.Grid: mode = 1; break; case ParticleSystemAnimationMode.Sprites: mode = 2; break; default: break; } textureSheetAnimationData.AddField("mode", mode); #endif JSONObject vec2 = new JSONObject(JSONObject.Type.ARRAY); vec2.Add(particleSys.textureSheetAnimation.numTilesX); vec2.Add(particleSys.textureSheetAnimation.numTilesY); textureSheetAnimationData.AddField("tiles", vec2); mode = 1; switch (particleSys.textureSheetAnimation.animation) { case ParticleSystemAnimationType.WholeSheet: mode = 1; break; case ParticleSystemAnimationType.SingleRow: mode = 2; break; default: break; } textureSheetAnimationData.AddField("animationType", mode); textureSheetAnimationData.AddField("randomRow", particleSys.textureSheetAnimation.useRandomRow); textureSheetAnimationData.AddField("row", particleSys.textureSheetAnimation.rowIndex); //mode = 1; //switch (particleSys.textureSheetAnimation.timeMode) //{ // case ParticleSystemAnimationTimeMode.Lifetime: // mode = 1; // break; // case ParticleSystemAnimationTimeMode.Speed: // mode = 2; // break; // case ParticleSystemAnimationTimeMode.FPS: // mode = 3; // break; // default: // break; //} textureSheetAnimationData.AddField("timeMode", 1); if (mode == 1) { textureSheetAnimationData.AddField("frameOverTime", ParseMinMaxCurve(particleSys.textureSheetAnimation.frameOverTime, particleSys.textureSheetAnimation.numTilesX * particleSys.textureSheetAnimation.numTilesY)); } else { textureSheetAnimationData.AddField("frameOverTime", ParseMinMaxCurve(particleSys.textureSheetAnimation.frameOverTime, particleSys.textureSheetAnimation.numTilesX)); } textureSheetAnimationData.AddField("startFrame", ParseMinMaxCurve(particleSys.textureSheetAnimation.startFrame)); textureSheetAnimationData.AddField("cycles", particleSys.textureSheetAnimation.cycleCount); mode = 0; var a = particleSys.textureSheetAnimation.uvChannelMask; var b = a & UVChannelFlags.UV0; if ((a & UVChannelFlags.UV0) != 0) { mode += 1; } if ((a & UVChannelFlags.UV1) != 0) { mode += 2; } if ((a & UVChannelFlags.UV2) != 0) { mode += 3; } if ((a & UVChannelFlags.UV3) != 0) { mode += 4; } textureSheetAnimationData.AddField("affectedUVChannels", mode); } if (particleSys.subEmitters.enabled) { JSONObject subEmittersData = new JSONObject(JSONObject.Type.ARRAY); data.AddField("subEmitters", subEmittersData); int count = particleSys.subEmitters.subEmittersCount; for (int i = 0; i < count; i++) { ParticleSystemSubEmitterProperties properties = particleSys.subEmitters.GetSubEmitterProperties(i); ParticleSystemSubEmitterType type = particleSys.subEmitters.GetSubEmitterType(i); JSONObject res = new JSONObject(JSONObject.Type.OBJECT); int typeNum = 0; switch (type) { case ParticleSystemSubEmitterType.Birth: typeNum = 0; break; case ParticleSystemSubEmitterType.Collision: typeNum = 1; break; case ParticleSystemSubEmitterType.Death: typeNum = 2; break; default: break; } res.AddField("type", typeNum); int propertiesNum = 0; switch (properties) { case ParticleSystemSubEmitterProperties.InheritNothing: propertiesNum = 0; break; case ParticleSystemSubEmitterProperties.InheritEverything: propertiesNum = 1; break; case ParticleSystemSubEmitterProperties.InheritColor: propertiesNum = 2; break; case ParticleSystemSubEmitterProperties.InheritSize: propertiesNum = 3; break; case ParticleSystemSubEmitterProperties.InheritRotation: propertiesNum = 4; break; default: break; } res.AddField("properties", propertiesNum); subEmittersData.Add(res); } } return(json); }
public JSONObject ToJSON() { // 创建json对象 JSONObject json = new JSONObject(JSONObject.Type.OBJECT); json.AddField("name", name); if (isPrefabNodeInParentInstance) { json.AddField("__type", "prefabNode"); json.AddField("__prefab", prefabPath); } if (isNestedPrefabRoot) { json.AddField("__type", "nestedPrefabRoot"); json.AddField("__prefab", prefabPath); json.AddField("__prefabInstanceFileId", prefabRootInstanceFileId.ToString()); } if (isOutermostPrefabRoot) { json.AddField("__type", "outermostPrefabRoot"); json.AddField("__prefab", prefabPath); json.AddField("__prefabInstanceFileId", prefabRootInstanceFileId.ToString()); } json.AddField("__fileId", fileIdInOriginalSource.ToString()); if (children.Count > 0) { // 如果有一个子元素,就创建json数组 JSONObject childrenArray = new JSONObject(JSONObject.Type.ARRAY); foreach (WXEntity go in children) { childrenArray.Add(go.arrayId); } json.AddField("children", childrenArray); } if (components.Count > 0) { JSONObject componentsArray = new JSONObject(JSONObject.Type.ARRAY); foreach (int comp in components) { componentsArray.Add(comp); } json.AddField("components", componentsArray); } JSONObject data = json.GetField("data"); if (data != null) { data.AddField("active", active); data.AddField("layer", gameObject == null ? 0 : gameObject.layer); } else { JSONObject newData = new JSONObject(JSONObject.Type.OBJECT); newData.AddField("active", active); newData.AddField("layer", gameObject == null ? 0 : gameObject.layer); json.AddField("data", newData); } //if (isExtraEntity && !isNguiChild) //{ // json = new JSONObject(JSONObject.Type.BAKED); //} return(json); }
private JSONObject ParseConeShape(ParticleSystem.ShapeModule shape) { JSONObject res = new JSONObject(JSONObject.Type.OBJECT); JSONObject data = new JSONObject(JSONObject.Type.OBJECT); res.AddField("type", "ParticleConeShape"); res.AddField("data", data); data.AddField("angle", shape.angle); data.AddField("radius", shape.radius); data.AddField("arc", shape.arc); #if UNITY_2017_1_OR_NEWER data.AddField("arcMode", GetArcMode(shape)); data.AddField("arcSpread", shape.arcSpread); data.AddField("radiusThickness", shape.radiusThickness); data.AddField("position", GetVect3(shape.position)); data.AddField("rotation", GetVect3(shape.rotation)); data.AddField("scale", GetVect3(shape.scale)); #endif data.AddField("length", shape.length); int emitfrom = 1; if (shape.shapeType == ParticleSystemShapeType.ConeVolume) { emitfrom = 2; } else if (shape.shapeType == ParticleSystemShapeType.ConeVolumeShell) { emitfrom = 3; data.AddField("radiusThickness", 0); } data.AddField("emitFrom", emitfrom); return(res); }
protected void SetBlendOn(bool on) { m_renderStates.AddField("blendOn", on); }
protected override JSONObject ExportResource(ExportPreset preset) { // 搞配置 string[] lines = System.IO.File.ReadAllLines(unityAssetPath); string pattern = @"^\s+"; JSONObject bitmapFontResource = new JSONObject(JSONObject.Type.OBJECT); JSONObject bitmapFontConfig = new JSONObject(JSONObject.Type.OBJECT); JSONObject currentcharacterConfig = null; string currentIndex = ""; for (int i = 0; i < lines.Length; i++) { string line = Regex.Replace(lines[i], pattern, ""); if (line.StartsWith("mSize")) { string[] array = line.Split(':'); int lineHeight = Int32.Parse(array[1].Trim()); bitmapFontResource.AddField("lineHeight", lineHeight); } else if (line.StartsWith("mBase")) { string[] array = line.Split(':'); int fontSize = Int32.Parse(array[1].Trim()); bitmapFontResource.AddField("fontSize", fontSize); } else if (line.StartsWith("mWidth")) { string[] array = line.Split(':'); int width = Int32.Parse(array[1].Trim()); bitmapFontResource.AddField("width", width); } else if (line.StartsWith("mHeight")) { string[] array = line.Split(':'); int height = Int32.Parse(array[1].Trim()); bitmapFontResource.AddField("height", height); } if (line.StartsWith("- index")) { if (currentcharacterConfig) { bitmapFontConfig.AddField(currentIndex, currentcharacterConfig); currentcharacterConfig = null; } JSONObject characterConfig = new JSONObject(JSONObject.Type.OBJECT); string index = line.Replace("- index: ", ""); currentcharacterConfig = characterConfig; currentIndex = index; } else if (currentcharacterConfig) { string[] array = line.Split(':'); string key = array[0].Trim(); if (key == "x" || key == "y" || key == "width" || key == "height" || key == "offsetX" || key == "offsetY" || key == "advance" || key == "channel") { int value = Int32.Parse(array[1].Trim()); currentcharacterConfig.AddField(key, value); } } } if (currentcharacterConfig) { bitmapFontConfig.AddField(currentIndex, currentcharacterConfig); } Texture2D unityTexture = _bitmapFont.material.mainTexture as Texture2D; string wxbbTextureID = AddDependencies(new WXTexture(unityTexture)); List <string> dependencyResource = new List <string>(); dependencyResource.Add(wxbbTextureID); bitmapFontResource.AddField("frames", bitmapFontConfig); bitmapFontResource.AddField("texture", wxbbTextureID); bitmapFontResource.AddField("version", 2); return(bitmapFontResource); }
public static JSONObject getMeta (Texture tex) { var res = new JSONObject (JSONObject.Type.OBJECT); res.AddField ("width", tex.width); res.AddField ("height", tex.height); if (tex is Texture2D) { res.AddField ("mipmap", ((Texture2D) tex).mipmapCount); } else if (tex is Cubemap) { res.AddField ("mipmap", ((Cubemap) tex).mipmapCount); } else { res.AddField ("mipmap", 1); } bool m_useMipmap = false; bool m_sRGB = false; if (tex is Texture2D) { AssetImporter importer = TextureImporter.GetAtPath(AssetDatabase.GetAssetPath(tex.GetInstanceID())); if (importer is TextureImporter || importer == null) { TextureImporter textureImporter = (TextureImporter)importer; m_useMipmap = importer == null ? false : textureImporter.mipmapEnabled; m_sRGB = importer == null ? false : textureImporter.sRGBTexture; } else { ErrorUtil.ExportErrorReporter.create() .error(ErrorUtil.ErrorCode.Texture_TypeUnsupported, "遇到了不支持的纹理类型:" + AssetDatabase.GetAssetPath(tex.GetInstanceID())); } } res.AddField ("useMipmap", m_useMipmap); res.AddField ("sRGB", m_sRGB); res.AddField ("needPremultiplyAlpha", false); #if UNITY_2017_1_OR_NEWER res.AddField ("wrapU", ResolveTextureWrapMode (tex.wrapModeU)); res.AddField ("wrapV", ResolveTextureWrapMode (tex.wrapModeV)); #else res.AddField ("wrapU", ResolveTextureWrapMode (tex.wrapMode)); res.AddField ("wrapV", ResolveTextureWrapMode (tex.wrapMode)); #endif FilterMode minF = tex.filterMode; if (minF == FilterMode.Bilinear) { res.AddField ("filterMode", 1); } if (minF == FilterMode.Point) { res.AddField ("filterMode", 0); } if (minF == FilterMode.Trilinear) { if (m_useMipmap) { res.AddField ("filterMode", 2); } else { res.AddField ("filterMode", 0); } } res.AddField ("anisoLevel", tex.anisoLevel); var sformat = ResolveTexturePixelFormat (GetTextureFormat (tex)); res.AddField ("pixelFormat", sformat); return res; }
protected override JSONObject ExportResource(ExportPreset preset) { if (avatar.isHuman) { isHuman = GetHumanDescription(avatar, ref desc); if (isHuman) { foreach (var pair in desc.human) { humanMap.Add(pair.humanName, pair.boneName); } } } JSONObject avatarJSON = new JSONObject(JSONObject.Type.OBJECT); /* * { * avatar:{ * path, * linkSprites * } * } */ int id = -2; // GetAvatarNodeData(gameObject, rootNode, gameObject, ref id); bool succ = false; JSONObject avatarRootNodeJSON = GetAvatarRootNodeJSON(gameObject, gameObject, ref id, ref succ); if (avatarRootNodeJSON == null) { return(null); } JSONObject paths = new JSONObject(JSONObject.Type.ARRAY); AssetImporter importer = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(avatar.GetInstanceID())); ModelImporter mImporter = importer as ModelImporter; if (mImporter != null) { for (int k = 0; k < mImporter.extraExposedTransformPaths.Length; k++) { paths.Add(mImporter.extraExposedTransformPaths[k]); } } avatarJSON.AddField("version", "1"); avatarJSON.AddField("rootNode", avatarRootNodeJSON); avatarJSON.AddField("optimized", mImporter.optimizeGameObjects); string avatarPath = Path.GetFullPath(Directory.GetParent(Application.dataPath) + "/" + AssetDatabase.GetAssetPath(avatar.GetInstanceID())); float scale = (Path.GetExtension(avatarPath).ToLower() == ".fbx" && mImporter.useFileUnits) ? 0.01f : 1.0f; avatarJSON.AddField("scaleFactor", succ ? scale : 1.0f); avatarJSON.AddField("paths", paths); avatarJSON.AddField("version", 2); // 在importsetting里关联fbx文件 if (Path.GetExtension(avatarPath).ToLower() == ".fbx") { importSetting = new JSONObject(); WXRawResource fbx = new WXRawResource(AssetDatabase.GetAssetPath(avatar.GetInstanceID())); string fbxExportedPath = fbx.Export(preset); importSetting.AddField("associateFbx", fbxExportedPath); AddDependencies(fbxExportedPath); } return(avatarJSON); }
protected override JSONObject ToJSON(WXHierarchyContext context) { JSONObject json = new JSONObject(JSONObject.Type.OBJECT); JSONObject data = new JSONObject(JSONObject.Type.OBJECT); json.AddField("type", getTypeName()); json.AddField("data", data); data.AddField("active", true); data.AddField("ref", context.AddComponent(new WXUIButton(uiButton, go, entity), uiButton)); JSONObject onClick = new JSONObject(JSONObject.Type.ARRAY); data.AddField("onClick", onClick); JSONObject colorPressed = new JSONObject(JSONObject.Type.ARRAY); colorPressed.Add(255f * uiButton.pressed.r); colorPressed.Add(255f * uiButton.pressed.g); colorPressed.Add(255f * uiButton.pressed.b); colorPressed.Add(255f * uiButton.pressed.a); data.AddField("pressedColor", colorPressed); JSONObject colorDisabledColor = new JSONObject(JSONObject.Type.ARRAY); colorDisabledColor.Add(255f * uiButton.disabledColor.r); colorDisabledColor.Add(255f * uiButton.disabledColor.g); colorDisabledColor.Add(255f * uiButton.disabledColor.b); colorDisabledColor.Add(255f * uiButton.disabledColor.a); data.AddField("disabledColor", colorDisabledColor); if (uiButton.tweenTarget != null) { JSONObject colorNormal = new JSONObject(JSONObject.Type.ARRAY); var mWidget = uiButton.tweenTarget.GetComponent <UIWidget>(); colorNormal.Add(255f * mWidget.color.r); colorNormal.Add(255f * mWidget.color.g); colorNormal.Add(255f * mWidget.color.b); colorNormal.Add(255f * mWidget.color.a); data.AddField("normalColor", colorNormal); } // onClick // onClick.AddField(""); foreach (var click in uiButton.onClick) { var __onClick = new JSONObject(JSONObject.Type.OBJECT); // var target = new JSONObject(JSONObject.Type.OBJECT); // target.AddField(click.target.GetType().FullName.EscapeNamespaceSimple(), context.AddComponent(new WXEngineMonoBehaviour(click.target), click.target)); // onClick.AddField("target", WXMonoBehaviourPropertiesHandler.InvokePropertyHandler(typeof(UnityEngine.MonoBehaviour), click.target, context)); __onClick.AddField("target", context.AddComponent(new WXEngineMonoBehaviour(click.target), click.target)); __onClick.AddField("method", click.methodName); var _params = new JSONObject(JSONObject.Type.ARRAY); __onClick.AddField("params", _params); if (click.parameters != null) { foreach (var p in click.parameters) { if (p.obj != null) { _params.Add(WXMonoBehaviourPropertiesHandler.InvokePropertyHandler(p.expectedType, p.obj, context)); } } } onClick.Add(__onClick); } return(json); }
protected override JSONObject ToJSON(WXHierarchyContext context) { if (uiSprite != null) { //if (uiSprite.isAnchored) //{ // JSONObject anchorJson = new JSONObject(JSONObject.Type.OBJECT); // anchorJson.AddField("type", "UIWidget"); // JSONObject anchorSubJSON = new JSONObject(JSONObject.Type.OBJECT); // anchorSubJSON.AddField("leftMargin", uiSprite.leftAnchor.absolute); // anchorSubJSON.AddField("rightMargin", uiSprite.rightAnchor.absolute); // anchorSubJSON.AddField("topMargin", uiSprite.topAnchor.absolute); // anchorSubJSON.AddField("bottomMargin", uiSprite.bottomAnchor.absolute); // anchorJson.AddField("data", anchorSubJSON); //} JSONObject json = new JSONObject(JSONObject.Type.OBJECT); json.AddField("type", "UISprite"); JSONObject subJSON = new JSONObject(JSONObject.Type.OBJECT); JSONObject color = new JSONObject(JSONObject.Type.ARRAY); color.Add(255f * uiSprite.color.r); color.Add(255f * uiSprite.color.g); color.Add(255f * uiSprite.color.b); color.Add(255f * uiSprite.color.a); subJSON.AddField("color", color); subJSON.AddField("colorBlendType", 0); //if (uiSprite.name == "PageBagChecked") //{ // Debug.Log("++==++==++"); // Debug.Log(uiSprite.isAnchored); // Debug.Log(uiSprite.bottomAnchor.absolute); // Debug.Log(uiSprite.bottomAnchor.target.name); //} UI2DSprite.Type type = uiSprite.type; subJSON.AddField("type", (int)type); UI2DSprite.Flip flipType = uiSprite.flip; subJSON.AddField("flip", (int)flipType); subJSON.AddField("fillCenter", uiSprite.centerType == UI2DSprite.AdvancedType.Sliced); subJSON.AddField("fillDir", (int)uiSprite.fillDirection); subJSON.AddField("fillAmount", uiSprite.fillAmount); subJSON.AddField("invertFill", uiSprite.invert); if (uiSprite.atlas != null) { string uuid = WXSpriteFrame.getSprite(uiSprite.atlas, uiSprite.spriteName, context.preset); if (uuid == null) { Debug.LogWarning("获取sprite失败: " + uiSprite.spriteName); } else { context.AddResource(uuid); } if (uuid != null) { subJSON.AddField("spriteFrame", uuid); } else { JSONObject nullJSON = new JSONObject(JSONObject.Type.NULL); subJSON.AddField("spriteFrame", nullJSON); } } else { JSONObject nullJSON = new JSONObject(JSONObject.Type.NULL); subJSON.AddField("spriteFrame", nullJSON); } subJSON.AddField("active", uiSprite.enabled); json.AddField("data", subJSON); return(json); } else { JSONObject json = new JSONObject(JSONObject.Type.OBJECT); json.AddField("type", "UISprite"); JSONObject subJSON = new JSONObject(JSONObject.Type.OBJECT); JSONObject color = new JSONObject(JSONObject.Type.ARRAY); color.Add(255f); color.Add(255f); color.Add(255f); color.Add(255f); subJSON.AddField("color", color); subJSON.AddField("colorBlendType", 0); subJSON.AddField("type", (int)UI2DSprite.Type.Simple); subJSON.AddField("flip", (int)UI2DSprite.Flip.Nothing); subJSON.AddField("fillCenter", false); subJSON.AddField("fillDir", (int)UI2DSprite.FillDirection.Horizontal); subJSON.AddField("fillAmount", 0); subJSON.AddField("invertFill", false); JSONObject nullJSON = new JSONObject(JSONObject.Type.NULL); subJSON.AddField("spriteFrame", nullJSON); subJSON.AddField("active", true); json.AddField("data", subJSON); return(json); } }
private void GetLightConfig(JSONObject propsObj, WXHierarchyContext context) { if (RenderSettings.ambientMode == AmbientMode.Skybox) { propsObj.AddField("ambientMode", 0); } else if (RenderSettings.ambientMode == AmbientMode.Trilight) { propsObj.AddField("ambientMode", 1); } else // if (RenderSettings.ambientMode == AmbientMode.Flat) { propsObj.AddField("ambientMode", 2); } Color ambientLight = RenderSettings.ambientLight; JSONObject ambientLightObj = new JSONObject(JSONObject.Type.ARRAY); ambientLightObj.Add(ambientLight.r); ambientLightObj.Add(ambientLight.g); ambientLightObj.Add(ambientLight.b); propsObj.AddField("ambientColor", ambientLightObj); propsObj.AddField("ambientIntensity", RenderSettings.ambientIntensity); JSONObject ambientSkyColorObj = new JSONObject(JSONObject.Type.ARRAY); ambientSkyColorObj.Add(RenderSettings.ambientSkyColor.r); ambientSkyColorObj.Add(RenderSettings.ambientSkyColor.g); ambientSkyColorObj.Add(RenderSettings.ambientSkyColor.b); ambientSkyColorObj.Add(RenderSettings.ambientSkyColor.a); propsObj.AddField("ambientSkyColor", ambientSkyColorObj); JSONObject ambientEquatorColorObj = new JSONObject(JSONObject.Type.ARRAY); ambientEquatorColorObj.Add(RenderSettings.ambientEquatorColor.r); ambientEquatorColorObj.Add(RenderSettings.ambientEquatorColor.g); ambientEquatorColorObj.Add(RenderSettings.ambientEquatorColor.b); ambientEquatorColorObj.Add(RenderSettings.ambientEquatorColor.a); propsObj.AddField("ambientEquatorColor", ambientEquatorColorObj); JSONObject ambientGroundColorObj = new JSONObject(JSONObject.Type.ARRAY); ambientGroundColorObj.Add(RenderSettings.ambientGroundColor.r); ambientGroundColorObj.Add(RenderSettings.ambientGroundColor.g); ambientGroundColorObj.Add(RenderSettings.ambientGroundColor.b); ambientGroundColorObj.Add(RenderSettings.ambientGroundColor.a); propsObj.AddField("ambientGroundColor", ambientGroundColorObj); object Rs = RenderSettings.defaultReflectionMode; if (RenderSettings.defaultReflectionMode == DefaultReflectionMode.Custom) { //saveCubeMapFile(RenderSettings.customReflection, propsObj, false, null); propsObj.AddField("reflectionIntensity", RenderSettings.reflectionIntensity); } else { propsObj.AddField("reflectionResolution", RenderSettings.defaultReflectionResolution); } // saveLightMapFile(propsObj); propsObj.AddField("fogMode", 0); if (RenderSettings.fog) { JSONObject jSONObject5 = new JSONObject(JSONObject.Type.ARRAY); Color fogColor = RenderSettings.fogColor; jSONObject5.Add(fogColor.r); jSONObject5.Add(fogColor.g); jSONObject5.Add(fogColor.b); propsObj.AddField("fogColor", jSONObject5); propsObj.AddField("fogMode", (int)RenderSettings.fogMode); } if (RenderSettings.fogMode == FogMode.Linear) { propsObj.AddField("fogStart", RenderSettings.fogStartDistance); propsObj.AddField("fogRange", RenderSettings.fogEndDistance - RenderSettings.fogStartDistance); } else { propsObj.AddField("fogDensity", RenderSettings.fogDensity); } if (RenderSettings.skybox != null && WXMaterial.IsMaterialRegistered(RenderSettings.skybox)) { WXMaterial materialConverter = new WXMaterial(RenderSettings.skybox, null); propsObj.AddField("skyBox", AddDependencies(materialConverter)); } else { propsObj.AddField("skyBox", new JSONObject(JSONObject.Type.NULL)); } // lightMapMode JSONObject subtractiveShadowColorObj = new JSONObject(JSONObject.Type.ARRAY); #if UNITY_5_6_OR_NEWER Color subtractiveShadowColor = RenderSettings.subtractiveShadowColor; #else // before 5.5 use default Color Color subtractiveShadowColor = new Color(0.42f, 0.48f, 0.63f, 1f); #endif subtractiveShadowColorObj.Add(subtractiveShadowColor.r); subtractiveShadowColorObj.Add(subtractiveShadowColor.g); subtractiveShadowColorObj.Add(subtractiveShadowColor.b); subtractiveShadowColorObj.Add(subtractiveShadowColor.a); propsObj.AddField("subtractiveShadowColor", subtractiveShadowColorObj); bool shadowMaskFlag = false; JSONObject lightMapDatasObj = new JSONObject(JSONObject.Type.ARRAY); LightmapData[] lightmaps = LightmapSettings.lightmaps; if (lightmaps != null && lightmaps.Length != 0) { for (int i = 0; i < lightmaps.Length; i++) { LightmapData lightmap = lightmaps[i]; JSONObject lightMapDescObj = new JSONObject(JSONObject.Type.OBJECT); #if UNITY_5_6_OR_NEWER if ( lightmap.lightmapColor == null || "" == AssetDatabase.GetAssetPath(lightmap.lightmapColor.GetInstanceID()) ) { continue; } if (lightmap.shadowMask) { shadowMaskFlag = true; WXLightMap textureConverter = new WXLightMap(lightmap.shadowMask); lightMapDescObj.AddField("shadowMask", AddDependencies(textureConverter)); WXLightMap textureConverter2 = new WXLightMap(lightmap.lightmapColor); lightMapDescObj.AddField("color", AddDependencies(textureConverter2)); } else { WXLightMap textureConverter = new WXLightMap(lightmap.lightmapColor); lightMapDescObj.AddField("color", AddDependencies(textureConverter)); } #else if ( lightmap.lightmapLight == null || "" == AssetDatabase.GetAssetPath(lightmap.lightmapLight.GetInstanceID()) ) { continue; } WXLightMap textureConverter = new WXLightMap(lightmap.lightmapLight); lightMapDescObj.AddField("color", AddDependencies(textureConverter)); #endif lightMapDatasObj.Add(lightMapDescObj); } } propsObj.AddField("lightMapDatas", lightMapDatasObj); // 0:subtractive 1:shadowMask propsObj.AddField("lightMapType", shadowMaskFlag ? (int)LightMapType.ShadowMask : (int)LightMapType.Subtractive); // reflection probe JSONObject reflectionCubeDataObj = new JSONObject(JSONObject.Type.ARRAY); List <string> reflectionMaps = ReflectionProbeUtil.getReflectionEquirectangular(scenePath); if (reflectionMaps.Count > 0) { for (int i = 0; i < reflectionMaps.Count; i++) { JSONObject reflectionMapDescObj = new JSONObject(JSONObject.Type.OBJECT); WXEnvironmentMap mapConverter = new WXEnvironmentMap(reflectionMaps[i]); reflectionMapDescObj.AddField("color", AddDependencies(mapConverter)); reflectionCubeDataObj.Add(reflectionMapDescObj); } } propsObj.AddField("panoramaDatas", reflectionCubeDataObj); // Spherical Harmonics JSONObject shDataObj = new JSONObject(JSONObject.Type.ARRAY); var coefficients = new float[9][]; UnityEngine.Rendering.SphericalHarmonicsL2 shs; LightProbes.GetInterpolatedProbe(new UnityEngine.Vector3(), null, out shs); if (shs != null) { for (int i = 0; i < 9; i++) { coefficients[i] = new float[3]; for (var j = 0; j < 3; j++) { coefficients[i][j] = shs[j, i]; Debug.Log(coefficients[i][j]); shDataObj.Add(coefficients[i][j]); } } propsObj.AddField("shCoefficients", shDataObj); } else { Debug.LogWarning("There is no baked light probe."); } }
protected override void DoExport() { var build = DirectoryBuilder.GetDirectory("build"); // check cache var projectDir = new DirectoryInfo(build["Project"].FullPath); // Debug.Log(projectDir.GetFiles().Length); if (!projectDir.Exists || projectDir.GetFiles() == null || projectDir.GetFiles().Length <= 1) { BridgeExport.ExportCodeMenu(); } // convert // BridgeExport.ExportCode(); // EditorUtility.ClearProgressBar(); // BridgeExport.isProcessing = false; EditorUtility.DisplayProgressBar("代码导出", "", 0.0f); var dirPath = BridgeExport.PROJECT_CODE_PATH; var files = Directory.EnumerateFiles(dirPath, "*.js", SearchOption.AllDirectories).ToList(); List <string> allRecursiveAssets = new List <string>(); // all converted scripts var t = 0; foreach (var file in files) { // bridge plugin blacklist var name = Path.GetFileName(file); // Debug.Log(name); // 使用引擎插件不打包这几个文件,以节省代码包体积 if (WXBridge.isWXBridgePlugin && ( name.Equals("minigame-adaptor-lib.js") || name.Equals("minigame-adaptor-lib.meta.js") || name.Equals("minigame-adaptor-lib-patch.js"))) { continue; } JSONObject metadata = new JSONObject(JSONObject.Type.OBJECT); metadata.AddField("version", 1); // string path = Path.GetFullPath(file).Replace(Path.Combine(Application.dataPath.Replace("Assets", ""), "__tmp_dist_script~"), "Assets"); var cutIndex = Path.GetFullPath(file).IndexOf(dirPath) + dirPath.Length + 1; // +1 : '/' string path = Path.GetFullPath(file).Substring(cutIndex).Replace('\\', '/'); // Debug.Log(path); // Debug.Log(file + "===" + path); // Debug.Log(path); string content = File.ReadAllText(file); ExportStore.AddTextFile(path, content, WXUtility.GetMD5FromString(content)); List <string> useFile = new List <string>(); useFile.Add(path); ExportStore.AddResource(path, "script", null, useFile); allRecursiveAssets.Add(path); EditorUtility.DisplayProgressBar("代码导出", "", t++ / files.Count); } // var libs = Directory.EnumerateFiles(Path.Combine(bridgeRootPath, "lib"), "*.lib"); var libs = Directory.EnumerateFiles(DirectoryBuilder.GetDirectory("references")["Adaptor"].FullPath, "*.lib"); // Debug.Log(libs); foreach (var lib in libs) { var name = Path.GetFileName(lib); // Debug.Log(name); // bridge plugin blacklist // 使用引擎插件的情况 if (WXBridge.isWXBridgePlugin) { // 如果使用了插件但是要用自己的adaptor.js,这个文件也要打包 if (!WXBridge.isWXBridgePluginAdaptor) { if (!name.Equals("minigame-adaptor-util.js.lib") && !name.Equals("minigame-adaptor-config.js.lib") && !name.Equals("minigame-adaptor.js.lib")) { continue; } } else { if (!name.Equals("minigame-adaptor-util.js.lib") && !name.Equals("minigame-adaptor-config.js.lib")) { continue; } } } JSONObject metadata = new JSONObject(JSONObject.Type.OBJECT); metadata.AddField("version", 1); string path = name.Substring(0, name.Length - 4); // 配置文件内容根据插件的配置来生成 if (name.Equals("minigame-adaptor-config.js.lib")) { // var content = String.Format("module.exports = {{\r\n userMiniGameAdaptorPlugin:{0},\r\n userMiniGameAdaptorJs:{1},\r\n pluginAlias:'WXBridge'\r\n}}", WXBridge.isWXBridgePlugin ? 1 : 0, WXBridge.isWXBridgePluginAdaptor ? 1 : 0); var content = ScriptExportHelper.ExportGameConfig(); ExportStore.AddTextFile(path, content, WXUtility.GetMD5FromString(content)); } else { string content = File.ReadAllText(lib); ExportStore.AddTextFile(path, content, WXUtility.GetMD5FromString(content)); } List <string> useFile = new List <string>(); useFile.Add(path); ExportStore.AddResource(path, "script", null, useFile); allRecursiveAssets.Add(path); } // game config js // { // JSONObject metadata = new JSONObject(JSONObject.Type.OBJECT); // metadata.AddField("version", 1); // string path = "Assets/bridge_game_config.js"; // JSONObject content = ScriptExportHelper.ExportSceneJson(); // WXExportStore.AddJSONFile(path, content, WXUtility.GetMD5FromString(content.ToString())); // List<string> useFile = new List<string>(); // useFile.Add(path); // WXExportStore.AddResource(path, "script", null, useFile); // allRecursiveAssets.Add(path); // } //string savePath = Path.Combine(SAVE_BASE_PATH, "Scripts.mgepackage/"); //JSONObject manifestRoot = new JSONObject(JSONObject.Type.OBJECT); //manifestRoot.AddField("resourceMeta", exportContext.writeResourcesTo(savePath, allRecursiveAssets)); //wxFileUtil.SaveJsonFile(manifestRoot, savePath + "group.manifest.json"); ExportStore.GenerateResourcePackage( "WXScripts", allRecursiveAssets ); EditorUtility.ClearProgressBar(); Debug.Log("导出工程代码: 1"); }
private void writeResourceRecursive(string resourceDescriptionFilePath) { // 如果已经转换过了 if (packageGroupManifest_resourceDefinitions.HasField(resourceDescriptionFilePath)) { return; } // 先找到之前已经写入缓存表的资源。 JSONObject resourceStorage = storage.GetField("assets").GetField(resourceDescriptionFilePath); if (resourceStorage == null) { Debug.LogError("创建资源包时写入'" + resourceDescriptionFilePath + "'失败,没有找到该资源的转换记录"); return; } // 创建每一个资源definition的json对象 JSONObject definitionObject = new JSONObject(JSONObject.Type.OBJECT); packageGroupManifest_resourceDefinitions.AddField(resourceDescriptionFilePath, definitionObject); // 写入字段 definitionObject.AddField("dependencies", resourceStorage.GetField("dependencies")); definitionObject.AddField("type", resourceStorage.GetField("type")); definitionObject.AddField("descriptionFileID", resourceDescriptionFilePath); // 把记在缓存里的useFile拿出来,遍历,写入group.manifest.json的fileDescription字段 // 并且排除掉resourceDescriptionFilePath之后放入resourceDefinition JSONObject outputUseFileArray = new JSONObject(JSONObject.Type.ARRAY); definitionObject.AddField("useFile", outputUseFileArray); // 放入文件 foreach (string usingFile in WXUtility.ConvertJSONArrayToList(resourceStorage.GetField("useFile"))) { if (usingFile != resourceDescriptionFilePath) { outputUseFileArray.Add(usingFile); } if (packageGroupManifest_fileDescription.HasField(usingFile)) { continue; } JSONObject fileStorage = storage.GetField("files").GetField(usingFile); // add fileDescriptions JSONObject fileDescription = new JSONObject(JSONObject.Type.OBJECT); packageGroupManifest_fileDescription.AddField(usingFile, fileDescription); fileDescription.AddField("path", usingFile); // add files 555 JSONObject fileItem = new JSONObject(JSONObject.Type.OBJECT); fileItem.AddField("path", usingFile); fileItem.AddField("filetype", fileStorage.GetField("filetype")); packageGroupManifest_files.Add(fileItem); wxFileUtil.CopyFile( Path.Combine(storagePath, Path.Combine(CONTENT_FOLDER, fileStorage.GetField("MD5").GetRawString())), Path.Combine(destPath, usingFile) ); } // 递归转依赖 foreach (string dependencyResource in WXUtility.ConvertJSONArrayToList(resourceStorage.GetField("dependencies"))) { writeResourceRecursive(dependencyResource); } }
private byte[] WriteMeshFile(ref JSONObject metadata) { MemoryStream fileStream = new MemoryStream(); //ushort subMeshCount = (ushort)mesh.subMeshCount; string item = meshName; // 分析vertexLayout WXMeshVertexLayout vertexLayout = new WXMeshVertexLayout(mesh); List <Transform> bones = new List <Transform>(); for (int j = 0; j < renderer.bones.Length; j++) { Transform item2 = renderer.bones[j]; if (bones.IndexOf(item2) == -1) { bones.Add(item2); } } //List<VertexData> vertexDatas = new List<VertexData>(); //List<VertexData> boneGroupVertex = new List<VertexData>(); //List<VertexData> vertexDataQueue = new List<VertexData>(); //int[] positionInBoneGroup = new int[3]; //List<int> indiceList = new List<int>(); //List<int> allBoneIndexes = new List<int>(); //List<int> vertexUsingBone = new List<int>(); //VertexData vertexData; //for (int i = 0; i < subMeshCount; i++) //{ // int[] indices = mesh.GetIndices(i); // for (int indiceIter = 0; indiceIter < indices.Length; indiceIter += 3) // { // // indice start // for (int k = 0; k < 3; k++) // { // int indiceIndex = indiceIter + k; // int vertexIndex = indices[indiceIndex]; // positionInBoneGroup[k] = -1; // int ii = 0; // while (ii < boneGroupVertex.Count) // { // if (boneGroupVertex[ii].index == vertexIndex) // { // positionInBoneGroup[k] = ii; // break; // } // ii++; // continue; // } // if (positionInBoneGroup[k] == -1) // { // vertexData = getVertexData(mesh, vertexIndex, vertexLayout); // vertexDataQueue.Add(vertexData); // // 每个点最多关联4根骨骼,所以遍历4下 // for (ii = 0; ii < 4; ii++) // { // float bone = vertexData.boneIndex[ii]; // if (allBoneIndexes.IndexOf((int)bone) == -1 && vertexUsingBone.IndexOf((int)bone) == -1) // { // vertexUsingBone.Add((int)bone); // } // } // } // } // // 没到达最大骨骼数 目前不知道这个24最大骨骼限制是干嘛用的 // if (allBoneIndexes.Count + vertexUsingBone.Count <= MaxBoneCount) // { // for (int l = 0; l < vertexUsingBone.Count; l++) // { // allBoneIndexes.Add(vertexUsingBone[l]); // } // int num8 = 1; // for (int l = 0; l < 3; l++) // { // if (positionInBoneGroup[l] == -1) // { // indiceList.Add(vertexDatas.Count + boneGroupVertex.Count - 1 + num8++); // } // else // { // indiceList.Add(vertexDatas.Count + positionInBoneGroup[l]); // } // } // for (int l = 0; l < vertexDataQueue.Count; l++) // { // boneGroupVertex.Add(vertexDataQueue[l]); // } // } // else // { // for (int l = 0; l < boneGroupVertex.Count; l++) // { // vertexDatas.Add(boneGroupVertex[l]); // } // // 回退一位? // indiceIter -= 3; // boneGroupVertex = new List<VertexData>(); // allBoneIndexes = new List<int>(); // } // // 最后一个face了 // if (indiceIter + 3 == indices.Length) // { // for (int l = 0; l < boneGroupVertex.Count; l++) // { // vertexDatas.Add(boneGroupVertex[l]); // } // boneGroupVertex = new List<VertexData>(); // allBoneIndexes = new List<int>(); // } // vertexUsingBone = new List<int>(); // vertexDataQueue = new List<VertexData>(); // // indice end // } //} long vertexStart = 0L; long vertexLength = 0L; long indiceStart = 0L; long indiceLength = 0L; long boneEndPosition = 0L; // 记录vertexBuffer在总buffer里的起始位置,一般是0 vertexStart = fileStream.Position; // 用于算包围球,计算模型的重心(所有点的位置均值) Vector3 vertexPositionAddup = new Vector3(0, 0, 0); // 遍历mesh里的所有定点 for (int j = 0; j < mesh.vertexCount; j++) { Vector3 vector = mesh.vertices[j]; // 写入position wxFileUtil.WriteData(fileStream, vector.x * -1f, vector.y, vector.z); // 统计position,用于算包围盒 vertexPositionAddup.Set(vertexPositionAddup.x + vector.x * -1f, vertexPositionAddup.y + vector.y, vertexPositionAddup.z + vector.z); // 如果vertexLayout有normal,写入normal if (vertexLayout.NORMAL) { Vector3 vector2 = mesh.normals[j]; wxFileUtil.WriteData(fileStream, vector2.x * -1f, vector2.y, vector2.z); } // 如果vertexLayout有color,写入color if (vertexLayout.COLOR) { Color color = mesh.colors[j]; wxFileUtil.WriteData(fileStream, color.r, color.g, color.b, color.a); } // 如果vertexLayout有uv,写入uv if (vertexLayout.UV) { Vector2 vector3 = mesh.uv[j]; wxFileUtil.WriteData(fileStream, vector3.x, vector3.y * -1f + 1f); } // 如果vertexLayout有uv1,写入uv1 if (vertexLayout.UV1) { Vector2 vector4 = mesh.uv2[j]; wxFileUtil.WriteData(fileStream, vector4.x, vector4.y * -1f + 1f); } if (vertexLayout.BONE) { BoneWeight boneWeight = mesh.boneWeights[j]; wxFileUtil.WriteData( fileStream, boneWeight.weight0, boneWeight.weight1, boneWeight.weight2, boneWeight.weight3 ); wxFileUtil.WriteData( fileStream, (float)boneWeight.boneIndex0, (float)boneWeight.boneIndex1, (float)boneWeight.boneIndex2, (float)boneWeight.boneIndex3 ); } // 如果vertexLayout有tangent,写入tangent if (vertexLayout.TANGENT) { Vector4 vector5 = mesh.tangents[j]; wxFileUtil.WriteData(fileStream, vector5.x * -1f, vector5.y, vector5.z, vector5.w); } } // 记录vertexBuffer在buffer里的结束位置 vertexLength = fileStream.Position - vertexStart; // 记录indiceBuffer在buffer里的起始位置 indiceStart = fileStream.Position; // indiceBuffer指的是给模型绘制面时,每个面所用的顶点index。在unity里叫triangles int[] triangles = mesh.triangles; for (int j = 0; j < triangles.Length; j++) { wxFileUtil.WriteData(fileStream, (ushort)triangles[j]); } // 记录indexBuffer在buffer里的结束位置 indiceLength = fileStream.Position - indiceStart; // 因为读取的时候是根据4位来读的所以末尾补0 long isFour = indiceLength % 4; if (isFour != 0) { wxFileUtil.WriteData(fileStream, (ushort)0.0); } long boneStartPosition = fileStream.Position; if (mesh.bindposes != null && mesh.bindposes.Length != 0) { Matrix4x4[] bonePoses = new Matrix4x4[mesh.bindposes.Length]; for (int i = 0; i < mesh.bindposes.Length; i++) { bonePoses[i] = mesh.bindposes[i]; bonePoses[i] = bonePoses[i].inverse; Vector3 s = default(Vector3); Quaternion q = default(Quaternion); Vector3 pos = default(Vector3); MathUtil.Decompose(bonePoses[i].transpose, out s, out q, out pos); pos.x *= -1f; q.x *= -1f; q.w *= -1f; bonePoses[i] = Matrix4x4.TRS(pos, q, s); } for (int i = 0; i < mesh.bindposes.Length; i++) { Matrix4x4 matrix4x = bonePoses[i]; } for (int i = 0; i < mesh.bindposes.Length; i++) { Matrix4x4 inverse = bonePoses[i].inverse; for (int j = 0; j < 16; j++) { wxFileUtil.WriteData(fileStream, inverse[j]); } } boneEndPosition = fileStream.Position; } long bonePoseLength = boneEndPosition - boneStartPosition; fileStream.Close(); metadata.AddField("indiceFormat", 1); // BIT16 = 1,BIT32 = 2 metadata.AddField("vertexLayout", vertexLayout.GetLayoutString()); //"POSITION,NORMAL,COLOR,UV,BLENDWEIGHT,BLENDINDICES,TANGENT", metadata.AddField("vertexStart", 0); metadata.AddField("vertexLength", vertexLength); metadata.AddField("indiceStart", vertexLength); // indice的偏移量 metadata.AddField("indiceLength", indiceLength); // indice的长度 metadata.AddField("bonePoseStart", boneStartPosition); metadata.AddField("bonePoseLength", bonePoseLength); metadata.AddField("capsule", GetCapsule()); bool succ = false; JSONObject bonesObject = GetSkinPaths(renderer.sharedMesh.name, ref succ); metadata.AddField("rootBone", bonesObject.GetField("root")); metadata.AddField("bones", bonesObject.GetField("bones")); metadata.AddField("version", 1); // 加入submesh JSONObject subMeshs = new JSONObject(JSONObject.Type.ARRAY); #if !UNITY_2017_1_OR_NEWER int indexStart = 0; #endif ushort subMeshCount = (ushort)mesh.subMeshCount; for (int i = 0; i < subMeshCount; i++) { JSONObject subMeshObj = new JSONObject(JSONObject.Type.OBJECT); #if !UNITY_2017_1_OR_NEWER subMeshObj.AddField("start", indexStart); subMeshObj.AddField("length", mesh.GetIndices(i).Length); indexStart += mesh.GetIndices(i).Length; #else subMeshObj.AddField("start", mesh.GetIndexStart(i)); subMeshObj.AddField("length", mesh.GetIndexCount(i)); #endif subMeshs.Add(subMeshObj); } // submesh一般指的是mesh里的其中一部分,所以用indiceBuffer的区间表示 metadata.AddField("subMeshs", subMeshs); return(fileStream.ToArray()); }