static public int constructor(IntPtr l) {
		try {
			UnityEngine.Debug o;
			o=new UnityEngine.Debug();
			pushValue(l,true);
			pushValue(l,o);
			return 2;
		}
		catch(Exception e) {
			return error(l,e);
		}
	}
예제 #2
0
 public static int constructor(IntPtr l)
 {
     try {
         UnityEngine.Debug o;
         o=new UnityEngine.Debug();
         pushValue(l,o);
         return 1;
     }
     catch(Exception e) {
         LuaDLL.luaL_error(l, e.ToString());
         return 0;
     }
 }
예제 #3
0
 public static void StartDetection(UnityAction callback)
 {
     Debug.LogError(FINAL_LOG_PREFIX + "is not supported on selected platform!");
 }
예제 #4
0
 public static void StopDetection()
 {
     Debug.LogError(FINAL_LOG_PREFIX + "is not supported on selected platform!");
 }
예제 #5
0
        private void StartDetectionInternal(UnityAction callback)
        {
            if (isRunning)
            {
                Debug.LogWarning(FINAL_LOG_PREFIX + "already running!", this);
                return;
            }

            if (!enabled)
            {
                Debug.LogWarning(FINAL_LOG_PREFIX + "disabled but StartDetection still called from somewhere (see stack trace for this message)!", this);
                return;
            }

#if UNITY_EDITOR
            if (!UnityEditor.EditorPrefs.GetBool("ACTDIDEnabledGlobal", false))
            {
                Debug.LogWarning(FINAL_LOG_PREFIX + "is not enabled in Anti-Cheat Toolkit Settings!\nPlease, check readme.pdf for details.", this);
                DisposeInternal();
                return;
            }
#if !DEBUG_NORMAL
            if (Application.isEditor)
            {
                Debug.LogWarning(FINAL_LOG_PREFIX + "does not work in editor (check readme.pdf for details).", this);
                DisposeInternal();
                return;
            }
#else
            Debug.LogWarning(FINAL_LOG_PREFIX + "works in debug mode. There WILL BE false positives in editor, it's fine!", this);
#endif
#endif
            if (callback != null && detectionEventHasListener)
            {
                Debug.LogWarning(FINAL_LOG_PREFIX + "has properly configured Detection Event in the inspector, but still get started with Action callback. Both Action and Detection Event will be called on detection. Are you sure you wish to do this?", this);
            }

            if (callback == null && !detectionEventHasListener)
            {
                Debug.LogWarning(FINAL_LOG_PREFIX + "was started without any callbacks. Please configure Detection Event in the inspector, or pass the callback Action to the StartDetection method.", this);
                enabled = false;
                return;
            }

            detectionAction = callback;
            started         = true;
            isRunning       = true;

            if (allowedAssemblies == null)
            {
                LoadAndParseAllowedAssemblies();
            }

            if (signaturesAreNotGenuine)
            {
                OnCheatingDetected();
                return;
            }

            if (!FindInjectionInCurrentAssemblies())
            {
                // listening for new assemblies
                AppDomain.CurrentDomain.AssemblyLoad += OnNewAssemblyLoaded;
            }
            else
            {
                OnCheatingDetected();
            }
        }
예제 #6
0
        private void WarnNoCellPrefab()
        {
#if !UNITY_EDITOR
            Debug.LogWarning("No cell prefab set");
#endif
        }
예제 #7
0
 public static void DrawLine(Vector3 start, Vector3 end, Color?color = null)
 {
     Debug.DrawLine(start, end, color ?? DefaultColor);
 }
예제 #8
0
    //TODO: Refactor Stringify functions to share core logic

    /*
     * I know, I know, this is really bad form.  It turns out that there is a
     * significant amount of garbage created when calling as a coroutine, so this
     * method is duplicated.  Hopefully there won't be too many future changes, but
     * I would still like a more elegant way to optionaly yield
     */
    void Stringify(int depth, StringBuilder builder, bool pretty = false)       //Convert the JSONObject into a string
    //Profiler.BeginSample("JSONprint");
    {
        if (depth++ > MAX_DEPTH)
        {
            Debug.Log("reached max depth!");
            return;
        }
        switch (type)
        {
        case Type.BAKED:
            builder.Append(str);
            break;

        case Type.STRING:
            builder.AppendFormat("\"{0}\"", str);
            break;

        case Type.NUMBER:
#if USEFLOAT
            if (float.IsInfinity(n))
            {
                builder.Append(INFINITY);
            }
            else if (float.IsNegativeInfinity(n))
            {
                builder.Append(NEGINFINITY);
            }
            else if (float.IsNaN(n))
            {
                builder.Append(NaN);
            }
#else
            if (double.IsInfinity(n))
            {
                builder.Append(INFINITY);
            }
            else if (double.IsNegativeInfinity(n))
            {
                builder.Append(NEGINFINITY);
            }
            else if (double.IsNaN(n))
            {
                builder.Append(NaN);
            }
#endif
            else
            {
                builder.Append(n.ToString());
            }
            break;

        case Type.OBJECT:
            builder.Append("{");
            if (list.Count > 0)
            {
#if (PRETTY)     //for a bit more readability, comment the define above to disable system-wide
                if (pretty)
                {
                    builder.Append("\n");
                }
#endif
                for (int i = 0; i < list.Count; i++)
                {
                    string     key = keys[i];
                    JSONObject obj = list[i];
                    if (obj)
                    {
#if (PRETTY)
                        if (pretty)
                        {
                            for (int j = 0; j < depth; j++)
                            {
                                builder.Append("\t");                                         //for a bit more readability
                            }
                        }
#endif
                        builder.AppendFormat("\"{0}\":", key);
                        obj.Stringify(depth, builder, pretty);
                        builder.Append(",");
#if (PRETTY)
                        if (pretty)
                        {
                            builder.Append("\n");
                        }
#endif
                    }
                }
#if (PRETTY)
                if (pretty)
                {
                    builder.Length -= 2;
                }
                else
#endif
                builder.Length--;
            }
#if (PRETTY)
            if (pretty && list.Count > 0)
            {
                builder.Append("\n");
                for (int j = 0; j < depth - 1; j++)
                {
                    builder.Append("\t");                             //for a bit more readability
                }
            }
#endif
            builder.Append("}");
            break;

        case Type.ARRAY:
            builder.Append("[");
            if (list.Count > 0)
            {
#if (PRETTY)
                if (pretty)
                {
                    builder.Append("\n");                             //for a bit more readability
                }
#endif
                for (int i = 0; i < list.Count; i++)
                {
                    if (list[i])
                    {
#if (PRETTY)
                        if (pretty)
                        {
                            for (int j = 0; j < depth; j++)
                            {
                                builder.Append("\t");                                         //for a bit more readability
                            }
                        }
#endif
                        list[i].Stringify(depth, builder, pretty);
                        builder.Append(",");
#if (PRETTY)
                        if (pretty)
                        {
                            builder.Append("\n");                                     //for a bit more readability
                        }
#endif
                    }
                }
#if (PRETTY)
                if (pretty)
                {
                    builder.Length -= 2;
                }
                else
#endif
                builder.Length--;
            }
#if (PRETTY)
            if (pretty && list.Count > 0)
            {
                builder.Append("\n");
                for (int j = 0; j < depth - 1; j++)
                {
                    builder.Append("\t");                             //for a bit more readability
                }
            }
#endif
            builder.Append("]");
            break;

        case Type.BOOL:
            if (b)
            {
                builder.Append("true");
            }
            else
            {
                builder.Append("false");
            }
            break;

        case Type.NULL:
            builder.Append("null");
            break;
        }
        //Profiler.EndSample();
    }
예제 #9
0
        IEnumerator FindPath(Vector3 startPos, Vector3 endPos)
        {
            Stopwatch sw = new Stopwatch();

            sw.Start();

            Vector3[] wayPoints   = new Vector3[0];
            bool      pathSuccess = false;

            Node startNode = grid.GetNodeFromWorldPosition(startPos);
            Node endNode   = grid.GetNodeFromWorldPosition(endPos);

            if (!endNode.Walkable)
            {
                Debug.LogError("End Node NOT Walkable");
                endNode = FindNearestNode(endNode);
            }

            if (startNode.Walkable && endNode.Walkable)
            {
                Heap <Node>    openSet   = new Heap <Node>(grid.MaxSize);
                HashSet <Node> closedSet = new HashSet <Node>();
                openSet.Add(startNode);

                while (openSet.Count > 0)
                {
                    Node currentNode = openSet.RemoveFirstItem();
                    closedSet.Add(currentNode);

                    if (currentNode == endNode)
                    {
                        sw.Stop();
                        pathSuccess = true;
                        Debug.Log("Path found in = " + sw.ElapsedMilliseconds + " ms");
                    }

                    foreach (Node neighbour in grid.GetNeighbours(currentNode))
                    {
                        if (!neighbour.Walkable || closedSet.Contains(neighbour))
                        {
                            continue;
                        }

                        int newMovementCostToNeighbour = currentNode.GCost + GetDistance(currentNode, neighbour);
                        if (newMovementCostToNeighbour < neighbour.GCost || !openSet.Contains(neighbour))
                        {
                            neighbour.GCost  = newMovementCostToNeighbour;
                            neighbour.HCost  = GetDistance(neighbour, endNode);
                            neighbour.parent = currentNode;

                            if (!openSet.Contains(neighbour))
                            {
                                openSet.Add(neighbour);
                            }
                            else
                            {
                                openSet.UpdateItem(neighbour);
                            }
                        }
                    }
                }
            }

            yield return(null);

            if (pathSuccess)
            {
                wayPoints = RetracePath(startNode, endNode);
            }
            RequestManager.FinishedProcessingPath(wayPoints, pathSuccess);
        }
