public void TestLoadBVH(DaydreamVertexLighting source)
        {
            DateTime   start      = DateTime.Now;
            MeshFilter meshFilter = source.GetComponent <MeshFilter>();

            if (meshFilter != null)
            {
                try
                {
                    VertexBakerLib.BVHHandle bvhHandle = null;
                    if (VertexBakerLib.Instance.LoadBVH(meshFilter, ref bvhHandle))
                    {
                        VertexBakerLib.Instance.FreeHandle(bvhHandle.Ptr());
                    }
                }
                catch (Exception e)
                {
                    Debug.LogError(e.Message + "\n" + e.StackTrace);
                }
            }

            VertexBakerLib.Log("Seconds to complete: " + (DateTime.Now - start).TotalSeconds);
        }
        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 static void UpdateLightBlockerSamplers(DaydreamVertexLighting source, int idx)
        {
            if (idx >= s_debugState.m_worldVerPos.Length)
            {
                return;
            }

            float   patchScale   = Mathf.Max(source.transform.localToWorldMatrix.m00, source.transform.localToWorldMatrix.m11, source.transform.localToWorldMatrix.m22);
            float   sampleRadius = patchScale * s_cacheWrapper.GetPatchRadius(idx);
            Vector3 worldPos     = s_debugState.m_worldVerPos[idx];
            Vector3 worldNormal  = s_debugState.m_worldNormals[idx];
            Vector3 bentNormal   = source.transform.TransformVector(s_cacheWrapper.GetBentNormal(idx)).normalized;

            Transform tr      = source.transform;
            Transform lightTr = s_debugState.m_testLight.transform;

            Vector4 riat = new Vector4(s_debugState.m_testLight.range
                                       , s_debugState.m_testLight.intensity
                                       , s_debugState.m_testLight.spotAngle
                                       , (float)s_debugState.m_testLight.type);

            List <Vector3> startPoints = new List <Vector3>();
            List <Vector3> endPoints   = new List <Vector3>();
            List <Vector3> colPoints   = new List <Vector3>();

            VertexBakerLib.Instance.LightBlockersAtVertex(s_bvhHandle, idx, tr.position, worldNormal, lightTr.position, lightTr.forward, s_debugState.m_testLight.color.ToVector3(), riat, ref startPoints, ref endPoints, ref colPoints);

            PushGizmoColor(Color.cyan);
            for (int i = 0; i < startPoints.Count; ++i)
            {
                Gizmos.DrawLine(startPoints[i], endPoints[i]);
            }
            PopGizmoColor();

            PushGizmoColor(Color.red);
            for (int i = 0; i < colPoints.Count; ++i)
            {
                Gizmos.DrawLine(endPoints[i], colPoints[i]);
            }

            // estimate color
            Color sampleColor = s_debugState.m_testLight.color;

            sampleColor *= (startPoints.Count - colPoints.Count) / startPoints.Count;
            PushGizmoColor(sampleColor);
            Gizmos.DrawSphere(worldPos, sampleRadius * 0.1F);
            PopGizmoColor();

            PushGizmoColor(new Color(1f, 0f, 1f));
            Gizmos.DrawLine(worldPos, worldPos + bentNormal);
            PopGizmoColor();


            if (s_bvhWrapper != null)
            {
                s_bvhWrapper.GetSamplePatch(idx, ref s_samplePatch);
                PushGizmoColor(new Color(1f, 1f, 0f, 0.25f));
                Vector3 center = s_samplePatch.m_center;

                PopGizmoColor();
                PushGizmoColor(new Color(1f, 0f, 1f, 1f));
                Gizmos.DrawSphere(center, sampleRadius * 0.1F);
                PopGizmoColor();

                PushGizmoColor(Color.red);
                Gizmos.DrawLine(center, center + s_samplePatch.m_basis0);
                PopGizmoColor();

                PushGizmoColor(Color.blue);
                Gizmos.DrawLine(center, center + s_samplePatch.m_basis1);
                PopGizmoColor();
            }
        }
        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();
                }
            }
        }
        public override void OnInspectorGUI()
        {
            DaydreamVertexLighting source = target as DaydreamVertexLighting;

            if (source.m_currentContainer != null)
            {
                EditorGUILayout.ObjectField(Styles.m_vertLightingLabel, source.m_currentContainer, typeof(MeshContainer), false);
            }

            if (source.VertexLighting != null)
            {
                EditorGUILayout.ObjectField(Styles.m_vertLightingLabel, source.VertexLighting, typeof(Mesh), false);
            }

#if _DAYDREAM_STATIC_LIGHTING_DEBUG
            s_debugState.m_debugEnabled = EditorGUILayout.Foldout(s_debugState.m_debugEnabled, Styles.m_debugLabel);

            EditorGUILayout.BeginHorizontal();
            GUILayout.Space(20f);
            EditorGUILayout.BeginVertical();
            EditorGUI.BeginChangeCheck();
            if (s_debugState.m_debugEnabled)
            {
                m_vertOffset = EditorGUILayout.IntField(Styles.m_vertOffset, m_vertOffset);
                s_debugState.m_showLightBlockerSamples = EditorGUILayout.Toggle(Styles.m_lightBlockerLabel, s_debugState.m_showLightBlockerSamples);
                if (s_debugState.m_showLightBlockerSamples)
                {
                    EditorGUILayout.BeginHorizontal();
                    GUILayout.Space(20f);
                    s_debugState.m_testLight = EditorGUILayout.ObjectField(Styles.m_sampleLightLabel, s_debugState.m_testLight, typeof(Light), true) as Light;
                    EditorGUILayout.EndHorizontal();
                }
                s_debugState.m_showSamplePatch       = EditorGUILayout.Toggle(Styles.m_samplePatchLabel, s_debugState.m_showSamplePatch);
                s_debugState.m_showAdjacencies       = EditorGUILayout.Toggle(Styles.m_adjacenciesLabel, s_debugState.m_showAdjacencies);
                s_debugState.m_showAOSamples         = EditorGUILayout.Toggle(Styles.m_aoSamplesLabel, s_debugState.m_showAOSamples);
                s_debugState.m_showBentNormalSamples = EditorGUILayout.Toggle(Styles.m_avgNormalsLabel, s_debugState.m_showBentNormalSamples);
                s_debugState.m_showBVH     = EditorGUILayout.Toggle(Styles.m_bvhLabel, s_debugState.m_showBVH);
                s_debugState.m_showNormals = EditorGUILayout.Toggle(Styles.m_normalsLabel, s_debugState.m_showNormals);
            }
            if (EditorGUI.EndChangeCheck())
            {
                EditorUtility.SetDirty(s_debugState);
                EditorUtility.SetDirty(source);
            }
            EditorGUILayout.EndVertical();
            EditorGUILayout.EndHorizontal();

            if (s_debugState != null && s_debugState.m_showSamplePatch && GUILayout.Button("Tessellate triangles") && s_bvhHandle.IsValid())
            {
                List <int> subMesh = new List <int>
                {
                    s_debugState.m_vertexSampleIndex
                };

                subMesh.AddRange(s_cacheWrapper.GetAdjacencies(s_debugState.m_vertexSampleIndex));

                // triangles with indices into mesh
                List <int> subMeshFaces = s_cacheWrapper.GetAllFacesForIndex(s_debugState.m_vertexSampleIndex);

                foreach (int face in subMeshFaces)
                {
                    int v0 = source.m_sourceMesh.triangles[face];
                    int v1 = source.m_sourceMesh.triangles[face + 1];
                    int v2 = source.m_sourceMesh.triangles[face + 2];


                    s_cacheWrapper.GetTrisForEdge(v0, v1);
                    s_cacheWrapper.GetTrisForEdge(v0, v2);
                    s_cacheWrapper.GetTrisForEdge(v1, v2);
                }

                // tessellate the sub mesh represented by the adjacencies list, triangles should
                // list all the faces for the adjacencies in question
                VertexBakerLib.Instance.TessellateTriangles(s_bvhHandle, subMeshFaces);
            }
#endif
        }
        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 DrawStaticRevertMaterials()
        {
            int convertedCount = s_staticMaterialHistory.m_convertedMaterials != null ? s_staticMaterialHistory.m_convertedMaterials.Count : 0;

            if (convertedCount == 0)
            {
                return;
            }

            // remove anything flagged for revert
            foreach (DaydreamRendererMaterialHistory.Entry sm in m_removeList)
            {
                s_staticMaterialHistory.m_convertedMaterials.Remove(sm);
            }
            m_removeList.Clear();

            foreach (DaydreamRendererMaterialHistory.Entry sm in m_removeSplitList)
            {
                s_staticMaterialHistory.m_splitMaterials.Remove(sm);
                s_listContainerStaticMats.Update();
            }
            m_removeSplitList.Clear();

            // Draw list of converted materials
            //s_listContainerStaticMats = new SerializedObject(s_staticMaterialHistory);
            s_listContainerStaticMats.Update();
            SerializedProperty convertList = s_listContainerStaticMats.FindProperty("m_convertedMaterials");

            EditorGUILayout.Separator();
            EditorGUILayout.LabelField(String.Format(Styles.kStaticConvertedMaterialListFrmt, convertList.arraySize));
            EditorGUILayout.BeginVertical();
            EditorGUIUtility.labelWidth = 75f;

            m_scrollPosConverted = DrawRevertList(m_scrollPosConverted, convertList, 400, delegate(SerializedProperty matHistoryEntry, int elIndex)
            {
                // OnRevert Callback

                // trigger refresh of metrics
                s_gatherMetrics = true;

                Material main   = matHistoryEntry.FindPropertyRelative("m_material").objectReferenceValue as Material;
                Material backup = matHistoryEntry.FindPropertyRelative("m_backupMaterial").objectReferenceValue as Material;

                main.shader = backup.shader;
                main.CopyPropertiesFromMaterial(backup);
                EditorUtility.SetDirty(main);
                AssetDatabase.SaveAssets();

                List <GameObject> revertSites = FindAllMaterialSites(main.name);
                foreach (GameObject go in revertSites)
                {
                    DaydreamVertexLighting dvl = go.GetComponent <DaydreamVertexLighting>();
                    if (dvl != null)
                    {
                        MeshRenderer mr = dvl.GetComponent <MeshRenderer>();
                        if (mr != null)
                        {
                            mr.additionalVertexStreams = null;
                        }
                        DestroyImmediate(dvl);
                    }
                }
                m_removeList.Add(s_staticMaterialHistory.m_convertedMaterials[elIndex]);
            });

            SerializedProperty splitList = s_listContainerStaticMats.FindProperty("m_splitMaterials");

            if (splitList.arraySize > 0)
            {
                EditorGUILayout.HelpBox(String.Format(Styles.kStaticSplitMaterialListFrmt, splitList.arraySize), MessageType.Info);
            }
            // Revert list for split materials
            m_scrollPosSplit = DrawRevertList(m_scrollPosSplit, splitList, 400, delegate(SerializedProperty matHistoryEntry, int elIndex)
            {
                // OnRevert Callback

                // trigger refresh of metrics
                s_gatherMetrics = true;

                Material main = matHistoryEntry.FindPropertyRelative("m_material").objectReferenceValue as Material;

                Material split = matHistoryEntry.FindPropertyRelative("m_splitMaterial").objectReferenceValue as Material;
                string path    = matHistoryEntry.FindPropertyRelative("m_sourceScenePath").stringValue;

                List <GameObject> gos = Utilities.FindAll(path);
                foreach (GameObject go in gos)
                {
                    if (go != null)
                    {
                        MeshRenderer mr = go.GetComponent <MeshRenderer>();
                        if (mr != null)
                        {
                            Material[] mats = mr.sharedMaterials;
                            //bool restored = false;
                            for (int midx = 0, k = mats.Length; midx < k; ++midx)
                            {
                                if (mr.sharedMaterials[midx].name == split.name)
                                {
                                    // restore the material
                                    //restored = true;
                                    mats[midx] = main;
                                    EditorUtility.SetDirty(mr);
                                    AssetDatabase.SaveAssets();
                                }
                            }

                            mr.sharedMaterials = mats;
                            //if (restored)
                            {
                                m_removeSplitList.Add(s_staticMaterialHistory.m_splitMaterials[elIndex]);

                                //// remove daydream component
                                //DaydreamVertexLighting dvl = mr.GetComponent<DaydreamVertexLighting>();
                                //if (dvl != null)
                                //{
                                //    // remove vertex stream
                                //    mr.additionalVertexStreams = null;
                                //    DestroyImmediate(dvl);
                                //}
                            }
                        }
                    }
                }
            },
                                              // draw extra properties of the material-history serialized object
                                              new string[]
            {
                "m_sourceScenePath",
            }
                                              );// end function call

            EditorGUILayout.EndVertical();
        }