Example #1
0
        protected static void Init(MeshFilter meshFilter, Mesh untessellatedMesh)
        {
            if (!Directory.Exists(FBSConstants.BasePath + "/Cache/"))
            {
                Directory.CreateDirectory(FBSConstants.BasePath + "/Cache/");
            }
            if (!Directory.Exists(FBSConstants.BasePath + "/BVHCache/"))
            {
                Directory.CreateDirectory(FBSConstants.BasePath + "/BVHCache/");
            }

            if (meshFilter.sharedMesh == null)
            {
                Debug.LogWarning(meshFilter.gameObject.GetPath() + " is missing its source mesh");
                return;
            }
            s_debugState = BakeData.Instance().GetDebugState();

#if _DAYDREAM_STATIC_LIGHTING_DEBUG
            DateTime start = DateTime.Now;

            // if we still have a handle for some reason try to free it
            if (s_lastInstanceId != meshFilter.GetUniqueId())
            {
                if (s_bvhHandle != null)
                {
                    VertexBakerLib.Instance.FreeHandle(s_bvhHandle.Ptr());
                }
                s_bvhHandle = null;

                BuildWorldVertices(meshFilter);

                s_debugState.m_tessFaces = null;
            }

            TryLoadBVH(meshFilter);

            s_lastInstanceId = meshFilter.GetUniqueId();

            if (s_bvhWrapper == null)
            {
                s_bvhWrapper = new BVHNode_FBWrapper();
            }

            string sourceAssetPath = AssetDatabase.GetAssetPath(untessellatedMesh);
            if (!string.IsNullOrEmpty(sourceAssetPath) && !Application.isPlaying)
            {
                Debug.LogWarning("Could not find asset " + untessellatedMesh.name + " the asset may be an instance. Some debug data may not be available.");
            }

            string path = BVH.ConvertMeshIdToBVHPath(s_lastInstanceId);
            s_bvhWrapper.SetPath(path);
            s_bvhWrapper.Validate();

            s_cacheWrapper.SetPath("" + s_lastInstanceId);
            s_cacheWrapper.Validate();

            VertexBakerLib.Log("Debug setup time: " + (DateTime.Now - start).TotalSeconds + " seconds");
#endif
        }
        public bool DrawColorCube(Color px, Color nx, Color py, Color ny, Color pz, Color nz, bool updateSettings = true)
        {
            bool         changed  = false;
            BakeSettings settings = BakeData.Instance().GetBakeSettings().SelectedBakeSet;

            Color newColor   = px;
            int   labelWidth = 25;

            if (DrawCubeColor("+X", labelWidth, px, out newColor))
            {
                changed = true;
                if (updateSettings)
                {
                    settings.SetColorCubeFace(Face.PosX, newColor);
                }
            }
            if (DrawCubeColor("-X", labelWidth, nx, out newColor))
            {
                changed = true;
                if (updateSettings)
                {
                    settings.SetColorCubeFace(Face.NegX, newColor);
                }
            }
            if (DrawCubeColor("+Y", labelWidth, py, out newColor))
            {
                changed = true;
                if (updateSettings)
                {
                    settings.SetColorCubeFace(Face.PosY, newColor);
                }
            }
            if (DrawCubeColor("-Y", labelWidth, ny, out newColor))
            {
                changed = true;
                if (updateSettings)
                {
                    settings.SetColorCubeFace(Face.NegY, newColor);
                }
            }
            if (DrawCubeColor("+Z", labelWidth, pz, out newColor))
            {
                changed = true;
                if (updateSettings)
                {
                    settings.SetColorCubeFace(Face.PosZ, newColor);
                }
            }
            if (DrawCubeColor("-Z", labelWidth, nz, out newColor))
            {
                changed = true;
                if (updateSettings)
                {
                    settings.SetColorCubeFace(Face.NegZ, newColor);
                }
            }

            return(changed);
        }
        public static void OnSceneChange()
        {
            // create import settings
            BakeData.Instance().GetImportSettings();

            MaterialInfo.m_targets.Clear();
            Configure();
        }
        public static void OnSceneChange()
        {
            BakeData.Instance().GetBakeSettings();

            if (m_ignoreNextChange)
            {
                m_ignoreNextChange = false;
            }
        }
        public override void OnInspectorGUI()
        {
            VertexLightingOverride source = target as VertexLightingOverride;

            BakeSettings settings = source.m_bakeSettingsOverride;

            DVLEditor.DrawShadowAndAOSettings(settings, source, true);

            if (GUILayout.Button("Copy Global Settings"))
            {
                source.m_bakeSettingsOverride.CopySettings(BakeData.Instance().GetBakeSettings().SelectedBakeSet);
                EditorUtility.SetDirty(source);
            }
        }