예제 #10
0
        private void _UpdateTextureFromNative()
        {
            // Debug.Log("_UpdateTextureFromNative");

            lock (this)
            {
#if UNITY_WEBGL && !UNITY_EDITOR
                // _UpdateStatus();   //hack todo onLoaded
                //  _UpdateDuration(); //hack todo onLoaded

                _UpdateNativeVideoSize();

                if (_videoTexture == null)
                {
                    Debug.Log("NEW.Texture");
                    Debug.Log(String.Format("NativeVideoSize({0}:{1})", _currentNativeVideoSize.x, _currentNativeVideoSize.y));
                    _videoTexture = new Texture2D(64, 64, TextureFormat.ARGB32, false);
                    //_videoTexture = new Texture2D(0, 0, TextureFormat.RGBA32, false);
                    // _videoTexture.wrapMode = TextureWrapMode.Repeat;
                    _videoTexture.wrapMode = TextureWrapMode.Clamp;
                    _videoTexture.Apply();
                    MPMP_SetNativeTextureID(_id, _videoTexture.GetNativeTexturePtr().ToInt32());
                }
                else
                {
                    if (_oldNativeVideoSize.x != _currentNativeVideoSize.x || _oldNativeVideoSize.y != _currentNativeVideoSize.y)
                    {
                        Debug.Log("CHANGE.Texture");
                        Debug.Log(String.Format("NativeVideoSize({0}:{1})", _currentNativeVideoSize.x, _currentNativeVideoSize.y));
                        _videoTexture.Resize((int)_currentNativeVideoSize.x, (int)_currentNativeVideoSize.y, TextureFormat.ARGB32, false);
                        _videoTexture.Apply();
                    }
                }


                MPMP_UpdateNativeTexture(_id, _videoTexture.GetNativeTexturePtr().ToInt32());//Rendering


                if (_videoMaterial != null)
                {
                    _videoMaterial.SetTexture(texturePropertyName, _videoTexture);
                }
#else
                nativeTexturePtr = MPMP_GetNativeTexture(_id);

                if (nativeTexturePtr == IntPtr.Zero)
                {
                    //Debug.Log("_UpdateTextureFromNative.NULLTexture");
                    return;
                }



                //GetNativeVideoSize(_id, ref _currentNativeVideoSize);
                _UpdateNativeVideoSize();


                if (_videoTexture == null)
                {
                    // Debug.Log("UpdateTextureFromNative.NEW");
                    // Debug.Log(String.Format("NativeVideoSize({0}:{1})", _currentNativeVideoSize.x, _currentNativeVideoSize.y));
                    _videoTexture            = Texture2D.CreateExternalTexture((int)_currentNativeVideoSize.x, (int)_currentNativeVideoSize.y, TextureFormat.RGBA32, true, true, nativeTexturePtr);
                    _videoTexture.filterMode = FilterMode.Bilinear;
                    _videoTexture.wrapMode   = TextureWrapMode.Repeat;
                }
                else
                {
                    // Debug.Log("UpdateTextureFromNative.RESIZE");
                    // Debug.Log(String.Format("NativeVideoSize({0}:{1})", _currentNativeVideoSize.x, _currentNativeVideoSize.y));
                    if (_oldNativeVideoSize.x != _currentNativeVideoSize.x || _oldNativeVideoSize.y != _currentNativeVideoSize.y)
                    {
                        //Debug.Log("UpdateTextureFromNative.RESIZE");
                        _videoTexture.Resize((int)_currentNativeVideoSize.x, (int)_currentNativeVideoSize.y, TextureFormat.RGBA32, true);
                        //_videoTexture.Apply();????
                        //Resources.UnloadUnusedAssets();
                        //GC.Collect;
                    }
                }



                _videoTexture.UpdateExternalTexture(nativeTexturePtr);

                if (_isOnWindows)
                {
                    _videoTexture.filterMode = (FilterMode)_filtermode;
                    _videoTexture.wrapMode   = TextureWrapMode.Repeat;//.Clamp;
                    if (_filtermode != FilterModeMPMP.Point)
                    {
                        _videoTexture.anisoLevel = _anisoLevel + 1;                                     // 16;
                    }
                }

                if (_videoMaterial != null)
                {
                    _videoMaterial.SetTexture(texturePropertyName, _videoTexture);

                    if (_isOnWindows)
                    {
                        if (_filtermode != FilterModeMPMP.Point)
                        {
                            _videoMaterial.GetTexture(texturePropertyName).anisoLevel = _anisoLevel;                                     //15
                        }
                    }
                }
#endif
            }//lock

            _oldNativeVideoSize = _currentNativeVideoSize;
        }
예제 #11
0
 //callback Method is called from native plugin if we debug
 static void CallbackNativeDebug(string str)
 {
     Debug.Log(String.Format("NATIVE::{0}", str));
 }
예제 #12
0
        void Awake()
        {
            // Debug.Log("::::::::::::::::::::::::::::::::::::::");

#if UNITY_EDITOR
            EditorPlayMode.PlayModeChanged += OnPlayModeChanged;
#endif

            Init();

            if (Application.platform.ToString().StartsWith("OSX"))
            {
                OnPixelBufferError += (mpmp) => { Load(); };
            }

            /*
             * OnTextureChanged += (mpmp) => {
             * // _UpdateTextureFromNative();
             * // _UpdateNativeVideoSize();
             * //  Vector2 size = mpmp.GetNativeVideoSize();
             * //  Debug.Log("OnTextureChanged:"+ size);
             *
             * };
             *
             * OnLoaded += (mpmp) =>
             * {
             *  Debug.Log("OnLoaded");
             * };
             */

            SetUpdateFrequency(_updateFrequency);



            if (_isOnWindows && _isOnWindows7)
            {
                return;                               // yield break;
            }
            // RenderEventFunc = GetRenderEventFunc();

#if !(UNITY_WEBGL && !UNITY_EDITOR)
            RenderEventFunc = MPMP_GetRenderEventFunc();
#endif



#if ((UNITY_STANDALONE_WIN && !UNITY_EDITOR_OSX) || UNITY_EDITOR_WIN)
            //Setup the debug callback system for Windows---

#if MPMP_DEBUG
            //http://www.gamedev.net/page/resources/_/technical/game-programming/c-plugin-debug-log-with-unity-r3349

            NativeCallbackDebugDelegate callbackDebug_delegate = new NativeCallbackDebugDelegate(CallbackNativeDebug);
            _handleNativeCallbackDebug = GCHandle.Alloc(callbackDebug_delegate, GCHandleType.Pinned);
            // Convert callback_delegate into a function pointer that can be used in unmanaged code.
            _intptr_NativeCallbackDebug_delegate = Marshal.GetFunctionPointerForDelegate(callbackDebug_delegate);

            // Call the API passing along the function pointer.
            MPMP_SetDebugFunction(_intptr_NativeCallbackDebug_delegate);


            try {
                if (!MPMP_IsMEPlayerInitialized())
                {
                    Debug.Log("InitDebugConsole");
                    MPMP_InitDebugConsole();
                }
            }
            catch (Exception e)
            {
                Debug.Log("EXCEPTION:" + e.Message);
            }
#endif


            MPMP_UnityPluginInit();//Set the Unity graphics device in the native plugin
#endif //Windows



#if UNITY_ANDROID && !UNITY_EDITOR
            AndroidJavaClass  unity_jc    = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
            AndroidJavaObject activity_jo = unity_jc.GetStatic <AndroidJavaObject>("currentActivity");


            AndroidJavaObject mpmp_jo = new AndroidJavaObject("org.monoflow.media.MPMP", activity_jo);
            //AndroidJavaClass mpmp_jc = new AndroidJavaClass("org.monoflow.media.MPMP");

            _id = mpmp_jo.Call <int>("GetId");
#else
            //Windows,Editor,iOS

            ColorSpace cs = QualitySettings.activeColorSpace;

            bool isLinear = (cs == ColorSpace.Linear);

            //There are some issues with dual graphic card setups/ NVIDIA and linear colorspace so we can force to use always RGB textures on the native side. But this will cause not accurate texture colors!
            if (forceGamma)
            {
                isLinear = false;
            }
            _id = MPMP_New(isLinear); //Create the native player
#endif
            // Debug.Log("ID:" + _id);


            if (!_instances.ContainsKey(_id))
            {
                _instances.Add(_id, this);
            }



            //Setup the callback system-----------------------

            // Call the API passing along the function pointer.
#if UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX || (UNITY_IPHONE && !UNITY_EDITOR_WIN)
            MPMP_SetCallbackFunction(_id, CallBackNativeAOT);
#else
            //-------
#if UNITY_WEBGL && !UNITY_EDITOR
            // SetCallbackFunction(WebGLCallbackFunc);
            MPMP_SetCallbackFunction(_id, CallBackNativeAOT);
#else
            NativeCallbackDelegate _callback_delegate = new NativeCallbackDelegate(CallBackNative);
            _handleNativeCallback = GCHandle.Alloc(_callback_delegate, GCHandleType.Pinned);
            // Convert callback_delegate into a function pointer that can be used in unmanaged code.
            _intptr_NativeCallback_delegate = Marshal.GetFunctionPointerForDelegate(_callback_delegate);

            MPMP_SetCallbackFunction(_id, _intptr_NativeCallback_delegate);
#endif
            //---------
#endif


            //--------------------------------------

            MPMP_SetAutoPlay(_id, autoPlay);
            MPMP_SetLooping(_id, looping);
            MPMP_SetVolume(_id, _volume);

#if (UNITY_ANDROID && !UNITY_EDITOR)
            Debug.Log("Application.dataPath: " + Application.dataPath);
            Debug.Log("Application.streamingAssetsPath: " + Application.streamingAssetsPath);
            if (Application.dataPath.Contains(".obb") || Application.dataPath.Contains("/base.apk"))
            {
                SetOBBPath(_id, Application.dataPath);
            }
            //SetOBBPath(_id,Application.dataPath);//DEBUG

            GL.IssuePluginEvent(RenderEventFunc, _id); //Trigger the OpenGL Initializing
#endif



#if (UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX || (UNITY_IPHONE && !UNITY_EDITOR_WIN)) && MPMP_DEBUG
            _ext2_SetLogCallback(_id, NativeCallbackFunc);
#endif

            _UpdateStatus();

            //Unity 5.3 bug with multiple instances of this script .Normal Update interval is used!
            //yield return StartCoroutine(_Update());

            /*
             * yield return new WaitForEndOfFrame();//One frame delay to be sure that all stuff is initialized on the native site
             * if (OnInit != null) OnInit(this);
             *
             * yield break;
             */
        }
예제 #13
0
 public static void NativeCallbackFunc(string message)
 {
     Debug.Log("Unity:NativeCallbackFunc:" + message);
 }
예제 #14
0
        public void Bake(int raySamples, List <Renderer> renderers, Action <SDFVolume, float[], float, object> bakeComplete, object passthrough = null)
        {
            onBakeComplete = bakeComplete;

            int progressInterval = _settings.CellCount / 4;
            int progress         = 0;

            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();

            vec3  halfVoxel   = _settings.HalfVoxel;
            float maxDistance = 0f;

            //adjusted to best timings from testing but it could vary by CPU
            int calcRayLengthBatchCount = 32;

            calcRayLengthBatchCount = Mathf.Clamp(calcRayLengthBatchCount, 1, raySamples);
            int raycastBatchCount = 8;

            raycastBatchCount = Mathf.Clamp(raycastBatchCount, 1, raySamples);
            int prepareRaysBatchCount = 64;

            prepareRaysBatchCount = Mathf.Clamp(prepareRaysBatchCount, 1, raySamples);
            int compareBatchCount = 128;

            //for raycast method front facing geo and flipped backfacing geo is required
            List <Collider> geoFront = new List <Collider>();
            List <Collider> geoBack  = new List <Collider>();

            CreateColliders(ref renderers, ref geoFront, ref geoBack);

            //prepare data
            NativeArray <float>       distances  = new NativeArray <float>(_settings.CellCount, Allocator.TempJob);
            NativeArray <CellResults> allResults = new NativeArray <CellResults>(_settings.CellCount, Allocator.TempJob);

            //constant for all cells
            NativeArray <vec3> sphereSamples = new NativeArray <vec3>(raySamples, Allocator.TempJob);
            //NativeArray<vec3> randomDirections = new NativeArray<vec3>(raySamples, Allocator.TempJob);
            NativeArray <vec4> volumePlanes = new NativeArray <vec4>(6, Allocator.TempJob);

            GetUniformPointsOnSphereNormalized(ref sphereSamples);
            //GetRandomDirections( _halfVoxel*settings.JitterScale, settings.JitterSeed, ref randomDirections);

            vec3 aabbMin = BoundsWorldAABB.min;
            vec3 aabbMax = BoundsWorldAABB.max;
            //the max ray length, used to normalize all resulting distances
            //so they are treated as 0 to 1 within a volume
            float aabbMagnitude = BoundsWorldAABB.size.magnitude;

            Plane pl = new Plane(Vector3.right, aabbMin);
            Plane pr = new Plane(Vector3.left, aabbMax);
            Plane pd = new Plane(Vector3.up, aabbMin);
            Plane pu = new Plane(Vector3.down, aabbMax);
            Plane pb = new Plane(Vector3.forward, aabbMin);
            Plane pf = new Plane(Vector3.back, aabbMax);

            volumePlanes[0] = new vec4(pl.normal.x, pl.normal.y, pl.normal.z, pl.distance);
            volumePlanes[1] = new vec4(pr.normal.x, pr.normal.y, pr.normal.z, pr.distance);
            volumePlanes[2] = new vec4(pd.normal.x, pd.normal.y, pd.normal.z, pd.distance);
            volumePlanes[3] = new vec4(pu.normal.x, pu.normal.y, pu.normal.z, pu.distance);
            volumePlanes[4] = new vec4(pb.normal.x, pb.normal.y, pb.normal.z, pb.distance);
            volumePlanes[5] = new vec4(pf.normal.x, pf.normal.y, pf.normal.z, pf.distance);

            //iterate each cell performing raycasted samples
            for (int i = 0; i < _settings.CellCount; i++)
            {
#if UNITY_EDITOR
                if (i % progressInterval == 0)
                {
                    EditorUtility.DisplayProgressBar(strProgressTitle, strProgress, i / (float)_settings.CellCount);
                }
#endif

                vec3 positionWS    = _settings.ToPositionWS(i, LocalToWorldNoScale);
                vec3 centerVoxelWS = positionWS + halfVoxel;

                NativeArray <float>          rayLengths       = new NativeArray <float>(raySamples, Allocator.TempJob);
                NativeArray <RaycastCommand> allRaycastsFront = new NativeArray <RaycastCommand>(raySamples, Allocator.TempJob);
                NativeArray <RaycastCommand> allRaycastsBack  = new NativeArray <RaycastCommand>(raySamples, Allocator.TempJob);
                NativeArray <RaycastHit>     frontHits        = new NativeArray <RaycastHit>(raySamples, Allocator.TempJob);
                NativeArray <RaycastHit>     backHits         = new NativeArray <RaycastHit>(raySamples, Allocator.TempJob);

                //calculate the ray lengths, just so rays are clipped within the volume when raycasting
                CalculateRayLengths calcRayLengths = new CalculateRayLengths
                {
                    Samples      = sphereSamples,
                    VolumePlanes = volumePlanes,
                    RayLengths   = rayLengths,
                    RayLength    = aabbMagnitude,
                    RayOrigin    = centerVoxelWS
                };
                JobHandle rayLengthHandle = calcRayLengths.Schedule(raySamples, calcRayLengthBatchCount);

                //prepare raycasts front
                PrepareRaycastCommands frontPrc = new PrepareRaycastCommands
                {
                    Samples    = sphereSamples,
                    RayLengths = rayLengths,
                    LayerMask  = LAYER_MASK_FRONT,
                    Raycasts   = allRaycastsFront,
                    RayOrigin  = centerVoxelWS,
                };
                //prepare raycasts back
                PrepareRaycastCommands backPrc = new PrepareRaycastCommands
                {
                    Samples    = sphereSamples,
                    RayLengths = rayLengths,
                    LayerMask  = LAYER_MASK_BACK,
                    Raycasts   = allRaycastsBack,
                    RayOrigin  = centerVoxelWS,
                };

                //schedule front raycasts
                JobHandle prepareFrontHandle = frontPrc.Schedule(
                    raySamples, prepareRaysBatchCount, rayLengthHandle);
                JobHandle scheduleFrontHandle = RaycastCommand.ScheduleBatch(
                    allRaycastsFront, frontHits, raycastBatchCount, prepareFrontHandle);

                //schedule back raycasts
                JobHandle prepareBackHandle = backPrc.Schedule(
                    raySamples, prepareRaysBatchCount, rayLengthHandle);
                JobHandle scheduleBackHandle = RaycastCommand.ScheduleBatch(
                    allRaycastsBack, backHits, raycastBatchCount, prepareBackHandle);

                //combine handles
                JobHandle frontBackHandle = JobHandle.CombineDependencies(scheduleFrontHandle, scheduleBackHandle);

                //process results and put into current cell index
                ProcessHits processHits = new ProcessHits
                {
                    FrontHits = frontHits,
                    BackHits  = backHits,
                    Results   = allResults.Slice(i, 1),
                };

                JobHandle cellHandle = processHits.Schedule(frontBackHandle);
                cellHandle.Complete();

                rayLengths.Dispose();
                allRaycastsFront.Dispose();
                allRaycastsBack.Dispose();
                frontHits.Dispose();
                backHits.Dispose();
            } //for each cell

            //final distances
            CompareDistances compareDistances = new CompareDistances
            {
                Distances = distances,
                Results   = allResults
            };

            JobHandle compareDistancesHandle = compareDistances.Schedule(_settings.CellCount, compareBatchCount);
            compareDistancesHandle.Complete();

            stopwatch.Stop();
            Debug.Log("SDF bake completed in " + stopwatch.Elapsed.ToString("mm\\:ss\\.ff"));
#if UNITY_EDITOR
            EditorUtility.ClearProgressBar();
#endif
            float[] distancesOut = new float[_settings.CellCount];
            distances.CopyTo(distancesOut);

            //cleanup all the temp arrays
            distances.Dispose();
            allResults.Dispose();
            sphereSamples.Dispose();
            //randomDirections.Dispose();
            volumePlanes.Dispose();

            foreach (var c in geoFront)
            {
                Object.DestroyImmediate(c.gameObject);
            }
            foreach (var c in geoBack)
            {
                Object.DestroyImmediate(c.gameObject);
            }

            //NOTE do not use max distance, instead use aabbMagnitude so distance fields are interchangeable
            bakeComplete?.Invoke(this, distancesOut, aabbMagnitude, passthrough);
        }
예제 #15
0
 public void Damage(int damageAmount)
 {
     Debug.Log("ouch!!@");
 }
예제 #16
0
        public static void OnKeyDown(this IInspectorDrawer inspectorDrawer, Event e)
        {
                        #if DEV_MODE && DEBUG_KEYBOARD_INPUT
            Debug.Log(StringUtils.ToColorizedString(inspectorDrawer.ToString(), ".OnKeyDown(", e.keyCode, ") with HasFocus=", inspectorDrawer.HasFocus, ", selectedControl=", StringUtils.ToString(inspectorDrawer.SelectedOrDefaultView().FocusedDrawer), ", SelectedPart=", inspectorDrawer.Manager.SelectedInspectorPart));
                        #endif

            if (!inspectorDrawer.HasFocus)
            {
                return;
            }

            var view = inspectorDrawer.SelectedOrDefaultView();
            var keys = view.Preferences.keyConfigs;

                        #if !POWER_INSPECTOR_LITE
            if (keys.stepBackInSelectionHistory.DetectAndUseInput(e))
            {
                view.StepBackInSelectionHistory();
                return;
            }
            if (keys.stepForwardInSelectionHistory.DetectAndUseInput(e))
            {
                view.StepForwardInSelectionHistory();
                return;
            }
                        #endif

            inspectorDrawer.Repaint();

            DrawGUI.RegisterInputEvent(e);

            var activeView = inspectorDrawer.SelectedOrDefaultView();

            inspectorDrawer.Manager.ActiveInspector = activeView;

            // give controls time to react to selection changes, editing text field changes etc.
            // before cached values are updated. (e.g. unapplied changes in delayed fields are
            // not discarded before they have time to get applied
            activeView.ResetNextUpdateCachedValues();

                        #if DEV_MODE && PI_ASSERTATIONS
            Debug.Assert(!inspectorDrawer.HasFocus || activeView.Selected);
                        #endif

                        #if DEV_MODE && DEBUG_KEYBOARD_INPUT
            Debug.Log(StringUtils.ToColorizedString("OnKeyDown activeView.Selected=", activeView.Selected, ", activeView.FocusedDrawer=", activeView.FocusedDrawer + ", Manager.SelectedInspector=", inspectorDrawer.Manager.SelectedInspector, ", inspectorDrawer.HasFocus=", inspectorDrawer.HasFocus));
                        #endif

            if (activeView.Toolbar.OnKeyboardInputGivenWhenNotSelected(e, activeView.Preferences.keyConfigs))
            {
                if (e.type != EventType.Used)
                {
                    DrawGUI.Use(e);
                    ExitGUIUtility.ExitGUI();
                }
            }

            IDrawer selectedControl = null;
            if (activeView.Selected)
            {
                selectedControl = activeView.FocusedDrawer;
                if (selectedControl != null)
                {
                    var onKeyboardInputBeingGiven = selectedControl.OnKeyboardInputBeingGiven;
                    if (onKeyboardInputBeingGiven != null)
                    {
                                                #if DEV_MODE && DEBUG_KEYBOARD_INPUT
                        Debug.Log("onKeyboardInputBeingGiven(" + StringUtils.ToString(e) + "): " + StringUtils.ToString(onKeyboardInputBeingGiven));
                                                #endif
                        if (onKeyboardInputBeingGiven(selectedControl, e, selectedControl.Inspector.Preferences.keyConfigs))
                        {
                            return;
                        }
                    }

                    if (selectedControl.OnKeyboardInputGiven(e, selectedControl.Inspector.Preferences.keyConfigs))
                    {
                        return;
                    }
                }
                else if (inspectorDrawer.Manager.SelectedInspectorPart == InspectorPart.Toolbar)
                {
                    activeView.Toolbar.OnKeyboardInputGiven(e, activeView.Preferences.keyConfigs);
                }
                else if (inspectorDrawer.Manager.SelectedInspectorPart == InspectorPart.Viewport || inspectorDrawer.Manager.SelectedInspectorPart == InspectorPart.None)
                {
                    bool fieldChangeInputGiven;
                    if (keys.DetectNextField(e, true) || keys.DetectPreviousField(e, true) ||
                        keys.nextFieldLeft.DetectAndUseInput(e) || keys.nextFieldRight.DetectAndUseInput(e) ||
                        keys.nextFieldDown.DetectAndUseInput(e) || keys.nextFieldUp.DetectAndUseInput(e))
                    {
                        fieldChangeInputGiven = true;
                    }
                    else if (e.modifiers == EventModifiers.FunctionKey)
                    {
                        switch (e.keyCode)
                        {
                        case KeyCode.DownArrow:
                        case KeyCode.UpArrow:
                        case KeyCode.LeftArrow:
                        case KeyCode.RightArrow:
                            fieldChangeInputGiven = true;
                            break;

                        default:
                            fieldChangeInputGiven = false;
                            break;
                        }
                    }
                    else
                    {
                        fieldChangeInputGiven = false;
                    }

                    if (fieldChangeInputGiven)
                    {
                        var drawers = activeView.State.drawers;
                        if (drawers.Length == 0)
                        {
                            if (activeView.Toolbar != null)
                            {
                                activeView.Toolbar.OnFindCommandGiven();
                            }
                            else
                            {
                                KeyboardControlUtility.SetKeyboardControl(0, 3);
                            }
                        }
                        else
                        {
                            var first  = drawers[0];
                            var select = first.GetNextSelectableDrawerRight(true, null);

                                                        #if DEV_MODE && DEBUG_NEXT_FIELD
                            Debug.Log(first + ".GetNextSelectableDrawerRight: " + StringUtils.ToString(select));
                                                        #endif

                            if (select != null)
                            {
                                activeView.Select(select, ReasonSelectionChanged.SelectNextControl);
                            }
                        }
                    }
                }
            }

            if (DrawGUI.EditingTextField && keys.DetectTextFieldReservedInput(e, TextFieldType.TextRow))
            {
                                #if DEV_MODE && DEBUG_KEYBOARD_INPUT
                Debug.Log(StringUtils.ToColorizedString("OnKeyboardInputGiven( ", StringUtils.ToString(e), ") DetectTextFieldReservedInput: ", true, " with selectedControl=", selectedControl));
                                #endif
                return;
            }

            if (keys.addComponent.DetectInput(e))
            {
                                #if DEV_MODE
                Debug.Log("AddComponent shortcut detected");
                                #endif

                if (AddComponentButtonDrawer.OpenSelectedOrFirstFoundInstance(activeView))
                {
                    DrawGUI.Use(e);
                }
            }

            if (keys.toggleSplitView.DetectInput(e))
            {
                var splittable = inspectorDrawer as ISplittableInspectorDrawer;
                if (splittable != null && splittable.CanSplitView)
                {
                    DrawGUI.Use(e);
                    splittable.SetSplitView(!splittable.ViewIsSplit);
                    ExitGUIUtility.ExitGUI();
                }
            }

            if (keys.refresh.DetectAndUseInput(e))
            {
                var selectedInspector = inspectorDrawer.Manager.SelectedInspector;
                if (selectedInspector != null && selectedInspector.InspectorDrawer == inspectorDrawer)
                {
                    selectedInspector.ForceRebuildDrawers();
                    ExitGUIUtility.ExitGUI();
                }
                else
                {
                    var mainView = inspectorDrawer.MainView;
                    mainView.ForceRebuildDrawers();
                    var splittable = inspectorDrawer as ISplittableInspectorDrawer;
                    if (splittable != null && splittable.ViewIsSplit)
                    {
                        splittable.SplitView.ForceRebuildDrawers();
                        ExitGUIUtility.ExitGUI();
                    }
                }
            }

            var keyCode = e.keyCode;
            switch (keyCode)
            {
            case KeyCode.Menu:
                if (selectedControl != null)
                {
                    selectedControl.OpenContextMenu(e, selectedControl.RightClickArea, false, selectedControl.SelectedPart);
                }
                break;

            case KeyCode.Space:
                inspectorDrawer.Manager.RegisterKeyHeldDown(keyCode, "space");
                break;

            case KeyCode.F2:
                inspectorDrawer.Repaint();
                if (!DrawGUI.EditingTextField)
                {
                    DrawGUI.Use(e);
                    DrawGUI.EditingTextField = true;
                }
                break;

            case KeyCode.Escape:

                                        #if DEV_MODE
                Debug.Log("!!! ESCAPE !!!");
                                        #endif

                //when dragging a control, allow aborting using the escape key
                if (inspectorDrawer.Manager.MouseDownInfo.MouseDownOverDrawer != null)
                {
                    inspectorDrawer.Manager.MouseDownInfo.Clear();
                }

                if (DrawGUI.EditingTextField)
                {
                    DrawGUI.Use(e);
                    DrawGUI.EditingTextField = false;
                }
                break;

            case KeyCode.AltGr:
            case KeyCode.RightAlt:
                KeyConfig.OnAltGrDown();
                break;

                                #if DEV_MODE
            case KeyCode.I:
                if (e.control && e.alt)
                {
                    Debug.Log("INFO: FocusedDrawer=" + StringUtils.ToString(inspectorDrawer.SelectedOrDefaultView().FocusedDrawer) + ", EditingTextField=" + DrawGUI.EditingTextField);
                }
                break;
                                #endif
            }
        }
 public AdjustParameter()
 {
     Debug.Log("AdjustParameter Constructor");
 }