Example #6
0
        void OnGUI()
        {
            GUILayout.Space(10);
            m_bakeSetName = EditorGUILayout.TextField(Styles.m_bakeSetLabel, m_bakeSetName);
            GUILayout.Space(20);
            if (GUILayout.Button("Create"))
            {
                if (string.IsNullOrEmpty(m_bakeSetName))
                {
                    EditorUtility.DisplayDialog(Styles.m_missingDataDialogTitle, Styles.m_missingNameMessage, "OK");
                }
                else
                {
                    DDRSettings settingsData = BakeData.Instance().GetBakeSettings();

                    string[] ids = new string[settingsData.m_settingsList.Count];
                    for (int i = 0, k = settingsData.m_settingsList.Count; i < k; ++i)
                    {
                        ids[i] = settingsData.m_settingsList[i].m_settingsId;
                    }


                    if (!settingsData.m_settingsList.Exists(delegate(DDRSettings.BakeSettings s)
                    {
                        return(s.m_settingsId == m_bakeSetName);
                    }))
                    {
                        // name is good
                        m_resultCallback(true, m_bakeSetName);
                        CloseDialog();
                    }
                    else
                    {
                        // name already exists
                        EditorUtility.DisplayDialog(Styles.m_nameConflictTitle, string.Format(Styles.m_conflictingNameMessage, m_bakeSetName), "OK");
                    }
                }
            }
            if (GUILayout.Button("Cancel"))
            {
                if (m_resultCallback != null)
                {
                    m_resultCallback(false, null);
                }
                CloseDialog();
            }
        }
        public static void UpdateAOSample(DaydreamVertexLighting source, int idx)
        {
            s_debugState.m_lastVertexSampleIndex = s_debugState.m_vertexSampleIndex;

            Vector3 worldPos    = s_debugState.m_worldVerPos[idx];
            Vector3 worldNormal = s_debugState.m_worldNormals[idx];
            Vector3 bentNormal  = source.transform.TransformVector(s_cacheWrapper.GetBentNormal(idx)).normalized;

            Vector3 normal = Vector3.Lerp(worldNormal, bentNormal, BakeData.Instance().GetBakeSettings().SelectedBakeSet.m_normalBend);

            s_occluderTestData.m_testPoints.Clear();
            s_occluderTestData.m_colPoints.Clear();

            VertexBakerLib.Instance.OccludersAtVertex(s_bvhHandle, idx, worldPos, normal
                                                      , ref s_occluderTestData.m_testPoints, ref s_occluderTestData.m_testPoints
                                                      , ref s_occluderTestData.m_accessability, ref s_occluderTestData.m_accumulatedRayDir);
        }
        protected static void Init(MeshFilter meshFilter)
        {
            if (meshFilter.sharedMesh == null)
            {
                Debug.LogWarning(meshFilter.gameObject.GetPath() + " is missing its mesh");
                return;
            }
            s_debugState = BakeData.Instance().GetDebugState();

#if _DAYDREAM_STATIC_LIGHTING_DEBUG
            // if we still have a handle for some reason try to free it
            if (s_lastInstanceId != meshFilter.GetUniqueId())
            {
                if (s_bvhHandle != null)
                {
                    VertexBakerLib.Instance.FreeHandle(s_bvhHandle.Ptr());
                }
                s_bvhHandle = null;

                BuildWorldVertices(meshFilter);
            }

            TryLoadBVH(meshFilter);

            s_lastInstanceId = meshFilter.GetUniqueId();

            if (s_bvhWrapper == null)
            {
                s_bvhWrapper = new BVHNode_FBWrapper();
            }
            string path = BVH.ConvertMeshIdToBVHPath(s_lastInstanceId);
            s_bvhWrapper.SetPath(path);
            s_bvhWrapper.Validate();

            string sourceAssetPath = AssetDatabase.GetAssetPath(meshFilter.sharedMesh);
            if (!string.IsNullOrEmpty(sourceAssetPath))
            {
                s_cacheWrapper.SetPath("" + s_lastInstanceId);
                s_cacheWrapper.Validate();
            }
            else if (!Application.isPlaying)
            {
                Debug.LogError("Could not find asset " + meshFilter.sharedMesh.name + " the asset may be an instance. Some debug data may not be available.");
            }
#endif
        }
            static void Update()
            {
                DaydreamRendererImportSettings settings = BakeData.Instance().GetImportSettings();

                if (!string.IsNullOrEmpty(SceneManager.GetActiveScene().name) && SceneManager.GetActiveScene().isLoaded)
                {
                    if (settings != null && settings.m_firstRun)
                    {
                        EditorApplication.update -= Update;
                        settings.m_firstRun       = false;
                        BakeData.Instance().SaveImportSettings();

                        DaydreamRendererImportManager.Init();
                    }
                }

                if (settings.m_enableLightingComponentsAutoAdd && settings.m_daydreamLightinSystemEnabled && (DateTime.Now - s_lastUpdate).TotalSeconds > 2)
                {
                    s_lastUpdate = DateTime.Now;
                    ApplyLightingComponents();
                }
            }
        public void InitBakeContext(List <MeshFilter> meshes, List <Light> lights)
        {
            BakeData.Instance().GetBakeSettings();

            // mark time
            m_bakeStart = DateTime.Now;

            string[] guids       = new string[meshes.Count];
            string[] sourcePaths = new string[meshes.Count];
            m_meshRenderers = new MeshRenderer[meshes.Count];
            m_lightBakers   = new DaydreamVertexLighting[meshes.Count];
            for (int i = 0; i < meshes.Count; ++i)
            {
                sourcePaths[i] = AssetDatabase.GetAssetPath(meshes[i].sharedMesh);
                //guids[i] = AssetDatabase.AssetPathToGUID(sourcePaths[i]);
                guids[i]           = "" + meshes[i].GetUniqueId();
                m_meshRenderers[i] = meshes[i].GetComponent <MeshRenderer>();

                // check for daydream
                DaydreamVertexLighting bakerComp = m_meshRenderers[i].GetComponent <DaydreamVertexLighting>();
                if (bakerComp == null)
                {
                    bakerComp = m_meshRenderers[i].gameObject.AddComponent <DaydreamVertexLighting>();
                }
                m_lightBakers[i] = bakerComp;
            }

            m_meshes = meshes;
            m_lights = lights;

            // counts
            m_meshCount  = meshes.Count;
            m_lightCount = lights != null ? lights.Count : 0;
            // other book-keeping data
            m_guids       = guids;
            m_sourcePaths = sourcePaths;
        }
        public bool DrawColorGradient(Color ground, Color equator, Color sky, bool updateSettings = true)
        {
            bool         changed  = false;
            BakeSettings settings = BakeData.Instance().GetBakeSettings().SelectedBakeSet;

            Color newColor = sky;

            int labelWidth = 90;

            if (DrawCubeColor("Sky Color", labelWidth, sky, out newColor))
            {
                changed = true;
                if (updateSettings)
                {
                    settings.SetColorGradient(GradientIndex.Sky, newColor);
                }
            }
            if (DrawCubeColor("Equator Color", labelWidth, equator, out newColor))
            {
                changed = true;
                if (updateSettings)
                {
                    settings.SetColorGradient(GradientIndex.Equator, newColor);
                }
            }
            if (DrawCubeColor("Ground Color", labelWidth, ground, out newColor))
            {
                changed = true;
                if (updateSettings)
                {
                    settings.SetColorGradient(GradientIndex.Ground, newColor);
                }
            }

            return(changed);
        }
        void OnGUI()
        {
            if (SceneManager.GetActiveScene().name == "")
            {
                GUILayout.Space(50);
                EditorGUILayout.HelpBox("Save the scene to begin baking", MessageType.Info);
                return;
            }

            if (!DaydreamRendererImportSettings.BakingEnabledForScene)
            {
                GUILayout.Space(50);
                EditorGUILayout.HelpBox("Enable vertex baking to use Daydream Static Lighting", MessageType.Info);
                if (GUILayout.Button("Enable Vertex Baking For Scene"))
                {
                    DaydreamRendererImportSettings.BakingEnabledForScene = true;
                }
                return;
            }

            if (!s_settingsRestored)
            {
                BakeData.Instance().SaveBakeSettings();
                s_settingsRestored = true;
            }

            if (Event.current.rawType == EventType.MouseUp)
            {
                if (s_settingsDirty)
                {
                    s_settingsDirty = false;
                    BakeData.Instance().SaveBakeSettings();
                }
            }

            if (s_bakeInProgress)
            {
                if (EditorUtility.DisplayCancelableProgressBar("Daydream Baker", "Baking meshes", VertexBakerLib.Instance.BakeProgress()))
                {
                    VertexBakerLib.Instance.BakeCancel();
                    if (!s_bakeInProgress)
                    {
                        s_bakeIsFinished = true;
                    }
                }

                if (s_bakeIsFinished)
                {
                    s_bakeIsFinished = false;
                    s_bakeInProgress = false;
                    EditorUtility.ClearProgressBar();

                    VertexBakerLib.Instance.BakeFinish(delegate(string msg, float complete)
                    {
                        EditorUtility.DisplayProgressBar("Daydream Baker", msg, complete);
                    });
                    EditorUtility.ClearProgressBar();

                    // queue up next bake
                    if (s_bakeSetQueue.Count > 0)
                    {
                        int bakeSet = s_bakeSetQueue.Dequeue();
                        BakeData.Instance().GetBakeSettings().SetBakeSetIndex(bakeSet);
                        BakeScene();
                    }
                }
            }

            EditorGUI.BeginChangeCheck();

#if DDR_RUNTIME_DLL_LINKING_
            if (GUILayout.Button("Reload Library"))
            {
                if (VertexBakerLib.Instance.LibLoaded)
                {
                    VertexBakerLib.Instance.UnloadLib();
                }
                else
                {
                    VertexBakerLib.Instance.LoadLib();
                }
            }
#endif

            DDRSettings settingsData = BakeData.Instance().GetBakeSettings();

            string[] ids = new string[settingsData.m_settingsList.Count];
            for (int i = 0, k = settingsData.m_settingsList.Count; i < k; ++i)
            {
                ids[i] = settingsData.m_settingsList[i].m_settingsId;
            }

            // update selected data
            GUILayout.Space(20);
            int settingsIndex = -1;
            int selected      = DrawToolBar(settingsData.GetBakeSetIndex(), ids, true, out settingsIndex);

            if (selected >= 0)
            {
                int cur = settingsData.GetBakeSetIndex();
                settingsData.SetBakeSetIndex(selected);

                if (cur != selected)
                {
                    DaydreamVertexLighting.UpdateAllVertexLighting(settingsData.SelectedBakeSet.m_settingsId);
                }
            }

            BakeSettings settings = settingsData.SelectedBakeSet;

            if (selected == Toolbar.kAdd)
            {
                if (!BakeSetDialog.m_active)
                {
                    BakeSetDialog.ShowDialog(delegate(bool result, string name)
                    {
                        if (result)
                        {
                            BakeSettings newSettings = new BakeSettings(name);
                            settingsData.AddBakeSettings(newSettings);
                            EditorUtility.SetDirty(settingsData);
                        }
                    });
                }
            }
            else if (selected == Toolbar.kRemove)
            {
                if (settingsData.m_settingsList.Count > 1)
                {
                    int current = settingsData.GetBakeSetIndex();

                    settingsData.RemoveBakeSetting(current);
                    EditorUtility.SetDirty(settingsData);

                    --current;
                    if (current < 0)
                    {
                        current = 0;
                    }

                    settingsData.SetBakeSetIndex(current);
                    DaydreamVertexLighting.UpdateAllVertexLighting(settingsData.SelectedBakeSet.m_settingsId);
                }
            }
            else if (selected == Toolbar.kSettings)
            {
                if (!BakeSetSettingsDialog.m_active)
                {
                    BakeSettings curSettings = settingsData.m_settingsList[settingsIndex];
                    s_settingsDialog = BakeSetSettingsDialog.ShowDialog(curSettings.m_settingsId, curSettings.m_lightList
                                                                        , curSettings.m_activeSet
                                                                        , curSettings.m_forceAllLights
                                                                        , delegate(BakeSetSettingsDialog.Result result, string bakeSetName, List <LightEntry> selectedLights, bool activeSet, bool forceAllLights)
                    {
                        s_settingsDialog = null;
                        if (settingsData.m_settingsList.Count > 1 && result == BakeSetSettingsDialog.Result.Remove)
                        {
                            settingsData.RemoveBakeSetting(settingsIndex);
                            EditorUtility.SetDirty(settingsData);
                            curSettings = settingsData.m_settingsList[settingsIndex];
                        }
                        else if (result == BakeSetSettingsDialog.Result.Ok)
                        {
                            curSettings.m_settingsId     = bakeSetName;
                            curSettings.m_activeSet      = activeSet;
                            curSettings.m_forceAllLights = forceAllLights;
                            if (selectedLights != null)
                            {
                                // remove empty or stale entries
                                var idsInFile = Utilities.LightsByLocalFileId();
                                selectedLights.RemoveAll(delegate(LightEntry obj){
                                    return(string.IsNullOrEmpty(obj.m_group) && obj.m_idInFile == 0 ||
                                           (!idsInFile.ContainsKey(obj.m_idInFile) &&
                                            (string.IsNullOrEmpty(obj.m_group) || GameObject.Find(obj.m_group) == null)));
                                });

                                curSettings.m_lightList = selectedLights;
                            }
                            EditorUtility.SetDirty(settingsData);
                        }
                    });
                }
                else if (s_settingsDialog != null)
                {
                    s_settingsDialog.CancelDialog();
                }
            }

            DrawShadowAndAOSettings(settings, settingsData);

            //settings.m_diffuseEnergyConservation = EditorGUILayout.Slider("Diffuse Conservation", settings.m_diffuseEnergyConservation, 0f, 1f);

            EditorGUILayout.LabelField(Styles.m_ambientHeader);

            EditorGUILayout.BeginHorizontal();
            GUILayout.Space(Styles.kIndent);
            EditorGUILayout.BeginVertical();

            Color solidColor = settings.GetColorSolid();

            Color gradSky     = settings.GetColorGradient(GradientIndex.Sky);
            Color gradEquator = settings.GetColorGradient(GradientIndex.Equator);
            Color gradGround  = settings.GetColorGradient(GradientIndex.Ground);

            Color posX = settings.GetColorCubeFace(Face.PosX);
            Color posY = settings.GetColorCubeFace(Face.PosY);
            Color posZ = settings.GetColorCubeFace(Face.PosZ);

            Color negX = settings.GetColorCubeFace(Face.NegX);
            Color negY = settings.GetColorCubeFace(Face.NegY);
            Color negZ = settings.GetColorCubeFace(Face.NegZ);

            settings.m_colorMode = (BakeSettings.AmbientColorMode)EditorGUILayout.EnumPopup(Styles.m_ambientSource, settings.m_colorMode);

            // Draw color
            EditorGUILayout.BeginHorizontal();
            {
                //GUILayout.Space(Styles.kIndent);
                EditorGUILayout.BeginVertical();

                if (settings.m_colorMode == BakeSettings.AmbientColorMode.kColorCube)
                {
                    // Check for color value change
                    EditorGUILayout.BeginHorizontal();
                    GUILayout.Space(Styles.kIndent);
                    EditorGUILayout.BeginVertical();

                    DrawColorCube(posX, negX, posY, negY, posZ, negZ);
                    EditorGUILayout.EndVertical();
                    EditorGUILayout.EndHorizontal();
                }
                else if (settings.m_colorMode == BakeSettings.AmbientColorMode.kColorGradient)
                {
                    // Check for color value change
                    EditorGUILayout.BeginHorizontal();
                    GUILayout.Space(Styles.kIndent);
                    EditorGUILayout.BeginVertical();

                    DrawColorGradient(gradGround, gradEquator, gradSky);
                    EditorGUILayout.EndVertical();
                    EditorGUILayout.EndHorizontal();
                }
                else
                {
                    EditorGUILayout.BeginHorizontal();
                    GUILayout.Space(Styles.kIndent);
                    Color c = EditorGUILayout.ColorField(Styles.m_ambientColor, solidColor);
                    EditorGUILayout.EndHorizontal();

                    if (c != solidColor)
                    {
                        settings.SetColorSolid(c);
                    }
                }
                EditorGUILayout.EndVertical();
            }
            EditorGUILayout.EndHorizontal();

            float max = settings.m_ambientMax;
            settings.m_ambientMax = EditorGUILayout.Slider(Styles.m_max, settings.m_ambientMax, 0f, 1f);
            if (!s_maxSliderActive && max != settings.m_ambientMax)
            {
                s_control         = EditorGUIUtility.hotControl;
                s_maxSliderActive = true;
            }
            if (s_maxSliderActive && s_control != EditorGUIUtility.hotControl)
            {
                s_control         = -1;
                s_maxSliderActive = false;
            }

            float min = settings.m_ambientMin;
            settings.m_ambientMin = EditorGUILayout.Slider(Styles.m_min, settings.m_ambientMin, 0f, 1f);
            if (!s_minSliderActive && min != settings.m_ambientMin)
            {
                s_control         = EditorGUIUtility.hotControl;
                s_minSliderActive = true;
            }
            if (s_minSliderActive && s_control != EditorGUIUtility.hotControl)
            {
                s_control         = -1;
                s_minSliderActive = false;
            }

            settings.m_ambientMax = Mathf.Clamp(settings.m_ambientMax, settings.m_ambientMin, 1f);
            settings.m_ambientMin = Mathf.Clamp(settings.m_ambientMin, 0f, settings.m_ambientMax);

            if (s_minSliderActive || s_maxSliderActive)
            {
                Color a = Color.black;
                float t = settings.m_ambientMin;
                if (s_maxSliderActive)
                {
                    t = settings.m_ambientMax;
                }

                if (settings.m_colorMode == BakeSettings.AmbientColorMode.kColorCube)
                {
                    Color px = Color.Lerp(a, posX, t);
                    Color nx = Color.Lerp(a, negX, t);
                    Color py = Color.Lerp(a, posY, t);
                    Color ny = Color.Lerp(a, negY, t);
                    Color pz = Color.Lerp(a, posZ, t);
                    Color nz = Color.Lerp(a, negZ, t);

                    EditorGUILayout.BeginHorizontal();
                    GUILayout.Space(Styles.kIndent);
                    EditorGUILayout.BeginVertical();
                    DrawColorCube(px, nx, py, ny, pz, nz, false);
                    EditorGUILayout.EndVertical();
                    EditorGUILayout.EndHorizontal();
                }
                else
                if (settings.m_colorMode == BakeSettings.AmbientColorMode.kColorGradient)
                {
                    Color sky     = Color.Lerp(a, gradSky, t);
                    Color equator = Color.Lerp(a, gradEquator, t);
                    Color ground  = Color.Lerp(a, gradGround, t);

                    EditorGUILayout.BeginHorizontal();
                    GUILayout.Space(Styles.kIndent);
                    EditorGUILayout.BeginVertical();
                    DrawColorGradient(ground, equator, sky, false);
                    EditorGUILayout.EndVertical();
                    EditorGUILayout.EndHorizontal();
                }
                else
                {
                    Color solid = Color.Lerp(a, solidColor, t);

                    EditorGUILayout.BeginHorizontal();
                    GUILayout.Space(Styles.kIndent);
                    EditorGUILayout.BeginVertical();
                    EditorGUILayout.ColorField(solid);
                    EditorGUILayout.EndVertical();
                    EditorGUILayout.EndHorizontal();
                }
            }

            EditorGUILayout.EndVertical();
            EditorGUILayout.EndHorizontal();

            GUILayout.Space(50);

            if (VertexBakerLib.Instance.BakeInProgress())
            {
                if (GUILayout.Button("Cancel"))
                {
                    VertexBakerLib.Instance.BakeCancel();
                }
            }
            else
            {
                settings.m_bakeAllLightSets = EditorGUILayout.ToggleLeft(Styles.m_bakeAll, settings.m_bakeAllLightSets);

                if (GUILayout.Button("Bake Scene"))
                {
                    if (settings.m_bakeAllLightSets)
                    {
                        // enqueue all bake sets
                        for (int i = 0, k = settingsData.m_settingsList.Count; i < k; ++i)
                        {
                            if (settingsData.m_settingsList[i].m_activeSet)
                            {
                                s_bakeSetQueue.Enqueue(i);
                            }
                        }

                        // set the first bake set
                        if (s_bakeSetQueue.Count > 0)
                        {
                            int bakeSet = s_bakeSetQueue.Dequeue();
                            settingsData.SetBakeSetIndex(bakeSet);
                        }
                    }

                    BakeScene();
                }
            }

            BakeSets bakeSets = BakeData.Instance().GetBakeSets();
            GUILayout.BeginHorizontal();
            GUILayout.FlexibleSpace();
            if (bakeSets.m_containers.Count > 0 && GUILayout.Button(Styles.m_clearAllBakeData, Styles.m_clearButton))
            {
                if (EditorUtility.DisplayDialog(Styles.kEditorTitle, "Clear all data, are you sure?", "Yes", "No"))
                {
                    for (int i = 0, k = bakeSets.m_containers.Count; i < k; ++i)
                    {
                        List <Mesh> meshes = bakeSets.m_containers[i].m_list;
                        for (int j = 0; j < meshes.Count; ++j)
                        {
                            DestroyImmediate(meshes[j], true);
                        }
                    }
                }

                EditorUtility.SetDirty(bakeSets);
                AssetDatabase.SaveAssets();
            }
            GUILayout.EndHorizontal();


            if (EditorGUI.EndChangeCheck())
            {
                s_settingsDirty = true;
                Undo.RecordObject(settingsData, "SettingsUndo");
                //VertexBakerLib.Instance.WriteSettings();
                //VertexBakerLib.Instance.SaveSettings();
            }
        }
        static void DrawBakerGizmos(DaydreamVertexLighting source, GizmoType gizmoType)
        {
            if (s_bvhHandle != null && !s_bvhHandle.IsValid())
            {
                TryLoadBVH(source.GetComponent <MeshFilter>());
            }

            if (s_bvhWrapper.IsValid() && s_cacheWrapper.IsValid() && s_bvhHandle.IsValid())
            {
                if (s_debugState.m_worldVerPos == null || s_debugState.m_worldVerPos.Length == 0)
                {
                    BuildWorldVertices(source.GetComponent <MeshFilter>());
                }

                // update selection
                if (Event.current != null && s_inputUpdate)
                {
                    s_inputUpdate = false;
                    Ray   ray      = HandleUtility.GUIPointToWorldRay(s_position);
                    float farPlane = 10000.0f;
                    if (Camera.main != null)
                    {
                        farPlane = Camera.main.farClipPlane;
                    }
                    int index = VertexBakerLib.Instance.RayToIndex(s_bvhHandle, ray.origin, ray.direction * farPlane);
                    if (index < 0)
                    {
                        return;
                    }
                    s_currentIdx = index;
                }

                if (s_currentIdx + s_debugState.m_indexOffset < 0)
                {
                    return;
                }

                int idx = (s_currentIdx + s_debugState.m_indexOffset) % s_debugState.m_worldVerPos.Length;

                s_debugState.m_vertexSampleIndex = idx;

                float patchScale   = Mathf.Max(source.transform.localToWorldMatrix.m00, source.transform.localToWorldMatrix.m11, source.transform.localToWorldMatrix.m22);
                float radius       = s_cacheWrapper.GetPatchRadius(idx);
                float sampleRadius = radius * patchScale;

                if (s_debugState.m_showBVH)
                {
                    List <Bounds> bounds = s_bvhWrapper.GetBounds();

                    foreach (Bounds b in bounds)
                    {
                        Gizmos.DrawWireCube(b.center, b.size);
                    }
                }

                if (s_debugState.m_showSamplePatch)
                {
                    Color c = Color.green;
                    PushGizmoColor(c);
                    Gizmos.DrawWireSphere(s_debugState.m_worldVerPos[idx], sampleRadius);

                    Vector3[] corners = s_bvhWrapper.GetPatchCorners(idx);

                    PushGizmoColor(Color.blue);
                    Vector3 n = s_debugState.m_worldNormals[idx] * 0.07f;
                    Gizmos.DrawLine(n + corners[0], n + corners[1]); // TL->TR
                    Gizmos.DrawLine(n + corners[1], n + corners[2]); // TR->BR
                    Gizmos.DrawLine(n + corners[2], n + corners[3]); // BR->BL
                    Gizmos.DrawLine(n + corners[3], n + corners[0]); // BL->TL
                    PopGizmoColor();

                    PopGizmoColor();
                }

                if (s_debugState.m_showAOSamples)
                {
                    UpdateAOSample(source, idx);
                    if (s_occluderTestData.m_testPoints.Count > 0)
                    {
                        PushGizmoColor(Color.cyan);
                        Gizmos.DrawWireSphere(s_debugState.m_worldVerPos[idx], s_cacheWrapper.GetPatchRadius(idx) * BakeData.Instance().GetBakeSettings().SelectedBakeSet.m_occlusionRayLength);
                        PushGizmoColor(Color.green * 1.5f);
                        Gizmos.DrawSphere(s_debugState.m_worldVerPos[idx], 0.01f);
                        PopGizmoColor();
                        PopGizmoColor();

                        PushGizmoColor(Color.green + Color.cyan * 0.5f);
                        for (int i = 0; i < s_occluderTestData.m_testPoints.Count; ++i)
                        {
                            Gizmos.DrawSphere(s_occluderTestData.m_testPoints[i], sampleRadius * 0.1F);
                        }
                        PopGizmoColor();
                        PushGizmoColor(Color.red);
                        for (int i = 0; i < s_occluderTestData.m_colPoints.Count; ++i)
                        {
                            Gizmos.DrawSphere(s_occluderTestData.m_colPoints[i], sampleRadius * 0.1F);
                        }
                        PopGizmoColor();

                        PushGizmoColor(new Color(1f, 0f, 1f));
                        Gizmos.DrawLine(s_debugState.m_worldVerPos[idx], s_debugState.m_worldVerPos[idx] + s_occluderTestData.m_accumulatedRayDir);
                        PopGizmoColor();

                        s_debugState.m_accessability = s_occluderTestData.m_accessability;
                    }
                }

                if (s_debugState.m_showAdjacencies)
                {
                    List <int> adj = s_cacheWrapper.GetAdjacencies(idx);
                    PushGizmoColor(Color.cyan);
                    Gizmos.DrawSphere(s_debugState.m_worldVerPos[idx], SphereSize(sampleRadius));
                    PopGizmoColor();

                    PushGizmoColor(Color.red);
                    for (int i = 0; i < adj.Count; ++i)
                    {
                        if (s_debugState.m_worldVerPos.Length > adj[i])
                        {
                            Gizmos.DrawSphere(s_debugState.m_worldVerPos[adj[i]], SphereSize(sampleRadius));
                        }
                    }
                    PopGizmoColor();
                }

                if (s_debugState.m_showLightBlockerSamples)
                {
                    UpdateLightBlockerSamplers(source, idx);
                }

                if (s_debugState.m_showNormals)
                {
                    PushGizmoColor(Color.green);
                    Gizmos.DrawLine(s_debugState.m_worldVerPos[idx], s_debugState.m_worldVerPos[idx] + s_debugState.m_worldNormals[idx]);
                    if (s_debugState.m_showAdjacencies)
                    {
                        List <int> adj = s_cacheWrapper.GetAdjacencies(idx);
                        for (int i = 0; i < adj.Count; ++i)
                        {
                            Gizmos.DrawLine(s_debugState.m_worldVerPos[adj[i]], s_debugState.m_worldVerPos[adj[i]] + s_debugState.m_worldNormals[idx]);
                        }
                    }
                    PopGizmoColor();
                }

                if (s_debugState.m_showBentNormalSamples)
                {
                    List <int> adj = s_cacheWrapper.GetAdjacencies(idx);

                    PushGizmoColor(Color.red);
                    Vector3 pos  = s_debugState.m_worldVerPos[idx];
                    Vector3 norm = s_cacheWrapper.GetBentNormal(idx);
                    // normal move to world space
                    norm = source.transform.TransformVector(norm).normalized;

                    Gizmos.DrawLine(pos, pos + norm);

                    for (int i = 0; i < adj.Count; ++i)
                    {
                        pos  = s_debugState.m_worldVerPos[adj[i]];
                        norm = s_cacheWrapper.GetBentNormal(adj[i]);
                        // normal move to world space
                        norm = source.transform.TransformVector(norm).normalized;

                        Gizmos.DrawLine(pos, pos + norm);
                    }
                    PopGizmoColor();
                }
            }
        }
        // Helper method for marshaling mesh data with sub mesh definition
        public static void BuildSceneContext(MeshFilter[] meshes, List <List <int> > subMeshIndices, List <List <int> > subMeshTriangleIndices, BakeContext ctx, IVertex vertex = null)
        {
            if (vertex == null)
            {
                vertex = new DefaultVertex();
            }

            ctx.m_vertexEementCount = vertex.ElementCount;
            ctx.m_vertexDefinition  = vertex.Definition.ToArray();

            int totalVertCount = 0;
            int totalTriCount  = 0;
            int meshCount      = meshes.Length;

            // extract mesh renderer options
            MeshRenderer[] renderer = ctx.m_meshRenderers;

            // calculate mesh data size
            for (int i = 0; i < meshCount; ++i)
            {
                // if a sub mesh is defined use it for vert count
                if (subMeshIndices != null && subMeshIndices[i] != null)
                {
                    totalVertCount += subMeshIndices[i].Count;
                }
                else
                {
                    totalVertCount += meshes[i].sharedMesh.vertices.Length;
                }

                // if a sub mesh is defined use it for triangle index count
                if (subMeshTriangleIndices != null && subMeshTriangleIndices[i] != null)
                {
                    totalTriCount += subMeshTriangleIndices[i].Count;
                }
                else
                {
                    totalTriCount += meshes[i].sharedMesh.triangles.Length;
                }
            }

            // data size
            const int triangleSize = 3;
            const int matSize      = 16;

            int totalMatrixDataSize = matSize * meshCount * SIZE_FLOAT;
            // mesh size depends on vertex definition
            int totalMeshDataSize     = totalVertCount * SIZE_FLOAT * (vertex.VertexSize + meshCount);
            int totalTriangleDataSize = totalTriCount * triangleSize * SIZE_INT;

            VertexBakerLib instance = VertexBakerLib.Instance;

            ctx.m_meshIdsPtr         = instance.Alloc(meshCount * SIZE_INT);
            ctx.m_vertexCountsPtr    = instance.Alloc(meshCount * SIZE_INT);
            ctx.m_triangleCountPtr   = instance.Alloc(meshCount * SIZE_INT);
            ctx.m_matDataPtr         = instance.Alloc(totalMatrixDataSize);
            ctx.m_meshDataPtr        = instance.Alloc(totalMeshDataSize);
            ctx.m_triangleDataPtr    = instance.Alloc(totalTriangleDataSize);
            ctx.m_settingsIndicesPtr = instance.Alloc(meshCount * SIZE_INT);
            ctx.m_bakeOptionsPtr     = instance.Alloc(meshCount * SIZE_INT);
            ctx.m_layerPtr           = instance.Alloc(meshCount * SIZE_INT);

            // temp buffer for matrix
            float[] matArr = new float[16];

            int matDestOffset      = 0;
            int meshDestOffset     = 0;
            int triangleDestOffset = 0;

            int[]  vertexCounts   = new int[meshCount];
            int[]  triangleCounts = new int[meshCount];
            int[]  ids            = new int[meshCount];
            uint[] perMeshBakeOpt = new uint[meshCount];
            uint[] layerMask      = new uint[meshCount];

            // data for settings
            int[]         settingsIdx  = new int[meshCount];
            List <IntPtr> settingsList = new List <IntPtr>();

            // global settings
            int    globalSettingsIdx = 0;
            IntPtr globalSettings    = SettingsToIntPtr(BakeData.Instance().GetBakeSettings().SelectedBakeSet);

            settingsList.Add(globalSettings);

            for (int m = 0; m < meshCount; ++m)
            {
                bool processSubMesh = false;

                // assume sub mesh
                if (subMeshIndices != null && subMeshIndices[m] != null &&
                    subMeshTriangleIndices != null && subMeshTriangleIndices[m] != null)
                {
                    processSubMesh = true;
                }
                // setup settings
                settingsIdx[m] = globalSettingsIdx;
                // check for override settings
                VertexLightingOverride ovrdSettings = meshes[m].GetComponent <VertexLightingOverride>();
                if (ovrdSettings != null)
                {
                    // point at this overrides index
                    settingsIdx[m] = settingsList.Count;
                    // ensure ambient settings (copy from global which contains the valid ambient settings for now)
                    ovrdSettings.m_bakeSettingsOverride.CopyAmbient(BakeData.Instance().GetBakeSettings().SelectedBakeSet);
                    IntPtr settingsPtr = SettingsToIntPtr(ovrdSettings.m_bakeSettingsOverride);
                    settingsList.Add(settingsPtr);
                }

                Mesh mesh = meshes[m].sharedMesh;
                ids[m] = meshes[m].GetUniqueId();

                // layer mask
                layerMask[m] = (uint)(1 << meshes[m].gameObject.layer);

                // clear data
                perMeshBakeOpt[m] = 0;

                // if mesh has no normals or tangents flag them for generation
                // should calculate normals
                if (meshes[m].sharedMesh.normals.Length == 0)
                {
                    // set bit for normals
                    perMeshBakeOpt[m] |= BakeOptions.kCalcNormals;
                }
                // should calculate tangents
                if (meshes[m].sharedMesh.tangents.Length == 0)
                {
                    // set bit for tangents
                    perMeshBakeOpt[m] |= BakeOptions.kCalcTangents;
                }

                // extract shadowing options from renderer
                switch (renderer[m].shadowCastingMode)
                {
                case UnityEngine.Rendering.ShadowCastingMode.Off:
                {
                    perMeshBakeOpt[m] |= BakeOptions.kShadowsOff;
                }
                break;

                case UnityEngine.Rendering.ShadowCastingMode.TwoSided:
                {
                    perMeshBakeOpt[m] |= BakeOptions.kTwoSided;
                }
                break;

                case UnityEngine.Rendering.ShadowCastingMode.On:
                {
                    perMeshBakeOpt[m] |= BakeOptions.kShadowsOn;
                }
                break;

                case UnityEngine.Rendering.ShadowCastingMode.ShadowsOnly:
                {
                    perMeshBakeOpt[m] |= BakeOptions.kShadowsOnly;
                }
                break;

                default:
                    break;
                }

                if (renderer[m].receiveShadows)
                {
                    perMeshBakeOpt[m] |= BakeOptions.kReceiveShadow;
                }
                else
                {
                    perMeshBakeOpt[m] &= ~BakeOptions.kReceiveShadow;
                }

                // use the list of unique indices of the sub mesh to find the count here unless its null then assume all vertices are being processed
                int vertexCount = processSubMesh ? subMeshIndices[m].Count : mesh.vertices.Length;

                // use the list of triangles from the sub mesh to find the count here unless its null then assume all triangles are being processed
                int triangleCount = processSubMesh ? subMeshTriangleIndices[m].Count : mesh.triangles.Length;

                vertexCounts[m]   = vertexCount;
                triangleCounts[m] = triangleCount;

                // copy mesh data into mesh buffer starting with world matrix
                int matIndex = 0;
                AssignMat4(ref matArr, meshes[m].transform.localToWorldMatrix, ref matIndex); // 64 bytes

                IntPtr matDestPtr = new IntPtr(ctx.m_matDataPtr.ToInt64() + matDestOffset * SIZE_FLOAT);
                Marshal.Copy(matArr, 0, matDestPtr, 16);
                matDestOffset += 16;

                if (processSubMesh)
                {
                    // build sub mesh
                    BuildMesh(ctx, meshes[m].sharedMesh, vertex, subMeshIndices[m], ref meshDestOffset);
                }
                else
                {
                    // build entire mesh
                    BuildMesh(ctx, meshes[m].sharedMesh, vertex, ref meshDestOffset);
                }

                // triangles
                IntPtr indexPtr = new IntPtr(ctx.m_triangleDataPtr.ToInt64() + triangleDestOffset * SIZE_INT);
                if (processSubMesh)
                {
                    // copy sub mesh triangle list
                    Marshal.Copy(subMeshTriangleIndices[m].ToArray(), 0, indexPtr, triangleCount);
                }
                else
                {
                    // copy entire triangle list
                    Marshal.Copy(mesh.triangles, 0, indexPtr, triangleCount);
                }

                triangleDestOffset += triangleCount;
            }

            // copy the mesh into pointer
            instance.CopyArray(ctx.m_meshIdsPtr, meshCount * SIZE_INT, ids, meshCount * SIZE_INT);
            instance.CopyArray(ctx.m_vertexCountsPtr, meshCount * SIZE_INT, vertexCounts, meshCount * SIZE_INT);
            instance.CopyArray(ctx.m_triangleCountPtr, meshCount * SIZE_INT, triangleCounts, meshCount * SIZE_INT);
            instance.CopyUIntArray(ctx.m_bakeOptionsPtr, meshCount * SIZE_INT, perMeshBakeOpt, meshCount * SIZE_INT);
            instance.CopyUIntArray(ctx.m_layerPtr, meshCount * SIZE_INT, layerMask, meshCount * SIZE_INT);
            instance.CopyArray(ctx.m_settingsIndicesPtr, meshCount * SIZE_INT, settingsIdx, meshCount * SIZE_INT);

            ctx.m_settingsPtrs = settingsList.ToArray();
            ctx.m_vertCounts   = vertexCounts;
        }
        public int BakeFinish(OnFinishedUpdate onUpdate)
        {
            VertexBakerLib.Assert(this != null && !m_run, "BakeFinished called but bake is still in process");

            string outputPath = BakeData.DataPath;

            if (!Directory.Exists(outputPath))
            {
                Directory.CreateDirectory(outputPath);
            }

            if (m_result != 0)
            {
                string error = VertexBakerLib.Instance.GetLastError();
                VertexBakerLib.LogError(error);
            }
            else if (!m_cancel && m_outBasis0[0] != IntPtr.Zero && m_outBasis1[0] != IntPtr.Zero && m_outBasis2[0] != IntPtr.Zero)
            {
                string bakeSetId = BakeData.Instance().GetBakeSettings().SelectedBakeSet.m_settingsId;

                BakeSets      bakeSets      = BakeData.Instance().GetBakeSets();
                MeshContainer meshContainer = BakeData.Instance().GetMeshContainer(bakeSetId);

                EditorUtility.SetDirty(meshContainer);
                AssetDatabase.SaveAssets();
                AssetDatabase.Refresh();

                AssetDatabase.StartAssetEditing();
                try
                {
                    int ptrOffset  = 0;
                    int meshOffset = 0;
                    for (int m = 0; m < m_meshes.Count; ++m)
                    {
                        int count      = m_vertCounts[m];
                        int floatCount = count * 3;

                        // the ID used to look up this mesh later
                        string objectId = "" + m_lightBakers[m].GetUniqueId();

                        m_lightBakers[m].m_currentContainer = meshContainer;


                        Mesh outputMesh = meshContainer.m_list.Find(delegate(Mesh mesh)
                        {
                            if (mesh != null)
                            {
                                return(mesh.name == bakeSetId + "_" + objectId);
                            }
                            return(false);
                        });

                        if (outputMesh == null)
                        {
                            if (m_lightBakers[m].VertexLighting != null)
                            {
                                // if we are here than the mesh name may have changed, try and remove the stale data
                                string oldName = m_lightBakers[m].VertexLighting.name;
                                Mesh   found   = meshContainer.m_list.Find(delegate(Mesh mesh)
                                {
                                    // remove the old reference
                                    if (mesh != null)
                                    {
                                        return(mesh.name == oldName);
                                    }
                                    // remove null mesh
                                    return(false);
                                });

                                if (found != null)
                                {
                                    GameObject.DestroyImmediate(found, true);
                                }
                            }

                            // if no mesh exists for this target create it here
                            outputMesh = new Mesh();

                            BakeData.Instance().AddToMeshContainer(meshContainer, outputMesh);

                            //meshContainer.m_list.Add(outputMesh);
                            //// add to the container asset
                            //string outputFileName = bakeSetId + "_lighting";
                            //AssetDatabase.AddObjectToAsset(outputMesh, outputPath + "/" + outputFileName + ".asset");
                        }

                        outputMesh.name = bakeSetId + "_" + objectId;

                        // HACK: Work around to make Unity happy. If vertices are not found the additional vertex stream fails
                        //outMeshes[m].vertices = m_meshes[m].sharedMesh.vertices;
                        outputMesh.vertices = m_meshes[m].sharedMesh.vertices;

                        // 3 floats per vector
                        float[] rawData0 = new float[floatCount];
                        float[] rawData1 = new float[floatCount];
                        float[] rawData2 = new float[floatCount];

                        // offset pointer to next mesh
                        IntPtr basis0 = new IntPtr(m_outBasis0[0].ToInt64() + ptrOffset * SIZE_FLOAT);
                        IntPtr basis1 = new IntPtr(m_outBasis1[0].ToInt64() + ptrOffset * SIZE_FLOAT);
                        IntPtr basis2 = new IntPtr(m_outBasis2[0].ToInt64() + ptrOffset * SIZE_FLOAT);
                        ptrOffset += floatCount;

                        // marshal data into float arrays
                        Marshal.Copy(basis0, rawData0, 0, floatCount);
                        Marshal.Copy(basis1, rawData1, 0, floatCount);
                        Marshal.Copy(basis2, rawData2, 0, floatCount);

                        // lists to hold output vectors
                        List <Color> colorList0 = new List <Color>();
                        colorList0.Resize(count, Color.black);
                        List <Vector3> colorList1 = new List <Vector3>();
                        colorList1.Resize(count, Vector3.zero);
                        List <Vector3> colorList2 = new List <Vector3>();
                        colorList2.Resize(count, Vector3.zero);

                        // copy float arrays into mesh data
                        for (int i = 0; i < count; ++i)
                        {
                            int idx = i * 3;
                            colorList0[i] = new Color(rawData0[idx], rawData0[idx + 1], rawData0[idx + 2], 1.0f);
                            colorList1[i] = new Vector3(rawData1[idx], rawData1[idx + 1], rawData1[idx + 2]);
                            colorList2[i] = new Vector3(rawData2[idx], rawData2[idx + 1], rawData2[idx + 2]);
                        }

                        // this offset is target uv sets 1, 2, and 3 for data destination
                        const int uvOffset = 1;

                        outputMesh.SetColors(colorList0);
                        outputMesh.SetUVs(uvOffset + 1, colorList1);
                        outputMesh.SetUVs(uvOffset + 2, colorList2);
                        //outputMesh.UploadMeshData(true);
                        meshOffset += count;

                        EditorUtility.SetDirty(meshContainer);
                        m_meshRenderers[m].additionalVertexStreams = outputMesh;
                        m_lightBakers[m].m_bakeSets     = bakeSets;
                        m_lightBakers[m].VertexLighting = outputMesh;
                        m_lightBakers[m].m_bakeId       = objectId;

                        EditorUtility.SetDirty(m_lightBakers[m]);

                        onUpdate("Uploading Mesh Data", m_meshCount / (float)m);
                    }

                    // remove any null slots
                    meshContainer.m_list.RemoveAll(delegate(Mesh m)
                    {
                        return(m == null);
                    });

                    // aggregate containers under one super container
                    int existingIdx = bakeSets.m_containers.FindIndex(delegate(MeshContainer mc) { return(mc.name == meshContainer.name); });
                    if (existingIdx != -1)
                    {
                        // replace existing entry
                        bakeSets.m_containers[existingIdx] = meshContainer;
                    }
                    else
                    {
                        bakeSets.m_containers.Add(meshContainer);
                    }

                    BakeSetsInspector.CleanupStaleReferences(bakeSets);
                    EditorUtility.SetDirty(bakeSets);
                    AssetDatabase.SaveAssets();
                }
                finally
                {
                    onUpdate("Uploading Mesh Data", 1f);
                    AssetDatabase.StopAssetEditing();
                }
            }
            else
            {
                VertexBakerLib.LogWarning("Bake completed successfully but there was no output data available");
            }

            // free data
            FreeContext(true);

            // since basis memory was allocated in one chunk
            // freeing this handle frees all basis memory
            VertexBakerLib.Instance.Free(m_outBasis0[0]);

            EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene());
            EditorSceneManager.SaveScene(EditorSceneManager.GetActiveScene());

            VertexBakerLib.Log("Bake time: " + (DateTime.Now - m_bakeStart).TotalSeconds + " seconds");

            while (VertexBakerLib.Instance.GetErrorCount() > 0)
            {
                string err = VertexBakerLib.Instance.GetLastError();
                VertexBakerLib.LogError(err);
            }

            GC.Collect();

            return(m_result);
        }
        void OnGUI()
        {
            GUILayout.Space(10);

            m_bakeSetName = EditorGUILayout.TextField(m_bakeSetName);

            m_forceAllLights = EditorGUILayout.ToggleLeft(Styles.m_bakeAllLights, m_forceAllLights);

            if (m_groups == null)
            {
                CloseDialog();
                m_resultCallback(Result.Cancel, m_bakeSetName, null, m_activeSet, m_forceAllLights);
            }

            if (!m_forceAllLights)
            {
                EditorGUILayout.LabelField(Styles.m_lightGroups);

                m_scrollPosition = EditorGUILayout.BeginScrollView(m_scrollPosition);
                {
                    // 'ungrouped' lights under root
                    List <Light> rootLights = null;
                    if (m_groups.TryGetValue(Constants.kRoot, out rootLights))
                    {
                        for (int i = 0; i < rootLights.Count; ++i)
                        {
                            EditorGUILayout.BeginHorizontal();
                            GUILayout.Space(10);
                            EditorGUILayout.LabelField(rootLights[i].name, Styles.m_ungroupedStyle);

                            int idInFile = rootLights[i].GetLocalIDinFile();
                            // search to see if light already exists in the list
                            bool included = m_selectedLights.Exists(delegate(LightEntry obj)
                            {
                                // find by object reference
                                return(obj.m_idInFile == idInFile);
                            });

                            // Create UI and list for toggle
                            if (EditorGUILayout.Toggle(included))
                            {
                                // added - toggle was checked and the item was not already selected
                                if (!included)
                                {
                                    m_selectedLights.Add(new LightEntry(rootLights[i], null));
                                }
                            }
                            else
                            {
                                // was included - it was unchecked and was previously selected so it needs to be removed
                                if (included)
                                {
                                    m_selectedLights.RemoveAll(delegate(LightEntry obj)
                                    {
                                        // find by object reference
                                        return(obj.m_idInFile == idInFile);
                                    });
                                }
                            }
                            EditorGUILayout.EndHorizontal();
                        }
                    }

                    // Lights contained under a parent group
                    Dictionary <string, List <Light> > .Enumerator iter = m_groups.GetEnumerator();
                    while (iter.MoveNext())
                    {
                        string groupPath = iter.Current.Key;
                        if (groupPath == Constants.kRoot)
                        {
                            continue;
                        }


                        EditorGUILayout.BeginHorizontal();
                        GUILayout.Space(10);
                        GUIContent groupName = new GUIContent(groupPath, "Lights grouped by parent");
                        EditorGUILayout.LabelField(groupName, Styles.m_groupedStyle);

                        // search for group path
                        bool included = m_selectedLights.Exists(delegate(LightEntry obj) {
                            return(obj.m_group == groupPath);
                        });

                        if (EditorGUILayout.Toggle(included))
                        {
                            // added
                            if (!included)
                            {
                                // add new group path
                                m_selectedLights.Add(new LightEntry(null, groupPath));
                            }
                        }
                        else
                        {
                            // was included
                            if (included)
                            {
                                int idx = m_selectedLights.FindIndex(delegate(LightEntry obj)
                                {
                                    return(obj.m_group == groupPath);
                                });

                                if (idx >= 0)
                                {
                                    m_selectedLights.RemoveAt(idx);
                                }
                            }
                        }
                        EditorGUILayout.EndHorizontal();
                    }
                }
                EditorGUILayout.EndScrollView();
            }

            GUILayout.Space(20);

            m_activeSet = EditorGUILayout.ToggleLeft(Styles.m_activeBake, m_activeSet);

            EditorGUILayout.BeginHorizontal();
            if (GUILayout.Button("OK"))
            {
                m_resultCallback(Result.Ok, m_bakeSetName, m_selectedLights, m_activeSet, m_forceAllLights);
                CloseDialog();
            }
            if (GUILayout.Button("Cancel"))
            {
                m_resultCallback(Result.Cancel, m_bakeSetName, m_selectedLights, m_activeSet, m_forceAllLights);
                CloseDialog();
            }
            EditorGUILayout.EndHorizontal();

            BakeSets bakeSets = BakeData.Instance().GetBakeSets();

            GUILayout.BeginHorizontal();
            GUILayout.FlexibleSpace();
            if (bakeSets.m_containers.Count > 0 && GUILayout.Button(Styles.m_clearBakeData, Styles.m_clearButton))
            {
                if (EditorUtility.DisplayDialog(m_bakeSetName, "Clear data, are you sure?", "Yes", "No"))
                {
                    for (int i = 0, k = bakeSets.m_containers.Count; i < k; ++i)
                    {
                        if (bakeSets.m_containers[i].m_bakeSetId == m_bakeSetName)
                        {
                            List <Mesh> meshes = bakeSets.m_containers[i].m_list;
                            for (int j = 0; j < meshes.Count; ++j)
                            {
                                DestroyImmediate(meshes[j], true);
                            }
                            break;
                        }
                    }
                }

                EditorUtility.SetDirty(bakeSets);
                AssetDatabase.SaveAssets();
            }
            GUILayout.EndHorizontal();
        }
        private static void BakeHelper(GameObject[] bakeRoots)
        {
            VertexBakerLib.Instance.BakeReset();

            DateTime bakeStart = DateTime.Now;

            List <MeshFilter> meshes = new List <MeshFilter>();

            s_meshRenderers = new List <MeshRenderer>();

            // gather meshes in selection
            foreach (GameObject go in bakeRoots)
            {
                MeshFilter[] filters = go.GetComponentsInChildren <MeshFilter>();
                foreach (MeshFilter filter in filters)
                {
                    MeshRenderer mr = filter.GetComponent <MeshRenderer>();
                    if (filter.sharedMesh == null)
                    {
                        Debug.LogWarning(filter.gameObject.GetPath() + " has a missing mesh");
                    }

                    bool staticLit = (StaticEditorFlags.LightmapStatic & GameObjectUtility.GetStaticEditorFlags(filter.gameObject)) > 0;
                    if (filter.sharedMesh != null && filter.gameObject.activeSelf && staticLit && mr != null && mr.enabled)
                    {
                        s_meshRenderers.Add(mr);
                        meshes.Add(filter);
                    }
                }
            }
            if (meshes.Count == 0)
            {
                EditorUtility.DisplayDialog(Styles.kEditorTitle, Styles.kNoStaticMeshes, "ok");
                return;
            }

            if (meshes.Count != s_meshRenderers.Count)
            {
                EditorUtility.DisplayDialog(Styles.kEditorTitle, "MeshRenderers are not 1 to 1 with Mesh Filters", "ok");
                return;
            }

            List <Light> lights       = new List <Light>();
            DDRSettings  settingsData = BakeData.Instance().GetBakeSettings();

            if (settingsData.SelectedBakeSet.m_forceAllLights)
            {
                List <GameObject> sceneRoots = Utilities.GetAllRoots();

                foreach (GameObject go in sceneRoots)
                {
                    Light[] lightList = go.GetComponentsInChildren <Light>();
                    foreach (Light light in lightList)
                    {
                        if (light.IsLightmapLight())
                        {
                            lights.Add(light);
                        }
                    }
                }
            }
            else
            {
                List <LightEntry>       lightFilter        = settingsData.SelectedBakeSet.m_lightList;
                Dictionary <int, Light> localFileIdToLight = Utilities.LightsByLocalFileId();

                foreach (LightEntry lightEntry in lightFilter)
                {
                    Light light = null;

                    // group if lights
                    if (!string.IsNullOrEmpty(lightEntry.m_group))
                    {
                        // get parent objects for each path that matches the group path
                        List <GameObject> parents = Utilities.FindAll(lightEntry.m_group);

                        // gather all lights under group
                        if (parents.Count > 0)
                        {
                            // add lights to the new group
                            foreach (GameObject parent in parents)
                            {
                                for (int i = 0; i < parent.transform.childCount; ++i)
                                {
                                    GameObject child = parent.transform.GetChild(i).gameObject;
                                    light = child.GetComponent <Light>();
                                    if (light.IsLightmapLight())
                                    {
                                        lights.Add(light);
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        // ungrouped light
                        if (localFileIdToLight.TryGetValue(lightEntry.m_idInFile, out light))
                        {
                            if (light.IsLightmapLight())
                            {
                                lights.Add(light);
                            }
                        }
                    }
                }
            }



            VertexBakerLib.Log("Collect data time: " + (DateTime.Now - bakeStart).TotalSeconds + " seconds");

            ///////////////
            // native bake
            ///////////////
            try
            {
                // stop listening for changes
                m_ignoreNextChange = true;

//                int activeLightCount = DaydreamRendererSceneData.GetActiveLightCount();
//                DaydreamRendererSceneData sceneData = TypeExtensions.FindOrCreateScriptableAsset<DaydreamRendererSceneData>(VertexBakerLib.DataPath, "scenedata");

                s_bakeInProgress = true;
                VertexBakerLib.Instance.Bake(meshes, lights, delegate()
                {
                    s_bakeIsFinished = true;
                });
            }
            catch (Exception e)
            {
                Debug.LogError(e.Message);
                Debug.LogError(e.StackTrace);
            }
        }
        void OnGUI()
        {
            DaydreamRendererImportSettings settings = BakeData.Instance().GetImportSettings();

            EditorGUILayout.HelpBox(Styles.kWelcomeMsg, MessageType.Info);

            if (s_staticMaterialHistory == null || s_dynamicMaterialHistory == null)
            {
                Configure();
            }

            EditorGUI.BeginChangeCheck();
            GUILayout.Space(20);
            EditorGUILayout.HelpBox(Styles.kToggleComponentsHelp, MessageType.Info);

            EditorGUI.BeginChangeCheck();
            settings.m_daydreamLightinSystemEnabled = EditorGUILayout.BeginToggleGroup(Styles.toggleLightingSystem, settings.m_daydreamLightinSystemEnabled);
            if (EditorGUI.EndChangeCheck())
            {
                if (!settings.m_daydreamLightinSystemEnabled)
                {
                    RemoveAllLightingComponents();
                }

                DaydreamRenderer renderer = FindObjectOfType <DaydreamRenderer>();
                if (renderer)
                {
                    renderer.EnableEnlighten(!settings.m_daydreamLightinSystemEnabled);
                }
            }

            EditorGUILayout.BeginHorizontal();
            GUILayout.Space(20);
            settings.m_enableLightingComponentsAutoAdd = EditorGUILayout.ToggleLeft(Styles.toggleComponents, settings.m_enableLightingComponentsAutoAdd);
            EditorGUILayout.EndHorizontal();
            if (!settings.m_enableLightingComponentsAutoAdd)
            {
                EditorGUILayout.BeginHorizontal();
                GUILayout.Space(20);
                if (GUILayout.Button(Styles.addComponents))
                {
                    ApplyLightingComponents();
                }
                if (GUILayout.Button(Styles.removeComponents))
                {
                    RemoveAllLightingComponents();
                }
                EditorGUILayout.EndHorizontal();
            }


            EditorGUILayout.EndToggleGroup();

            GUILayout.Space(50);
            if (EditorGUI.EndChangeCheck())
            {
                EditorUtility.SetDirty(settings);
            }

            if (GUILayout.Button("Scan Materials") || m_convertableMaterials == null || m_convertableMaterials.Count == 0 || s_gatherMetrics)
            {
                List <GameObject> roots = Utilities.GetAllRoots();
                GatherMaterials(roots.ToArray());
            }

            EditorGUILayout.Separator();

            EditorGUILayout.HelpBox(String.Format(Styles.kObjectsWaiting, m_dynamicConvertableCount, m_staticConvertableCount), MessageType.Info);

            if (GUILayout.Button("Convert Materials Now"))
            {
                DoDynamicLightingConversion();
                DoStaticLightingConversion();
            }

            string[] text = new string[] { "Dynamic Converted Materials", "Static Converted Materials", "List All Daydream Materials" };
            s_importType = GUILayout.SelectionGrid(s_importType, text, 3, EditorStyles.radioButton);

            if (s_importType == 0)
            {
                DrawDynamicRevertMaterials();
            }
            else if (s_importType == 1)
            {
                DrawStaticRevertMaterials();
            }
            else if (m_convertedCount > 0)
            {
                DrawDaydreamMaterialList();
            }
        }
 public static void Init()
 {
     BakeData.Instance().GetBakeSettings();
     s_settingsRestored = true;
     OpenWindow();
 }
Example #20
0
 public void LoadSettings()
 {
     BakeData.Instance().GetBakeSettings();
 }
Example #21
0
 public void WriteSettings()
 {
     BakeData.Instance().SaveBakeSettings();
 }