예제 #18
0
        /// <summary>
        /// Collect CPU combinations for the specified TargetPlatform and TargetCPU
        /// </summary>
        /// <param name="targetPlatform">The target platform (e.g Windows)</param>
        /// <param name="targetCpu">The target CPU (e.g X64_SSE4)</param>
        /// <param name="report">Error reporting</param>
        /// <returns>The list of CPU combinations</returns>
        private static List <BurstOutputCombination> CollectCombinations(TargetPlatform targetPlatform, TargetCpu targetCpu, BuildReport report)
        {
            var combinations = new List <BurstOutputCombination>();

            if (targetPlatform == TargetPlatform.macOS)
            {
                // NOTE: OSX has a special folder for the plugin
                // Declared in GetStagingAreaPluginsFolder
                // PlatformDependent\OSXPlayer\Extensions\Managed\OSXDesktopStandalonePostProcessor.cs
#if UNITY_2019_3_OR_NEWER
                combinations.Add(new BurstOutputCombination(Path.Combine(Path.GetFileName(report.summary.outputPath), "Contents", "Plugins"), targetCpu));
#else
                combinations.Add(new BurstOutputCombination("UnityPlayer.app/Contents/Plugins", targetCpu));
#endif
            }
            else if (targetPlatform == TargetPlatform.iOS)
            {
                if (Application.platform != RuntimePlatform.OSXEditor)
                {
                    Debug.LogWarning("Burst Cross Compilation to iOS for standalone player, is only supported on OSX Editor at this time, burst is disabled for this build.");
                }
                else
                {
                    var targetArchitecture = (IOSArchitecture)UnityEditor.PlayerSettings.GetArchitecture(report.summary.platformGroup);
                    if (targetArchitecture == IOSArchitecture.ARMv7 || targetArchitecture == IOSArchitecture.Universal)
                    {
                        // PlatformDependent\iPhonePlayer\Extensions\Common\BuildPostProcessor.cs
                        combinations.Add(new BurstOutputCombination("StaticLibraries", TargetCpu.ARMV7A_NEON32, DefaultLibraryName + "32"));
                    }

                    if (targetArchitecture == IOSArchitecture.ARM64 || targetArchitecture == IOSArchitecture.Universal)
                    {
                        // PlatformDependent\iPhonePlayer\Extensions\Common\BuildPostProcessor.cs
                        combinations.Add(new BurstOutputCombination("StaticLibraries", TargetCpu.ARMV8A_AARCH64, DefaultLibraryName + "64"));
                    }
                }
            }
            else if (targetPlatform == TargetPlatform.Android)
            {
                //TODO: would be better to query AndroidNdkRoot (but thats not exposed from unity)
                string ndkRoot = null;

#if UNITY_2019_3_OR_NEWER && UNITY_ANDROID
                ndkRoot = UnityEditor.Android.AndroidExternalToolsSettings.ndkRootPath;
#elif UNITY_2019_1_OR_NEWER
                // 2019.1 now has an embedded ndk
                if (EditorPrefs.HasKey("NdkUseEmbedded"))
                {
                    if (EditorPrefs.GetBool("NdkUseEmbedded"))
                    {
                        ndkRoot = Path.Combine(BuildPipeline.GetPlaybackEngineDirectory(BuildTarget.Android, BuildOptions.None), "NDK");
                    }
                    else
                    {
                        ndkRoot = EditorPrefs.GetString("AndroidNdkRootR16b");
                    }
                }
#endif

                // If we still don't have a valid root, try the old key
                if (string.IsNullOrEmpty(ndkRoot))
                {
                    ndkRoot = EditorPrefs.GetString("AndroidNdkRoot");
                }

                // Verify the directory at least exists, if not we fall back to ANDROID_NDK_ROOT current setting
                if (!string.IsNullOrEmpty(ndkRoot) && !Directory.Exists(ndkRoot))
                {
                    ndkRoot = null;
                }

                // Always set the ANDROID_NDK_ROOT (if we got a valid result from above), so BCL knows where to find the Android toolchain and its the one the user expects
                if (!string.IsNullOrEmpty(ndkRoot))
                {
                    Environment.SetEnvironmentVariable("ANDROID_NDK_ROOT", ndkRoot);
                }

                var androidTargetArch = UnityEditor.PlayerSettings.Android.targetArchitectures;
                if ((androidTargetArch & AndroidArchitecture.ARMv7) != 0)
                {
                    combinations.Add(new BurstOutputCombination("libs/armeabi-v7a", TargetCpu.ARMV7A_NEON32));
                }

                if ((androidTargetArch & AndroidArchitecture.ARM64) != 0)
                {
                    combinations.Add(new BurstOutputCombination("libs/arm64-v8a", TargetCpu.ARMV8A_AARCH64));
                }
#if !UNITY_2019_2_OR_NEWER
                if ((androidTargetArch & AndroidArchitecture.X86) != 0)
                {
                    combinations.Add(new BurstOutputCombination("libs/x86", TargetCpu.X86_SSE2));
                }
#endif
            }
            else if (targetPlatform == TargetPlatform.UWP)
            {
                // TODO: Make it configurable for x86 (sse2, sse4)
                combinations.Add(new BurstOutputCombination("Plugins/x64", TargetCpu.X64_SSE4));
                combinations.Add(new BurstOutputCombination("Plugins/x86", TargetCpu.X86_SSE2));
                combinations.Add(new BurstOutputCombination("Plugins/ARM", TargetCpu.THUMB2_NEON32));
                combinations.Add(new BurstOutputCombination("Plugins/ARM64", TargetCpu.ARMV8A_AARCH64));
            }
            else if (targetPlatform == TargetPlatform.Lumin)
            {
                // Set the LUMINSDK_UNITY so bcl.exe will be able to find the SDK
                if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("LUMINSDK_UNITY")))
                {
                    var sdkRoot = EditorPrefs.GetString("LuminSDKRoot");
                    if (!string.IsNullOrEmpty(sdkRoot))
                    {
                        Environment.SetEnvironmentVariable("LUMINSDK_UNITY", sdkRoot);
                    }
                }
                combinations.Add(new BurstOutputCombination("Data/Plugins/", targetCpu));
            }
            else
            {
                combinations.Add(new BurstOutputCombination("Data/Plugins/", targetCpu));
            }

            return(combinations);
        }
예제 #19
0
    void Parse(string str, int maxDepth = -2, bool storeExcessLevels = false, bool strict = false)
    {
        if (!string.IsNullOrEmpty(str))
        {
            str = str.Trim(WHITESPACE);
            if (strict)
            {
                if (str[0] != '[' && str[0] != '{')
                {
                    type = Type.NULL;
                    Debug.LogWarning("Improper (strict) JSON formatting.  First character must be [ or {");
                    return;
                }
            }
            if (str.Length > 0)
            {
#if UNITY_WP8
                if (str == "true")
                {
                    type = Type.BOOL;
                    b    = true;
                }
                else if (str == "false")
                {
                    type = Type.BOOL;
                    b    = false;
                }
                else if (str == "null")
                {
                    type = Type.NULL;
#else
                if (string.Compare(str, "true", true) == 0)
                {
                    type = Type.BOOL;
                    b    = true;
                }
                else if (string.Compare(str, "false", true) == 0)
                {
                    type = Type.BOOL;
                    b    = false;
                }
                else if (string.Compare(str, "null", true) == 0)
                {
                    type = Type.NULL;
#endif
#if USEFLOAT
                }
                else if (str == INFINITY)
                {
                    type = Type.NUMBER;
                    n    = float.PositiveInfinity;
                }
                else if (str == NEGINFINITY)
                {
                    type = Type.NUMBER;
                    n    = float.NegativeInfinity;
                }
                else if (str == NaN)
                {
                    type = Type.NUMBER;
                    n    = float.NaN;
#else
                }
                else if (str == INFINITY)
                {
                    type = Type.NUMBER;
                    n    = double.PositiveInfinity;
                }
                else if (str == NEGINFINITY)
                {
                    type = Type.NUMBER;
                    n    = double.NegativeInfinity;
                }
                else if (str == NaN)
                {
                    type = Type.NUMBER;
                    n    = double.NaN;
#endif
                }
                else if (str[0] == '"')
                {
                    type     = Type.STRING;
                    this.str = str.Substring(1, str.Length - 2);
                }
                else
                {
                    int tokenTmp = 1;

                    /*
                     * Checking for the following formatting (www.json.org)
                     * object - {"field1":value,"field2":value}
                     * array - [value,value,value]
                     * value - string	- "string"
                     *		 - number	- 0.0
                     *		 - bool		- true -or- false
                     *		 - null		- null
                     */
                    int offset = 0;
                    switch (str[offset])
                    {
                    case '{':
                        type = Type.OBJECT;
                        keys = new List <string>();
                        list = new List <JSONObject>();
                        break;

                    case '[':
                        type = Type.ARRAY;
                        list = new List <JSONObject>();
                        break;

                    default:
                        try {
#if USEFLOAT
                            n = System.Convert.ToSingle(str);
#else
                            n = System.Convert.ToDouble(str);
#endif
                            type = Type.NUMBER;
                        } catch (System.FormatException) {
                            type = Type.NULL;
                            Debug.LogWarning("improper JSON formatting:" + str);
                        }
                        return;
                    }
                    string propName  = "";
                    bool   openQuote = false;
                    bool   inProp    = false;
                    int    depth     = 0;
                    while (++offset < str.Length)
                    {
                        if (System.Array.IndexOf(WHITESPACE, str[offset]) > -1)
                        {
                            continue;
                        }
                        if (str[offset] == '\\')
                        {
                            offset += 1;
                            continue;
                        }
                        if (str[offset] == '"')
                        {
                            if (openQuote)
                            {
                                if (!inProp && depth == 0 && type == Type.OBJECT)
                                {
                                    propName = str.Substring(tokenTmp + 1, offset - tokenTmp - 1);
                                }
                                openQuote = false;
                            }
                            else
                            {
                                if (depth == 0 && type == Type.OBJECT)
                                {
                                    tokenTmp = offset;
                                }
                                openQuote = true;
                            }
                        }
                        if (openQuote)
                        {
                            continue;
                        }
                        if (type == Type.OBJECT && depth == 0)
                        {
                            if (str[offset] == ':')
                            {
                                tokenTmp = offset + 1;
                                inProp   = true;
                            }
                        }

                        if (str[offset] == '[' || str[offset] == '{')
                        {
                            depth++;
                        }
                        else if (str[offset] == ']' || str[offset] == '}')
                        {
                            depth--;
                        }
                        //if  (encounter a ',' at top level)  || a closing ]/}
                        if ((str[offset] == ',' && depth == 0) || depth < 0)
                        {
                            inProp = false;
                            string inner = str.Substring(tokenTmp, offset - tokenTmp).Trim(WHITESPACE);
                            if (inner.Length > 0)
                            {
                                if (type == Type.OBJECT)
                                {
                                    keys.Add(propName);
                                }
                                if (maxDepth != -1)                                                                                                                                                     //maxDepth of -1 is the end of the line
                                {
                                    list.Add(Create(inner, (maxDepth < -1) ? -2 : maxDepth - 1));
                                }
                                else if (storeExcessLevels)
                                {
                                    list.Add(CreateBakedObject(inner));
                                }
                            }
                            tokenTmp = offset + 1;
                        }
                    }
                }
            }
            else
            {
                type = Type.NULL;
            }
        }
        else
        {
            type = Type.NULL;                   //If the string is missing, this is a null
        }
        //Profiler.EndSample();
    }
예제 #20
0
        private void OnPostBuildPlayerScriptDLLsImpl(BuildReport report)
        {
            var aotSettingsForTarget = BurstPlatformAotSettings.GetOrCreateSettings(report.summary.platform);

            // Early exit if burst is not activated or the platform is not supported
            if (aotSettingsForTarget.DisableBurstCompilation || !IsSupportedPlatform(report.summary.platform))
            {
                return;
            }

            var commonOptions = new List <string>();
            var stagingFolder = Path.GetFullPath(TempStagingManaged);

            var playerAssemblies = GetPlayerAssemblies(report);

            // grab the location of the root of the player folder - for handling nda platforms that require keys
            var keyFolder = BuildPipeline.GetPlaybackEngineDirectory(report.summary.platform, BuildOptions.None);

            commonOptions.Add(GetOption(OptionAotKeyFolder, keyFolder));

            // Extract the TargetPlatform and Cpu from the current build settings
            TargetCpu targetCpu;
            var       targetPlatform = GetTargetPlatformAndDefaultCpu(report.summary.platform, out targetCpu);

            commonOptions.Add(GetOption(OptionPlatform, targetPlatform));

            // --------------------------------------------------------------------------------------------------------
            // 1) Calculate AssemblyFolders
            // These are the folders to look for assembly resolution
            // --------------------------------------------------------------------------------------------------------
            var assemblyFolders = new List <string> {
                stagingFolder
            };

            if (report.summary.platform == BuildTarget.WSAPlayer)
            {
                // On UWP, not all assemblies are copied to StagingArea, so we want to
                // find all directories that we can reference assemblies from
                // If we don't do this, we will crash with AssemblyResolutionException
                // when following type references.
                foreach (var assembly in playerAssemblies)
                {
                    foreach (var assemblyRef in assembly.compiledAssemblyReferences)
                    {
                        // Exclude folders with assemblies already compiled in the `folder`
                        var assemblyName = Path.GetFileName(assemblyRef);
                        if (assemblyName != null && File.Exists(Path.Combine(stagingFolder, assemblyName)))
                        {
                            continue;
                        }

                        var directory = Path.GetDirectoryName(assemblyRef);
                        if (directory != null)
                        {
                            var fullPath = Path.GetFullPath(directory);
                            if (IsMonoReferenceAssemblyDirectory(fullPath) || IsDotNetStandardAssemblyDirectory(fullPath))
                            {
                                // Don't pass reference assemblies to burst because they contain methods without implementation
                                // If burst accidentally resolves them, it will emit calls to burst_abort.
                                fullPath = Path.Combine(EditorApplication.applicationContentsPath, "MonoBleedingEdge/lib/mono/unityaot");
                                fullPath = Path.GetFullPath(fullPath); // GetFullPath will normalize path separators to OS native format
                                if (!assemblyFolders.Contains(fullPath))
                                {
                                    assemblyFolders.Add(fullPath);
                                }

                                fullPath = Path.Combine(fullPath, "Facades");
                                if (!assemblyFolders.Contains(fullPath))
                                {
                                    assemblyFolders.Add(fullPath);
                                }
                            }
                            else if (!assemblyFolders.Contains(fullPath))
                            {
                                assemblyFolders.Add(fullPath);
                            }
                        }
                    }
                }
            }

            // Copy assembly used during staging to have a trace
            if (BurstLoader.IsDebugging)
            {
                try
                {
                    var copyAssemblyFolder = Path.Combine(Environment.CurrentDirectory, "Logs", "StagingAssemblies");
                    try
                    {
                        if (Directory.Exists(copyAssemblyFolder))
                        {
                            Directory.Delete(copyAssemblyFolder);
                        }
                    }
                    catch
                    {
                    }

                    if (!Directory.Exists(copyAssemblyFolder))
                    {
                        Directory.CreateDirectory(copyAssemblyFolder);
                    }
                    foreach (var file in Directory.EnumerateFiles(stagingFolder))
                    {
                        File.Copy(file, Path.Combine(copyAssemblyFolder, Path.GetFileName(file)));
                    }
                }
                catch
                {
                }
            }

            // --------------------------------------------------------------------------------------------------------
            // 2) Calculate root assemblies
            // These are the assemblies that the compiler will look for methods to compile
            // This list doesn't typically include .NET runtime assemblies but only assemblies compiled as part
            // of the current Unity project
            // --------------------------------------------------------------------------------------------------------
            var rootAssemblies = new List <string>();

            foreach (var playerAssembly in playerAssemblies)
            {
                // the file at path `playerAssembly.outputPath` is actually not on the disk
                // while it is in the staging folder because OnPostBuildPlayerScriptDLLs is being called once the files are already
                // transferred to the staging folder, so we are going to work from it but we are reusing the file names that we got earlier
                var playerAssemblyPathToStaging = Path.Combine(stagingFolder, Path.GetFileName(playerAssembly.outputPath));
                if (!File.Exists(playerAssemblyPathToStaging))
                {
                    Debug.LogWarning($"Unable to find player assembly: {playerAssemblyPathToStaging}");
                }
                else
                {
                    rootAssemblies.Add(playerAssemblyPathToStaging);
                }
            }

            commonOptions.AddRange(assemblyFolders.Select(folder => GetOption(OptionAotAssemblyFolder, folder)));


            // --------------------------------------------------------------------------------------------------------
            // 3) Calculate the different target CPU combinations for the specified OS
            //
            // Typically, on some platforms like iOS we can be asked to compile a ARM32 and ARM64 CPU version
            // --------------------------------------------------------------------------------------------------------
            var combinations = CollectCombinations(targetPlatform, targetCpu, report);

            // --------------------------------------------------------------------------------------------------------
            // 4) Compile each combination
            //
            // Here bcl.exe is called for each target CPU combination
            // --------------------------------------------------------------------------------------------------------

            string debugLogFile = null;

            if (BurstLoader.IsDebugging)
            {
                // Reset log files
                try
                {
                    var logDir = Path.Combine(Environment.CurrentDirectory, "Logs");
                    debugLogFile = Path.Combine(logDir, "burst_bcl_editor.log");
                    if (!Directory.Exists(logDir))
                    {
                        Directory.CreateDirectory(logDir);
                    }
                    File.WriteAllText(debugLogFile, string.Empty);
                }
                catch
                {
                    debugLogFile = null;
                }
            }

            // Log the targets generated by BurstReflection.FindExecuteMethods
            foreach (var combination in combinations)
            {
                // Gets the output folder
                var stagingOutputFolder = Path.GetFullPath(Path.Combine(TempStaging, combination.OutputPath));
                var outputFilePrefix    = Path.Combine(stagingOutputFolder, combination.LibraryName);

                var options = new List <string>(commonOptions)
                {
                    GetOption(OptionAotOutputPath, outputFilePrefix),
                    GetOption(OptionTarget, combination.TargetCpu)
                };

                if (targetPlatform == TargetPlatform.iOS)
                {
                    options.Add(GetOption(OptionStaticLinkage));
                }

                // finally add method group options
                options.AddRange(rootAssemblies.Select(path => GetOption(OptionRootAssembly, path)));

                // Log the targets generated by BurstReflection.FindExecuteMethods
                if (BurstLoader.IsDebugging && debugLogFile != null)
                {
                    try
                    {
                        var writer = new StringWriter();
                        writer.WriteLine("-----------------------------------------------------------");
                        writer.WriteLine("Combination: " + combination);
                        writer.WriteLine("-----------------------------------------------------------");

                        foreach (var option in options)
                        {
                            writer.WriteLine(option);
                        }

                        writer.WriteLine("Assemblies in AssemblyFolders:");
                        foreach (var assemblyFolder in assemblyFolders)
                        {
                            writer.WriteLine("|- Folder: " + assemblyFolder);
                            foreach (var assemblyOrDll in Directory.EnumerateFiles(assemblyFolder, "*.dll"))
                            {
                                var fileInfo = new FileInfo(assemblyOrDll);
                                writer.WriteLine("   |- " + assemblyOrDll + " Size: " + fileInfo.Length + " Date: " + fileInfo.LastWriteTime);
                            }
                        }

                        File.AppendAllText(debugLogFile, writer.ToString());
                    }
                    catch
                    {
                        // ignored
                    }
                }

                // Write current options to the response file
                var responseFile = Path.GetTempFileName();
                File.WriteAllLines(responseFile, options);

                if (BurstLoader.IsDebugging)
                {
                    Debug.Log($"bcl @{responseFile}\n\nResponse File:\n" + string.Join("\n", options));
                }

                try
                {
                    string generatedDebugInformationInOutput = "";
                    if ((report.summary.options & BuildOptions.Development) != 0)
                    {
                        generatedDebugInformationInOutput = GetOption(OptionDebug);
                    }

                    BclRunner.RunManagedProgram(Path.Combine(BurstLoader.RuntimePath, BurstAotCompilerExecutable),
                                                $"{generatedDebugInformationInOutput} @{responseFile}",
                                                new BclOutputErrorParser(),
                                                report);
                }
                catch (BuildFailedException)
                {
                    throw;
                }
                catch (Exception e)
                {
                    throw new BuildFailedException(e);
                }
            }
        }
        public void Log(string txt, LogType type         = LogType.Log, Exception e = null,
                        Dictionary <string, string> data = null)
        {
            var dataString = string.Empty;

            if (data != null)
            {
                dataString = DataToString.DetailString(data);
            }

            string stack;

#if UNITY_EDITOR
            string frame = $"thread: {Environment.CurrentManagedThreadId}";
            try
            {
                if (MAINTHREADID == Environment.CurrentManagedThreadId)
                {
                    frame += $" frame: {Time.frameCount}";
                }
            }
            catch
            {
                //there is something wrong with  Environment.CurrentManagedThreadId
            }
#endif

            switch (type)
            {
            case LogType.Log:
            {
#if UNITY_EDITOR
                stack = ExtractFormattedStackTrace();

                Debug.Log($"{frame} <b><color=teal>".FastConcat(txt, "</color></b> ", Environment.NewLine, stack)
                          .FastConcat(Environment.NewLine, dataString));
#else
                Debug.Log(txt);
#endif
                break;
            }

            case LogType.LogDebug:
            {
#if UNITY_EDITOR
                stack = ExtractFormattedStackTrace();

                Debug.Log($"{frame} <b><color=orange>".FastConcat(txt, "</color></b> ", Environment.NewLine, stack)
                          .FastConcat(Environment.NewLine, dataString));
#else
                Debug.Log(txt);
#endif
                break;
            }

            case LogType.Warning:
            {
#if UNITY_EDITOR
                stack = ExtractFormattedStackTrace();

                Debug.LogWarning($"{frame} <b><color=yellow>".FastConcat(txt, "</color></b> ", Environment.NewLine, stack)
                                 .FastConcat(Environment.NewLine, dataString));
#else
                Debug.LogWarning(txt);
#endif
                break;
            }

            case LogType.Error:
            case LogType.Exception:
            {
                if (e != null)
                {
                    txt   = txt.FastConcat(e.Message);
                    stack = ExtractFormattedStackTrace(new StackTrace(e, true));
                }
                else
                {
                    stack = ExtractFormattedStackTrace();
                }

#if UNITY_EDITOR
                var fastConcat = $"{frame} <b><color=red>".FastConcat(txt, "</color></b> ", Environment.NewLine, stack)
                                 .FastConcat(Environment.NewLine, dataString);

                if (MAINTHREADID == Environment.CurrentManagedThreadId)
                {
                    var error = Application.GetStackTraceLogType(UnityEngine.LogType.Error);
                    Application.SetStackTraceLogType(UnityEngine.LogType.Error, StackTraceLogType.None);
                    Debug.LogError(fastConcat);
                    Application.SetStackTraceLogType(UnityEngine.LogType.Error, error);
                }
                else
                {
                    Debug.LogError(txt);
                }
#else
                if (type == LogType.Error)
                {
                    Debug.LogError(txt);
                }
                else
                if (e != null)
                {
                    Debug.LogException(e);
                }
#endif
                break;
            }
            }
        }
예제 #22
0
            private static void RunProgram(
                Program p,
                string exe,
                string args,
                string workingDirectory,
                CompilerOutputParserBase parser,
                BuildReport report)
            {
                Stopwatch stopwatch = new Stopwatch();

                stopwatch.Start();
                using (p)
                {
                    p.GetProcessStartInfo().WorkingDirectory = workingDirectory;
                    p.Start();
                    p.WaitForExit();
                    stopwatch.Stop();

                    Console.WriteLine("{0} exited after {1} ms.", (object)exe, (object)stopwatch.ElapsedMilliseconds);
                    IEnumerable <UnityEditor.Scripting.Compilers.CompilerMessage> compilerMessages = null;
                    string[] errorOutput    = p.GetErrorOutput();
                    string[] standardOutput = p.GetStandardOutput();
                    if (parser != null)
                    {
                        compilerMessages = parser.Parse(errorOutput, standardOutput, true, "n/a (burst)");
                    }

                    var errorMessageBuilder = new StringBuilder();
                    if (p.ExitCode != 0)
                    {
                        if (compilerMessages != null)
                        {
                            foreach (UnityEditor.Scripting.Compilers.CompilerMessage compilerMessage in compilerMessages)
                            {
                                Debug.LogPlayerBuildError(compilerMessage.message, compilerMessage.file, compilerMessage.line, compilerMessage.column);
                            }
                        }

                        // We try to output the version in the heading error if we can
                        var matchVersion = MatchVersion.Match(exe);
                        errorMessageBuilder.Append(matchVersion.Success ?
                                                   "Burst compiler (" + matchVersion.Groups[1].Value + ") failed running" :
                                                   "Burst compiler failed running");
                        errorMessageBuilder.AppendLine();
                        errorMessageBuilder.AppendLine();
                        // Don't output the path if we are not burst-debugging or the exe exist
                        if (BurstLoader.IsDebugging || !File.Exists(exe))
                        {
                            errorMessageBuilder.Append(exe).Append(" ").Append(args);
                            errorMessageBuilder.AppendLine();
                            errorMessageBuilder.AppendLine();
                        }

                        errorMessageBuilder.AppendLine("stdout:");
                        foreach (string str in standardOutput)
                        {
                            errorMessageBuilder.AppendLine(str);
                        }
                        errorMessageBuilder.AppendLine("stderr:");
                        foreach (string str in errorOutput)
                        {
                            errorMessageBuilder.AppendLine(str);
                        }

                        throw new BuildFailedException(errorMessageBuilder.ToString());
                    }
                    Console.WriteLine(p.GetAllOutput());
                }
            }
        void BuildTreeInternal(PWNode node, BiomeSwitchNode currentNode, int depth, BiomeSwitchNode parent = null)
        {
            if (node == null)
            {
                return;
            }

            //TODO: anchor to multiple PWNodeBiomeSwitch management
            if (node.GetType() == typeof(PWNodeBiomeSwitch))
            {
                PWNodeBiomeSwitch bSwitch      = node as PWNodeBiomeSwitch;
                int           outputLinksCount = bSwitch.GetLinks().Count;
                int           childIndex       = 0;
                List <PWNode> outputNodeList   = new List <PWNode>();

                Debug.Log("encountered switch: " + bSwitch.switchMode);
                currentNode.SetChildCount(outputLinksCount);
                switch (bSwitch.switchMode)
                {
                case BiomeSwitchMode.Water:
                    int?terrestrialAnchorId = node.GetAnchorId(PWAnchorType.Output, 0);
                    int?aquaticAnchorId     = node.GetAnchorId(PWAnchorType.Output, 1);

                    if (terrestrialAnchorId != null)
                    {
                        var nodes = node.GetNodesAttachedToAnchor(terrestrialAnchorId.Value);
                        outputNodeList.AddRange(nodes);
                        // Debug.Log("terrestrialNodes: " + nodes[0].nodeId);
                        for (int i = 0; i < nodes.Count; i++)
                        {
                            currentNode.GetChildAt(childIndex++).SetSwitchValue(false, bSwitch.switchMode, "terrestrial", Color.black);
                        }
                        biomeCoverage[BiomeSwitchMode.Water] += 0.5f;
                    }
                    //get all nodes on the first anchor:
                    if (aquaticAnchorId != null)
                    {
                        var nodes = node.GetNodesAttachedToAnchor(aquaticAnchorId.Value);
                        // Debug.Log("aquaticNodes: " + nodes[0].nodeId);
                        outputNodeList.AddRange(nodes);
                        for (int i = 0; i < nodes.Count; i++)
                        {
                            currentNode.GetChildAt(childIndex++).SetSwitchValue(true, bSwitch.switchMode, "aquatic", Color.blue);
                        }
                        biomeCoverage[BiomeSwitchMode.Water] += 0.5f;
                    }

                    break;

                default:
                    // Debug.Log("swicth data count for node " + node.nodeId + ": " + bSwitch.switchDatas.Count);

                    for (int anchorIndex = 0; anchorIndex < bSwitch.switchDatas.Count; anchorIndex++)
                    {
                        int?anchorId = node.GetAnchorId(PWAnchorType.Output, anchorIndex);
                        var sData    = bSwitch.switchDatas[anchorIndex];

                        if (anchorId == null)
                        {
                            continue;
                        }

                        var attachedNodesToAnchor = node.GetNodesAttachedToAnchor(anchorId.Value);
                        outputNodeList.AddRange(attachedNodesToAnchor);

                        // if (attachedNodesToAnchor.Count == 0)
                        // Debug.LogWarning("nothing attached to the biome switch output " + anchorIndex);

                        foreach (var attachedNode in attachedNodesToAnchor)
                        {
                            var child = currentNode.GetChildAt(childIndex++);

                            child.SetSwitchValue(sData.min, sData.max, bSwitch.switchMode, sData.name, sData.color);
                        }

                        biomeCoverage[bSwitch.switchMode] += (sData.max - sData.min) / (sData.absoluteMax - sData.absoluteMin);
                    }
                    break;
                }
                childIndex = 0;
                foreach (var outNode in outputNodeList)
                {
                    if (bSwitch.switchMode == BiomeSwitchMode.Water)
                    {
                        Debug.Log("water switch mode output type: " + currentNode.GetChildAt(childIndex) + " [" + childIndex + "] -> " + outNode);
                    }
                    BuildTreeInternal(outNode, currentNode.GetChildAt(childIndex, true), depth + 1, currentNode);
                    Type outNodeType = outNode.GetType();
                    if (outNodeType == typeof(PWNodeBiomeSwitch) || outNodeType == typeof(PWNodeBiomeBinder))
                    {
                        childIndex++;
                    }
                }
            }
            else if (node.GetType() == typeof(PWNodeBiomeBinder))
            {
                PWNodeBiomeBinder binder = node as PWNodeBiomeBinder;

                string biomeName = currentNode.biomeName;

                if (String.IsNullOrEmpty(biomeName))
                {
                    Debug.LogWarning("Biome name null or empty for biomeBinder: " + binder);
                    return;
                }

                //Biome binder detected, assign the biome to the current Node:
                currentNode.biome = binder.outputBiome;

                // Debug.Log("current node: " + currentNode + ", preview color: " + currentNode.previewColor);

                //set the color of the biome in the binder
                binder.outputBiome.previewColor = currentNode.previewColor;

                Debug.Log("set biome " + currentNode.biome + " in node " + currentNode);

                //set the biome ID and name:
                currentNode.biome.name = biomeName;
                currentNode.biome.id   = biomeIdCount++;

                //store the biome in dictionaries for fast access
                biomePerId[currentNode.biome.id] = currentNode.biome;
                biomePerName[biomeName]          = currentNode.biome;
            }
            else
            {
                foreach (var outNode in node.GetOutputNodes())
                {
                    BuildTreeInternal(outNode, currentNode, depth++, parent);
                }
            }
            return;
        }
예제 #24
0
    // Update the view count as often as possible
    private IEnumerator UpdateViews()
    {
        while (Connected && IRC.ChannelName.Length > 0)
        {
            var form = new WWWForm();
            form.AddField("name", "value");
            var headers = form.headers;
            var url     = "https://api.twitch.tv/kraken/streams/" + IRC.ChannelName;

            headers["Client-ID"] = "REMOVED FOR GITHUB"; //#TODO Replace with your Client-ID
            var www = new WWW(url, null, headers);

            yield return(www);

            if (string.IsNullOrEmpty(www.error))
            {
                var obj = JsonUtility.FromJson <ChannelDataFull>(www.text);
                if (obj != null)
                {
                    if (obj.stream != null)
                    {
                        if (obj.stream.channel != null)
                        {
                            if (ChannelNameTextMesh != null)
                            {
                                var text = "";
                                if (!string.IsNullOrEmpty(obj.stream.channel.display_name))
                                {
                                    text = string.Format("#{0}", obj.stream.channel.display_name);
                                }
                                else if (!string.IsNullOrEmpty(obj.stream.channel.name))
                                {
                                    text = string.Format("#{0}", obj.stream.channel.name);
                                }
                                else
                                {
                                    text = "Not Streaming";
                                }
                                ChannelNameTextMesh.text = text;
                            }
                            if (ViewerCountTextMesh != null)
                            {
                                ViewerCountTextMesh.text = string.Format("Viewers: {0}", obj.stream.viewers);
                            }
                        }
                        else
                        {
                            ClearViewerCountAndChannelName();
                        }
                    }
                    else
                    {
                        ClearViewerCountAndChannelName();
                    }
                }
            }
            else
            {
                Debug.LogError("Error on page (" + url + "): " + www.error);
            }
            yield return(new WaitForSeconds(10f));
        }
    }
예제 #25
0
        private void LoadAndParseAllowedAssemblies()
        {
#if DEBUG_NORMAL
            Debug.Log(Constants.LOG_PREFIX + "Starting LoadAndParseAllowedAssemblies()", this);
            Stopwatch sw = Stopwatch.StartNew();
#endif
            TextAsset assembliesSignatures = (TextAsset)Resources.Load("fndid", typeof(TextAsset));
            if (assembliesSignatures == null)
            {
                signaturesAreNotGenuine = true;
                return;
            }

#if DEBUG_NORMAL
            sw.Stop();
            Debug.Log(Constants.LOG_PREFIX + "Creating separator array and opening MemoryStream", this);
            sw.Start();
#endif

            string[] separator = { ":" };

            MemoryStream ms = new MemoryStream(assembliesSignatures.bytes);
            BinaryReader br = new BinaryReader(ms);

            int count = br.ReadInt32();

#if DEBUG_NORMAL
            sw.Stop();
            Debug.Log(Constants.LOG_PREFIX + "Allowed assemblies count from MS: " + count, this);
            sw.Start();
#endif

            allowedAssemblies = new AllowedAssembly[count];

            for (int i = 0; i < count; i++)
            {
                string line = br.ReadString();
#if DEBUG_PARANOID
                sw.Stop();
                Debug.Log(Constants.LOG_PREFIX + "Line: " + line, this);
                sw.Start();
#endif
                line = ObscuredString.EncryptDecrypt(line, "Elina");
#if DEBUG_PARANOID
                sw.Stop();
                Debug.Log(Constants.LOG_PREFIX + "Line decrypted : " + line, this);
                sw.Start();
#endif
                string[] strArr       = line.Split(separator, StringSplitOptions.RemoveEmptyEntries);
                int      stringsCount = strArr.Length;
#if DEBUG_PARANOID
                sw.Stop();
                Debug.Log(Constants.LOG_PREFIX + "stringsCount : " + stringsCount, this);
                sw.Start();
#endif
                if (stringsCount > 1)
                {
                    string assemblyName = strArr[0];

                    int[] hashes = new int[stringsCount - 1];
                    for (int j = 1; j < stringsCount; j++)
                    {
                        hashes[j - 1] = int.Parse(strArr[j]);
                    }

                    allowedAssemblies[i] = new AllowedAssembly(assemblyName, hashes);
                }
                else
                {
                    signaturesAreNotGenuine = true;
                    br.Close();
                    ms.Close();
#if DEBUG_NORMAL
                    sw.Stop();
#endif
                    return;
                }
            }
            br.Close();
            ms.Close();
            Resources.UnloadAsset(assembliesSignatures);

#if DEBUG_NORMAL
            sw.Stop();
            Debug.Log(Constants.LOG_PREFIX + "Allowed Assemblies parsing duration: " + sw.ElapsedMilliseconds + " ms.", this);
#endif

            hexTable = new string[256];
            for (int i = 0; i < 256; i++)
            {
                hexTable[i] = i.ToString("x2");
            }
        }
예제 #26
0
    // Build the given messages and materials into a list of lines for our TextMeshes
    private void WordWrapText(List <TwitchChat> messages, TwitchEmoteMaterialRecycler.EmoteMaterial[] mats) // TODO: Don't rebuild the #$%^ing list every time we get a message, just push the data along and rebuild the newest line
    {
        try
        {
            lock (BuilderLocker)
            {
                mats = mats.DistinctBy(p => p.Id).ToArray();
                _emoteMap.Clear();
                for (var i = 0; i < mats.Length; i++)
                {
                    _emoteMap.Add(mats[i].Id, mats[i].Material);
                }
                const int maxEmotesPerLine = 7;
                var       lines            = new List <LineEmotePair>();
                TextMesh.text = "";
                var         ren           = TextMesh.GetComponent <Renderer>();
                const float rowLimit      = 0.975f; //find the sweet spot
                var         messageEmotes = new List <MaterialIndexPair> [messages.Count];
                for (var mi = 0; mi < messages.Count; mi++)
                {
                    messageEmotes[mi] = new List <MaterialIndexPair>();
                }
                for (var mi = 0; mi < messages.Count; mi++)
                {
                    var m = messages[mi];
                    TextMesh.text = string.Format("<color=#{0}FF>{1}</color>: ", m.Color, m.Name);
                    var builder = "";
                    var message = m.Message;

                    // Insert the Emotes for this message
                    if (m.Emotes != null && m.Emotes.Count > 0)
                    {
                        var indexIncrease = 0;
                        var nextIndex     = 0;
                        foreach (var key in m.Emotes)
                        {
                            // Cache the emote list so we can have seven unique emotes per message
                            Material mat;
                            if (!_emoteMap.TryGetValue(key.EmoteId, out mat))
                            {
                                continue;
                            }
                            var ind      = 0;
                            var foundKey = false;
                            foreach (var matPair in messageEmotes[mi].Where(matPair => key.EmoteId == matPair.EmoteId))
                            {
                                foundKey = true;
                                ind      = matPair.Index;
                                break;
                            }
                            if (!foundKey)
                            {
                                ind = nextIndex;
                                messageEmotes[mi].Add(new MaterialIndexPair(ind, key.EmoteId, mat));
                                nextIndex++;
                            }

                            var text = string.Format("<quad material={0} size=64 x=0 y=0 width=1 height=1 />", ind);
                            message        = message.Insert(key.EmoteStart + indexIncrease, text);
                            indexIncrease += text.Length;
                        }
                    }

                    // Convert this message into Lines, such that they do not exceed the bounds of the chat box
                    var buildingQuad    = false;
                    var buildingQuadNow = false;
                    var quadBuilder     = "";
                    var parts           = message.Split(' ');
                    var lineEmotes      = new List <MaterialIndexPair>();
                    var lineEmoteCount  = 0;
                    var emotes          = messageEmotes[mi].ToArray();
                    var emoteMap        = new Dictionary <int, int>();
                    var currentIndex    = -1;
                    foreach (var t in parts)
                    {
                        builder = TextMesh.text;
                        if (t == "<quad") // This is the beginning of an emote
                        {
                            buildingQuad = true;
                        }
                        if (!buildingQuad)
                        {
                            // Add these text pieces
                            TextMesh.text += t + " ";
                            if (ren.bounds.extents.x > rowLimit)
                            {
                                lines.Add(new LineEmotePair(builder.TrimEnd(), lineEmotes.ToArray()));
                                lineEmotes.Clear();
                                emoteMap.Clear();
                                lineEmoteCount = 0;
                                TextMesh.text  = t + " ";
                            }
                            builder = TextMesh.text;
                        }
                        else
                        {
                            if (buildingQuadNow || lineEmoteCount < maxEmotesPerLine)
                            {
                                buildingQuadNow = true; // Allow an emoji to finish building even if it exceeds the limits
                                // Here we are constructing the quad used in the TextMesh so that it will display an Emoji
                                string te;
                                if (t.StartsWith("material="))
                                {
                                    // Remap the materials for this line
                                    var index = int.Parse(t.Substring(9, 1));
                                    currentIndex = index;
                                    int ind;
                                    if (emoteMap.TryGetValue(index, out ind))
                                    {
                                        // This emote was already used on this line
                                        te = "material=" + ind;
                                    }
                                    else
                                    {
                                        // This emote is new to this line, we must map it for future use on this line
                                        lineEmoteCount++;
                                        lineEmotes.Add(new MaterialIndexPair(lineEmoteCount, emotes[index].EmoteId, emotes[index].Material));
                                        te = "material=" + lineEmoteCount;
                                        emoteMap.Add(index, lineEmoteCount);
                                    }
                                }
                                else
                                {
                                    te = t;
                                }

                                quadBuilder += te + " ";
                                if (t != "/>")
                                {
                                    continue;
                                }
                                buildingQuad    = false;
                                buildingQuadNow = false;
                                TextMesh.text  += quadBuilder.TrimEnd() + " ";

                                if (currentIndex == -1)
                                {
                                    Debug.LogWarning("This shouldn't happen..");
                                    continue;
                                }
                                if (ren.bounds.extents.x > rowLimit)
                                {
                                    // This Emoji violates the line's bounds
                                    // Check if this material belongs on the next line only
                                    var curId = lineEmotes[lineEmoteCount - 1].EmoteId;
                                    var count = 0;
                                    foreach (var emote in lineEmotes.Where(emote => emote.EmoteId == curId))
                                    {
                                        count++;
                                        if (count >= 2)
                                        {
                                            break;
                                        }
                                    }
                                    if (count == 1)
                                    {
                                        lineEmotes.RemoveAt(lineEmoteCount - 1);                           // Remove the last material if it only belongs to this emote
                                    }
                                    lines.Add(new LineEmotePair(builder.TrimEnd(), lineEmotes.ToArray())); // Assign the previous working buffer to the last line
                                    // Push this Emoji to the next line and reconstruct it there
                                    lineEmotes.Clear();
                                    emoteMap.Clear();

                                    var nextQuad     = "";
                                    var nexQuadParts = quadBuilder.Split(' ');

                                    lineEmoteCount = 1;
                                    // Reconstruct this Emoji for the next line
                                    foreach (var tt in nexQuadParts)
                                    {
                                        string tte;
                                        if (tt.StartsWith("material="))
                                        {
                                            tte = "material=" + lineEmoteCount;
                                        }
                                        else
                                        {
                                            tte = tt;
                                        }

                                        nextQuad += tte + " ";
                                    }
                                    // Update the Emoji map with the material for the Emoji being pushed to the next line
                                    lineEmotes.Add(new MaterialIndexPair(lineEmoteCount, emotes[currentIndex].EmoteId, emotes[currentIndex].Material));
                                    emoteMap.Add(currentIndex, lineEmoteCount);
                                    currentIndex  = -1;
                                    TextMesh.text = " " + nextQuad.Trim() + " ";
                                }
                                // Clear the working buffers
                                builder     = TextMesh.text;
                                quadBuilder = "";
                            }
                            else // Too many emotes on this line, ignore this quad
                            {
                                if (t != "/>")
                                {
                                    continue;
                                }
                                buildingQuad = false;
                            }
                        }
                    }
                    lines.Add(new LineEmotePair(builder.TrimEnd(), lineEmotes.ToArray())); // Add the final line from the builder to the list of lines
                }
                // Clear the builder's text
                TextMesh.text = "";

                // Remove excess lines
                while (lines.Count > ChatLineCount)
                {
                    lines.RemoveAt(0);
                }

                // Set the Emote materials and TextMesh texts
                var offset = ChatLineCount - lines.Count;
                for (var i = 0; i < ChatLineCount; i++)
                {
                    if (i >= lines.Count)
                    {
                        continue;
                    }
                    SetMaterialSize(ChatTextRenderers[i + offset], lines[i].EmoteList.Length + 1);
                    for (var j = 0; j < lines[i].EmoteList.Length; j++)
                    {
                        SetMaterial(ChatTextRenderers[i + offset], lines[i].EmoteList[j].Index, lines[i].EmoteList[j].Material);
                    }
                    ChatTextMeshes[i + offset].text = lines[i].LineText;
                }

                // Refresh the texts to force them to display correctly
                foreach (TextMesh t in ChatTextMeshes)
                {
                    t.anchor = TextAnchor.UpperLeft;
                    t.anchor = TextAnchor.LowerLeft;
                }
            }
        }
        catch (Exception e)
        {
            Debug.LogException(e);
        }
    }
예제 #27
0
 public static void Dispose()
 {
     Debug.LogError(FINAL_LOG_PREFIX + "is not supported on selected platform!");
 }
예제 #28
0
    // ========================================================================== //

    /* protected - Override & Unity API         */

    private void OnGUI()
    {
        UnitySO_GeneratorConfig pConfig = UnitySO_GeneratorConfig.instance;

        if (pConfig == null)
        {
            Debug.LogError("pConfig == null");
            return;
        }

        GUILayout.Space(10f);
        DrawPath_File(pConfig, "Credential Path", ref pConfig.strCredential_FilePath);
        GUILayout.Space(10f);


        DrawPath_Folder(pConfig, "SOScript Folder Path", ref pConfig.strSOScript_FolderPath);
        DrawPath_Folder(pConfig, "Json Data Folder Path", ref pConfig.strJsonData_FolderPath);
        GUILayout.Space(10f);

        DrawPath_Folder(pConfig, "SO Export Path", ref pConfig.strDataExport_FolderPath);

        if (_pTypeDataList == null)
        {
            ParsingConfig(pConfig);
        }

        GUILayout.BeginHorizontal();
        {
            EditorGUI.BeginChangeCheck();
            pConfig.pTypeDataFile = (TextAsset)EditorGUILayout.ObjectField("TypeData File : ", pConfig.pTypeDataFile, typeof(TextAsset), false, GUILayout.Width(700f));
            if (EditorGUI.EndChangeCheck())
            {
                pConfig.DoSave();
            }

            if (GUILayout.Button("Parsing File"))
            {
                if (ParsingConfig(pConfig) == false)
                {
                    Debug.LogError("TypeDataList JsonParsing Fail");
                    return;
                }
            }
        }
        GUILayout.EndHorizontal();
        GUILayout.Space(30f);

        if (_pTypeDataList != null)
        {
            GUILayout.Label($"TypeData File is Valid");
        }
        else
        {
            GUILayout.Label($"TypeData File is InValid");
        }

        bool bIsPossibleUpdate = Check_IsPossible_Update(pConfig);

        GUI.enabled = bIsPossibleUpdate;

        if (GUILayout.Button("Update Form Local", GUILayout.Width(200f)))
        {
            DoUpdate_FromLocalFile();
        }
        GUILayout.Space(30f);

        GUILayout.BeginHorizontal();
        {
            GUILayout.Label($"SheetID : ", GUILayout.Width(100f));

            EditorGUI.BeginChangeCheck();
            pConfig.strSheetID = GUILayout.TextField(pConfig.strSheetID);
            if (EditorGUI.EndChangeCheck())
            {
                pConfig.DoSave();
            }

            if (GUILayout.Button("Connect!", GUILayout.Width(100f)))
            {
#pragma warning disable 4014
                DoConnect();
#pragma warning restore 4014
            }
        }
        GUILayout.EndHorizontal();

        if (_pConnector.bIsConnected)
        {
            GUILayout.Label($"Excel is Connected : {_strSheetID_Connected} - Sheet List");
        }
        else
        {
            GUILayout.Label($"Excel is Not Connected", GetRedGUIStyle());
        }


        GUILayout.Space(30f);

        if (_pTypeDataList == null)
        {
            return;
        }

        bool bIsMatchSheetID     = Check_IsMatch_SheetID();
        bool bIsPossibleDownload = Check_IsPossibleDownload(bIsMatchSheetID);

        DrawSheetsScroll(pConfig, bIsPossibleUpdate, bIsPossibleDownload);

        GUILayout.Space(30f);

        if (bIsMatchSheetID == false)
        {
            GUILayout.Label($"SheetID Is Not Match - Local : {_pTypeDataList.strFileName}, Current Connected : {_strSheetID_Connected}", GetRedGUIStyle());
        }

        GUILayout.BeginHorizontal();
        {
            GUILayout.Label($"CommandLine : ", GUILayout.Width(100f));

            EditorGUI.BeginChangeCheck();
            pConfig.strSOCommandLine = GUILayout.TextField(pConfig.strSOCommandLine);
            if (EditorGUI.EndChangeCheck())
            {
                pConfig.DoSave();
            }
        }
        GUILayout.EndHorizontal();

        GUI.enabled = bIsPossibleDownload;
        if (GUILayout.Button("Download And Update", GUILayout.Width(200f)))
        {
            DoDownload_And_Update();
        }
    }
예제 #29
0
    private static void ChangeFormat(List <string> fbxFiles)
    {
        ResConfig resConfig    = null;
        var       databaseFile = "database_models_gltf.txt";

        if (!File.Exists(databaseFile))
        {
            resConfig = new ResConfig()
            {
                items = new List <ResItem>()
            };
        }
        else
        {
            var content = File.ReadAllText(databaseFile);
            resConfig = JsonUtility.FromJson <ResConfig>(content);
        }

        bool          hasError = false;
        StringBuilder errorMsg = new StringBuilder();
        string        destDir  = "res_models";

        int totalCount = fbxFiles.Count;
        int counter    = 0;

        foreach (var fbxFile in fbxFiles)
        {
            string input = Path.GetFullPath(fbxFile);

            string refPath   = Path.GetFullPath(fbxFile).Replace(dataPath + Path.DirectorySeparatorChar, "").ToLower();
            string outputDir = Path.Combine(destDir, refPath);
            outputDir = Path.GetDirectoryName(outputDir) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(fbxFile);
            outputDir = outputDir.ToLower();
            if (!Directory.Exists(outputDir))
            {
                Directory.CreateDirectory(outputDir);
            }

            var glftFileName = Path.GetFileNameWithoutExtension(fbxFile) + ".gltf";
            var gltfFilePath = Path.Combine(Environment.CurrentDirectory, Path.Combine(outputDir, glftFileName).ToLower());

            string arguments = input + " -o " + gltfFilePath;
            RunCommand(arguments);

            EditorUtility.DisplayProgressBar(title, "请稍后", counter / totalCount * 1.0f);
            counter++;

            var prefix         = outputDir.Replace("res_models/", string.Empty);
            var bufferFilePath = prefix + "/buffer.bin";
            var gltfRefPath    = prefix + "/" + glftFileName;

            var realPath     = outputDir + "/buffer.bin";
            var gltfRealPath = outputDir + "/" + glftFileName;


            var gltfItems   = resConfig.items.Where(s => s.path == gltfRefPath);
            var bufferItems = resConfig.items.Where(s => s.path == bufferFilePath);

            for (int i = 0; i < gltfItems.Count(); i++)
            {
                resConfig.items.Remove(gltfItems.ElementAt(i));
            }

            for (int i = 0; i < bufferItems.Count(); i++)
            {
                resConfig.items.Remove(bufferItems.ElementAt(i));
            }

            var gltfItem   = CreateConfigItem(gltfRealPath, glftFileName, gltfRefPath);
            var bufferItem = CreateConfigItem(realPath, Path.GetFileNameWithoutExtension(fbxFile) + "/buffer.bin", bufferFilePath);
            resConfig.items.Add(gltfItem);
            resConfig.items.Add(bufferItem);
        }
        EditorUtility.ClearProgressBar();

        if (hasError)
        {
            Debug.LogError(errorMsg.ToString());
        }

        File.WriteAllText(databaseFile, JsonUtility.ToJson(resConfig, true));

        EditorUtility.DisplayDialog(title, hasError?errorMsg.ToString():"转换完成", "确定");
    }
예제 #30
0
 public JSONObjectEnumer(JSONObject jsonObject)
 {
     Debug.Assert(jsonObject.isContainer); //must be an array or object to itterate
     _jobj = jsonObject;
 }
 public static void Initialize()
 {
     Debug.Log("AdjustParameter Initialize");
 }
예제 #32
0
        public override void DoUpdate(float deltaTime)
        {
            if (!Running)
            {
                return;
            }

            if (_constStateService.IsVideoMode)
            {
                return;
            }

            cmdBuffer.Ping = _networkService.Ping;
            cmdBuffer.UpdateFramesInfo();
            var missFrameTick = cmdBuffer.GetMissServerFrameTick();

            //客户端落后服务器太多帧 请求丢失帧
            if (cmdBuffer.IsNeedReqMissFrame())
            {
                _networkService.SendMissFrameReq(missFrameTick);
            }

            //if (!cmdBuffer.CanExecuteNextFrame()) { //因为网络问题 需要等待服务器发送确认包 才能继续往前
            //    return;
            //}
            _frameDeadline = Time.realtimeSinceStartup + MaxSimulationMsPerFrame;

            var minTickToBackup = missFrameTick - FrameBuffer.SnapshotFrameInterval;

            //追帧 无输入
            _constStateService.isPursueFrame = true;
            if (!PursueServer(minTickToBackup))
            {
                _constStateService.isPursueFrame = false;
                Debug.Log($"PurchaseServering curTick:" + _world.Tick);
                return;
            }

            _constStateService.isPursueFrame = false;

            var frameDeltaTime = (Time.realtimeSinceStartup - timestampOnPurcue) * 1000;
            var targetTick     = Mathf.CeilToInt(frameDeltaTime / NetworkDefine.UPDATE_DELTATIME) + tickOnPursue;

            //正常跑帧
            while (_world.Tick < targetTick)
            {
                var curTick = _world.Tick;
                cmdBuffer.UpdateFramesInfo();
                //校验服务器包  如果有预测失败 则需要进行回滚
                if (cmdBuffer.IsNeedRevert)
                {
                    _world.RollbackTo(cmdBuffer.nextTickToCheck, missFrameTick);
                    _world.CleanUselessSnapshot(System.Math.Min(cmdBuffer.nextTickToCheck - 1, _world.Tick));

                    minTickToBackup = System.Math.Max(minTickToBackup, _world.Tick + 1);
                    while (_world.Tick < missFrameTick)
                    {
                        var sFrame = cmdBuffer.GetServerFrame(_world.Tick);
                        Logging.Debug.Assert(sFrame != null && sFrame.tick == _world.Tick,
                                             $" logic error: server Frame  must exist tick {_world.Tick}");
                        //服务器超前 客户端 应该追上去 将服务器中的输入作为客户端输入
                        cmdBuffer.PushLocalFrame(sFrame);
                        Simulate(sFrame, _world.Tick >= minTickToBackup);
                    }

                    while (_world.Tick < curTick)
                    {
                        var frame = cmdBuffer.GetLocalFrame(_world.Tick);
                        FillInputWithLastFrame(frame); //加上输入预判 减少回滚
                        Logging.Debug.Assert(frame != null && frame.tick == _world.Tick,
                                             $" logic error: local frame must exist tick {_world.Tick}");
                        Predict(frame, _world.Tick > minTickToBackup);
                    }
                }

                {
                    if (_world.Tick == curTick)   //当前帧 没有被执行 需要执行之
                    {
                        ServerFrame cFrame = null;
                        var         sFrame = cmdBuffer.GetServerFrame(_world.Tick);
                        if (sFrame != null)
                        {
                            cFrame = sFrame;
                        }
                        else
                        {
                            var input = new Msg_PlayerInput(curTick, _localActorId, _inputService.GetInputCmds());
                            cFrame = new ServerFrame();
                            var inputs = new Msg_PlayerInput[_actorCount];
                            inputs[_localActorId] = input;
                            cFrame.Inputs         = inputs;
                            cFrame.tick           = curTick;
                            FillInputWithLastFrame(cFrame);
#if DEBUG_FRAME_DELAY
                            input.timeSinceStartUp = Time.realtimeSinceStartup;
#endif
                            if (curTick > cmdBuffer.maxServerTickInBuffer)   //服务器的输入还没到 需要同步输入到服务器
                            {
                                SendInput(input);
                            }
                        }

                        cmdBuffer.PushLocalFrame(cFrame);
                        Predict(cFrame);
                    }
                }
            } //end of while(_world.Tick < targetTick)

            CheckAndSendHashCodes();
        }